Exemplo n.º 1
0
        public void Activate(ContextRef cr)
        {
            bool begun = false;

            //this needs a begin signal to set the swap chain to the next backbuffer
            if (cr.gl is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9)
            {
                cr.gc.Begin();
                begun = true;
            }

            if (cr == ActiveContext)
            {
                return;
            }

            ActiveContext = cr;
            if (cr.gc != null)
            {
                //TODO - this is checking the current context inside to avoid an extra NOP context change. make this optional or remove it, since we're tracking it here
                if (!begun)
                {
                    cr.gc.Begin();
                }
            }
            if (cr.gl != null)
            {
                if (cr.gl is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)
                {
                    ((BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)cr.gl).MakeDefaultCurrent();
                }
            }
        }
Exemplo n.º 2
0
        public void Activate(ContextRef cr)
        {
            bool begun = false;

            //this needs a begin signal to set the swap chain to the next backbuffer
            if (cr.GL.DispMethodEnum is EDispMethod.SlimDX9)
            {
                cr.Gc.Begin();
                begun = true;
            }

            if (cr == _activeContext)
            {
                return;
            }

            _activeContext = cr;
            if (cr.Gc != null)
            {
                //TODO - this is checking the current context inside to avoid an extra NOP context change. make this optional or remove it, since we're tracking it here
                if (!begun)
                {
                    cr.Gc.Begin();
                }
            }
            else
            {
                if (cr.GL is IGL_TK tk)
                {
                    tk.MakeDefaultCurrent();
                }
            }
        }
Exemplo n.º 3
0
		public void Activate(ContextRef cr)
		{
			bool begun = false;

			//this needs a begin signal to set the swap chain to the next backbuffer
			if (cr.gl is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9)
			{
				cr.gc.Begin();
				begun = true;
			}

			if (cr == ActiveContext)
				return;

			ActiveContext = cr;
			if (cr.gc != null)
			{
				//TODO - this is checking the current context inside to avoid an extra NOP context change. make this optional or remove it, since we're tracking it here
				if(!begun)
					cr.gc.Begin();
			}
			else if (cr.gl != null)
			{
				if(cr.gl is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)
					((BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)cr.gl).MakeDefaultCurrent();
			}
		}
Exemplo n.º 4
0
 public ContextRef CreateGLContext()
 {
     var ret = new ContextRef
     {
         gl = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK()
     };
     return ret;
 }
Exemplo n.º 5
0
 public _IRunnable_26(_IRunnable_21 _enclosing, FixtureVariable f1, FixtureVariable
                      f2, ContextRef c2)
 {
     this._enclosing = _enclosing;
     this.f1         = f1;
     this.f2         = f2;
     this.c2         = c2;
 }
Exemplo n.º 6
0
        public DefaultABI(ContextRef context, TargetDataRef targetData)
        {
            this.context = context;
            this.targetData = targetData;

            var intPtrLLVM = LLVM.PointerType(LLVM.Int8TypeInContext(context), 0);
            intPtrSize = (int)LLVM.ABISizeOfType(targetData, intPtrLLVM);
        }
Exemplo n.º 7
0
 public _IRunnable_21(_IRunnable_19 _enclosing, FixtureVariable f1, FixtureVariable
     f2, ContextRef c1, ContextRef c2)
 {
     this._enclosing = _enclosing;
     this.f1 = f1;
     this.f2 = f2;
     this.c1 = c1;
     this.c2 = c2;
 }
Exemplo n.º 8
0
 public _IRunnable_19(FixtureContextTestCase _enclosing, FixtureVariable f1, FixtureVariable
                      f2, ContextRef c1, ContextRef c2)
 {
     this._enclosing = _enclosing;
     this.f1         = f1;
     this.f2         = f2;
     this.c1         = c1;
     this.c2         = c2;
 }
Exemplo n.º 9
0
        //[System.Runtime.InteropServices.DllImport("opengl32.dll")]
        //bool wglShareLists(IntPtr hglrc1, IntPtr hglrc2);

        public ContextRef CreateGLContext(int major_version, int minor_version, bool forward_compatible)
        {
            var gl  = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK(major_version, minor_version, forward_compatible);
            var ret = new ContextRef {
                gl = gl
            };

            return(ret);
        }
Exemplo n.º 10
0
        public ContextRef CreateGLContext(int majorVersion, int minorVersion, bool forwardCompatible)
        {
            var gl  = new IGL_TK(majorVersion, minorVersion, forwardCompatible);
            var ret = new ContextRef {
                GL = gl
            };

            return(ret);
        }
