Exemplo n.º 1
0
        internal EmittingContext(LLVMModuleRef pModule, LLVMPassManagerRef pPass, bool pEmitDebug)
        {
            CurrentModule       = pModule;
            _passManager        = pPass;
            _context            = LLVM.GetGlobalContext();
            _deferredStatements = new Stack <List <Syntax.SyntaxNode> >();
            Builder             = LLVM.CreateBuilder();
            _emitDebug          = pEmitDebug;
            Locals         = new ScopeCache <LocalDefinition>();
            AccessStack    = new AccessStack <MemberAccess>();
            BreakLocations = new AccessStack <LLVMValueRef>(1);

            if (_emitDebug)
            {
                _debugLocations = new Stack <LLVMMetadataRef>();
                _debugInfo      = Utils.LlvmPInvokes.LLVMCreateDIBuilder(CurrentModule);
                _debugFile      = Utils.LlvmPInvokes.LLVMDIBuilderCreateFile(_debugInfo, "debug", 5, ".", 1);

                //Set debug version
                var version = LLVM.MDNode(new LLVMValueRef[] { GetInt(1),                               //Error on mismatch
                                                               LLVM.MDString("Debug Info Version", 18), //Constant string. Cannot change.
                                                               GetInt(3) });                            //Debug version
                LLVM.AddNamedMetadataOperand(CurrentModule, "llvm.module.flags", version);
            }
        }
Exemplo n.º 2
0
        private void InitRegisters(LLVMContextRef context, LLVMModuleRef module)
        {
            var int32Type = context.Int32Type;

            GetThreadIdxX = new Lazy <LLVMValueRef>(() => AddFunction(
                                                        module, "llvm.nvvm.read.ptx.sreg.tid.x", FunctionType(int32Type)));
            GetThreadIdxY = new Lazy <LLVMValueRef>(() => AddFunction(
                                                        module, "llvm.nvvm.read.ptx.sreg.tid.y", FunctionType(int32Type)));
            GetThreadIdxZ = new Lazy <LLVMValueRef>(() => AddFunction(
                                                        module, "llvm.nvvm.read.ptx.sreg.tid.z", FunctionType(int32Type)));

            GetBlockIdxX = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.read.ptx.sreg.ctaid.x", FunctionType(int32Type)));
            GetBlockIdxY = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.read.ptx.sreg.ctaid.y", FunctionType(int32Type)));
            GetBlockIdxZ = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.read.ptx.sreg.ctaid.z", FunctionType(int32Type)));

            GetBlockDimX = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.read.ptx.sreg.ntid.x", FunctionType(int32Type)));
            GetBlockDimY = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.read.ptx.sreg.ntid.y", FunctionType(int32Type)));
            GetBlockDimZ = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.read.ptx.sreg.ntid.z", FunctionType(int32Type)));

            GetGridDimX = new Lazy <LLVMValueRef>(() => AddFunction(
                                                      module, "llvm.nvvm.read.ptx.sreg.nctaid.x", FunctionType(int32Type)));
            GetGridDimY = new Lazy <LLVMValueRef>(() => AddFunction(
                                                      module, "llvm.nvvm.read.ptx.sreg.nctaid.y", FunctionType(int32Type)));
            GetGridDimZ = new Lazy <LLVMValueRef>(() => AddFunction(
                                                      module, "llvm.nvvm.read.ptx.sreg.nctaid.z", FunctionType(int32Type)));

            GetGridDimensions  = new Lazy <LLVMValueRef>[] { GetGridDimX, GetGridDimY, GetGridDimZ };
            GetBlockDimensions = new Lazy <LLVMValueRef>[] { GetBlockDimX, GetBlockDimY, GetBlockDimZ };
        }
Exemplo n.º 3
0
 public void Initiate()
 {
     ClassSkeletons = new Dictionary <string, LLVMTypeRef>();
     Context        = LLVM.ContextCreate();
     Module         = LLVM.ModuleCreateWithNameInContext("ADefaultModuleId", Context);
     Builder        = LLVM.CreateBuilderInContext(Context);
 }
