Example #1
0
 private MemoryMappedStorage GetVariableLayout(Variable var)
 {
     MemoryMappedStorage result;
     if (!_variableLayout.TryGetValue(var, out result))
     {
         result = Mapper.DefaultRegion.Map(var);
         _variableLayout[var] = result;
     }
     return result;
 }
Example #2
0
 public void VisitVariable(Variable variable)
 {
     Result = false;
 }
Example #3
0
 public void VisitVariable(Variable variable)
 {
     OnVisitVariable(variable);
 }
Example #4
0
 /// <summary>
 /// Indicates which variable should be semantically equivalent to "this".
 /// </summary>
 /// <param name="var">"this" variable</param>
 protected void DeclareThis(Variable var)
 {
     ResultFunction.ThisVariable = var;
 }
Example #5
0
        /// <summary>
        /// Ensures that a given local variable does not have the same name as any existing input argument,
        /// local variable or output argument.
        /// </summary>
        /// <param name="var">variable to check</param>
        /// <returns>the passed variable if it is new or a newly created variable with same type but different name</returns>
        protected Variable UniqueVariable(Variable var)
        {
            int count = 0;
            do
            {
                string tname = (count == 0) ? var.Name : var.Name + "_" + count;
                ++count;
                Variable tvar = new Variable(var.Type)
                {
                    Name = tname
                };
                if (ResultFunction.LocalVariables.Contains(tvar))
                    continue;
                if (ResultFunction.InputVariables.Contains(tvar))
                    continue;
                if (ResultFunction.OutputVariables.Contains(tvar))
                    continue;

                return tvar;
            } while (true);
        }
Example #6
0
 public virtual void InlineCall(Function fn, Expression[] inArgs, Variable[] outArgs, bool shareLocals = false)
 {
     StmtVariableReplacer svr = new StmtVariableReplacer();
     for (int i = 0; i < inArgs.Length; i++)
     {
         var v = (Literal)fn.InputVariables[i];
         var v_ = v;
         if (v is Variable)
             v_ = UniqueVariable((Variable)v);
         svr.AddReplacement(v, v_);
         DeclareLocal((IStorableLiteral)v_);
     }
     foreach (Variable v in fn.LocalVariables)
     {
         if (shareLocals)
         {
             if (!ResultFunction.LocalVariables.Contains(v))
                 DeclareLocal(v);
         }
         else
         {
             Variable v_ = UniqueVariable(v);
             svr.AddReplacement(v, v_);
             DeclareLocal(v_);
         }
     }
     for (int i = 0; i < outArgs.Length; i++)
     {
         var v = fn.OutputVariables[i];
         var v_ = outArgs[i];
         svr.AddReplacement((Literal)v, v_);
     }
     for (int i = 0; i < inArgs.Length; i++)
     {
         IStorableLiteral v_ = (IStorableLiteral)svr.Lookup((Literal)fn.InputVariables[i]);
         Expression vlr = (Variable)v_;
         if (!vlr.Equals(inArgs[i]))
             Store(v_, inArgs[i]);
     }
     Statement body = fn.Body.Clone;
     body.Accept(svr);
     Variable returnVariable;
     Statement inlined = body.RemoveRets(out returnVariable);
     if (returnVariable != null)
         DeclareLocal(returnVariable);
     _cstack.Peek().Statements.Add(inlined);
 }
Example #7
0
 public void InlineCall(Function fn, Expression[] inArgs, Variable[] outArgs, bool shareLocals = false)
 {
     Contract.Requires(fn != null);
     Contract.Requires(inArgs != null);
     Contract.Requires(outArgs != null);
     Contract.Requires(inArgs.Length == fn.InputVariables.Count);
     Contract.Requires(outArgs.Length == fn.OutputVariables.Count);
 }
 private void ProcessStoreVariable(XILSInstr i)
 {
     var lit = (IStorableLiteral)i.StaticOperand;
     var local = lit as Variable;
     IStorableLiteral newLit;
     if (local != null)
     {
         Variable newLocal;
         if (!_localDic.TryGetValue(local.Name, out newLocal))
         {
             newLocal = new Variable(TypeStack.Peek())
             {
                 Name = local.Name
             };
             _localDic[local.Name] = newLocal;
         }
         newLit = newLocal;
     }
     else
     {
         newLit = lit;
     }
     var preds = RemapPreds(i.Preds);
     if (!TypeStack.Peek().Equals(newLit.Type))
     {
         Convert(preds, TypeStack.Peek(), newLit.Type);
         preds = new InstructionDependency[0];
     }
     var inew = new XILSInstr(
         DefaultInstructionSet.Instance.StoreVar(newLit),
         preds,
         new TypeDescriptor[] { newLit.Type },
         new TypeDescriptor[0]);
     Emit(inew);
 }
 public object EvalVariable(Variable variable)
 {
     return DoEvalVariable(variable);
 }