Exemplo n.º 11
0
        public DefaultABI(ContextRef context, TargetDataRef targetData)
        {
            this.context    = context;
            this.targetData = targetData;

            var intPtrLLVM = LLVM.PointerType(LLVM.Int8TypeInContext(context), 0);

            intPtrSize = (int)LLVM.ABISizeOfType(targetData, intPtrLLVM);
        }
Exemplo n.º 12
0
        public ContextRef CreateGLContext()
        {
            var ret = new ContextRef
            {
                gl = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK()
            };

            return(ret);
        }
Exemplo n.º 13
0
 public virtual void Test()
 {
     var f1 = new FixtureVariable();
     var f2 = new FixtureVariable();
     var c1 = new ContextRef();
     var c2 = new ContextRef();
     new FixtureContext().Run(new _IRunnable_19(this, f1, f2, c1, c2));
     AssertNoValue(f1);
     AssertNoValue(f2);
     c1.value.Run(new _IRunnable_41(this, f1, f2));
     c2.value.Run(new _IRunnable_48(this, f1, f2));
 }
Exemplo n.º 14
0
        public virtual void Test()
        {
            var f1 = new FixtureVariable();
            var f2 = new FixtureVariable();
            var c1 = new ContextRef();
            var c2 = new ContextRef();

            new FixtureContext().Run(new _IRunnable_19(this, f1, f2, c1, c2));
            AssertNoValue(f1);
            AssertNoValue(f2);
            c1.value.Run(new _IRunnable_41(this, f1, f2));
            c2.value.Run(new _IRunnable_48(this, f1, f2));
        }
Exemplo n.º 15
0
        public void PrepareAssembly(AssemblyDefinition assembly)
        {
            this.assembly = assembly;

            RegisterExternalTypes();

            // Resolve corlib assembly
            corlib = assembly.MainModule.Import(typeof(void)).Resolve().Module.Assembly;

            // Prepare LLVM context, module and data layouts
            context = LLVM.GetGlobalContext();
            module  = LLVM.ModuleCreateWithName(assembly.Name.Name);

            // Prepare system types, for easier access
            InitializeCommonTypes();

            // TODO: Choose appropriate triple depending on target
            var target = LLVM.GetTarget(runtimeModule);

            LLVM.SetTarget(module, target);

            // Initialize ABI
            abi = new DefaultABI(context, targetData);

            // Prepare LLVM builders
            builder       = LLVM.CreateBuilderInContext(context);
            builder2      = LLVM.CreateBuilderInContext(context);
            builderAlloca = LLVM.CreateBuilderInContext(context);

            InitializeDebug();

            if (!TestMode)
            {
                // Register SharpLangModule objects for each module
                metadataPerModule = new Dictionary <Mono.Cecil.ModuleDefinition, ValueRef>();
                var mangledModuleName     = Regex.Replace(assembly.Name.Name + ".sharplangmodule", @"(\W)", "_");
                var sharpLangModuleGlobal = LLVM.AddGlobal(module, sharpLangModuleType.ObjectTypeLLVM, mangledModuleName);
                metadataPerModule[assembly.MainModule] = sharpLangModuleGlobal;

                // Generate extern globals for SharpLangModule instances of other modules
                foreach (var referencedAssembly in referencedAssemblies)
                {
                    mangledModuleName = Regex.Replace(referencedAssembly.Name.Name + ".sharplangmodule", @"(\W)", "_");
                    var externalSharpLangModuleGlobal = LLVM.AddGlobal(module, sharpLangModuleType.ObjectTypeLLVM, mangledModuleName);
                    LLVM.SetLinkage(externalSharpLangModuleGlobal, Linkage.ExternalLinkage);
                    metadataPerModule[referencedAssembly.MainModule] = externalSharpLangModuleGlobal;
                }
            }
        }
Exemplo n.º 16
0
 public void Activate(ContextRef cr)
 {
     if (cr == ActiveContext)
         return;
     ActiveContext = cr;
     if (cr.gc != null)
     {
         //TODO - this is checking the current context inside to avoid an extra NOP context change. make this optional or remove it, since we're tracking it here
          cr.gc.Begin();
     }
     if (cr.gl != null)
     {
         if(cr.gl is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)
             ((BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)cr.gl).MakeDefaultCurrent();
     }
 }