Exemplo n.º 4
0
 public void TestLazyIRCompilation( )
 {
     using (Library.InitializeLLVM( ))
     {
         Library.RegisterNative( );
         using (LLVMContextRef context = LLVMContextCreate( ))
         {
             string nativeTriple = LLVMGetDefaultTargetTriple();
             Assert.IsFalse(string.IsNullOrWhiteSpace(nativeTriple));
             Assert.IsTrue(LLVMGetTargetFromTriple(nativeTriple, out LLVMTargetRef targetHandle, out string errorMessag).Succeeded);
             LLVMTargetMachineRef machine = LLVMCreateTargetMachine(
                 targetHandle,
                 nativeTriple,
                 string.Empty,
                 string.Empty,
                 LLVMCodeGenOptLevel.LLVMCodeGenLevelDefault,
                 LLVMRelocMode.LLVMRelocDefault,
                 LLVMCodeModel.LLVMCodeModelJITDefault);
             using ( machine )
             {
                 LLVMOrcJITStackRef orcJit = LLVMOrcCreateInstance(machine);
                 using ( orcJit )
                 {
                     // try several different modules with the same function name replacing the previous
                     AddAndExecuteTestModule(orcJit, context, machine, 42);
                     AddAndExecuteTestModule(orcJit, context, machine, 12345678);
                     AddAndExecuteTestModule(orcJit, context, machine, 87654321);
                 }
             }
         }
     }
 }
Exemplo n.º 5
0
 public static LLVMTypeRef StructTypeInContext(LLVMContextRef context, params LLVMTypeRef[] elementTypes)
 {
     if (elementTypes == null || elementTypes.Length < 1)
     {
         return(StructTypeInContext(context, out LLVMTypeRef _, 0, false));
     }
     return(StructTypeInContext(context, out elementTypes[0], elementTypes.Length, false));
 }
Exemplo n.º 6
0
 public ClepsMemberGeneratorParser(ClassManager classManager, CompileStatus status, LLVMContextRef context, LLVMModuleRef module, LLVMBuilderRef builder, ClepsLLVMTypeConvertor clepsLLVMTypeConvertor)
 {
     ClassManager = classManager;
     Status       = status;
     Context      = context;
     Module       = module;
     Builder      = builder;
     ClepsLLVMTypeConvertorInst = clepsLLVMTypeConvertor;
 }
Exemplo n.º 7
0
        private void InitWarps(LLVMContextRef context, LLVMModuleRef module)
        {
            var getterType = FunctionType(context.Int32Type);

            GetWarpSize = new Lazy <LLVMValueRef>(() => AddFunction(
                                                      module, "llvm.nvvm.read.ptx.sreg.warpsize", getterType));
            GetLaneId = new Lazy <LLVMValueRef>(() => AddFunction(
                                                    module, "llvm.nvvm.read.ptx.sreg.laneid", getterType));
        }
 public ClepsClassNamesGeneratorParser(ClassManager classManager, CompileStatus status, LLVMContextRef context, LLVMModuleRef module, LLVMBuilderRef builder, out Dictionary <string, LLVMTypeRef> classSkeletons)
 {
     ClassManager   = classManager;
     Status         = status;
     Context        = context;
     Module         = module;
     Builder        = builder;
     classSkeletons = new Dictionary <string, LLVMTypeRef>();
     ClassSkeletons = classSkeletons;
 }