Example #10
0
 /// <summary>
 /// Maps a variable to this region.
 /// </summary>
 /// <param name="v">variable to map</param>
 /// <returns>storage mapping of the variable</returns>
 public MemoryMappedStorage Map(Variable v)
 {
     Contract.Requires(v != null);
     var result = new MemoryMappedStorage(v, this, Marshal.Layout(v.Type, MarshalInfo));
     Items.Add(result);
     return result;
 }
 public void VisitVariable(Variable variable)
 {
     _result = variable;
 }
 private object EvaluateVariable(Variable variable)
 {
     return _varValues[variable];
 }
Example #13
0
        public override bool Rewrite(CodeDescriptor decompilee, Expression waitObject, IDecompiler stack, IFunctionBuilder builder)
        {
            if (stack.HasAttribute<Analysis.M2M.HLS>())
            {
                return true;
            }

            var curps = DesignContext.Instance.CurrentProcess;
            SLSignal clk = (SLSignal)curps.Sensitivity[0].Owner;
            SignalRef srEdge;
            if (curps.Predicate.Equals((Func<bool>)clk.RisingEdge))
                srEdge = SignalRef.Create(clk.Descriptor, SignalRef.EReferencedProperty.RisingEdge);
            else
                srEdge = SignalRef.Create(clk.Descriptor, SignalRef.EReferencedProperty.FallingEdge);
            var lrEdge = new LiteralReference(srEdge);

            int nwait = 0;
            var nwaitEx = waitObject.Children[0];
            bool nwaitConst = nwaitEx.IsConst();
            if (nwaitConst)
            {
                nwait = (int)TypeConversions.ConvertValue(
                        nwaitEx.Eval(DefaultEvaluator.DefaultConstEvaluator),
                        typeof(int));
            }

            var fspec = new FunctionSpec(typeof(void))
            {
                IntrinsicRep = IntrinsicFunctions.Wait(WaitParams.EWaitKind.WaitUntil)
            };

            Variable v = null;
            LiteralReference lrV = null;

            if (!nwaitConst || nwait > 3)
            {
                v = new Variable(typeof(int))
                {
                    Name = "_wait_i" + (ictr++)
                };
                builder.DeclareLocal(v);
                lrV = new LiteralReference(v);
                builder.Store(v, LiteralReference.CreateConstant((int)0));
                var loop = builder.Loop();
                builder.If(Expression.Equal(lrV, nwaitEx));
                {
                    builder.Break(loop);
                }
                builder.EndIf();
            }
            int ncalls = 1;
            if (nwaitConst && nwait <= 3)
                ncalls = nwait;
            for (int i = 0; i < ncalls; i++)
            {
                builder.Call(fspec, lrEdge);
            }
            if (!nwaitConst || nwait > 3)
            {
                builder.Store(v, lrV + LiteralReference.CreateConstant((int)1));
                builder.EndLoop();
            }
            return true;
        }