Exemplo n.º 17
0
        public void PrepareAssembly(AssemblyDefinition assembly)
        {
            this.assembly = assembly;

            RegisterExternalTypes();

            // Resolve corlib assembly
            corlib = assembly.MainModule.Import(typeof (void)).Resolve().Module.Assembly;

            // Prepare LLVM context, module and data layouts
            context = LLVM.GetGlobalContext();
            module = LLVM.ModuleCreateWithName(assembly.Name.Name);

            // Prepare system types, for easier access
            InitializeCommonTypes();

            // TODO: Choose appropriate triple depending on target
            LLVM.SetTarget(module, triple);

            // Initialize ABI
            abi = new DefaultABI(context, targetData);

            // Prepare LLVM builders
            builder = LLVM.CreateBuilderInContext(context);
            builder2 = LLVM.CreateBuilderInContext(context);
            builderAlloca = LLVM.CreateBuilderInContext(context);

            InitializeDebug();

            if (!TestMode)
            {
                // Register SharpLangModule objects for each module
                metadataPerModule = new Dictionary<Mono.Cecil.ModuleDefinition, ValueRef>();
                var mangledModuleName = Regex.Replace(assembly.Name.Name + ".sharplangmodule", @"(\W)", "_");
                var sharpLangModuleGlobal = LLVM.AddGlobal(module, sharpLangModuleType.ObjectTypeLLVM, mangledModuleName);
                metadataPerModule[assembly.MainModule] = sharpLangModuleGlobal;

                // Generate extern globals for SharpLangModule instances of other modules
                foreach (var referencedAssembly in referencedAssemblies)
                {
                    mangledModuleName = Regex.Replace(referencedAssembly.Name.Name + ".sharplangmodule", @"(\W)", "_");
                    var externalSharpLangModuleGlobal = LLVM.AddGlobal(module, sharpLangModuleType.ObjectTypeLLVM, mangledModuleName);
                    LLVM.SetLinkage(externalSharpLangModuleGlobal, Linkage.ExternalLinkage);
                    metadataPerModule[referencedAssembly.MainModule] = externalSharpLangModuleGlobal;
                }
            }
        }
Exemplo n.º 18
0
 public void Activate(ContextRef cr)
 {
     if (cr == ActiveContext)
     {
         return;
     }
     ActiveContext = cr;
     if (cr.gc != null)
     {
         //TODO - this is checking the current context inside to avoid an extra NOP context change. make this optional or remove it, since we're tracking it here
         cr.gc.Begin();
     }
     if (cr.gl != null)
     {
         if (cr.gl is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)
         {
             ((BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)cr.gl).MakeDefaultCurrent();
         }
     }
 }
Exemplo n.º 19
0
        private static ModuleRef LoadModule(ContextRef context, string fileName)
        {
            MemoryBufferRef memoryBuffer;
            string          message;

            if (LLVM.CreateMemoryBufferWithContentsOfFile(fileName, out memoryBuffer, out message))
            {
                throw new InvalidOperationException(message);
            }

            ModuleRef runtimeModule;

            if (LLVM.GetBitcodeModuleInContext(context, memoryBuffer, out runtimeModule, out message))
            {
                throw new InvalidOperationException(message);
            }

            LLVM.DisposeMemoryBuffer(memoryBuffer);

            return(runtimeModule);
        }
Exemplo n.º 20
0
 public unsafe static ValueRef MDStringInContext(ContextRef C, string Str, uint SLen) {
   ValueRef ret = new ValueRef(LLVMPINVOKE.MDStringInContext(C.Value, Str, SLen));
   return ret;
 }