Exemplo n.º 9
0
        private void EmitNativeMain(LLVMContextRef context)
        {
            LLVMValueRef shadowStackTop = Module.GetNamedGlobal("t_pShadowStackTop");

            LLVMBuilderRef builder        = context.CreateBuilder();
            var            mainSignature  = LLVMTypeRef.CreateFunction(LLVMTypeRef.Int32, new LLVMTypeRef[] { LLVMTypeRef.Int32, LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0) }, false);
            var            mainFunc       = Module.AddFunction("__managed__Main", mainSignature);
            var            mainEntryBlock = mainFunc.AppendBasicBlock("entry");

            builder.PositionAtEnd(mainEntryBlock);
            LLVMValueRef managedMain = Module.GetNamedFunction("StartupCodeMain");

            if (managedMain.Handle == IntPtr.Zero)
            {
                throw new Exception("Main not found");
            }

            LLVMTypeRef  reversePInvokeFrameType = LLVMTypeRef.CreateStruct(new LLVMTypeRef[] { LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0), LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0) }, false);
            LLVMValueRef reversePinvokeFrame     = builder.BuildAlloca(reversePInvokeFrameType, "ReversePInvokeFrame");
            LLVMValueRef RhpReversePInvoke2      = Module.GetNamedFunction("RhpReversePInvoke2");

            if (RhpReversePInvoke2.Handle == IntPtr.Zero)
            {
                RhpReversePInvoke2 = Module.AddFunction("RhpReversePInvoke2", LLVMTypeRef.CreateFunction(LLVMTypeRef.Void, new LLVMTypeRef[] { LLVMTypeRef.CreatePointer(reversePInvokeFrameType, 0) }, false));
            }

            builder.BuildCall(RhpReversePInvoke2, new LLVMValueRef[] { reversePinvokeFrame }, "");

            var shadowStack     = builder.BuildMalloc(LLVMTypeRef.CreateArray(LLVMTypeRef.Int8, 1000000), String.Empty);
            var castShadowStack = builder.BuildPointerCast(shadowStack, LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0), String.Empty);

            builder.BuildStore(castShadowStack, shadowStackTop);

            var shadowStackBottom = Module.AddGlobal(LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0), "t_pShadowStackBottom");

            shadowStackBottom.Linkage         = LLVMLinkage.LLVMExternalLinkage;
            shadowStackBottom.Initializer     = LLVMValueRef.CreateConstPointerNull(LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0));
            shadowStackBottom.ThreadLocalMode = LLVMThreadLocalMode.LLVMLocalDynamicTLSModel;
            builder.BuildStore(castShadowStack, shadowStackBottom);

            // Pass on main arguments
            LLVMValueRef argc = mainFunc.GetParam(0);
            LLVMValueRef argv = mainFunc.GetParam(1);

            LLVMValueRef mainReturn = builder.BuildCall(managedMain, new LLVMValueRef[]
            {
                castShadowStack,
                argc,
                argv,
            },
                                                        "returnValue");

            builder.BuildRet(mainReturn);
            mainFunc.Linkage = LLVMLinkage.LLVMExternalLinkage;
        }
Exemplo n.º 10
0
        private void InitMemoryFences(LLVMContextRef context, LLVMModuleRef module)
        {
            var fenceType = FunctionType(context.VoidType);

            BlockLevelFence = new Lazy <LLVMValueRef>(() => AddFunction(
                                                          module, "llvm.nvvm.membar.cta", fenceType));
            DeviceLevelFence = new Lazy <LLVMValueRef>(() => AddFunction(
                                                           module, "llvm.nvvm.membar.gl", fenceType));
            SystemLevelFence = new Lazy <LLVMValueRef>(() => AddFunction(
                                                           module, "llvm.nvvm.membar.sys", fenceType));
        }
Exemplo n.º 11
0
        private Context(LLVMContextRef contextRef)
        {
            ContextHandle = contextRef;
            lock ( ContextCache )
            {
                ContextCache.Add(contextRef, this);
            }

            ActiveHandler = new WrappedNativeCallback(new LLVMDiagnosticHandler(DiagnosticHandler));
            NativeMethods.ContextSetDiagnosticHandler(ContextHandle, ActiveHandler.GetFuncPointer( ), IntPtr.Zero);
        }
Exemplo n.º 12
0
 public Context()
 {
     _context  = LLVMContextRef.Create();
     VoidType  = _context.VoidType;
     Int1Type  = _context.Int1Type;
     Int8Type  = _context.Int8Type;
     Int16Type = _context.Int16Type;
     Int32Type = _context.Int32Type;
     Int64Type = _context.Int64Type;
     SetDiagnosticHandler(diagnosticInfo =>
                          Console.WriteLine($"LLVM {diagnosticInfo.Severity}: {diagnosticInfo.DescriptionString}"));
 }
Exemplo n.º 13
0
        private void InitGroups(LLVMContextRef context, LLVMModuleRef module)
        {
            GroupBarrier = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.barrier0", FunctionType(context.VoidType)));
            var genericGroupBarrierType = FunctionType(context.Int32Type, context.Int32Type);

            GroupBarrierAnd = new Lazy <LLVMValueRef>(() => AddFunction(
                                                          module, "llvm.nvvm.barrier0.and", genericGroupBarrierType));
            GroupBarrierOr = new Lazy <LLVMValueRef>(() => AddFunction(
                                                         module, "llvm.nvvm.barrier0.or", genericGroupBarrierType));
            GroupBarrierPopCount = new Lazy <LLVMValueRef>(() => AddFunction(
                                                               module, "llvm.nvvm.barrier0.popc", genericGroupBarrierType));
        }