Example #14
0
 public void VisitVariable(Variable variable)
 {
     Result = _vhdg.MakeIDName(variable.Name, variable);
 }
        private CoFSM DecompileToCoFSM(string prefix)
        {
            ImplStyle = EAsyncImplStyle.FSM;
            InjectAttributes(prefix);
            InitializeCFGs();

            CoFSM cofsm = new CoFSM();

            var args = _code.AsyncMethod.GetParameters();
            cofsm.Arguments = new Variable[args.Length];
            _argFields = new Dictionary<string, Variable>();
            for (int i = 0; i < args.Length; i++)
            {
                string name = prefix + "_" + args[i].Name;
                var argv = new Variable(TypeDescriptor.GetTypeOf(_arguments[i]))
                {
                    Name = name
                };
                _argFields[args[i].Name] = argv;
                cofsm.Arguments[i] = argv;
            }

            int numILStates = _stateCFGs.Length;
            var mym = _code as MethodDescriptor;
            cofsm.Method = mym;
            cofsm.Dependencies = new HashSet<Task>();

            // Create result variable and done flag
            cofsm.DoneVar = new Variable(typeof(bool)) {
                Name = prefix + "_$done"
            };
            if (_code.AsyncMethod.ReturnType.IsGenericType &&
                _code.AsyncMethod.ReturnType.GetGenericTypeDefinition().Equals(typeof(Task<>)))
            {
                var resultType = _code.AsyncMethod.ReturnType.GetGenericArguments()[0];
                if (!resultType.Equals(typeof(void)))
                {
                    cofsm.ResultVar = new Variable(resultType)
                    {
                        Name = prefix + "_$result"
                    };

                    var builderType = typeof(AsyncTaskMethodBuilder<>).MakeGenericType(resultType);
                    AttributeInjector.Inject(builderType,
                        new MapToIntrinsicType(Meta.EIntrinsicTypes.IllegalRuntimeType));
                    var aoc1 = builderType.GetMethod("AwaitOnCompleted");
                    var aoc2 = builderType.GetMethod("AwaitUnsafeOnCompleted");
                    var rwc = new AwaitOnCompletedRewriter();
                    AttributeInjector.Inject(aoc1, rwc);
                    AttributeInjector.Inject(aoc2, rwc);
                    var sr = builderType.GetMethod("SetResult");
                    var rwsr = new SetResultRewriter();
                    AttributeInjector.Inject(sr, rwsr);
                    var se = builderType.GetMethod("SetException");
                    var serw = new SetExceptionRewriter();
                    AttributeInjector.Inject(se, serw);
                    AttributeInjector.Inject(builderType, new HideDeclaration());

                    var awaiterType = typeof(TaskAwaiter<>).MakeGenericType(resultType);
                    AttributeInjector.Inject(awaiterType,
                        new MapToIntrinsicType(Meta.EIntrinsicTypes.IllegalRuntimeType));
                    AttributeInjector.Inject(awaiterType.GetMethod("get_IsCompleted"), new RewriteIsCompleted());
                    AttributeInjector.Inject(awaiterType.GetMethod("OnCompleted"), new AwaitOnCompletedRewriter());
                    AttributeInjector.Inject(awaiterType.GetMethod("UnsafeOnCompleted"), new AwaitOnCompletedRewriter());
                    AttributeInjector.Inject(awaiterType.GetMethod("GetResult"), new RewriteGetResult());
                    AttributeInjector.Inject(awaiterType, new HideDeclaration());
                }
            }

            // Decompile state handlers
            _stateInfos = new Dictionary<StateInfo, StateInfo>();
            var decomp = new MSILDecompiler(_code, _stateCFGs[0], _fsmInstance);
            _curTempl = decomp.Template;
            _curTempl.AddAttribute(this);
            _curTempl.DisallowReturnStatements = true;
            _curTempl.DisallowConditionals = true;
            _curTempl.DisallowLoops = true;
            var lvState = _curTempl.ExportLocalVariableState();
            var startSI = new StateInfo(-1);
            foreach (var kvp in _locFields)
                startSI.LVState[kvp.Key] = kvp.Value.Type.GetSampleInstance(ETypeCreationOptions.ForceCreation);
            _stateInfos[startSI] = startSI;
            _curSI = startSI;
            var stateList = new List<StateInfo>();
            stateList.Add(startSI);
            _stateQ = new Queue<StateInfo>();
            _curCoFSM = cofsm;
            startSI.Result = decomp.Decompile();
            while (_stateQ.Any())
            {
                var nextSI = _stateQ.Dequeue();
                _curSI = nextSI.Fork(nextSI.ILState);
                decomp = new MSILDecompiler(_code, _stateCFGs[nextSI.ILState + 1], _fsmInstance);
                _curTempl = decomp.Template;
                _curTempl.AddAttribute(this);
                _curTempl.DisallowReturnStatements = true;
                _curTempl.DisallowConditionals = true;
                _curTempl.DisallowLoops = true;
                _curSI.Result = decomp.Decompile();
                stateList.Add(_curSI);
                _stateInfos[_curSI] = _curSI;
            }

            // Create state active variables
            cofsm.StateActiveVars = new List<Variable>();
            int j = 0;
            for (int i = 0; i < stateList.Count; i++)
            {
                if (stateList[i].HasWaitState)
                {
                    cofsm.StateActiveVars.Add(new Variable(typeof(bool))
                    {
                        Name = prefix + "_$waitStateActive" + i
                    });
                    stateList[i].WaitStateValue = j++;
                }
                cofsm.StateActiveVars.Add(new Variable(typeof(bool))
                {
                    Name = prefix + "_$stateActive" + i
                });
                stateList[i].StateValue = j++;
            }

            int numStates = j;

            // Replace ProceedWithState calls with actual states
            var states = new Statement[numStates];

            j = 0;
            for (int i = 0; i < stateList.Count; i++)
            {
                if (stateList[i].HasWaitState)
                {
                    var wsb = new DefaultAlgorithmBuilder();
                    ImplementJoin(stateList[i].JP, wsb, stateList[i]);
                    //wsb.Call(stateList[i].JoinSpec, new Expression[0]);
                    var join = wsb.Complete();
                    states[j++] = join.Body;
                }
                states[j++] = stateList[i].Result.Decompiled.Body;
            }

            for (j = 0; j < states.Length; j++)
            {
                var orgBody = states[j];
                var xform = new CoStateAssigner(this, cofsm.StateActiveVars, orgBody, j);
                var state = xform.GetAlgorithm();
                states[j] = state.Body;
            }

            var calledMethods = stateList
                .SelectMany(b => b.Result.CalledMethods)
                .Distinct()
                .ToList();
            var calledSyncMethods = calledMethods
                .Where(mci => !mci.Method.IsAsync())
                .ToList();
            cofsm.CalledMethods = calledSyncMethods;

            // State handlers
            var alg = new DefaultAlgorithmBuilder();
            alg.Store(cofsm.DoneVar, LiteralReference.CreateConstant(false));
            for (int i = states.Length - 1; i >= 1; i--)
            {
                var lrsa = (LiteralReference)cofsm.StateActiveVars[i];
                alg.If(lrsa);
                alg.InlineCall(states[i]);
                alg.EndIf();
            }
            var handlerAlg = alg.Complete();
            cofsm.HandlerBody = handlerAlg.Body;
            alg = new DefaultAlgorithmBuilder();
            alg.Store(cofsm.DoneVar, LiteralReference.CreateConstant(false));
            alg.InlineCall(states[0]);
            cofsm.InitialHandler = alg.Complete().Body;

            return cofsm;
        }
 public object DefaultEvalVariable(Variable variable)
 {
     throw new BreakEvaluationException();
 }
        private void InjectAttributes(string prefix)
        {
            var fsmType = _code.AsyncMethod.GetStateMachineType();
            _fsmInstance = Activator.CreateInstance(fsmType);
            AttributeInjector.Inject(fsmType, new HideDeclaration());

            var thisField = fsmType
                .GetFields(BindingFlags.Public | BindingFlags.Instance)
                .Where(f => f.Name.Contains("this") && f.FieldType.Equals(_code.AsyncMethod.DeclaringType))
                .FirstOrDefault();
            if (thisField != null)
            {
                AttributeInjector.Inject(thisField, new StaticEvaluation());
                thisField.SetValue(_fsmInstance, _instance);
            }

            var stateField = fsmType
                .GetFields(BindingFlags.Public | BindingFlags.Instance)
                .Where(f => f.Name.Contains("state") && f.FieldType.Equals(typeof(int)))
                .FirstOrDefault();
            if (stateField != null)
            {
                AttributeInjector.Inject(stateField, new StateAccessRewriter());
            }

            var awaiterFields = fsmType
                .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                .Where(f => f.Name.Contains("$awaiter"));

            foreach (var awaiterField in awaiterFields)
            {
                AttributeInjector.Inject(awaiterField, new AwaiterAccessRewriter());
            }

            _locFields = new Dictionary<string, Variable>();
            _declared = new HashSet<Variable>();
            _tasks = new Dictionary<string, object>();
            var fields = fsmType.GetFields();
            var lfar = new LocalFieldAccessRewriter();
            var afar = new ArgFieldAccessRewriter();
            var tar = new TaskAccessRewriter();
            var argNames = _code.AsyncMethod
                .GetParameters()
                .Select(p => p.Name)
                .ToArray();
            foreach (var field in fields)
            {
                var name = field.Name;

                bool isTask = false;

                if (field.FieldType.IsGenericType &&
                    field.FieldType.GetGenericTypeDefinition().Equals(typeof(Task<>)))
                {
                    // it is a task variable
                    AttributeInjector.Inject(field, tar);
                    AttributeInjector.Inject(field.FieldType,
                        new MapToIntrinsicType(Meta.EIntrinsicTypes.IllegalRuntimeType));
                    AttributeInjector.Inject(field.FieldType, new HideDeclaration());
                    isTask = true;
                }

                if (field.FieldType.IsGenericType &&
                    field.FieldType.GetGenericTypeDefinition().Equals(typeof(AsyncTaskMethodBuilder<>)))
                {
                    var builderType = field.FieldType;
                    var aoc1 = builderType.GetMethod("AwaitOnCompleted");
                    var aoc2 = builderType.GetMethod("AwaitUnsafeOnCompleted");
                    var rwc = new AwaitOnCompletedRewriter();
                    AttributeInjector.Inject(aoc1, rwc);
                    AttributeInjector.Inject(aoc2, rwc);
                    var sr = builderType.GetMethod("SetResult");
                    var rwsr = new SetResultRewriter();
                    AttributeInjector.Inject(sr, rwsr);
                    var se = builderType.GetMethod("SetException");
                    var serw = new SetExceptionRewriter();
                    AttributeInjector.Inject(se, serw);
                }

                int pindex = Array.IndexOf(argNames, name);
                if (pindex >= 0)
                {
                    field.SetValue(_fsmInstance, _arguments[pindex]);
                    if (isTask)
                    {
                        var task = _arguments[pindex];
                        var lr = LiteralReference.CreateConstant(task);
                        _tasks[field.Name] = new StackElement(lr, task, EVariability.Constant);
                    }
                    else
                    {
                        AttributeInjector.Inject(field, afar);
                    }
                    continue;
                }

                if (isTask)
                    continue;

                int beg = name.IndexOf('<');
                int end = name.LastIndexOf('>');
                if (beg == -1 || end == -1 || (end - beg) <= 1)
                    continue;

                var locName = prefix + name.Substring(beg + 1, end - beg - 1);

                var v = new Variable(field.FieldType)
                {
                    Name = locName
                };
                _locFields[field.Name] = v;
                AttributeInjector.Inject(field, lfar);
            }

            foreach (var local in _code.Method.GetMethodBody().LocalVariables)
            {
                var locType = local.LocalType;
                if (locType.IsGenericType &&
                    locType.GetGenericTypeDefinition().Equals(typeof(TaskAwaiter<>)))
                {
                    AttributeInjector.Inject(locType, new HideDeclaration());
                }
            }
        }
Example #18
0
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 /// <param name="mappedVariable">variable to be hardware-mapped</param>
 /// <param name="directFeed"><c>true</c>, if write-trough semantics hold, i.e. input is combinatorially routed to output during write access</param>
 public LocalStorageUnit(Variable mappedVariable, bool directFeed)
 {
     MappedVariable = mappedVariable;
     _directFeed = directFeed;
     DataWidth = (int)TypeLowering.Instance.GetWireType(mappedVariable.Type).Constraints[0].Size;
     StdLogicVector initial;
     if (mappedVariable.InitialValue == null)
         initial = StdLogicVector._0s(TypeLowering.Instance.GetWireWidth(mappedVariable.Type));
     else
         initial = Marshal.SerializeForHW(mappedVariable.InitialValue);
     _stg = new SLVSignal(DataWidth)
     {
         InitialValue = initial
     };
     _taSite = new LocalStorageUnitTransactionSite(this);
 }