Exemplo n.º 21
0
 public unsafe static ContextRef ContextCreate() {
   ContextRef ret = new ContextRef(LLVMPINVOKE.ContextCreate());
   return ret;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Compiles an IL assembly to LLVM bytecode.
        /// </summary>
        /// <param name="moduleName">The module name.</param>
        public void Compile(string moduleName)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            // Create LLVM module and its context.
            LLVM.EnablePrettyStackTrace();
            mModule  = LLVM.ModuleCreateWithName(moduleName);
            mContext = LLVM.GetModuleContext(mModule);

            // Targets.
            LLVM.InitializeAllTargetInfos();
            LLVM.InitializeAllTargets();
            LLVM.InitializeAllTargetMCs();
            LLVM.InitializeAllAsmParsers();
            LLVM.InitializeAllAsmPrinters();

            string   triplet = (Options.Target == "default") ? LLVM.GetDefaultTargetTriple() : Options.Target;
            MyString error   = new MyString();

            LLVM.SetTarget(mModule, triplet);
            TargetRef target;

            if (LLVM.GetTargetFromTriple(triplet, out target, error))
            {
                throw new InvalidOperationException(error.ToString());
            }

            // Optimizer.
            mFunctionPassManager = LLVM.CreateFunctionPassManagerForModule(mModule);
            mPassManager         = LLVM.CreatePassManager();
            LLVM.InitializeFunctionPassManager(mFunctionPassManager);

#if !DEBUG
            // O0
            if (Options.Optimization >= OptimizationLevel.O0)
            {
                // Function passes.
                LLVM.AddPromoteMemoryToRegisterPass(mFunctionPassManager);
                LLVM.AddConstantPropagationPass(mFunctionPassManager);
                LLVM.AddReassociatePass(mFunctionPassManager);
                LLVM.AddInstructionCombiningPass(mFunctionPassManager);

                // Module passes.
                LLVM.AddAlwaysInlinerPass(mPassManager);
                LLVM.AddStripDeadPrototypesPass(mPassManager);
                LLVM.AddStripSymbolsPass(mPassManager);
            }

            // O1
            if (Options.Optimization >= OptimizationLevel.O1)
            {
                // Function passes.
                LLVM.AddLowerExpectIntrinsicPass(mFunctionPassManager);
                LLVM.AddEarlyCSEPass(mFunctionPassManager);
                LLVM.AddLoopRotatePass(mFunctionPassManager);
                LLVM.AddLoopUnswitchPass(mFunctionPassManager);
                LLVM.AddLoopUnrollPass(mFunctionPassManager);
                LLVM.AddLoopDeletionPass(mFunctionPassManager);
                LLVM.AddTailCallEliminationPass(mFunctionPassManager);
                LLVM.AddGVNPass(mFunctionPassManager);
                LLVM.AddDeadStoreEliminationPass(mFunctionPassManager);
                LLVM.AddJumpThreadingPass(mFunctionPassManager);
                LLVM.AddCFGSimplificationPass(mFunctionPassManager);
                LLVM.AddMemCpyOptPass(mFunctionPassManager);

                // Module passes.
                LLVM.AddDeadArgEliminationPass(mPassManager);
                LLVM.AddAggressiveDCEPass(mFunctionPassManager);
            }

            // O2
            if (Options.Optimization >= OptimizationLevel.O2)
            {
                // Function passes.
                LLVM.AddLoopVectorizePass(mFunctionPassManager);
                LLVM.AddSLPVectorizePass(mFunctionPassManager);

                // Module passes.
                LLVM.AddFunctionInliningPass(mPassManager);
                LLVM.AddConstantMergePass(mPassManager);
                LLVM.AddArgumentPromotionPass(mPassManager);
            }
#endif

            // Initialize types and runtime.
            string dataLayout = LLVM.GetDataLayout(Module);
            TargetData = LLVM.CreateTargetData(dataLayout);

            TypeHelper.Init(TargetData, this);
            RuntimeHelper.ImportFunctions(Module);
            mBuiltinCompiler.Compile();
            compileModules();
            LLVM.RunPassManager(mPassManager, Module);

            // Log time.
            stopWatch.Stop();
            Logger.LogDetail("Compilation time: " + stopWatch.Elapsed);

            // Debug: print LLVM assembly code.
#if DEBUG
            Console.WriteLine(LLVM.PrintModuleToString(mModule));
#endif

            // Verify and throw exception on error.
            Console.ForegroundColor = ConsoleColor.DarkGray;
            if (LLVM.VerifyModule(mModule, VerifierFailureAction.ReturnStatusAction, error))
            {
                Logger.LogError("Compilation of module failed.");
                Logger.LogInfo(error.ToString());
                LLVM.DisposeTargetData(TargetData);
                return;
            }
            else
            {
                Logger.LogDetail("Compilation of module succeeded.");
            }

            // Output assembly or object file.
            if (!Options.OutputLLVMIR && !Options.OutputLLVMBitCode)
            {
                TargetMachineRef machine = LLVM.CreateTargetMachine(target, triplet, "generic", "", CodeGenOptLevel.CodeGenLevelDefault, RelocMode.RelocDefault, CodeModel.CodeModelDefault);
                LLVM.SetModuleDataLayout(mModule, LLVM.CreateTargetDataLayout(machine));
                CodeGenFileType type = (Options.OutputAssembly) ? CodeGenFileType.AssemblyFile : CodeGenFileType.ObjectFile;

                if (LLVM.TargetMachineEmitToFile(machine, mModule, Options.OutputFile, type, error))
                {
                    throw new InvalidOperationException(error.ToString());
                }
            }
            // Output LLVM IR code to a file.
            else if (Options.OutputLLVMIR)
            {
                if (LLVM.PrintModuleToFile(mModule, Options.OutputFile, error))
                {
                    Logger.LogError("Writing the LLVM code to a file failed.");
                    Logger.LogInfo(error.ToString());
                }
            }
            // Output LLVM bitcode.
            else if (Options.OutputLLVMBitCode)
            {
                if (LLVM.WriteBitcodeToFile(mModule, Options.OutputFile) != 0)
                {
                    Logger.LogError("Writing the LLVM code to a file failed.");
                    Logger.LogInfo(error.ToString());
                }
            }

            // Cleanup.
            LLVM.DisposeTargetData(TargetData);
        }
Exemplo n.º 23
0
		public void ReleaseGLContext(object o)
		{
			ContextRef cr = (ContextRef)o;
			cr.gl.Dispose();
		}