Exemplo n.º 14
0
        public CompileStatus CompileFiles()
        {
            ClassManager  classManager = new ClassManager();
            CompileStatus status       = new CompileStatus(false /* exit on first error */);

            LLVMContextRef context = LLVM.ContextCreate();
            LLVMModuleRef  module  = LLVM.ModuleCreateWithNameInContext(OutputFileName, context);
            LLVMBuilderRef builder = LLVM.CreateBuilderInContext(context);

            try
            {
                //Byte code is generated in multiple passes so that all member variables and functions are stubbed out before they are referred to in function bodies
                //This allows functions on the top of a file to call functions on the bottom of a file as well

                Dictionary <string, LLVMTypeRef> classSkeletons;

                {
                    ClepsClassNamesGeneratorParser classSkeletonGenerator = new ClepsClassNamesGeneratorParser(classManager, status, context, module, builder, out classSkeletons);
                    ParseFilesWithGenerator(classSkeletonGenerator, status);
                }

                ClepsLLVMTypeConvertor clepsLLVMTypeConvertor = new ClepsLLVMTypeConvertor(classSkeletons, context);

                {
                    ClepsMemberGeneratorParser memberGenerator = new ClepsMemberGeneratorParser(classManager, status, context, module, builder, clepsLLVMTypeConvertor);
                    ParseFilesWithGenerator(memberGenerator, status);
                }

                {
                    ClepsFunctionBodyGeneratorParser functionBodyGenerator = new ClepsFunctionBodyGeneratorParser(classManager, status, context, module, builder, clepsLLVMTypeConvertor);
                    ParseFilesWithGenerator(functionBodyGenerator, status);
                }

                AddEntryPoint(classManager, status, context, module, builder);

                VerifyModule(module, status);
                PrintModuleToFile(module, status);
            }
            catch (CompilerErrorException)
            {
                //Supress compiler errors
            }
            finally
            {
                LLVM.DisposeBuilder(builder);
                LLVM.DisposeModule(module);
                LLVM.ContextDispose(context);
            }

            return(status);
        }
Exemplo n.º 15
0
        private void InitShuffles(LLVMContextRef context, LLVMModuleRef module)
        {
            var int32Type   = context.Int32Type;
            var float32Type = context.FloatType;

            var shuffleI32Type = FunctionType(
                int32Type,
                int32Type,
                int32Type,
                int32Type);
            var shuffleF32Type = FunctionType(
                float32Type,
                float32Type,
                int32Type,
                int32Type);

            ShuffleI32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                     module, "llvm.nvvm.shfl.idx.i32", shuffleI32Type));
            ShuffleF32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                     module, "llvm.nvvm.shfl.idx.f32", shuffleF32Type));

            ShuffleDownI32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                         module, "llvm.nvvm.shfl.down.i32", shuffleI32Type));
            ShuffleDownF32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                         module, "llvm.nvvm.shfl.down.f32", shuffleF32Type));

            ShuffleUpI32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.shfl.up.i32", shuffleI32Type));
            ShuffleUpF32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.shfl.up.f32", shuffleF32Type));

            ShuffleXorI32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                        module, "llvm.nvvm.shfl.bfly.i32", shuffleI32Type));
            ShuffleXorF32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                        module, "llvm.nvvm.shfl.bfly.f32", shuffleF32Type));

            ShuffleLookup = new Dictionary <WarpIntrinsicKind, KeyValuePair <Lazy <LLVMValueRef>, bool> >()
            {
                { WarpIntrinsicKind.ShuffleI32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleI32, true) },
                { WarpIntrinsicKind.ShuffleF32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleF32, true) },

                { WarpIntrinsicKind.ShuffleDownI32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleDownI32, true) },
                { WarpIntrinsicKind.ShuffleDownF32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleDownF32, true) },

                { WarpIntrinsicKind.ShuffleUpI32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleUpI32, false) },
                { WarpIntrinsicKind.ShuffleUpF32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleUpF32, false) },

                { WarpIntrinsicKind.ShuffleXorI32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleXorI32, true) },
                { WarpIntrinsicKind.ShuffleXorF32, new KeyValuePair <Lazy <LLVMValueRef>, bool>(ShuffleXorF32, true) },
            };
        }