Exemplo n.º 24
0
 public unsafe static ModuleRef ModuleCreateWithNameInContext(string ModuleID, ContextRef C) {
   ModuleRef ret = new ModuleRef(LLVMPINVOKE.ModuleCreateWithNameInContext(ModuleID, C.Value));
   return ret;
 }
Exemplo n.º 25
0
        public void TestPTX()
        {
            LLVM.InitializeAllTargets();
            LLVM.InitializeAllTargetMCs();
            LLVM.InitializeAllTargetInfos();
            LLVM.InitializeAllAsmPrinters();
            ModuleRef mod = LLVM.ModuleCreateWithName("llvmptx");
            var       pt  = LLVM.PointerType(LLVM.Int64Type(), 1);

            TypeRef[]     param_types = { pt };
            TypeRef       ret_type    = LLVM.FunctionType(LLVM.VoidType(), param_types, false);
            ValueRef      sum         = LLVM.AddFunction(mod, "sum", ret_type);
            BasicBlockRef entry       = LLVM.AppendBasicBlock(sum, "entry");
            BuilderRef    builder     = LLVM.CreateBuilder();

            LLVM.PositionBuilderAtEnd(builder, entry);
            var      v   = LLVM.BuildLoad(builder, LLVM.GetParam(sum, 0), "");
            ValueRef tmp = LLVM.BuildAdd(builder, v, LLVM.ConstInt(LLVM.Int64Type(), 1, false), "tmp");

            LLVM.BuildStore(builder, tmp, LLVM.GetParam(sum, 0));
            LLVM.BuildRetVoid(builder);
            MyString the_error = new MyString();

            LLVM.VerifyModule(mod, VerifierFailureAction.PrintMessageAction, the_error);

            string    triple = "nvptx64-nvidia-cuda";
            TargetRef t2;
            var       b = LLVM.GetTargetFromTriple(triple, out t2, the_error);

            string cpu      = "";
            string features = "";

            TargetMachineRef tmr = LLVM.CreateTargetMachine(t2, triple, cpu, features,
                                                            CodeGenOptLevel.CodeGenLevelDefault,
                                                            RelocMode.RelocDefault,
                                                            CodeModel.CodeModelKernel);
            ContextRef context_ref = LLVM.ContextCreate();
            ValueRef   kernelMd    = LLVM.MDNodeInContext(context_ref, new ValueRef[3]
            {
                sum,
                LLVM.MDStringInContext(context_ref, "kernel", 6),
                LLVM.ConstInt(LLVM.Int32TypeInContext(context_ref), 1, false)
            });

            LLVM.AddNamedMetadataOperand(mod, "nvvm.annotations", kernelMd);
            var y1 = LLVM.TargetMachineEmitToMemoryBuffer(
                tmr,
                mod,
                Swigged.LLVM.CodeGenFileType.AssemblyFile,
                the_error,
                out MemoryBufferRef buffer);
            string ptx = null;

            try
            {
                ptx = LLVM.GetBufferStart(buffer);
                uint length = LLVM.GetBufferSize(buffer);
                // Output the PTX assembly code. We can run this using the CUDA Driver API
                System.Console.WriteLine(ptx);
            }
            finally
            {
                LLVM.DisposeMemoryBuffer(buffer);
            }


            // RUN THE MF.

            Int64[]     h_C             = new Int64[100];
            CudaContext ctx             = new CudaContext(CudaContext.GetMaxGflopsDeviceId());
            CudaKernel  kernel          = ctx.LoadKernelPTX(Encoding.ASCII.GetBytes(ptx), "sum");
            var         d_C             = new CudaDeviceVariable <Int64>(100);
            int         N               = 1;
            int         threadsPerBlock = 256;

            kernel.BlockDimensions = threadsPerBlock;
            kernel.GridDimensions  = (N + threadsPerBlock - 1) / threadsPerBlock;
            kernel.Run(d_C.DevicePointer);
            h_C = d_C;
            System.Console.WriteLine("Result " + h_C[0]);
            if (h_C[0] != 1)
            {
                throw new Exception("Failed.");
            }
            LLVM.DumpModule(mod);
            LLVM.DisposeBuilder(builder);
        }
Exemplo n.º 26
0
 public unsafe static TypeRef IntTypeInContext(ContextRef C, uint NumBits) {
   TypeRef ret = new TypeRef(LLVMPINVOKE.IntTypeInContext(C.Value, NumBits));
   return ret;
 }
Exemplo n.º 27
0
 public unsafe static void ContextDispose(ContextRef C) {
   LLVMPINVOKE.ContextDispose(C.Value);
 }
Exemplo n.º 28
0
 public static TypeRef getIntNTy(ContextRef C, uint AS)
 {
     return(LLVM.IntTypeInContext(C, AS));
 }
Exemplo n.º 29
0
 public unsafe static ValueRef ConstStructInContext(ContextRef C, ValueRef[] ConstantVals, bool Packed) {
   fixed (ValueRef* swig_ptrTo_ConstantVals = ConstantVals)
   {
     ValueRef ret = new ValueRef(LLVMPINVOKE.ConstStructInContext(C.Value, (System.IntPtr)swig_ptrTo_ConstantVals, (uint)ConstantVals.Length, Packed));
     return ret;
   }
 }
Exemplo n.º 30
0
 public unsafe static BasicBlockRef InsertBasicBlockInContext(ContextRef C, BasicBlockRef BB, string Name) {
   BasicBlockRef ret = new BasicBlockRef(LLVMPINVOKE.InsertBasicBlockInContext(C.Value, BB.Value, Name));
   return ret;
 }
Exemplo n.º 31
0
 public unsafe static BasicBlockRef AppendBasicBlockInContext(ContextRef C, ValueRef Fn, string Name) {
   BasicBlockRef ret = new BasicBlockRef(LLVMPINVOKE.AppendBasicBlockInContext(C.Value, Fn.Value, Name));
   return ret;
 }
Exemplo n.º 32
0
 public unsafe static ValueRef MDNodeInContext(ContextRef C, ValueRef[] Vals) {
   fixed (ValueRef* swig_ptrTo_Vals = Vals)
   {
     ValueRef ret = new ValueRef(LLVMPINVOKE.MDNodeInContext(C.Value, (System.IntPtr)swig_ptrTo_Vals, (uint)Vals.Length));
     return ret;
   }
 }
Exemplo n.º 33
0
 public unsafe static ContextRef GetGlobalContext() {
   ContextRef ret = new ContextRef(LLVMPINVOKE.GetGlobalContext());
   return ret;
 }
Exemplo n.º 34
0
 public void Invalidate()
 {
     ActiveContext = null;
 }
Exemplo n.º 35
0
 public unsafe static TypeRef X86MMXTypeInContext(ContextRef C) {
   TypeRef ret = new TypeRef(LLVMPINVOKE.X86MMXTypeInContext(C.Value));
   return ret;
 }
Exemplo n.º 36
0
        public ModuleRef CompileAssembly(AssemblyDefinition assembly)
        {
            this.assembly = assembly;
            corlib        = assembly.MainModule.Import(typeof(void)).Resolve().Module.Assembly;
            module        = LLVM.ModuleCreateWithName(assembly.Name.Name);

            allocObjectFunction = RuntimeInline.Runtime.define_allocObject(module);

            context       = LLVM.GetModuleContext(module);
            builder       = LLVM.CreateBuilderInContext(context);
            intPtrType    = LLVM.PointerType(LLVM.Int8TypeInContext(context), 0);
            int32Type     = LLVM.Int32TypeInContext(context);
            int64Type     = LLVM.Int64TypeInContext(context);
            intPtrSize    = 4;         // Or 8?
            nativeIntType = int32Type; // Or int64Type?
            builderPhi    = LLVM.CreateBuilderInContext(context);

            intPtr = GetType(corlib.MainModule.GetType(typeof(IntPtr).FullName));
            int32  = GetType(corlib.MainModule.GetType(typeof(int).FullName));
            int64  = GetType(corlib.MainModule.GetType(typeof(long).FullName));

            // struct IMTSlot { i8* functionPtr, i32 functionId, IMTEntry* nextEntry }
            imtEntryType = LLVM.StructCreateNamed(context, "IMTEntry");
            LLVM.StructSetBody(imtEntryType, new[] { intPtrType, int32Type, LLVM.PointerType(imtEntryType, 0) }, false);

            // Process types
            foreach (var assemblyModule in assembly.Modules)
            {
                var typeReferences = assemblyModule.GetTypeReferences();
                foreach (var type in typeReferences)
                {
                    CreateType(type);
                }

                var memberReferences = assemblyModule.GetMemberReferences();
                foreach (var member in memberReferences)
                {
                    var method = member as MethodReference;
                    if (member.DeclaringType.ContainsGenericParameter())
                    {
                        continue;
                    }
                    CreateType(member.DeclaringType);
                    if (method != null)
                    {
                        if (!method.HasGenericParameters)
                        {
                            CreateFunction(method);
                        }
                    }
                }

                foreach (var type in assemblyModule.Types)
                {
                    if (!type.HasGenericParameters && type.FullName != typeof(void).FullName)
                    {
                        GetClass(type);
                    }

                    foreach (var nestedType in type.NestedTypes)
                    {
                        if (!nestedType.HasGenericParameters)
                        {
                            GetClass(nestedType);
                        }
                    }
                }
            }

            // Process methods
            foreach (var @class in classes)
            {
                CompileClassMethods(@class.Value);
            }

            // Generate code
            while (methodsToCompile.Count > 0)
            {
                var methodToCompile = methodsToCompile.Dequeue();
                CompileFunction(methodToCompile.Key, methodToCompile.Value);
            }

            // Emit "main" which will call the assembly entry point (if any)
            Function entryPoint;

            if (assembly.EntryPoint != null && functions.TryGetValue(assembly.EntryPoint, out entryPoint))
            {
                var mainFunctionType = LLVM.FunctionType(int32Type, new TypeRef[0], false);
                var mainFunction     = LLVM.AddFunction(module, "main", mainFunctionType);
                LLVM.SetLinkage(mainFunction, Linkage.ExternalLinkage);
                LLVM.PositionBuilderAtEnd(builder, LLVM.AppendBasicBlockInContext(context, mainFunction, string.Empty));

                var parameters = (entryPoint.ParameterTypes.Length > 0)
                        ? new[] { LLVM.ConstPointerNull(entryPoint.ParameterTypes[0].DefaultType) }
                        : new ValueRef[0];

                LLVM.BuildCall(builder, entryPoint.GeneratedValue, parameters, string.Empty);
                LLVM.BuildRet(builder, LLVM.ConstInt(int32Type, 0, false));
            }

            LLVM.DisposeBuilder(builder);

            // Verify module
#if VERIFY_LLVM
            string message;
            if (LLVM.VerifyModule(module, VerifierFailureAction.PrintMessageAction, out message))
            {
                throw new InvalidOperationException(message);
            }
#endif

            return(module);
        }