Exemplo n.º 16
0
        private void InitAssertions(LLVMContextRef context, LLVMModuleRef module, LLVMTypeRef intPtrType)
        {
            var voidPtrType = context.VoidPtrType;

            AssertFailedMethod = new Lazy <LLVMValueRef>(() =>
                                                         AddFunction(module, "__assertfail",
                                                                     FunctionType(context.VoidType,
                                                                                  voidPtrType,
                                                                                  voidPtrType,
                                                                                  context.Int32Type,
                                                                                  voidPtrType,
                                                                                  intPtrType
                                                                                  )));
        }
Exemplo n.º 17
0
        internal Context(LLVMContextRef contextRef)
        {
            if (contextRef.Handle == default)
            {
                throw new ArgumentNullException(nameof(contextRef));
            }

            this.ContextHandle       = contextRef;
            this.activeHandler       = new WrappedNativeCallback <LLVMDiagnosticHandler>(DiagnosticHandler);
            this.valueCache          = new Value.InterningFactory(this);
            this.moduleCache         = new BitcodeModule.InterningFactory(this);
            this.typeCache           = new TypeRef.InterningFactory(this);
            this.attributeValueCache = new AttributeValue.InterningFactory(this);

            LLVM.ContextSetDiagnosticHandler(this.ContextHandle, this.activeHandler, (void *)default);
Exemplo n.º 18
0
        private void EmitReadyToRunHeaderCallback(LLVMContextRef context)
        {
            LLVMTypeRef intPtr    = LLVMTypeRef.CreatePointer(LLVMTypeRef.Int32, 0);
            LLVMTypeRef intPtrPtr = LLVMTypeRef.CreatePointer(intPtr, 0);
            var         callback  = Module.AddFunction("RtRHeaderWrapper", LLVMTypeRef.CreateFunction(intPtrPtr, new LLVMTypeRef[0], false));
            var         builder   = context.CreateBuilder();
            var         block     = callback.AppendBasicBlock("Block");

            builder.PositionAtEnd(block);

            LLVMValueRef rtrHeaderPtr     = GetSymbolValuePointer(Module, _nodeFactory.ReadyToRunHeader, _nodeFactory.NameMangler, false);
            LLVMValueRef castRtrHeaderPtr = builder.BuildPointerCast(rtrHeaderPtr, intPtrPtr, "castRtrHeaderPtr");

            builder.BuildRet(castRtrHeaderPtr);
        }
Exemplo n.º 19
0
        internal static Context GetContextFor(LLVMContextRef contextRef)
        {
            if (contextRef == default)
            {
                return(null);
            }

            if (TryGetValue(contextRef, out Context retVal))
            {
                return(retVal);
            }

            // Context constructor will add itself to this cache
            // and remove itself on Dispose/finalize
            return(new Context(contextRef));
        }
Exemplo n.º 20
0
        // These interning methods provide unique mapping between the .NET wrappers and the underlying LLVM instances
        // The mapping ensures that any LibLLVM handle is always re-mappable to a exactly one wrapper instance.
        // This helps reduce the number of wrapper instances created and also allows reference equality to work
        // as expected for managed types.
        // TODO: Refactor the interning to class dedicated to managing the mappings, this can allow looking up the
        // context from handles where ther isn't any APIs to retrieve the Context.
        #region LLVM handle Interning

        internal static Context GetContextFor(LLVMContextRef contextRef)
        {
            if (contextRef.Pointer == IntPtr.Zero)
            {
                return(null);
            }

            lock ( ContextCache )
            {
                if (ContextCache.TryGetValue(contextRef, out Context retVal))
                {
                    return(retVal);
                }

                return(new Context(contextRef));
            }
        }
Exemplo n.º 21
0
        internal static Module DeserializeModuleAsBitcode(this byte[] moduleBytes, LLVMContextRef contextRef)
        {
            LLVMMemoryBufferRef bufferRef = CreateMemoryBufferRefFromBytes(moduleBytes);
            LLVMModuleRef       moduleRef;

            try
            {
                if (LLVMSharp.LLVM.ParseBitcodeInContext2(contextRef, bufferRef, out moduleRef) != false)
                {
                    throw new ArgumentException("Failed to load bitcode module", nameof(moduleBytes));
                }
                return(moduleRef.ModuleFromModuleRef());
            }
            finally
            {
                LLVMSharp.LLVM.DisposeMemoryBuffer(bufferRef);
            }
        }
Exemplo n.º 22
0
        private void InitAtomics(LLVMContextRef context, LLVMModuleRef module)
        {
            var int32Type   = context.Int32Type;
            var float32Type = context.FloatType;

            AtomicAddF32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.atomic.load.add.f32.p0f32",
                                                       FunctionType(float32Type, PointerType(float32Type), float32Type)
                                                       ));

            AtomicIncU32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.atomic.load.inc.32.p0i32",
                                                       FunctionType(int32Type, PointerType(int32Type), int32Type)));

            AtomicDecU32 = new Lazy <LLVMValueRef>(() => AddFunction(
                                                       module, "llvm.nvvm.atomic.load.dec.32.p0i32",
                                                       FunctionType(int32Type, PointerType(int32Type), int32Type)));
        }