Exemplo n.º 37
0
 public unsafe static uint GetMDKindIDInContext(ContextRef C, string Name, uint SLen) {
   uint ret = LLVMPINVOKE.GetMDKindIDInContext(C.Value, Name, SLen);
   return ret;
 }
Exemplo n.º 38
0
 public unsafe static TypeRef PPCFP128TypeInContext(ContextRef C) {
   TypeRef ret = new TypeRef(LLVMPINVOKE.PPCFP128TypeInContext(C.Value));
   return ret;
 }
Exemplo n.º 39
0
 public unsafe static ValueRef ConstStringInContext(ContextRef C, string Str, uint Length, bool DontNullTerminate) {
   ValueRef ret = new ValueRef(LLVMPINVOKE.ConstStringInContext(C.Value, Str, Length, DontNullTerminate));
   return ret;
 }
Exemplo n.º 40
0
 public unsafe static TypeRef IntPtrTypeForASInContext(ContextRef C, TargetDataRef TD, uint AS) {
   TypeRef ret = new TypeRef(LLVMPINVOKE.IntPtrTypeForASInContext(C.Value, TD.Value, AS));
   return ret;
 }
Exemplo n.º 41
0
        public void RegisterMainAssembly(AssemblyDefinition assembly)
        {
            this.assembly = assembly;
            corlib        = assembly.MainModule.Import(typeof(void)).Resolve().Module.Assembly;

            context = LLVM.GetGlobalContext();
            module  = LLVM.ModuleCreateWithName(assembly.Name.Name);

            MemoryBufferRef memoryBuffer;
            string          message;

            if (LLVM.CreateMemoryBufferWithContentsOfFile(@"..\..\..\..\src\SharpLang.Runtime\Runtime.bc", out memoryBuffer, out message))
            {
                throw new InvalidOperationException(message);
            }

            if (LLVM.GetBitcodeModuleInContext(context, memoryBuffer, out runtimeModule, out message))
            {
                throw new InvalidOperationException(message);
            }

            LLVM.DisposeMemoryBuffer(memoryBuffer);

            // TODO: Choose appropriate triple depending on target
            LLVM.SetTarget(module, "i686-pc-mingw32");

            var dataLayout = LLVM.GetDataLayout(runtimeModule);

            targetData = LLVM.CreateTargetData(dataLayout);

            allocObjectFunction           = ImportRuntimeFunction(module, "allocObject");
            resolveInterfaceCallFunction  = ImportRuntimeFunction(module, "resolveInterfaceCall");
            isInstInterfaceFunction       = ImportRuntimeFunction(module, "isInstInterface");
            throwExceptionFunction        = ImportRuntimeFunction(module, "throwException");
            sharpPersonalityFunction      = ImportRuntimeFunction(module, "sharpPersonality");
            pinvokeLoadLibraryFunction    = ImportRuntimeFunction(module, "PInvokeOpenLibrary");
            pinvokeGetProcAddressFunction = ImportRuntimeFunction(module, "PInvokeGetProcAddress");

            builder       = LLVM.CreateBuilderInContext(context);
            intPtrType    = LLVM.PointerType(LLVM.Int8TypeInContext(context), 0);
            int32Type     = LLVM.Int32TypeInContext(context);
            int64Type     = LLVM.Int64TypeInContext(context);
            intPtrSize    = 4;         // Or 8?
            nativeIntType = int32Type; // Or int64Type?
            builder2      = LLVM.CreateBuilderInContext(context);

            debugBuilder = LLVM.DIBuilderCreate(module);

            intPtr  = GetType(corlib.MainModule.GetType(typeof(IntPtr).FullName));
            int8    = GetType(corlib.MainModule.GetType(typeof(sbyte).FullName));
            int16   = GetType(corlib.MainModule.GetType(typeof(short).FullName));
            int32   = GetType(corlib.MainModule.GetType(typeof(int).FullName));
            int64   = GetType(corlib.MainModule.GetType(typeof(long).FullName));
            uint8   = GetType(corlib.MainModule.GetType(typeof(byte).FullName));
            uint16  = GetType(corlib.MainModule.GetType(typeof(ushort).FullName));
            uint32  = GetType(corlib.MainModule.GetType(typeof(uint).FullName));
            uint64  = GetType(corlib.MainModule.GetType(typeof(ulong).FullName));
            @bool   = GetType(corlib.MainModule.GetType(typeof(bool).FullName));
            @float  = GetType(corlib.MainModule.GetType(typeof(float).FullName));
            @double = GetType(corlib.MainModule.GetType(typeof(double).FullName));

            @object = GetType(corlib.MainModule.GetType(typeof(object).FullName));

            // struct IMTEntry { i32 functionId, i8* functionPtr }
            imtEntryType = LLVM.StructCreateNamed(context, "IMTEntry");
            LLVM.StructSetBody(imtEntryType, new[] { int32Type, intPtrType }, false);

            caughtResultType = LLVM.StructCreateNamed(context, "CaughtResultType");
            LLVM.StructSetBody(caughtResultType, new[] { intPtrType, int32Type }, false);

            RegisterAssembly(assembly);
        }