Exemplo n.º 23
0
        private void EmitDebugMetadata(LLVMContextRef context)
        {
            var dwarfVersion = LLVMValueRef.CreateMDNode(new[]
            {
                LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 2, false),
                context.GetMDString("Dwarf Version", 13),
                LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 4, false)
            });
            var dwarfSchemaVersion = LLVMValueRef.CreateMDNode(new[]
            {
                LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 2, false),
                context.GetMDString("Debug Info Version", 18),
                LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 3, false)
            });

            Module.AddNamedMetadataOperand("llvm.module.flags", dwarfVersion);
            Module.AddNamedMetadataOperand("llvm.module.flags", dwarfSchemaVersion);
            DIBuilder.DIBuilderFinalize();
        }
Exemplo n.º 24
0
        private static void AddAndExecuteTestModule(LLVMOrcJITStackRef orcJit, LLVMContextRef context, LLVMTargetMachineRef machine, int expectedResult)
        {
            LLVMModuleRef module = CreateModule(context, machine, expectedResult);
            LLVMErrorRef  err    = LLVMOrcAddEagerlyCompiledIR(orcJit, out ulong jitHandle, module, SymbolResolver, IntPtr.Zero);

            Assert.IsTrue(err.IsInvalid);

            // ORC now owns the module, so it must never be released
            module.SetHandleAsInvalid();
            LLVMOrcGetMangledSymbol(orcJit, out string mangledName, "main");
            err = LibLLVMOrcGetSymbolAddress(orcJit, out ulong funcAddress, mangledName, false);
            Assert.IsTrue(err.IsInvalid);
            Assert.AreNotEqual(0ul, funcAddress);
            var callableMain = Marshal.GetDelegateForFunctionPointer <TestMain>(( IntPtr )funcAddress);

            Assert.AreEqual(expectedResult, callableMain( ));

            LLVMOrcRemoveModule(orcJit, jitHandle);
        }
Exemplo n.º 25
0
        private void AddEntryPoint(ClassManager classManager, CompileStatus status, LLVMContextRef context, LLVMModuleRef module, LLVMBuilderRef builder)
        {
            LLVMTypeRef       functionType  = LLVM.FunctionType(LLVM.Int32TypeInContext(context), new LLVMTypeRef[] { }, false);
            LLVMValueRef      functionValue = LLVM.AddFunction(module, "main", functionType);
            LLVMBasicBlockRef blockValue    = LLVM.AppendBasicBlockInContext(context, functionValue, "entry");

            LLVM.PositionBuilderAtEnd(builder, blockValue);

            LLVMValueRef intRet = LLVM.ConstInt(LLVM.Int32Type(), 0, false);

            if (classManager.MainFunctionFullNames.Count < 1)
            {
                status.AddError(new CompilerError("", 0, 0, "No main functions found in the program"));
            }
            else if (classManager.MainFunctionFullNames.Count > 1)
            {
                status.AddError(new CompilerError("", 0, 0, "Multiple main functions found in the program: " + String.Join(",", classManager.MainFunctionFullNames)));
            }
            else
            {
                LLVMValueRef functionToCall        = LLVM.GetNamedFunction(module, classManager.MainFunctionFullNames.First());
                LLVMValueRef intOrIntMappedTypeRet = LLVM.BuildCall(builder, functionToCall, new LLVMValueRef[0], "entryPointCall");
                LLVMTypeRef  returnType            = LLVM.TypeOf(intOrIntMappedTypeRet);

                if (returnType.TypeKind == LLVMTypeKind.LLVMIntegerTypeKind && returnType.GetIntTypeWidth() == 32)
                {
                    intRet = intOrIntMappedTypeRet;
                }
                else
                {
                    LLVMValueRef intMappedTypeRetPtr = LLVM.BuildAlloca(builder, LLVM.TypeOf(intOrIntMappedTypeRet), "intMappedType");
                    LLVM.BuildStore(builder, intOrIntMappedTypeRet, intMappedTypeRetPtr);
                    //Extract the first field to get the int value from the mapped type
                    //See rawtypemap for more details
                    LLVMValueRef fieldPtr = LLVM.BuildStructGEP(builder, intMappedTypeRetPtr, 0, "returnIntFieldPtr");
                    intRet = LLVM.BuildLoad(builder, fieldPtr, "returnValue");
                }
            }

            LLVM.BuildRet(builder, intRet);
        }
Exemplo n.º 26
0
        public void FinishObjWriter(LLVMContextRef context)
        {
            // Since emission to llvm is delayed until after all nodes are emitted... emit now.
            foreach (var nodeData in _dataToFill)
            {
                nodeData.Fill(Module, _nodeFactory);
            }

            EmitNativeMain(context);

            EmitDebugMetadata(context);

#if DEBUG
            Module.PrintToFile(Path.ChangeExtension(_objectFilePath, ".txt"));
#endif //DEBUG
            Module.Verify(LLVMVerifierFailureAction.LLVMAbortProcessAction);

            Module.WriteBitcodeToFile(_objectFilePath);

            //throw new NotImplementedException(); // This function isn't complete
        }
Exemplo n.º 27
0
        private static LLVMModuleRef CreateModule(LLVMContextRef context, LLVMTargetMachineRef machine, int magicNumber)
        {
            var module = LLVMModuleCreateWithNameInContext("test", context);
            var layout = LLVMCreateTargetDataLayout(machine);

            LLVMSetModuleDataLayout(module, layout);

            LLVMTypeRef       int32T     = LLVMInt32TypeInContext(context);
            LLVMTypeRef       signature  = LLVMFunctionType(int32T, null, 0, false);
            LLVMValueRef      main       = LLVMAddFunction(module, "main", signature);
            LLVMBasicBlockRef entryBlock = LLVMAppendBasicBlock(main, "entry");

            LLVMBuilderRef builder = LLVMCreateBuilder( );

            LLVMPositionBuilderAtEnd(builder, entryBlock);

            LLVMValueRef constNum = LLVMConstInt(int32T, ( ulong )magicNumber, true);

            LLVMBuildRet(builder, constNum);
            Debug.WriteLine(LLVMPrintModuleToString(module));
            return(module);
        }
Exemplo n.º 28
0
 public static extern LLVMTypeRef* PPCFP128TypeInContext(LLVMContextRef* C);
Exemplo n.º 29
0
 public static extern LLVMTypeRef* FloatTypeInContext(LLVMContextRef* C);
Exemplo n.º 30
0
 public static extern LLVMTypeRef* IntTypeInContext(LLVMContextRef* C, uint NumBits);
Exemplo n.º 31
0
 public static extern LLVMModuleRef* ModuleCreateWithNameInContext([In][MarshalAs(UnmanagedType.LPStr)] string ModuleID, LLVMContextRef* C);
Exemplo n.º 32
0
 public static extern void ContextDispose(LLVMContextRef* C);
Exemplo n.º 33
0
 public static extern LLVMBuilderRef* CreateBuilderInContext(LLVMContextRef* C);
Exemplo n.º 34
0
 public static LLVMTypeRef X86MMXTypeInContext(LLVMContextRef @C)
 {
     return LLVM.X86MMXTypeInContext(@C);
 }
Exemplo n.º 35
0
 public static LLVMTypeRef LabelTypeInContext(LLVMContextRef @C)
 {
     return LLVM.LabelTypeInContext(@C);
 }
Exemplo n.º 36
0
 public static LLVMTypeRef PPCFP128TypeInContext(LLVMContextRef @C)
 {
     return LLVM.PPCFP128TypeInContext(@C);
 }