Exemplo n.º 42
0
 public unsafe static TypeRef StructTypeInContext(ContextRef C, TypeRef[] ElementTypes, bool Packed) {
   fixed (TypeRef* swig_ptrTo_ElementTypes = ElementTypes)
   {
     TypeRef ret = new TypeRef(LLVMPINVOKE.StructTypeInContext(C.Value, (System.IntPtr)swig_ptrTo_ElementTypes, (uint)ElementTypes.Length, Packed));
     return ret;
   }
 }
Exemplo n.º 43
0
 public void Invalidate()
 {
     ActiveContext = null;
 }
Exemplo n.º 44
0
 public unsafe static TypeRef StructCreateNamed(ContextRef C, string Name) {
   TypeRef ret = new TypeRef(LLVMPINVOKE.StructCreateNamed(C.Value, Name));
   return ret;
 }
Exemplo n.º 45
0
 public unsafe static bool ParseBitcodeInContext(ContextRef ContextRef, MemoryBufferRef MemBuf, out ModuleRef OutModule, out string OutMessage) {
   bool ret = LLVMPINVOKE.ParseBitcodeInContext(ContextRef.Value, MemBuf.Value, out OutModule.Value, out OutMessage);
   return ret;
 }
Exemplo n.º 46
0
 public unsafe static ContextRef GetModuleContext(ModuleRef M) {
   ContextRef ret = new ContextRef(LLVMPINVOKE.GetModuleContext(M.Value));
   return ret;
 }
Exemplo n.º 47
0
 public unsafe static ContextRef GetTypeContext(TypeRef Ty) {
   ContextRef ret = new ContextRef(LLVMPINVOKE.GetTypeContext(Ty.Value));
   return ret;
 }
Exemplo n.º 48
0
 public unsafe static bool GetBitcodeModuleProviderInContext(ContextRef ContextRef, MemoryBufferRef MemBuf, out ModuleProviderRef OutMP, out string OutMessage) {
   bool ret = LLVMPINVOKE.GetBitcodeModuleProviderInContext(ContextRef.Value, MemBuf.Value, out OutMP.Value, out OutMessage);
   return ret;
 }
Exemplo n.º 49
0
 public static TypeRef getVoidTy(ContextRef C)
 {
     return(LLVM.VoidTypeInContext(C));
 }
Exemplo n.º 50
0
 public unsafe static BuilderRef CreateBuilderInContext(ContextRef C) {
   BuilderRef ret = new BuilderRef(LLVMPINVOKE.CreateBuilderInContext(C.Value));
   return ret;
 }