Exemplo n.º 37
0
 public static LLVMTypeRef StructCreateNamed(LLVMContextRef @C, string @Name)
 {
     return LLVM.StructCreateNamed(@C, @Name);
 }
Exemplo n.º 38
0
 public static LLVMTypeRef VoidTypeInContext(LLVMContextRef @C)
 {
     return LLVM.VoidTypeInContext(@C);
 }
Exemplo n.º 39
0
 public static extern LLVMTypeRef* StructCreateNamed(LLVMContextRef* C, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
Exemplo n.º 40
0
 public static LLVMTypeRef IntTypeInContext(LLVMContextRef @C, uint @NumBits)
 {
     return LLVM.IntTypeInContext(@C, @NumBits);
 }
Exemplo n.º 41
0
 public static extern LLVMTypeRef* LabelTypeInContext(LLVMContextRef* C);
Exemplo n.º 42
0
 public static LLVMTypeRef IntPtrTypeInContext(LLVMContextRef @C, LLVMTargetDataRef @TD)
 {
     return LLVM.IntPtrTypeInContext(@C, @TD);
 }
Exemplo n.º 43
0
 public static extern LLVMBasicBlockRef* InsertBasicBlockInContext(LLVMContextRef* C, LLVMBasicBlockRef* BB, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
Exemplo n.º 44
0
 public static LLVMTypeRef HalfTypeInContext(LLVMContextRef @C)
 {
     return(LLVM.HalfTypeInContext(@C));
 }
Exemplo n.º 45
0
 public static extern int GetBitcodeModuleProviderInContext(LLVMContextRef* ContextRef, LLVMMemoryBufferRef* MemBuf, ref LLVMModuleProviderRef * OutMP, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
Exemplo n.º 46
0
 public static LLVMTypeRef FloatTypeInContext(LLVMContextRef @C)
 {
     return(LLVM.FloatTypeInContext(@C));
 }
Exemplo n.º 47
0
 public static extern uint GetMDKindIDInContext(LLVMContextRef* C, [In][MarshalAs(UnmanagedType.LPStr)] string Name, uint SLen);
Exemplo n.º 48
0
 public static LLVMTypeRef DoubleTypeInContext(LLVMContextRef @C)
 {
     return(LLVM.DoubleTypeInContext(@C));
 }
Exemplo n.º 49
0
 public static extern LLVMTypeRef* Int64TypeInContext(LLVMContextRef* C);
Exemplo n.º 50
0
 public static extern LLVMValueRef* ConstStringInContext(LLVMContextRef* C, [In][MarshalAs(UnmanagedType.LPStr)] string Str, uint Length, int DontNullTerminate);
Exemplo n.º 51
0
 public static extern LLVMTypeRef* HalfTypeInContext(LLVMContextRef* C);
Exemplo n.º 52
0
 public static extern LLVMValueRef* ConstStructInContext(LLVMContextRef* C, System.IntPtr[] ConstantVals, uint Count, int Packed);
Exemplo n.º 53
0
 public static extern LLVMTypeRef* DoubleTypeInContext(LLVMContextRef* C);
Exemplo n.º 54
0
 public static extern LLVMValueRef* MDStringInContext(LLVMContextRef* C, [In][MarshalAs(UnmanagedType.LPStr)] string Str, uint SLen);
Exemplo n.º 55
0
 public static extern LLVMTypeRef* StructTypeInContext(LLVMContextRef* C, System.IntPtr[] ElementTypes, uint ElementCount, int Packed);
Exemplo n.º 56
0
 public static extern LLVMValueRef* MDNodeInContext(LLVMContextRef* C, System.IntPtr[] Vals, uint Count);
Exemplo n.º 57
0
 public static extern LLVMTypeRef* VoidTypeInContext(LLVMContextRef* C);
Exemplo n.º 58
0
 public static extern LLVMBasicBlockRef* AppendBasicBlockInContext(LLVMContextRef* C, LLVMValueRef* Fn, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
Exemplo n.º 59
0
 public static extern LLVMTypeRef* X86MMXTypeInContext(LLVMContextRef* C);
Exemplo n.º 60
0
 public static LLVMTypeRef DoubleTypeInContext(LLVMContextRef @C)
 {
     return LLVM.DoubleTypeInContext(@C);
 }