├── .gitignore ├── examples ├── nim.cfg ├── nimcall.nim └── factorial.nim ├── README.md ├── llvm.nimble ├── src ├── llvm_support.nim ├── llvm_irreader.nim ├── transforms │ ├── llvm_vectorize.nim │ ├── llvm_ipo.nim │ ├── llvm_passmanagerbuilder.nim │ └── llvm_scalar.nim ├── llvm_lib.nim ├── llvm_linker.nim ├── llvm_bitwriter.nim ├── llvm_analysis.nim ├── llvm_bitreader.nim ├── llvm_object.nim ├── llvm_config.nim ├── llvm_targetmachine.nim ├── llvm_executionengine.nim ├── llvm_target.nim ├── llvm_lto.nim ├── llvm_disassembler.nim └── llvm_core.nim └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | nimcache/ 2 | -------------------------------------------------------------------------------- /examples/nim.cfg: -------------------------------------------------------------------------------- 1 | path = "../src" 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LLVM 2 | 3 | LLVM bindings for the Nim language. 4 | 5 | ## Documentation 6 | 7 | [http://FedeOmoto.github.io/llvm/](http://FedeOmoto.github.io/llvm/) 8 | -------------------------------------------------------------------------------- /llvm.nimble: -------------------------------------------------------------------------------- 1 | [Package] 2 | name = "llvm" 3 | version = "3.5" 4 | author = "Federico Omoto" 5 | description = "LLVM wrapper" 6 | license = "MIT" 7 | srcDir = "src" 8 | 9 | [Deps] 10 | requires = "nim >= 0.11.2" 11 | -------------------------------------------------------------------------------- /src/llvm_support.nim: -------------------------------------------------------------------------------- 1 | ## This file defines the C interface to the LLVM support library. 2 | 3 | include llvm_lib 4 | 5 | type Bool* = cint 6 | 7 | type MemoryBufferRef* = ptr object 8 | ## Used to pass regions of memory through LLVM interfaces. 9 | 10 | proc loadLibraryPermanently*(filename: cstring): Bool {. 11 | importc: "LLVMLoadLibraryPermanently", libllvm.} 12 | ## This function permanently loads the dynamic library at the given path. 13 | ## It is safe to call this function multiple times for the same library. 14 | -------------------------------------------------------------------------------- /src/llvm_irreader.nim: -------------------------------------------------------------------------------- 1 | ## This file defines the C interface to the IR Reader. 2 | 3 | import llvm_core 4 | 5 | include llvm_lib 6 | 7 | proc parseIRInContext*(contextRef: ContextRef, memBuf: MemoryBufferRef, 8 | outM: ptr ModuleRef, outMessage: cstringArray): Bool {. 9 | importc: "LLVMParseIRInContext", libllvm.} 10 | ## Read LLVM IR from a memory buffer and convert it into an in-memory Module 11 | ## object. Returns 0 on success. 12 | ## Optionally returns a human-readable description of any errors that 13 | ## occurred during parsing IR. OutMessage must be disposed with 14 | ## LLVMDisposeMessage. 15 | -------------------------------------------------------------------------------- /src/transforms/llvm_vectorize.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMVectorize.a, which 2 | ## implements various vectorization transformations of the LLVM IR. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import ../llvm_core 9 | 10 | include ../llvm_lib 11 | 12 | # Vectorization transformations 13 | 14 | proc addBBVectorizePass*(pm: PassManagerRef) {. 15 | importc: "LLVMAddBBVectorizePass", libllvm.} 16 | 17 | proc addLoopVectorizePass*(pm: PassManagerRef) {. 18 | importc: "LLVMAddLoopVectorizePass", libllvm.} 19 | 20 | proc addSLPVectorizePass*(pm: PassManagerRef) {. 21 | importc: "LLVMAddSLPVectorizePass", libllvm.} 22 | -------------------------------------------------------------------------------- /src/llvm_lib.nim: -------------------------------------------------------------------------------- 1 | when not defined(static_link): 2 | const libname = "LLVM-3.5" 3 | 4 | {.passC: gorge("llvm-config --cflags").} 5 | 6 | when defined(dynamic_link) or defined(static_link): 7 | const ldflags = gorge("llvm-config --ldflags") 8 | {.pragma: libllvm, cdecl.} 9 | when defined(dynamic_link): # Dynamic linking 10 | {.passL: ldflags & "-l" & libname.} 11 | else: # Static linking 12 | {.passL: gorge("llvm-config --system-libs") & "-lstdc++ " & ldflags & 13 | gorge("llvm-config --libs").} 14 | else: # Dynamic loading 15 | when defined(windows): 16 | const dllname = libname & ".dll" 17 | elif defined(macosx): 18 | const dllname = "lib" & libname & "(|.0).dylib" 19 | else: 20 | const dllname = "lib" & libname & "(|.0).so" 21 | {.pragma: libllvm, cdecl, dynlib: dllname.} 22 | -------------------------------------------------------------------------------- /src/llvm_linker.nim: -------------------------------------------------------------------------------- 1 | ## This file defines the C interface to the module/file/archive linker. 2 | 3 | import llvm_core 4 | 5 | include llvm_lib 6 | 7 | type LinkerMode* = enum 8 | LinkerDestroySource = 0 9 | LinkerPreserveSource = 1 10 | 11 | proc linkModules*(dest: ModuleRef, src: ModuleRef, mode: LinkerMode, 12 | outMessage: cstringArray): Bool {.importc: "LLVMLinkModules", 13 | libllvm.} 14 | ## Links the source module into the destination module, taking ownership 15 | ## of the source module away from the caller. Optionally returns a 16 | ## human-readable description of any errors that occurred in linking. 17 | ## OutMessage must be disposed with LLVMDisposeMessage. The return value 18 | ## is true if an error occurred, false otherwise. 19 | -------------------------------------------------------------------------------- /src/llvm_bitwriter.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMBitWriter.a, which 2 | ## implements output of the LLVM bitcode format. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core 9 | 10 | include llvm_lib 11 | 12 | # Bit Writer 13 | 14 | proc writeBitcodeToFile*(m: ModuleRef, path: cstring): cint {. 15 | importc: "LLVMWriteBitcodeToFile", libllvm.} 16 | ## Writes a module to the specified path. Returns 0 on success. 17 | 18 | proc writeBitcodeToFD*(m: ModuleRef, fd: cint, shouldClose: cint, 19 | unbuffered: cint): cint {. 20 | importc: "LLVMWriteBitcodeToFD", libllvm.} 21 | ## Writes a module to an open file descriptor. Returns 0 on success. 22 | 23 | proc writeBitcodeToFileHandle*(m: ModuleRef, handle: cint): cint {. 24 | deprecated, importc: "LLVMWriteBitcodeToFD", libllvm.} 25 | ## Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file 26 | ## descriptor. Returns 0 on success. Closes the Handle. 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Federico Omoto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /src/transforms/llvm_ipo.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMIPO.a, which implements 2 | ## various interprocedural transformations of the LLVM IR. 3 | 4 | import ../llvm_core 5 | 6 | include ../llvm_lib 7 | 8 | # Interprocedural transformations 9 | 10 | proc addArgumentPromotionPass*(pm: PassManagerRef) {. 11 | importc: "LLVMAddArgumentPromotionPass", libllvm.} 12 | 13 | proc addConstantMergePass*(pm: PassManagerRef) {. 14 | importc: "LLVMAddConstantMergePass", libllvm.} 15 | 16 | proc addDeadArgEliminationPass*(pm: PassManagerRef) {. 17 | importc: "LLVMAddDeadArgEliminationPass", libllvm.} 18 | 19 | proc addFunctionAttrsPass*(pm: PassManagerRef) {. 20 | importc: "LLVMAddFunctionAttrsPass", libllvm.} 21 | 22 | proc addFunctionInliningPass*(pm: PassManagerRef) {. 23 | importc: "LLVMAddFunctionInliningPass", libllvm.} 24 | 25 | proc addAlwaysInlinerPass*(pm: PassManagerRef) {. 26 | importc: "LLVMAddAlwaysInlinerPass", libllvm.} 27 | 28 | proc addGlobalDCEPass*(pm: PassManagerRef) {. 29 | importc: "LLVMAddGlobalDCEPass", libllvm.} 30 | 31 | proc addGlobalOptimizerPass*(pm: PassManagerRef) {. 32 | importc: "LLVMAddGlobalOptimizerPass", libllvm.} 33 | 34 | proc addIPConstantPropagationPass*(pm: PassManagerRef) {. 35 | importc: "LLVMAddIPConstantPropagationPass", libllvm.} 36 | 37 | proc addPruneEHPass*(pm: PassManagerRef) {.importc: "LLVMAddPruneEHPass", libllvm.} 38 | 39 | proc addIPSCCPPass*(pm: PassManagerRef) {.importc: "LLVMAddIPSCCPPass", libllvm.} 40 | 41 | proc addInternalizePass*(pm: PassManagerRef, allButMain: cuint) {. 42 | importc: "LLVMAddInternalizePass", libllvm.} 43 | 44 | proc addStripDeadPrototypesPass*(pm: PassManagerRef) {. 45 | importc: "LLVMAddStripDeadPrototypesPass", libllvm.} 46 | 47 | proc addStripSymbolsPass*(pm: PassManagerRef) {. 48 | importc: "LLVMAddStripSymbolsPass", libllvm.} 49 | -------------------------------------------------------------------------------- /src/llvm_analysis.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMAnalysis.a, which 2 | ## implements various analyses of the LLVM IR. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core 9 | 10 | include llvm_lib 11 | 12 | # Analysis 13 | 14 | type VerifierFailureAction* = enum ## Verifier Failure Action. 15 | AbortProcessAction ## Verifier will print to stderr and abort() 16 | PrintMessageAction ## Verifier will print to stderr and return 1 17 | ReturnStatusAction ## Verifier will just return 1 18 | 19 | proc verifyModule*(m: ModuleRef, action: VerifierFailureAction, 20 | outMessage: cstringArray): Bool {.importc: "LLVMVerifyModule", 21 | libllvm.} 22 | ## Verifies that a module is valid, taking the specified action if not. 23 | ## Optionally returns a human-readable description of any invalid constructs. 24 | ## OutMessage must be disposed with LLVMDisposeMessage. 25 | 26 | proc verifyFunction*(fn: ValueRef, action: VerifierFailureAction): Bool {. 27 | importc: "LLVMVerifyFunction", libllvm.} 28 | ## Verifies that a single function is valid, taking the specified action. Useful 29 | ## for debugging. 30 | 31 | proc viewFunctionCFG*(fn: ValueRef) {.importc: "LLVMViewFunctionCFG", libllvm.} 32 | ## Open up a ghostview window that displays the CFG of the current function. 33 | ## Useful for debugging. 34 | 35 | proc viewFunctionCFGOnly*(fn: ValueRef) {.importc: "LLVMViewFunctionCFGOnly", 36 | libllvm.} 37 | ## Open up a ghostview window that displays the CFG of the current function. 38 | ## Useful for debugging. 39 | -------------------------------------------------------------------------------- /src/transforms/llvm_passmanagerbuilder.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to the PassManagerBuilder class. 2 | 3 | import ../llvm_core 4 | 5 | include ../llvm_lib 6 | 7 | type PassManagerBuilderRef* = ptr object 8 | 9 | # Pass manager builder 10 | 11 | proc passManagerBuilderCreate*: PassManagerBuilderRef {. 12 | importc: "LLVMPassManagerBuilderCreate", libllvm.} 13 | 14 | proc passManagerBuilderDispose*(pmb: PassManagerBuilderRef) {. 15 | importc: "LLVMPassManagerBuilderDispose", libllvm.} 16 | 17 | proc passManagerBuilderSetOptLevel*(pmb: PassManagerBuilderRef, optLevel: cuint) {. 18 | importc: "LLVMPassManagerBuilderSetOptLevel", libllvm.} 19 | 20 | proc passManagerBuilderSetSizeLevel*(pmb: PassManagerBuilderRef, SizeLevel: cuint) {. 21 | importc: "LLVMPassManagerBuilderSetSizeLevel", libllvm.} 22 | 23 | proc passManagerBuilderSetDisableUnitAtATime*(pmb: PassManagerBuilderRef, 24 | value: Bool) {. 25 | importc: "LLVMPassManagerBuilderSetDisableUnitAtATime", libllvm.} 26 | 27 | proc passManagerBuilderSetDisableUnrollLoops*(pmb: PassManagerBuilderRef, 28 | value: Bool) {. 29 | importc: "LLVMPassManagerBuilderSetDisableUnrollLoops", libllvm.} 30 | 31 | proc passManagerBuilderSetDisableSimplifyLibCalls*(pmb: PassManagerBuilderRef, value: Bool) {. 32 | importc: "LLVMPassManagerBuilderSetDisableSimplifyLibCalls", libllvm.} 33 | 34 | proc passManagerBuilderUseInlinerWithThreshold*(pmb: PassManagerBuilderRef, 35 | threshold: cuint) {. 36 | importc: "LLVMPassManagerBuilderUseInlinerWithThreshold", libllvm.} 37 | 38 | proc passManagerBuilderPopulateFunctionPassManager*(pmb: PassManagerBuilderRef, 39 | pm: PassManagerRef) {. 40 | importc: "LLVMPassManagerBuilderPopulateFunctionPassManager", libllvm.} 41 | 42 | proc passManagerBuilderPopulateModulePassManager*(pmb: PassManagerBuilderRef, 43 | pm: PassManagerRef) {. 44 | importc: "LLVMPassManagerBuilderPopulateModulePassManager", libllvm.} 45 | 46 | proc passManagerBuilderPopulateLTOPassManager*(pmb: PassManagerBuilderRef, 47 | pm: PassManagerRef, 48 | internalize: Bool, 49 | runInliner: Bool) {. 50 | importc: "LLVMPassManagerBuilderPopulateLTOPassManager", libllvm.} 51 | -------------------------------------------------------------------------------- /src/llvm_bitreader.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMBitReader.a, which 2 | ## implements input of the LLVM bitcode format. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core 9 | 10 | include llvm_lib 11 | 12 | # Bit Reader 13 | 14 | proc parseBitcode*(memBuf: MemoryBufferRef, outModule: ptr ModuleRef, 15 | outMessage: cstringArray): Bool {. 16 | importc: "LLVMParseBitcode", libllvm.} 17 | ## Builds a module from the bitcode in the specified memory buffer, returning a 18 | ## reference to the module via the OutModule parameter. Returns 0 on success. 19 | ## Optionally returns a human-readable error message via OutMessage. 20 | 21 | proc parseBitcodeInContext*(contextRef: ContextRef, memBuf: MemoryBufferRef, 22 | outModule: ptr ModuleRef, outMessage: cstringArray): 23 | Bool {.importc: "LLVMParseBitcodeInContext", libllvm.} 24 | 25 | proc getBitcodeModuleInContext*(contextRef: ContextRef, memBuf: MemoryBufferRef, 26 | outModule: ptr ModuleRef, 27 | outMessage: cstringArray): Bool {. 28 | importc: "LLVMGetBitcodeModuleInContext", libllvm.} 29 | ## Reads a module from the specified path, returning via the OutMP parameter 30 | ## a module provider which performs lazy deserialization. Returns 0 on success. 31 | ## Optionally returns a human-readable error message via OutMessage. 32 | 33 | proc getBitcodeModule*(memBuf: MemoryBufferRef, outModule: ptr ModuleRef, 34 | outMessage: cstringArray): Bool {. 35 | importc: "LLVMGetBitcodeModule", libllvm.} 36 | 37 | proc getBitcodeModuleProviderInContext*(contextRef: ContextRef, 38 | memBuf: MemoryBufferRef, 39 | outMP: ptr ModuleProviderRef, 40 | outMessage: cstringArray): Bool {. 41 | deprecated, importc: "LLVMGetBitcodeModuleProviderInContext", libllvm.} 42 | ## Deprecated: Use LLVMGetBitcodeModuleInContext instead. 43 | 44 | proc getBitcodeModuleProvider*(memBuf: MemoryBufferRef, 45 | outMP: ptr ModuleProviderRef, 46 | outMessage: cstringArray): Bool {. 47 | deprecated, importc: "LLVMGetBitcodeModuleProvider", libllvm.} 48 | ## Deprecated: Use LLVMGetBitcodeModule instead. 49 | -------------------------------------------------------------------------------- /examples/nimcall.nim: -------------------------------------------------------------------------------- 1 | import 2 | llvm_core, llvm_analysis, llvm_executionengine, llvm_targetmachine, 3 | llvm_target, transforms/llvm_scalar 4 | 5 | # TODO: Delete this line and uncomment the addGlobalMapping call in future 6 | # versions of LLVM. 7 | # See: https://llvm.org/bugs/show_bug.cgi?id=20656 8 | {.passL: "-rdynamic".} 9 | 10 | proc greet {.exportc.} = echo "\nHello World!" 11 | 12 | proc callNimProc = 13 | linkInMCJIT() 14 | discard initializeNativeTarget() 15 | discard initializeNativeAsmPrinter() 16 | 17 | let module = moduleCreateWithName("nimCallModule") 18 | 19 | let greetType = functionType(voidType(), nil, 0, 0) 20 | let greetProc = module.addFunction("greet", greetType) 21 | greetProc.setFunctionCallConv(FastCallConv) 22 | 23 | let nimCallType = functionType(voidType(), nil, 0, 0) 24 | let nimCall = module.addFunction("nimCall", nimCallType) 25 | nimCall.setFunctionCallConv(CCallConv) 26 | 27 | let 28 | entry = nimCall.appendBasicBlock("") 29 | builder = createBuilder() 30 | 31 | builder.positionBuilderAtEnd(entry) 32 | discard builder.buildCall(greetProc, nil, 0, "") 33 | discard builder.buildRetVoid 34 | 35 | var error: cstring 36 | let errorP = cast[cstringArray](error.addr) 37 | 38 | discard verifyModule(module, AbortProcessAction, errorP) 39 | disposeMessage(error) 40 | 41 | var opts: MCJITCompilerOptions 42 | initializeMCJITCompilerOptions(opts.addr, sizeOf(opts)) 43 | opts.optLevel = 2 44 | opts.enableFastISel = 1 45 | opts.noFramePointerElim = 1 46 | opts.codeModel = CodeModelJITDefault 47 | 48 | var engine: ExecutionEngineRef 49 | error = nil 50 | if createMCJITCompilerForModule(engine.addr, module, opts.addr, sizeOf(opts), 51 | errorP) != 0: 52 | stderr.write($error & "\n") 53 | disposeMessage(error) 54 | quit 1 55 | 56 | #engine.addGlobalMapping(greetProc, greet) 57 | 58 | let pass = createPassManager() 59 | addTargetData(engine.getExecutionEngineTargetData(), pass) 60 | pass.addConstantPropagationPass() 61 | pass.addInstructionCombiningPass() 62 | pass.addPromoteMemoryToRegisterPass() 63 | pass.addGVNPass() 64 | pass.addCFGSimplificationPass() 65 | discard pass.runPassManager(module) 66 | 67 | module.dumpModule() 68 | 69 | # Slower 70 | #discard engine.runFunction(nimCall, 0, nil) 71 | 72 | # Faster 73 | let nimCallProc: proc () {.cdecl.} = cast[proc () {.cdecl.}](engine.getPointerToGlobal(nimCall)) 74 | nimCallProc() 75 | 76 | pass.disposePassManager() 77 | engine.disposeExecutionEngine() 78 | builder.disposeBuilder() 79 | 80 | callNimProc() 81 | -------------------------------------------------------------------------------- /examples/factorial.nim: -------------------------------------------------------------------------------- 1 | import 2 | llvm_core, llvm_analysis, llvm_executionengine, llvm_targetmachine, 3 | llvm_target, transforms/llvm_scalar, os, strutils 4 | 5 | proc factorial = 6 | linkInMCJIT() 7 | discard initializeNativeTarget() 8 | discard initializeNativeAsmPrinter() 9 | 10 | let module = moduleCreateWithName("fac_module") 11 | 12 | var facArgs = [int32Type()] 13 | let facType = functionType(int32Type(), facArgs[0].addr, 1, 0) 14 | let fac = module.addFunction("fac", facType) 15 | fac.setFunctionCallConv(CCallConv) 16 | let n = fac.getParam(0) 17 | 18 | let 19 | entry = fac.appendBasicBlock("entry") 20 | ifTrue = fac.appendBasicBlock("iftrue") 21 | ifFalse = fac.appendBasicBlock("iffalse") 22 | endBB = fac.appendBasicBlock("end") 23 | builder = createBuilder() 24 | 25 | builder.positionBuilderAtEnd(entry) 26 | let ifCmp = builder.buildICmp(IntEQ, n, constInt(int32Type(), 0, 0), "n == 0") 27 | discard builder.buildCondBr(ifCmp, ifTrue, ifFalse) 28 | 29 | builder.positionBuilderAtEnd(ifTrue) 30 | let resIfTrue = constInt(int32Type(), 1, 0) 31 | discard builder.buildBr(endBB) 32 | 33 | builder.positionBuilderAtEnd(ifFalse) 34 | var 35 | nMinus = builder.buildSub(n, constInt(int32Type(), 1, 0), "n - 1") 36 | callFacArgs = [nMinus] 37 | callFac = builder.buildCall(fac, callFacArgs[0].addr, 1, "fac(n - 1)") 38 | resIfFalse = builder.buildMul(n, callFac, "n * fac(n - 1)") 39 | discard builder.buildBr(endBB) 40 | 41 | builder.positionBuilderAtEnd(endBB) 42 | var 43 | res = builder.buildPhi(int32Type(), "result") 44 | phiVals = [resIfTrue, resIfFalse] 45 | phiBlocks = [ifTrue, ifFalse] 46 | res.addIncoming(phiVals[0].addr, phiBlocks[0].addr, 2) 47 | discard builder.buildRet(res) 48 | 49 | var error: cstring 50 | let errorP = cast[cstringArray](error.addr) 51 | 52 | discard verifyModule(module, AbortProcessAction, errorP) 53 | disposeMessage(error) 54 | 55 | var opts: MCJITCompilerOptions 56 | initializeMCJITCompilerOptions(opts.addr, sizeOf(opts)) 57 | opts.optLevel = 2 58 | opts.enableFastISel = 1 59 | opts.noFramePointerElim = 1 60 | opts.codeModel = CodeModelJITDefault 61 | 62 | var engine: ExecutionEngineRef 63 | error = nil 64 | if createMCJITCompilerForModule(engine.addr, module, opts.addr, sizeOf(opts), 65 | errorP) != 0: 66 | stderr.write($error & "\n") 67 | disposeMessage(error) 68 | quit 1 69 | 70 | let pass = createPassManager() 71 | addTargetData(engine.getExecutionEngineTargetData(), pass) 72 | pass.addConstantPropagationPass() 73 | pass.addInstructionCombiningPass() 74 | pass.addPromoteMemoryToRegisterPass() 75 | pass.addGVNPass() 76 | pass.addCFGSimplificationPass() 77 | discard pass.runPassManager(module) 78 | 79 | module.dumpModule() 80 | 81 | var num = 10 82 | if paramCount() > 0: 83 | try: 84 | num = parseInt(paramStr(1)) 85 | except: 86 | discard 87 | 88 | var 89 | execArgs = [createGenericValueOfInt(int32Type(), num.culonglong, 0)] 90 | execRes = engine.runFunction(fac, 1, execArgs[0].addr) 91 | 92 | echo "\nRunning factorial(" & $num & ") with JIT..." 93 | echo "Result: " & $execRes.genericValueToInt(0) 94 | 95 | pass.disposePassManager() 96 | engine.disposeExecutionEngine() 97 | builder.disposeBuilder() 98 | 99 | factorial() 100 | -------------------------------------------------------------------------------- /src/transforms/llvm_scalar.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMScalarOpts.a, which 2 | ## implements various scalar transformations of the LLVM IR. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import ../llvm_core 9 | 10 | include ../llvm_lib 11 | 12 | # Scalar transformations 13 | 14 | proc addAggressiveDCEPass*(pm: PassManagerRef) {. 15 | importc: "LLVMAddAggressiveDCEPass", libllvm.} 16 | 17 | proc addCFGSimplificationPass*(pm: PassManagerRef) {. 18 | importc: "LLVMAddCFGSimplificationPass", libllvm.} 19 | 20 | proc addDeadStoreEliminationPass*(pm: PassManagerRef) {. 21 | importc: "LLVMAddDeadStoreEliminationPass", libllvm.} 22 | 23 | proc addScalarizerPass*(pm: PassManagerRef) {.importc: "LLVMAddScalarizerPass", 24 | libllvm.} 25 | 26 | proc addMergedLoadStoreMotionPass*(pm: PassManagerRef) {. 27 | importc: "LLVMAddMergedLoadStoreMotionPass", libllvm.} 28 | 29 | proc addGVNPass*(pm: PassManagerRef) {.importc: "LLVMAddGVNPass", libllvm.} 30 | 31 | proc addIndVarSimplifyPass*(pm: PassManagerRef) {. 32 | importc: "LLVMAddIndVarSimplifyPass", libllvm.} 33 | 34 | proc addInstructionCombiningPass*(pm: PassManagerRef) {. 35 | importc: "LLVMAddInstructionCombiningPass", libllvm.} 36 | 37 | proc addJumpThreadingPass*(pm: PassManagerRef) {. 38 | importc: "LLVMAddJumpThreadingPass", libllvm.} 39 | 40 | proc addLICMPass*(pm: PassManagerRef) {.importc: "LLVMAddLICMPass", libllvm.} 41 | 42 | proc addLoopDeletionPass*(pm: PassManagerRef) {. 43 | importc: "LLVMAddLoopDeletionPass", libllvm.} 44 | 45 | proc addLoopIdiomPass*(pm: PassManagerRef) {.importc: "LLVMAddLoopIdiomPass", 46 | libllvm.} 47 | 48 | proc addLoopRotatePass*(pm: PassManagerRef) {.importc: "LLVMAddLoopRotatePass", 49 | libllvm.} 50 | 51 | proc addLoopRerollPass*(pm: PassManagerRef) {.importc: "LLVMAddLoopRerollPass", 52 | libllvm.} 53 | 54 | proc addLoopUnrollPass*(pm: PassManagerRef) {.importc: "LLVMAddLoopUnrollPass", 55 | libllvm.} 56 | 57 | proc addLoopUnswitchPass*(pm: PassManagerRef) {. 58 | importc: "LLVMAddLoopUnswitchPass", libllvm.} 59 | 60 | proc addMemCpyOptPass*(pm: PassManagerRef) {.importc: "LLVMAddMemCpyOptPass", 61 | libllvm.} 62 | 63 | proc addPartiallyInlineLibCallsPass*(pm: PassManagerRef) {. 64 | importc: "LLVMAddPartiallyInlineLibCallsPass", libllvm.} 65 | 66 | proc addPromoteMemoryToRegisterPass*(pm: PassManagerRef) {. 67 | importc: "LLVMAddPromoteMemoryToRegisterPass", libllvm.} 68 | 69 | proc addReassociatePass*(pm: PassManagerRef) {. 70 | importc: "LLVMAddReassociatePass", libllvm.} 71 | 72 | proc addSCCPPass*(pm: PassManagerRef) {.importc: "LLVMAddSCCPPass", libllvm.} 73 | 74 | proc addScalarReplAggregatesPass*(pm: PassManagerRef) {. 75 | importc: "LLVMAddScalarReplAggregatesPass", libllvm.} 76 | 77 | proc addScalarReplAggregatesPassSSA*(pm: PassManagerRef) {. 78 | importc: "LLVMAddScalarReplAggregatesPassSSA", libllvm.} 79 | 80 | proc addScalarReplAggregatesPassWithThreshold*(pm: PassManagerRef, 81 | threshold: cint) {. 82 | importc: "LLVMAddScalarReplAggregatesPassWithThreshold", libllvm.} 83 | 84 | proc addSimplifyLibCallsPass*(pm: PassManagerRef) {. 85 | importc: "LLVMAddSimplifyLibCallsPass", libllvm.} 86 | 87 | proc addTailCallEliminationPass*(pm: PassManagerRef) {. 88 | importc: "LLVMAddTailCallEliminationPass", libllvm.} 89 | 90 | proc addConstantPropagationPass*(pm: PassManagerRef) {. 91 | importc: "LLVMAddConstantPropagationPass", libllvm.} 92 | 93 | proc addDemoteMemoryToRegisterPass*(pm: PassManagerRef) {. 94 | importc: "LLVMAddDemoteMemoryToRegisterPass", libllvm.} 95 | 96 | proc addVerifierPass*(pm: PassManagerRef) {.importc: "LLVMAddVerifierPass", 97 | libllvm.} 98 | 99 | proc addCorrelatedValuePropagationPass*(pm: PassManagerRef) {. 100 | importc: "LLVMAddCorrelatedValuePropagationPass", libllvm.} 101 | 102 | proc addEarlyCSEPass*(pm: PassManagerRef) {.importc: "LLVMAddEarlyCSEPass", 103 | libllvm.} 104 | 105 | proc addLowerExpectIntrinsicPass*(pm: PassManagerRef) {. 106 | importc: "LLVMAddLowerExpectIntrinsicPass", libllvm.} 107 | 108 | proc addTypeBasedAliasAnalysisPass*(pm: PassManagerRef) {. 109 | importc: "LLVMAddTypeBasedAliasAnalysisPass", libllvm.} 110 | 111 | proc addBasicAliasAnalysisPass*(pm: PassManagerRef) {. 112 | importc: "LLVMAddBasicAliasAnalysisPass", libllvm.} 113 | -------------------------------------------------------------------------------- /src/llvm_object.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMObject.a, which 2 | ## implements object file reading and writing. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core 9 | 10 | include llvm_lib 11 | 12 | # Object file reading and writing 13 | 14 | # Opaque type wrappers 15 | type 16 | ObjectFileRef = ptr object 17 | SectionIteratorRef = ptr object 18 | SymbolIteratorRef = ptr object 19 | RelocationIteratorRef = ptr object 20 | 21 | # ObjectFile creation 22 | 23 | proc createObjectFile*(memBuf: MemoryBufferRef): ObjectFileRef {. 24 | importc: "LLVMCreateObjectFile", libllvm.} 25 | 26 | proc disposeObjectFile*(objectFile: ObjectFileRef) {. 27 | importc: "LLVMDisposeObjectFile", libllvm.} 28 | 29 | # ObjectFile Section iterators 30 | 31 | proc getSections*(objectFile: ObjectFileRef): SectionIteratorRef {. 32 | importc: "LLVMSectionIteratorRef", libllvm.} 33 | 34 | proc disposeSectionIterator*(si: SectionIteratorRef) {. 35 | importc: "LLVMDisposeSectionIterator", libllvm.} 36 | 37 | proc isSectionIteratorAtEnd*(objectFile: ObjectFileRef, si: SectionIteratorRef): 38 | Bool {.importc: "LLVMIsSectionIteratorAtEnd", 39 | libllvm.} 40 | 41 | proc moveToNextSection*(si: SectionIteratorRef) {. 42 | importc: "LLVMMoveToNextSection", libllvm.} 43 | 44 | proc moveToContainingSection*(sect: SectionIteratorRef, sym: SymbolIteratorRef) {. 45 | importc: "LLVMMoveToContainingSection", libllvm.} 46 | 47 | # ObjectFile Symbol iterators 48 | 49 | proc getSymbols*(objectFile: ObjectFileRef): SymbolIteratorRef {. 50 | importc: "LLVMGetSymbols", libllvm.} 51 | 52 | proc disposeSymbolIterator*(si: SymbolIteratorRef) {. 53 | importc: "LLVMDisposeSymbolIterator", libllvm.} 54 | 55 | proc isSymbolIteratorAtEnd*(objectFile: ObjectFileRef, si: SectionIteratorRef): 56 | Bool {.importc: "LLVMIsSymbolIteratorAtEnd", libllvm.} 57 | 58 | proc moveToNextSymbol*(si: SectionIteratorRef) {.importc: "LLVMMoveToNextSymbol", 59 | libllvm.} 60 | 61 | # SectionRef accessors 62 | 63 | proc getSectionName*(si: SectionIteratorRef): cstring {. 64 | importc: "LLVMGetSectionName", libllvm.} 65 | 66 | proc getSectionSize*(si: SectionIteratorRef): culonglong {. 67 | importc: "LLVMGetSectionSize", libllvm.} 68 | 69 | proc getSectionContents*(si: SectionIteratorRef): cstring {. 70 | importc: "LLVMGetSectionContents", libllvm.} 71 | 72 | proc getSectionAddress*(si: SectionIteratorRef): culonglong {. 73 | importc: "LLVMGetSectionAddress", libllvm.} 74 | 75 | proc getSectionContainsSymbol*(si: SectionIteratorRef, sym: SymbolIteratorRef): 76 | Bool {.importc: "LLVMGetSectionContainsSymbol", 77 | libllvm.} 78 | 79 | # Section Relocation iterators 80 | 81 | proc getRelocations*(section: SectionIteratorRef): RelocationIteratorRef {. 82 | importc: "LLVMGetRelocations", libllvm.} 83 | 84 | proc disposeRelocationIterator*(ri: RelocationIteratorRef) {. 85 | importc: "LLVMDisposeRelocationIterator", libllvm.} 86 | 87 | proc isRelocationIteratorAtEnd*(section: SectionIteratorRef, 88 | ri: RelocationIteratorRef): Bool {. 89 | importc: "LLVMIsRelocationIteratorAtEnd", libllvm.} 90 | 91 | proc moveToNextRelocation*(ri: RelocationIteratorRef) {. 92 | importc: "LLVMMoveToNextRelocation", libllvm.} 93 | 94 | # SymbolRef accessors 95 | 96 | proc getSymbolName*(si: SymbolIteratorRef): cstring {. 97 | importc: "LLVMGetSymbolName", libllvm.} 98 | 99 | proc getSymbolAddress*(si: SymbolIteratorRef): culonglong {. 100 | importc: "LLVMGetSymbolAddress", libllvm.} 101 | 102 | proc getSymbolSize*(si: SymbolIteratorRef): culonglong {. 103 | importc: "LLVMGetSymbolSize", libllvm.} 104 | 105 | # RelocationRef accessors 106 | 107 | proc getRelocationAddress*(ri: RelocationIteratorRef): culonglong {. 108 | importc: "LLVMGetRelocationAddress", libllvm.} 109 | 110 | proc getRelocationOffset*(ri: RelocationIteratorRef): culonglong {. 111 | importc: "LLVMGetRelocationOffset", libllvm.} 112 | 113 | proc getRelocationSymbol*(ri: RelocationIteratorRef): SymbolIteratorRef {. 114 | importc: "LLVMGetRelocationSymbol", libllvm.} 115 | 116 | proc getRelocationType*(ri: RelocationIteratorRef): culonglong {. 117 | importc: "LLVMGetRelocationType", libllvm.} 118 | 119 | # NOTE: Caller takes ownership of returned string of the two 120 | # following functions. 121 | 122 | proc getRelocationTypeName*(ri: RelocationIteratorRef): cstring {. 123 | importc: "LLVMGetRelocationTypeName", libllvm.} 124 | 125 | proc getRelocationValueString*(ri: RelocationIteratorRef): cstring {. 126 | importc: "LLVMGetRelocationValueString", libllvm.} 127 | -------------------------------------------------------------------------------- /src/llvm_config.nim: -------------------------------------------------------------------------------- 1 | ## This file enumerates variables from the LLVM configuration so that they 2 | ## can be in exported headers and won't override package specific directives. 3 | 4 | var 5 | LLVM_BINDIR* {.importc, header: "".}: cstring 6 | ## Installation directory for binary executables 7 | 8 | LLVM_CONFIGTIME* {.importc, header: "".}: cstring 9 | ## Time at which LLVM was configured 10 | 11 | LLVM_DATADIR* {.importc, header: "".}: cstring 12 | ## Installation directory for data files 13 | 14 | LLVM_DEFAULT_TARGET_TRIPLE* {.importc, header: "".}: cstring 15 | ## Target triple LLVM will generate code for by default 16 | 17 | LLVM_DOCSDIR* {.importc, header: "".}: cstring 18 | ## Installation directory for documentation 19 | 20 | LLVM_ENABLE_THREADS* {.importc, header: "".}: cint 21 | ## Define if threads enabled 22 | 23 | LLVM_ETCDIR* {.importc, header: "".}: cstring 24 | ## Installation directory for config files 25 | 26 | LLVM_HAS_ATOMICS* {.importc, header: "".}: cint 27 | ## Has gcc/MSVC atomic intrinsics 28 | 29 | LLVM_HOST_TRIPLE* {.importc, header: "".}: cstring 30 | ## Host triple LLVM will be executed on 31 | 32 | LLVM_INCLUDEDIR* {.importc, header: "".}: cstring 33 | ## Installation directory for include files 34 | 35 | LLVM_INFODIR* {.importc, header: "".}: cstring 36 | ## Installation directory for .info files 37 | 38 | LLVM_MANDIR* {.importc, header: "".}: cstring 39 | ## Installation directory for man pages 40 | 41 | LLVM_NATIVE_ARCH* {.importc, header: "".}: proc () {.cdecl.} 42 | ## LLVM architecture name for the native architecture, if available 43 | 44 | when defined(dynamic_link) or defined(static_link): 45 | var 46 | LLVM_NATIVE_ASMPARSER* {.importc, header: "".}: proc () {.cdecl.} 47 | ## LLVM name for the native AsmParser init function, if available 48 | 49 | LLVM_NATIVE_ASMPRINTER* {.importc, header: "".}: proc () {.cdecl.} 50 | ## LLVM name for the native AsmPrinter init function, if available 51 | 52 | LLVM_NATIVE_DISASSEMBLER* {.importc, header: "".}: proc () {.cdecl.} 53 | ## LLVM name for the native Disassembler init function, if available 54 | 55 | LLVM_NATIVE_TARGET* {.importc, header: "".}: proc () {.cdecl.} 56 | ## LLVM name for the native Target init function, if available 57 | 58 | LLVM_NATIVE_TARGETINFO* {.importc, header: "".}: proc () {.cdecl.} 59 | ## LLVM name for the native TargetInfo init function, if available 60 | 61 | LLVM_NATIVE_TARGETMC* {.importc, header: "".}: proc () {.cdecl.} 62 | ## LLVM name for the native target MC init function, if available 63 | else: 64 | var 65 | LLVM_NATIVE_ASMPARSER* {.importc, header: "".}: proc () {.nimcall.} 66 | ## LLVM name for the native AsmParser init function, if available 67 | 68 | LLVM_NATIVE_ASMPRINTER* {.importc, header: "".}: proc () {.nimcall.} 69 | ## LLVM name for the native AsmPrinter init function, if available 70 | 71 | LLVM_NATIVE_DISASSEMBLER* {.importc, header: "".}: proc () {.nimcall.} 72 | ## LLVM name for the native Disassembler init function, if available 73 | 74 | LLVM_NATIVE_TARGET* {.importc, header: "".}: proc () {.nimcall.} 75 | ## LLVM name for the native Target init function, if available 76 | 77 | LLVM_NATIVE_TARGETINFO* {.importc, header: "".}: proc () {.nimcall.} 78 | ## LLVM name for the native TargetInfo init function, if available 79 | 80 | LLVM_NATIVE_TARGETMC* {.importc, header: "".}: proc () {.nimcall.} 81 | ## LLVM name for the native target MC init function, if available 82 | 83 | var 84 | LLVM_ON_UNIX* {.importc, header: "".}: cint 85 | ## Define if this is Unixish platform 86 | 87 | LLVM_ON_WIN32* {.importc, header: "".}: cint 88 | ## Define if this is Win32ish platform 89 | 90 | LLVM_PREFIX* {.importc, header: "".}: cstring 91 | ## Installation prefix directory 92 | 93 | LLVM_USE_INTEL_JITEVENTS* {.importc, header: "".}: cint 94 | ## Define if we have the Intel JIT API runtime support library 95 | 96 | LLVM_USE_OPROFILE* {.importc, header: "".}: cint 97 | ## Define if we have the oprofile JIT-support library 98 | 99 | LLVM_VERSION_MAJOR* {.importc, header: "".}: cint 100 | ## Major version of the LLVM API 101 | 102 | LLVM_VERSION_MINOR* {.importc, header: "".}: cint 103 | ## Minor version of the LLVM API 104 | -------------------------------------------------------------------------------- /src/llvm_targetmachine.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to the Target and TargetMachine 2 | ## classes, which can be used to generate assembly or object files. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core, llvm_target 9 | 10 | include llvm_lib 11 | 12 | type 13 | TargetMachineRef* = ptr object 14 | TargetRef* = ptr object 15 | 16 | type 17 | CodeGenOptLevel* = enum 18 | CodeGenLevelNone 19 | CodeGenLevelLess 20 | CodeGenLevelDefault 21 | CodeGenLevelAggressive 22 | 23 | RelocMode* = enum 24 | RelocDefault 25 | RelocStatic 26 | RelocPIC 27 | RelocDynamicNoPic 28 | 29 | CodeModel* = enum 30 | CodeModelDefault 31 | CodeModelJITDefault 32 | CodeModelSmall 33 | CodeModelKernel 34 | CodeModelMedium 35 | CodeModelLarge 36 | 37 | CodeGenFileType* = enum 38 | AssemblyFile 39 | ObjectFile 40 | 41 | proc getFirstTarget*: TargetRef {.importc: "LLVMGetFirstTarget", libllvm.} 42 | ## Returns the first llvm::Target in the registered targets list. 43 | 44 | proc getNextTarget*(t: TargetRef): TargetRef {.importc: "LLVMGetNextTarget", 45 | libllvm.} 46 | ## Returns the next llvm::Target given a previous one (or null if there's none) 47 | 48 | # Target 49 | 50 | proc getTargetFromName*(name: cstring): TargetRef {. 51 | importc: "LLVMGetTargetFromName", libllvm.} 52 | ## Finds the target corresponding to the given name and stores it in T. 53 | ## Returns 0 on success. 54 | 55 | proc getTargetFromTriple*(triple: cstring, t: ptr TargetRef, 56 | errorMessage: cstringArray): Bool {. 57 | importc: "LLVMGetTargetFromTriple", libllvm.} 58 | ## Finds the target corresponding to the given triple and stores it in T. 59 | ## Returns 0 on success. Optionally returns any error in ErrorMessage. 60 | ## Use LLVMDisposeMessage to dispose the message. 61 | 62 | proc getTargetName*(t: TargetRef): cstring {.importc: "LLVMGetTargetName", 63 | libllvm.} 64 | ## Returns the name of a target. See llvm::Target::getName 65 | 66 | proc getTargetDescription*(t: TargetRef): cstring {. 67 | importc: "LLVMGetTargetDescription", libllvm.} 68 | ## Returns the description of a target. See llvm::Target::getDescription 69 | 70 | proc targetHasJIT*(t: TargetRef): Bool {.importc: "LLVMTargetHasJIT", libllvm.} 71 | ## Returns if the target has a JIT 72 | 73 | proc targetHasTargetMachine*(t: TargetRef): Bool {. 74 | importc: "LLVMTargetHasTargetMachine", libllvm.} 75 | ## Returns if the target has a TargetMachine associated 76 | 77 | proc targetHasAsmBackend*(t: TargetRef): Bool {. 78 | importc: "LLVMTargetHasAsmBackend", libllvm.} 79 | ## Returns if the target as an ASM backend (required for emitting output) 80 | 81 | # Target Machine 82 | 83 | proc createTargetMachine*(t: TargetRef, triple: cstring, cpu: cstring, 84 | features: cstring, level: CodeGenOptLevel, 85 | reloc: RelocMode, codeModel: CodeModel): 86 | TargetMachineRef {.importc: "LLVMCreateTargetMachine", 87 | libllvm.} 88 | ## Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine 89 | 90 | proc disposeTargetMachine*(t: TargetMachineRef) {. 91 | importc: "LLVMDisposeTargetMachine", libllvm.} 92 | ## Dispose the LLVMTargetMachineRef instance generated by 93 | ## LLVMCreateTargetMachine. 94 | 95 | proc getTargetMachineTarget*(t: TargetMachineRef): TargetRef {. 96 | importc: "LLVMGetTargetMachineTarget", libllvm.} 97 | ## Returns the Target used in a TargetMachine 98 | 99 | proc getTargetMachineTriple*(t: TargetMachineRef): cstring {. 100 | importc: "LLVMGetTargetMachineTriple", libllvm.} 101 | ## Returns the triple used creating this target machine. See 102 | ## llvm::TargetMachine::getTriple. The result needs to be disposed with 103 | ## LLVMDisposeMessage. 104 | 105 | proc getTargetMachineCPU*(t: TargetMachineRef): cstring {. 106 | importc: "LLVMGetTargetMachineCPU", libllvm.} 107 | ## Returns the cpu used creating this target machine. See 108 | ## llvm::TargetMachine::getCPU. The result needs to be disposed with 109 | ## LLVMDisposeMessage. 110 | 111 | proc getTargetMachineFeatureString*(t: TargetMachineRef): cstring {. 112 | importc: "LLVMGetTargetMachineFeatureString", libllvm.} 113 | ## Returns the feature string used creating this target machine. See 114 | ## llvm::TargetMachine::getFeatureString. The result needs to be disposed with 115 | ## LLVMDisposeMessage. 116 | 117 | proc getTargetMachineData*(t: TargetMachineRef): TargetDataRef {. 118 | importc: "LLVMGetTargetMachineData", libllvm.} 119 | ## Returns the llvm::DataLayout used for this llvm:TargetMachine. 120 | 121 | proc setTargetMachineAsmVerbosity*(t: TargetMachineRef, verboseAsm: Bool) {. 122 | importc: "LLVMSetTargetMachineAsmVerbosity", libllvm.} 123 | ## Set the target machine's ASM verbosity. 124 | 125 | proc targetMachineEmitToFile*(t: TargetMachineRef, m: ModuleRef, 126 | filename: cstring, codegen: CodeGenFileType, 127 | errorMessage: cstringArray): Bool {. 128 | importc: "LLVMTargetMachineEmitToFile", libllvm.} 129 | ## Emits an asm or object file for the given module to the filename. This 130 | ## wraps several c++ only classes (among them a file stream). Returns any 131 | ## error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. 132 | 133 | proc targetMachineEmitToMemoryBuffer*(t: TargetMachineRef, m: ModuleRef, 134 | codegen: CodeGenFileType, 135 | errorMessage: cstringArray, 136 | outMemBuf: ptr MemoryBufferRef): Bool {. 137 | importc: "LLVMTargetMachineEmitToMemoryBuffer", libllvm.} 138 | ## Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. 139 | 140 | # Triple 141 | 142 | proc getDefaultTargetTriple*: cstring {.importc: "LLVMGetDefaultTargetTriple", 143 | libllvm.} 144 | ## Get a triple for the host machine as a string. The result needs to be 145 | ## disposed with LLVMDisposeMessage. 146 | 147 | proc addAnalysisPasses*(t: TargetMachineRef, pm: PassManagerRef) {. 148 | importc: "LLVMAddAnalysisPasses", libllvm.} 149 | ## Adds the target-specific analysis passes to the pass manager. 150 | -------------------------------------------------------------------------------- /src/llvm_executionengine.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMExecutionEngine.o, which 2 | ## implements various analyses of the LLVM IR. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core, llvm_target, llvm_targetmachine 9 | 10 | include llvm_lib 11 | 12 | # Execution Engine 13 | 14 | proc linkInJIT* {.importc: "LLVMLinkInJIT", libllvm.} 15 | 16 | proc linkInMCJIT* {.importc: "LLVMLinkInMCJIT", libllvm.} 17 | 18 | proc linkInInterpreter* {.importc: "LLVMLinkInInterpreter", libllvm.} 19 | 20 | type 21 | GenericValueRef* = ptr object 22 | ExecutionEngineRef* = ptr object 23 | MCJITMemoryManagerRef* = ptr object 24 | 25 | type MCJITCompilerOptions* = object 26 | optLevel*: cuint 27 | codeModel*: CodeModel 28 | noFramePointerElim*: Bool 29 | enableFastISel*: Bool 30 | mcJMM*: MCJITMemoryManagerRef 31 | 32 | # Operations on generic values 33 | 34 | proc createGenericValueOfInt*(ty: TypeRef, n: culonglong, isSigned: Bool): 35 | GenericValueRef {. 36 | importc: "LLVMCreateGenericValueOfInt", libllvm.} 37 | 38 | proc createGenericValueOfPointer*(p: pointer): GenericValueRef {. 39 | importc: "LLVMCreateGenericValueOfPointer", libllvm.} 40 | 41 | proc createGenericValueOfFloat*(ty: TypeRef, n: cdouble): GenericValueRef {. 42 | importc: "LLVMCreateGenericValueOfFloat", libllvm.} 43 | 44 | proc genericValueIntWidth*(genValRef: GenericValueRef): cuint {. 45 | importc: "LLVMGenericValueIntWidth", libllvm.} 46 | 47 | proc genericValueToInt*(genVal: GenericValueRef, isSigned: Bool): culonglong {. 48 | importc: "LLVMGenericValueToInt", libllvm.} 49 | 50 | proc genericValueToPointer*(genVal: GenericValueRef): pointer {. 51 | importc: "LLVMGenericValueToPointer", libllvm.} 52 | 53 | proc genericValueToFloat*(tyRef: TypeRef, genVal: GenericValueRef): cdouble {. 54 | importc: "LLVMGenericValueToFloat", libllvm.} 55 | 56 | proc disposeGenericValue*(genVal: GenericValueRef) {. 57 | importc: "LLVMDisposeGenericValue", libllvm.} 58 | 59 | # Operations on execution engines 60 | 61 | proc createExecutionEngineForModule*(outEE: ptr ExecutionEngineRef, 62 | m: ModuleRef, outError: cstringArray): 63 | Bool {. 64 | importc: "LLVMCreateExecutionEngineForModule", libllvm.} 65 | 66 | proc createInterpreterForModule*(outInterp: ptr ExecutionEngineRef, 67 | m: ModuleRef, outError: cstringArray): Bool {. 68 | importc: "LLVMCreateInterpreterForModule", libllvm.} 69 | 70 | proc createJITCompilerForModule*(outJIT: ptr ExecutionEngineRef, m: ModuleRef, 71 | optLevel: cuint, outError: cstringArray): Bool {. 72 | importc: "LLVMCreateJITCompilerForModule", libllvm.} 73 | 74 | proc initializeMCJITCompilerOptions*(options: ptr MCJITCompilerOptions, 75 | sizeOfOptions: csize) {. 76 | importc: "LLVMInitializeMCJITCompilerOptions", libllvm.} 77 | 78 | proc createMCJITCompilerForModule*(outJIT: ptr ExecutionEngineRef, m: ModuleRef, 79 | options: ptr MCJITCompilerOptions, 80 | sizeOfOptions: csize, 81 | outError: cstringArray): Bool {. 82 | importc: "LLVMCreateMCJITCompilerForModule", libllvm.} 83 | ## Create an MCJIT execution engine for a module, with the given options. It is 84 | ## the responsibility of the caller to ensure that all fields in Options up to 85 | ## the given SizeOfOptions are initialized. It is correct to pass a smaller 86 | ## value of SizeOfOptions that omits some fields. The canonical way of using 87 | ## this is: 88 | ## 89 | ## LLVMMCJITCompilerOptions options; 90 | ## LLVMInitializeMCJITCompilerOptions(&options, sizeof(options)); 91 | ## ... fill in those options you care about 92 | ## LLVMCreateMCJITCompilerForModule(&jit, mod, &options, sizeof(options), 93 | ## &error); 94 | ## 95 | ## Note that this is also correct, though possibly suboptimal: 96 | ## 97 | ## LLVMCreateMCJITCompilerForModule(&jit, mod, 0, 0, &error); 98 | 99 | proc createExecutionEngine*(outEE: ptr ExecutionEngineRef, 100 | mp: ModuleProviderRef, outError: cstringArray): Bool {. 101 | deprecated, importc: "LLVMCreateExecutionEngine", libllvm.} 102 | ## Deprecated: Use LLVMCreateExecutionEngineForModule instead. 103 | 104 | proc createInterpreter*(outInterp: ptr ExecutionEngineRef, mp: ModuleProviderRef, 105 | outError: cstringArray): Bool {. 106 | deprecated, importc: "LLVMCreateInterpreter", libllvm.} 107 | ## Deprecated: Use LLVMCreateInterpreterForModule instead. 108 | 109 | proc createJITCompiler*(outJIT: ptr ExecutionEngineRef, mp: ModuleProviderRef, 110 | optLevel: cuint, outError: cstringArray): Bool {. 111 | deprecated, importc: "LLVMCreateJITCompiler", libllvm.} 112 | ## Deprecated: Use LLVMCreateJITCompilerForModule instead. 113 | 114 | proc disposeExecutionEngine*(ee: ExecutionEngineRef) {. 115 | importc: "LLVMDisposeExecutionEngine", libllvm.} 116 | 117 | proc runStaticConstructors*(ee: ExecutionEngineRef) {. 118 | importc: "LLVMRunStaticConstructors", libllvm.} 119 | 120 | proc runStaticDestructors*(ee: ExecutionEngineRef) {. 121 | importc: "LLVMRunStaticDestructors", libllvm.} 122 | 123 | proc runFunctionAsMain*(ee: ExecutionEngineRef, f: ValueRef, argC: cuint, 124 | argV: cstringArray, envP: cstringArray): cint {. 125 | importc: "LLVMRunFunctionAsMain", libllvm.} 126 | 127 | proc runFunction*(ee: ExecutionEngineRef, f: ValueRef, numArgs: cuint, 128 | args: ptr GenericValueRef): GenericValueRef {. 129 | importc: "LLVMRunFunction", libllvm.} 130 | 131 | proc freeMachineCodeForFunction*(ee: ExecutionEngineRef, f: ValueRef) {. 132 | importc: "LLVMFreeMachineCodeForFunction", libllvm.} 133 | 134 | proc addModule*(ee: ExecutionEngineRef, m: ModuleRef) {. 135 | importc: "LLVMAddModule", libllvm.} 136 | 137 | proc addModuleProvider*(ee: ExecutionEngineRef, mp: ModuleProviderRef) {. 138 | importc: "LLVMAddModuleProvider", libllvm.} 139 | ## Deprecated: Use LLVMAddModule instead. 140 | 141 | proc removeModule*(ee: ExecutionEngineRef, m: ModuleRef, outMod: ptr ModuleRef, 142 | outError: cstringArray): Bool {.importc: "LLVMRemoveModule", 143 | libllvm.} 144 | 145 | proc removeModuleProvider*(ee: ExecutionEngineRef, mp: ModuleProviderRef, 146 | outMod: ptr ModuleRef, outError: cstringArray): Bool {. 147 | deprecated, importc: "LLVMRemoveModuleProvider", libllvm.} 148 | ## Deprecated: Use LLVMRemoveModule instead. 149 | 150 | proc findFunction*(ee: ExecutionEngineRef, name: cstring, outFn: ptr ValueRef): 151 | Bool {.importc: "LLVMFindFunction", libllvm.} 152 | 153 | proc recompileAndRelinkFunction*(ee: ExecutionEngineRef, fn: ValueRef): pointer {. 154 | importc: "LLVMRecompileAndRelinkFunction", libllvm.} 155 | 156 | proc getExecutionEngineTargetData*(ee: ExecutionEngineRef): TargetDataRef {. 157 | importc: "LLVMGetExecutionEngineTargetData", libllvm.} 158 | 159 | proc getExecutionEngineTargetMachine*(ee: ExecutionEngineRef): TargetMachineRef {. 160 | importc: "LLVMGetExecutionEngineTargetMachine", libllvm.} 161 | 162 | proc addGlobalMapping*(ee: ExecutionEngineRef, global: ValueRef, address: pointer) {. 163 | importc: "LLVMAddGlobalMapping", libllvm.} 164 | 165 | proc getPointerToGlobal*(ee: ExecutionEngineRef, global: ValueRef): pointer {. 166 | importc: "LLVMGetPointerToGlobal", libllvm.} 167 | 168 | # Operations on memory managers 169 | 170 | type 171 | MemoryManagerAllocateCodeSectionCallback* = proc (opaque: pointer, size: uint, 172 | alignment: cuint, 173 | sectionID: cuint, 174 | sectionName: cstring): 175 | ptr cuchar {.cdecl.} 176 | 177 | MemoryManagerAllocateDataSectionCallback* = proc (opaque: pointer, size: uint, 178 | alignment: cuint, 179 | sectionID: cuint, 180 | sectionName: cstring, 181 | isReadOnly: Bool): 182 | ptr cuchar {.cdecl.} 183 | 184 | MemoryManagerFinalizeMemoryCallback* = proc (opaque: pointer, 185 | errMsg: cstringArray): Bool {.cdecl.} 186 | 187 | MemoryManagerDestroyCallback* = proc (opaque: pointer) {.cdecl.} 188 | 189 | proc createSimpleMCJITMemoryManager*(opaque: pointer, 190 | allocateCodeSection: MemoryManagerAllocateCodeSectionCallback, 191 | allocateDataSection: MemoryManagerAllocateDataSectionCallback, 192 | finalizeMemory: MemoryManagerFinalizeMemoryCallback, 193 | destroy: MemoryManagerDestroyCallback): 194 | MCJITMemoryManagerRef {. 195 | importc: "LLVMCreateSimpleMCJITMemoryManager", libllvm.} 196 | ## Create a simple custom MCJIT memory manager. This memory manager can 197 | ## intercept allocations in a module-oblivious way. This will return NULL 198 | ## if any of the passed functions are NULL. 199 | ## 200 | ## @param Opaque An opaque client object to pass back to the callbacks. 201 | ## @param AllocateCodeSection Allocate a block of memory for executable code. 202 | ## @param AllocateDataSection Allocate a block of memory for data. 203 | ## @param FinalizeMemory Set page permissions and flush cache. Return 0 on 204 | ## success, 1 on error. 205 | 206 | proc disposeMCJITMemoryManager*(mm: MCJITMemoryManagerRef) {. 207 | importc: "LLVMDisposeMCJITMemoryManager", libllvm.} 208 | -------------------------------------------------------------------------------- /src/llvm_target.nim: -------------------------------------------------------------------------------- 1 | ## This header declares the C interface to libLLVMTarget.a, which 2 | ## implements target information. 3 | ## 4 | ## Many exotic languages can interoperate with C code but have a harder time 5 | ## with C++ due to name mangling. So in addition to C, this interface enables 6 | ## tools written in such languages. 7 | 8 | import llvm_core, macros, strutils#, pegs 9 | 10 | include llvm_lib, llvm_config 11 | 12 | proc defPath(): string {.compileTime.} = 13 | result = ".." 14 | for i in 3..currentSourcePath.count("/"): 15 | result &= "/.." 16 | result &= gorge("llvm-config --includedir") & "/llvm/Config/" 17 | 18 | const DefPath = defPath() 19 | 20 | #macro targetsFor(suffix: string): stmt = 21 | # var targets = newSeq[string]() 22 | # let def = slurp(DefPath & suffix.strVal & "s.def") 23 | # for line in def.splitLines(): 24 | # if line.len != 0 and line =~ peg"(LLVM_\ident\({\ident}\)\s*)*": 25 | # for match in matches: 26 | # if match != nil: targets.add(match) 27 | # break 28 | # result = parseStmt("const " & suffix.strVal & "s* = " & repr(targets)) 29 | 30 | macro targetsFor(suffix: string): stmt = 31 | var targets = newSeq[string]() 32 | let def = slurp(DefPath & suffix.strVal & "s.def") 33 | for line in def.splitLines(): 34 | if line.startsWith("LLVM_"): 35 | for str in line.split(')'): 36 | var target = str.split('(') 37 | if target.len == 2: targets.add(target[1]) 38 | break 39 | result = parseStmt("const " & suffix.strVal & "s* = " & repr(targets)) 40 | 41 | # Target information 42 | 43 | const Targets* = gorge("llvm-config --targets-built").strip.split(' ') 44 | 45 | targetsFor("AsmPrinter") 46 | targetsFor("AsmParser") 47 | targetsFor("Disassembler") 48 | 49 | type 50 | ByteOrdering* = enum 51 | BigEndian 52 | LittleEndian 53 | 54 | type 55 | TargetDataRef* = ptr object 56 | TargetLibraryInfoRef* = ptr object 57 | 58 | macro declareTargetProcs(targets: static[openArray[string]], suffix: string): stmt = 59 | var src = "" 60 | for target in targets: 61 | when defined(dynamic_link) or defined(static_link): 62 | src &= ("proc LLVMInitialize$1$2 {.importc: \"LLVMInitialize$1$2\", " & 63 | "libllvm.}\n") % [target, suffix.strVal] 64 | src &= ("proc initialize$1$2* = LLVMInitialize$1$2()\n") % [target, suffix.strVal] 65 | else: 66 | src &= ("proc initialize$1$2* {.importc: \"LLVMInitialize$1$2\", " & 67 | "libllvm.}\n") % [target, suffix.strVal] 68 | src &= ("proc LLVMInitialize$1$2 {.exportc.} = initialize$1$2()\n") % 69 | [target, suffix.strVal] 70 | result = parseStmt(src) 71 | 72 | # Declare all of the target-initialization functions that are available. 73 | declareTargetProcs(Targets, "TargetInfo") 74 | declareTargetProcs(Targets, "Target") 75 | declareTargetProcs(Targets, "TargetMC") 76 | 77 | # Declare all of the available assembly printer initialization functions. 78 | declareTargetProcs(AsmPrinters, "AsmPrinter") 79 | 80 | # Declare all of the available assembly parser initialization functions. 81 | declareTargetProcs(AsmParsers, "AsmParser") 82 | 83 | # Declare all of the available disassembler initialization functions. 84 | declareTargetProcs(Disassemblers, "Disassembler") 85 | 86 | macro defineTargetProcBody(targets: static[openArray[string]], suffix: string): stmt = 87 | var src = "" 88 | for target in targets: 89 | src &= "initialize" & target & suffix.strVal & "()\n" 90 | result = parseStmt(src) 91 | 92 | proc initializeAllTargetInfos* {.inline.} = 93 | defineTargetProcBody(Targets, "TargetInfo") 94 | ## The main program should call this function if it wants access to all 95 | ## available targets that LLVM is configured to support. 96 | 97 | proc initializeAllTargets* {.inline.} = 98 | defineTargetProcBody(Targets, "Target") 99 | ## The main program should call this function if it wants to link in all 100 | ## available targets that LLVM is configured to support. 101 | 102 | proc initializeAllTargetMCs* {.inline.} = 103 | defineTargetProcBody(Targets, "TargetMC") 104 | ## The main program should call this function if it wants access to all 105 | ## available target MC that LLVM is configured to support. 106 | 107 | proc initializeAllAsmPrinters* {.inline.} = 108 | defineTargetProcBody(AsmPrinters, "AsmPrinter") 109 | ## The main program should call this function if it wants all asm printers that 110 | ## LLVM is configured to support, to make them available via the TargetRegistry. 111 | 112 | proc initializeAllAsmParsers* {.inline.} = 113 | defineTargetProcBody(AsmParsers, "AsmParser") 114 | ## The main program should call this function if it wants all asm parsers that 115 | ## LLVM is configured to support, to make them available via the TargetRegistry. 116 | 117 | proc initializeAllDisassemblers* {.inline.} = 118 | defineTargetProcBody(Disassemblers, "Disassembler") 119 | ## The main program should call this function if it wants all disassemblers that 120 | ## LLVM is configured to support, to make them available via the TargetRegistry. 121 | 122 | proc initializeNativeTarget*: Bool {.inline.} = 123 | # If we have a native target, initialize it to ensure it is linked in. 124 | when declared(LLVM_NATIVE_TARGET): 125 | LLVM_NATIVE_TARGETINFO() 126 | LLVM_NATIVE_TARGET() 127 | LLVM_NATIVE_TARGETMC() 128 | return 0 129 | else: 130 | return 1 131 | ## The main program should call this function to initialize the native target 132 | ## corresponding to the host. This is useful for JIT applications to ensure 133 | ## that the target gets linked in correctly. 134 | 135 | proc initializeNativeAsmParser*: Bool {.inline.} = 136 | when declared(LLVM_NATIVE_ASMPARSER): 137 | LLVM_NATIVE_ASMPARSER() 138 | return 0 139 | else: 140 | return 1 141 | ## The main program should call this function to initialize the parser for the 142 | ## native target corresponding to the host. 143 | 144 | proc initializeNativeAsmPrinter*: Bool {.inline.} = 145 | when declared(LLVM_NATIVE_ASMPRINTER): 146 | LLVM_NATIVE_ASMPRINTER() 147 | return 0 148 | else: 149 | retuen 1 150 | ## The main program should call this function to initialize the printer for the 151 | ## native target corresponding to the host. 152 | 153 | proc initializeNativeDisassembler*: Bool {.inline.} = 154 | when declared(LLVM_NATIVE_DISASSEMBLER): 155 | LLVM_NATIVE_DISASSEMBLER() 156 | return 0 157 | else: 158 | return 1 159 | ## The main program should call this function to initialize the disassembler 160 | ## for the native target corresponding to the host. 161 | 162 | # Target Data 163 | 164 | proc createTargetData*(stringRep: cstring): TargetDataRef {. 165 | importc: "LLVMCreateTargetData", libllvm.} 166 | ## Creates target data from a target layout string. 167 | 168 | proc addTargetData*(td: TargetDataRef, pm: PassManagerRef) {. 169 | importc: "LLVMAddTargetData", libllvm.} 170 | ## Adds target data information to a pass manager. This does not take ownership 171 | ## of the target data. 172 | 173 | proc addTargetLibraryInfo*(tli: TargetLibraryInfoRef, pm: PassManagerRef) {. 174 | importc: "LLVMAddTargetLibraryInfo", libllvm.} 175 | ## Adds target library information to a pass manager. This does not take 176 | ## ownership of the target library info. 177 | 178 | proc copyStringRepOfTargetData*(td: TargetDataRef): cstring {. 179 | importc: "LLVMCopyStringRepOfTargetData", libllvm.} 180 | ## Converts target data to a target layout string. The string must be disposed 181 | ## with LLVMDisposeMessage. 182 | 183 | proc byteOrder*(td: TargetDataRef): ByteOrdering {.importc: "LLVMByteOrder", 184 | libllvm.} 185 | ## Returns the byte order of a target, either LLVMBigEndian or LLVMLittleEndian. 186 | 187 | proc pointerSize*(td: TargetDataRef): cuint {.importc: "LLVMPointerSize", 188 | libllvm.} 189 | ## Returns the pointer size in bytes for a target. 190 | 191 | proc pointerSizeForAS*(td: TargetDataRef, addressSpace: cuint): cuint {. 192 | importc: "LLVMPointerSizeForAS", libllvm.} 193 | ## Returns the pointer size in bytes for a target for a specified 194 | ## address space. 195 | 196 | proc intPtrType*(td: TargetDataRef): TypeRef {.importc: "LLVMIntPtrType", 197 | libllvm.} 198 | ## Returns the integer type that is the same size as a pointer on a target. 199 | 200 | proc intPtrTypeForAS*(td: TargetDataRef, addressSpace: cuint): TypeRef {. 201 | importc: "LLVMIntPtrTypeForAS", libllvm.} 202 | ## Returns the integer type that is the same size as a pointer on a target. 203 | ## This version allows the address space to be specified. 204 | 205 | proc intPtrTypeInContext*(c: ContextRef, td: TargetDataRef): TypeRef {. 206 | importc: "LLVMIntPtrTypeInContext", libllvm.} 207 | ## Returns the integer type that is the same size as a pointer on a target. 208 | 209 | proc intPtrTypeForASInContext*(c: ContextRef, td: TargetDataRef, 210 | addressSpace: cuint): TypeRef {. 211 | importc: "LLVMIntPtrTypeForASInContext", libllvm.} 212 | ## Returns the integer type that is the same size as a pointer on a target. 213 | ## This version allows the address space to be specified. 214 | 215 | proc SizeOfTypeInBits*(td: TargetDataRef, ty: TypeRef): culonglong {. 216 | importc: "LLVMSizeOfTypeInBits", libllvm.} 217 | ## Computes the size of a type in bytes for a target. 218 | 219 | proc storeSizeOfType*(td: TargetDataRef, ty: TypeRef): culonglong {. 220 | importc: "LLVMStoreSizeOfType", libllvm.} 221 | ## Computes the storage size of a type in bytes for a target. 222 | 223 | proc abiSizeOfType*(td: TargetDataRef, ty: TypeRef): culonglong {. 224 | importc: "LLVMABISizeOfType", libllvm.} 225 | ## Computes the ABI size of a type in bytes for a target. 226 | 227 | proc abiAlignmentOfType*(td: TargetDataRef, ty: TypeRef): cuint {. 228 | importc: "LLVMABIAlignmentOfType", libllvm.} 229 | ## Computes the ABI alignment of a type in bytes for a target. 230 | 231 | proc callFrameAlignmentOfType*(td: TargetDataRef, ty: TypeRef): cuint {. 232 | importc: "LLVMCallFrameAlignmentOfType", libllvm.} 233 | ## Computes the call frame alignment of a type in bytes for a target. 234 | 235 | proc preferredAlignmentOfType*(td: TargetDataRef, ty: TypeRef): cuint {. 236 | importc: "LLVMPreferredAlignmentOfType", libllvm.} 237 | ## Computes the preferred alignment of a type in bytes for a target. 238 | 239 | proc preferredAlignmentOfGlobal*(td: TargetDataRef, globalVar: ValueRef): cuint {. 240 | importc: "LLVMPreferredAlignmentOfGlobal", libllvm.} 241 | ## Computes the preferred alignment of a global variable in bytes for a target. 242 | 243 | proc elementAtOffset*(td: TargetDataRef, structTy: TypeRef, offset: culonglong): 244 | cuint {.importc: "LLVMElementAtOffset", libllvm.} 245 | ## Computes the structure element that contains the byte offset for a target. 246 | 247 | proc offsetOfElement*(td: TargetDataRef, structTy: TypeRef, element: cuint): 248 | culonglong {.importc: "LLVMOffsetOfElement", libllvm.} 249 | ## Computes the byte offset of the indexed struct element for a target. 250 | 251 | proc disposeTargetData*(td: TargetDataRef) {.importc: "LLVMDisposeTargetData", 252 | libllvm.} 253 | ## Deallocates a TargetData. 254 | -------------------------------------------------------------------------------- /src/llvm_lto.nim: -------------------------------------------------------------------------------- 1 | ## This header provides public interface to an abstract link time optimization 2 | ## library. LLVM provides an implementation of this interface for use with 3 | ## llvm bitcode files. 4 | 5 | const libname = "LTO" 6 | 7 | {.passC: gorge("llvm-config --cflags").} 8 | 9 | when defined(dynamic_link) or defined(static_link): 10 | const ldflags = gorge("llvm-config --ldflags") 11 | {.pragma: liblto, cdecl.} 12 | when defined(dynamic_link): # Dynamic linking 13 | {.passL: ldflags & "-l" & libname.} 14 | else: # Static linking 15 | const libdir = gorge("llvm-config --libdir") 16 | {.passL: gorge("llvm-config --system-libs") & "-lstdc++ " & ldflags & 17 | libdir & "/lib" & libname & ".a " & gorge("llvm-config --libs").} 18 | else: # Dynamic loading 19 | when defined(windows): 20 | const dllname = libname & ".dll" 21 | elif defined(macosx): 22 | const dllname = "lib" & libname & ".dylib" 23 | else: 24 | const dllname = "lib" & libname & ".so" 25 | {.pragma: liblto, cdecl, dynlib: dllname.} 26 | 27 | type Bool* = cuchar 28 | 29 | # LTO 30 | 31 | var LTO_API_VERSION* {.importc, header: "".}: cint 32 | 33 | type 34 | SymbolAttributes* = enum ## Symbol attributes 35 | SymbolAlignmentMask = 0x0000001F ## log2 of alignment 36 | SymbolPermissionsROData = 0x00000080 37 | SymbolPermissionsCode = 0x000000A0 38 | SymbolPermissionsData = 0x000000C0 39 | SymbolPermissionsMask = 0x000000E0 40 | SymbolDefinitionRegular = 0x00000100 41 | SymbolDefinitionTentative = 0x00000200 42 | SymbolDefinitionWeak = 0x00000300 43 | SymbolDefinitionUndefined = 0x00000400 44 | SymbolDefinitionWeakUndef = 0x00000500 45 | SymbolDefinitionMask = 0x00000700 46 | SymbolScopeInternal = 0x00000800 47 | SymbolScopeHidden = 0x00001000 48 | SymbolScopeDefault = 0x00001800 49 | SymbolScopeProtected = 0x00002000 50 | SymbolScopeDefaultCanBeHidden = 0x00002800 51 | SymbolScopeMask = 0x00003800 52 | 53 | DebugModel* = enum 54 | DebugModelNone = 0 55 | DebugModelDwarf = 1 56 | 57 | CodegenModel* = enum 58 | CodegenPICModelStatic = 0 59 | CodegenPICModelDynamic = 1 60 | CodegenPICModelDynamicNoPIC = 2 61 | CodegenPICModelDefault = 3 62 | 63 | type 64 | Module* = ptr object 65 | ## opaque reference to a loaded object module 66 | CodeGen* = ptr object 67 | ## opaque reference to a code generator 68 | 69 | proc getVersion*: cstring {.importc: "lto_get_version", liblto.} 70 | ## Returns a printable string. 71 | 72 | proc getError*: cstring {.importc: "lto_get_error_message", liblto.} 73 | ## Returns the last error string or NULL if last operation was successful. 74 | 75 | proc moduleIsObjectFile*(path: cstring): Bool {. 76 | importc: "lto_module_is_object_file", liblto.} 77 | ## Checks if a file is a loadable object file. 78 | 79 | proc moduleIsObjectFileForTarget*(path: cstring, targetTriplePrefix: cstring): Bool {. 80 | importc: "lto_module_is_object_file_for_target", liblto.} 81 | ## Checks if a file is a loadable object compiled for requested target. 82 | 83 | proc moduleIsObjectFileInMemory*(mem: pointer, length: csize): Bool {. 84 | importc: "lto_module_is_object_file_in_memory", liblto.} 85 | ## Checks if a buffer is a loadable object file. 86 | 87 | proc moduleIsObjectFileInMemoryForTarget*(mem: pointer, length: csize, 88 | targetTriplePrefix: cstring): Bool {. 89 | importc: "lto_module_is_object_file_in_memory_for_target", liblto.} 90 | ## Checks if a buffer is a loadable object compiled for requested target. 91 | 92 | proc moduleCreate*(path: cstring): Module {.importc: "lto_module_create", liblto.} 93 | ## Loads an object file from disk. 94 | ## Returns NULL on error (check lto_get_error_message() for details). 95 | 96 | proc moduleCreateFromMemory*(mem: pointer, length: csize): Module {. 97 | importc: "lto_module_create_from_memory", liblto.} 98 | ## Loads an object file from memory. 99 | ## Returns NULL on error (check lto_get_error_message() for details). 100 | 101 | proc moduleCreateFromMemoryWithPath*(mem: pointer, length: csize, path: cstring): 102 | Module {. 103 | importc: "lto_module_create_from_memory_with_path", liblto.} 104 | ## Loads an object file from memory with an extra path argument. 105 | ## Returns NULL on error (check lto_get_error_message() for details). 106 | 107 | proc moduleCreateFromFD*(fd: cint, path: cstring, fileSize: csize): Module {. 108 | importc: "lto_module_create_from_fd", liblto.} 109 | ## Loads an object file from disk. The seek point of fd is not preserved. 110 | ## Returns NULL on error (check lto_get_error_message() for details). 111 | 112 | proc module_create_from_fd_at_offset*(fd: cint, path: cstring, fileSize: csize, 113 | mapSize: csize, offset: csize): Module {. 114 | importc: "lto_module_create_from_fd_at_offset", liblto.} 115 | ## Loads an object file from disk. The seek point of fd is not preserved. 116 | ## Returns NULL on error (check lto_get_error_message() for details). 117 | 118 | proc moduleDispose*(module: Module) {.importc: "lto_module_dispose", liblto.} 119 | ## Frees all memory internally allocated by the module. 120 | ## Upon return the lto_module_t is no longer valid. 121 | 122 | proc moduleGetTargetTriple*(module: Module): cstring {. 123 | importc: "lto_module_get_target_triple", liblto.} 124 | ## Returns triple string which the object module was compiled under. 125 | 126 | proc moduleSetTargetTriple*(module: Module, triple: cstring) {. 127 | importc: "lto_module_set_target_triple", liblto.} 128 | ## Sets triple string with which the object will be codegened. 129 | 130 | proc moduleGetNumSymbols*(module: Module): cuint {. 131 | importc: "lto_module_get_num_symbols", liblto.} 132 | ## Returns the number of symbols in the object module. 133 | 134 | proc moduleGetSymbolName*(module: Module, index: cuint): cstring {. 135 | importc: "lto_module_get_symbol_name", liblto.} 136 | ## Returns the name of the ith symbol in the object module. 137 | 138 | proc moduleGetSymbolAttribute*(module: Module, index: cuint): SymbolAttributes {. 139 | importc: "lto_module_get_symbol_attribute", liblto.} 140 | ## Returns the attributes of the ith symbol in the object module. 141 | 142 | proc moduleGetNumDeplibs*(module: Module): cuint {. 143 | importc: "lto_module_get_num_deplibs", liblto.} 144 | ## Returns the number of dependent libraries in the object module. 145 | 146 | proc moduleGetDeplib*(module: Module, index: cuint): cstring {. 147 | importc: "lto_module_get_deplib", liblto.} 148 | ## Returns the ith dependent library in the module. 149 | 150 | proc moduleGetNumLinkeropts*(module: Module): cuint {. 151 | importc: "lto_module_get_num_linkeropts", liblto.} 152 | ## Returns the number of linker options in the object module. 153 | 154 | proc moduleGetLinkeropt*(module: Module, index: cuint): cstring {. 155 | importc: "lto_module_get_linkeropt", liblto.} 156 | ## Returns the ith linker option in the module. 157 | 158 | type codegenDiagnosticSeverity* = enum ## Diagnostic severity. 159 | DSError = 0 160 | DSWarning = 1 161 | DSNote = 2 162 | DSRemark = 3 163 | 164 | type 165 | DiagnosticHandler* = proc (severity: codegenDiagnosticSeverity, diag: cstring, 166 | ctxt: pointer) {.cdecl.} 167 | ## Diagnostic handler type. 168 | ## severity defines the severity. 169 | ## diag is the actual diagnostic. 170 | ## The diagnostic is not prefixed by any of severity keyword, e.g., 'error: '. 171 | ## ctxt is used to pass the context set with the diagnostic handler. 172 | 173 | proc codegenSetDiagnosticHandler*(cg: CodeGen, dh: DiagnosticHandler, 174 | ctxt: pointer) {. 175 | importc: "lto_codegen_set_diagnostic_handler", liblto.} 176 | ## Set a diagnostic handler and the related context (void *). 177 | ## This is more general than lto_get_error_message, as the diagnostic handler 178 | ## can be called at anytime within lto. 179 | 180 | proc codegenCreate*: CodeGen {.importc: "lto_codegen_create", liblto.} 181 | ## Instantiates a code generator. 182 | ## Returns NULL on error (check lto_get_error_message() for details). 183 | 184 | proc codegenDispose*(cg: CodeGen) {.importc: "lto_codegen_dispose", liblto.} 185 | ## Frees all code generator and all memory it internally allocated. 186 | ## Upon return the lto_code_gen_t is no longer valid. 187 | 188 | proc codegenAddModule*(cg: CodeGen, module: Module): Bool {. 189 | importc: "lto_codegen_add_module", liblto.} 190 | ## Add an object module to the set of modules for which code will be generated. 191 | ## Returns true on error (check lto_get_error_message() for details). 192 | 193 | proc codegenSetDebugModel*(cg: CodeGen, dm: DebugModel): Bool {. 194 | importc: "lto_codegen_set_debug_model", liblto.} 195 | ## Sets if debug info should be generated. 196 | ## Returns true on error (check lto_get_error_message() for details). 197 | 198 | proc codegenSetPICModel*(cg: CodeGen, cgm: CodegenModel): Bool {. 199 | importc: "lto_codegen_set_pic_model", liblto.} 200 | ## Sets which PIC code model to generated. 201 | ## Returns true on error (check lto_get_error_message() for details). 202 | 203 | proc codegenSetCPU*(cg: CodeGen, cpu: cstring) {.importc: "lto_codegen_set_cpu", 204 | liblto.} 205 | ## Sets the cpu to generate code for. 206 | 207 | proc codegenSetAssemblerPath*(cg: CodeGen, path: cstring) {. 208 | importc: "lto_codegen_set_assembler_path", liblto.} 209 | ## Sets the location of the assembler tool to run. If not set, libLTO 210 | ## will use gcc to invoke the assembler. 211 | 212 | proc codegenSetAssemblerArgs*(cg: CodeGen, args: cstringArray, nArgs: cint) {. 213 | importc: "lto_codegen_set_assembler_args", liblto.} 214 | ## Sets extra arguments that libLTO should pass to the assembler. 215 | 216 | proc codegenAddMustPreserveSymbol*(cg: CodeGen, symbol: cstring) {. 217 | importc: "lto_codegen_add_must_preserve_symbol", liblto.} 218 | ## Adds to a list of all global symbols that must exist in the final generated 219 | ## code. If a function is not listed there, it might be inlined into every usage 220 | ## and optimized away. 221 | 222 | proc codegenWriteMergedModules*(cg: CodeGen, path: cstring): Bool {. 223 | importc: "lto_codegen_write_merged_modules", liblto.} 224 | ## Writes a new object file at the specified path that contains the 225 | ## merged contents of all modules added so far. 226 | ## Returns true on error (check lto_get_error_message() for details). 227 | 228 | proc codegenCompile*(cg: CodeGen, length: ptr csize): pointer {. 229 | importc: "lto_codegen_compile", liblto.} 230 | ## Generates code for all added modules into one native object file. 231 | ## On success returns a pointer to a generated mach-o/ELF buffer and 232 | ## length set to the buffer size. The buffer is owned by the 233 | ## lto_code_gen_t and will be freed when lto_codegen_dispose() 234 | ## is called, or lto_codegen_compile() is called again. 235 | ## On failure, returns NULL (check lto_get_error_message() for details). 236 | 237 | proc codegenCompileToFile*(cg: CodeGen, name: cstring): Bool {. 238 | importc: "lto_codegen_compile_to_file", liblto.} 239 | ## Generates code for all added modules into one native object file. 240 | ## The name of the file is written to name. Returns true on error. 241 | 242 | proc codegenDebugOptions*(cg: CodeGen, opts: cstring) {. 243 | importc: "lto_codegen_debug_options", liblto.} 244 | ## Sets options to help debug codegen bugs. 245 | 246 | proc initializeDisassembler* {.importc: "lto_initialize_disassembler", liblto.} 247 | ## Initializes LLVM disassemblers. 248 | -------------------------------------------------------------------------------- /src/llvm_disassembler.nim: -------------------------------------------------------------------------------- 1 | ## This header provides a public interface to a disassembler library. 2 | ## LLVM provides an implementation of this interface. 3 | 4 | include llvm_lib 5 | 6 | # Disassembler 7 | 8 | type DisasmContextRef* = pointer 9 | ## An opaque reference to a disassembler context. 10 | 11 | type OpInfoCallback* = proc (disInfo: pointer, pc: culonglong, 12 | offset: culonglong, size: culonglong, 13 | tagType: cint, tagBuf: pointer): cint {.cdecl.} 14 | ## The type for the operand information call back function. This is called to 15 | ## get the symbolic information for an operand of an instruction. Typically 16 | ## this is from the relocation information, symbol table, etc. That block of 17 | ## information is saved when the disassembler context is created and passed to 18 | ## the call back in the DisInfo parameter. The instruction containing operand 19 | ## is at the PC parameter. For some instruction sets, there can be more than 20 | ## one operand with symbolic information. To determine the symbolic operand 21 | ## information for each operand, the bytes for the specific operand in the 22 | ## instruction are specified by the Offset parameter and its byte widith is the 23 | ## size parameter. For instructions sets with fixed widths and one symbolic 24 | ## operand per instruction, the Offset parameter will be zero and Size parameter 25 | ## will be the instruction width. The information is returned in TagBuf and is 26 | ## Triple specific with its specific information defined by the value of 27 | ## TagType for that Triple. If symbolic information is returned the function 28 | ## returns 1, otherwise it returns 0. 29 | 30 | type OpInfoSymbol1* = object 31 | ## The initial support in LLVM MC for the most general form of a relocatable 32 | ## expression is "AddSymbol - SubtractSymbol + Offset". For some Darwin targets 33 | ## this full form is encoded in the relocation information so that AddSymbol and 34 | ## SubtractSymbol can be link edited independent of each other. Many other 35 | ## platforms only allow a relocatable expression of the form AddSymbol + Offset 36 | ## to be encoded. 37 | ## 38 | ## The LLVMOpInfoCallback() for the TagType value of 1 uses the struct 39 | ## LLVMOpInfo1. The value of the relocatable expression for the operand, 40 | ## including any PC adjustment, is passed in to the call back in the Value 41 | ## field. The symbolic information about the operand is returned using all 42 | ## the fields of the structure with the Offset of the relocatable expression 43 | ## returned in the Value field. It is possible that some symbols in the 44 | ## relocatable expression were assembly temporary symbols, for example 45 | ## "Ldata - LpicBase + constant", and only the Values of the symbols without 46 | ## symbol names are present in the relocation information. The VariantKind 47 | ## type is one of the Target specific #defines below and is used to print 48 | ## operands like "_foo@GOT", ":lower16:_foo", etc. 49 | present*: culonglong ## 1 if this symbol is present 50 | name*: cstring ## symbol name if not NULL 51 | value*: culonglong ## symbol value if name is NULL 52 | 53 | type OpInfo1* = object 54 | addSymbol*: OpInfoSymbol1 55 | subtractSymbol*: OpInfoSymbol1 56 | value*: culonglong 57 | variantKind*: culonglong 58 | 59 | var 60 | LLVMDisassembler_VariantKind_None* {.importc, header: "".}: cint # all targets 61 | ## The operand VariantKinds for symbolic disassembly. 62 | 63 | LLVMDisassembler_VariantKind_ARM_HI16* {.importc, header: "".}: cint # :upper16: 64 | ## The ARM target VariantKinds. 65 | 66 | LLVMDisassembler_VariantKind_ARM_LO16* {.importc, header: "".}: cint # :lower16: 67 | ## The ARM target VariantKinds. 68 | 69 | LLVMDisassembler_VariantKind_ARM64_PAGE* {.importc, header: "".}: cint # @page 70 | ## The ARM64 target VariantKinds. 71 | 72 | LLVMDisassembler_VariantKind_ARM64_PAGEOFF* {.importc, header: "".}: cint # @pageoff 73 | ## The ARM64 target VariantKinds. 74 | 75 | LLVMDisassembler_VariantKind_ARM64_GOTPAGE* {.importc, header: "".}: cint # @gotpage 76 | ## The ARM64 target VariantKinds. 77 | 78 | LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF* {.importc, header: "".}: cint # @gotpageoff 79 | ## The ARM64 target VariantKinds. 80 | 81 | LLVMDisassembler_VariantKind_ARM64_TLVP* {.importc, header: "".}: cint # @tvlppage 82 | ## The ARM64 target VariantKinds. 83 | 84 | LLVMDisassembler_VariantKind_ARM64_TLVOFF* {.importc, header: "".}: cint # @tvlppageoff 85 | ## The ARM64 target VariantKinds. 86 | 87 | type SymbolLookupCallback* = proc (disInfo: pointer, referenceValue: culonglong, 88 | referenceType: ptr culonglong, 89 | referencePC: culonglong, 90 | referenceName: cstringArray): cstring {.cdecl.} 91 | ## The type for the symbol lookup function. This may be called by the 92 | ## disassembler for things like adding a comment for a PC plus a constant 93 | ## offset load instruction to use a symbol name instead of a load address value. 94 | ## It is passed the block information is saved when the disassembler context is 95 | ## created and the ReferenceValue to look up as a symbol. If no symbol is found 96 | ## for the ReferenceValue NULL is returned. The ReferenceType of the 97 | ## instruction is passed indirectly as is the PC of the instruction in 98 | ## ReferencePC. If the output reference can be determined its type is returned 99 | ## indirectly in ReferenceType along with ReferenceName if any, or that is set 100 | ## to NULL. 101 | 102 | # The reference types on input and output. 103 | 104 | var 105 | LLVMDisassembler_ReferenceType_InOut_None* {.importc, header: "".}: cint 106 | ## No input reference type or no output reference type. 107 | 108 | LLVMDisassembler_ReferenceType_In_Branch* {.importc, header: "".}: cint 109 | ## The input reference is from a branch instruction. 110 | 111 | LLVMDisassembler_ReferenceType_In_PCrel_Load* {.importc, header: "".}: cint 112 | ## The input reference is from a PC relative load instruction. 113 | 114 | LLVMDisassembler_ReferenceType_In_ARM64_ADRP* {.importc, header: "".}: cint 115 | ## The input reference is from an ARM64::ADRP instruction. 116 | 117 | LLVMDisassembler_ReferenceType_In_ARM64_ADDXri* {.importc, header: "".}: cint 118 | ## The input reference is from an ARM64::ADDXri instruction. 119 | 120 | LLVMDisassembler_ReferenceType_In_ARM64_LDRXui* {.importc, header: "".}: cint 121 | ## The input reference is from an ARM64::LDRXui instruction. 122 | 123 | LLVMDisassembler_ReferenceType_In_ARM64_LDRXl* {.importc, header: "".}: cint 124 | ## The input reference is from an ARM64::LDRXl instruction. 125 | 126 | LLVMDisassembler_ReferenceType_In_ARM64_ADR* {.importc, header: "".}: cint 127 | ## The input reference is from an ARM64::ADR instruction. 128 | 129 | LLVMDisassembler_ReferenceType_Out_SymbolStub* {.importc, header: "".}: cint 130 | ## The output reference is to as symbol stub. 131 | 132 | LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr* {.importc, header: "".}: cint 133 | ## The output reference is to a symbol address in a literal pool. 134 | 135 | LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr* {.importc, header: "".}: cint 136 | ## The output reference is to a cstring address in a literal pool. 137 | 138 | LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref* {.importc, header: "".}: cint 139 | ## The output reference is to a Objective-C CoreFoundation string. 140 | 141 | LLVMDisassembler_ReferenceType_Out_Objc_Message* {.importc, header: "".}: cint 142 | ## The output reference is to a Objective-C message. 143 | 144 | LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref* {.importc, header: "".}: cint 145 | ## The output reference is to a Objective-C message ref. 146 | 147 | LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref* {.importc, header: "".}: cint 148 | ## The output reference is to a Objective-C selector ref. 149 | 150 | LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref* {.importc, header: "".}: cint 151 | ## The output reference is to a Objective-C class ref. 152 | 153 | LLVMDisassembler_ReferenceType_DeMangled_Name* {.importc, header: "".}: cint 154 | ## The output reference is to a C++ symbol name. 155 | 156 | proc createDisasm*(tripleName: cstring, disInfo: pointer, tagType: cint, 157 | getOpInfo: OpInfoCallback, symbolLookUp: SymbolLookupCallback): 158 | DisasmContextRef {.importc: "LLVMCreateDisasm", libllvm.} 159 | ## Create a disassembler for the TripleName. Symbolic disassembly is supported 160 | ## by passing a block of information in the DisInfo parameter and specifying the 161 | ## TagType and callback functions as described above. These can all be passed 162 | ## as NULL. If successful, this returns a disassembler context. If not, it 163 | ## returns NULL. This function is equivalent to calling LLVMCreateDisasmCPU() 164 | ## with an empty CPU name. 165 | 166 | proc createDisasmCPU*(triple: cstring, cpu: cstring, disInfo: pointer, 167 | tagType: cint, getOpInfo: OpInfoCallback, 168 | symbolLookUp: SymbolLookupCallback): DisasmContextRef {. 169 | importc: "LLVMCreateDisasmCPU", libllvm.} 170 | ## Create a disassembler for the TripleName and a specific CPU. Symbolic 171 | ## disassembly is supported by passing a block of information in the DisInfo 172 | ## parameter and specifying the TagType and callback functions as described 173 | ## above. These can all be passed * as NULL. If successful, this returns a 174 | ## disassembler context. If not, it returns NULL. 175 | 176 | proc setDisasmOptions*(dc: DisasmContextRef, options: culonglong): cint {. 177 | importc: "LLVMSetDisasmOptions", libllvm.} 178 | ## Set the disassembler's options. Returns 1 if it can set the Options and 0 179 | ## otherwise. 180 | 181 | var 182 | LLVMDisassembler_Option_UseMarkup* {.importc, header: "".}: cint 183 | ## The option to produce marked up assembly. 184 | 185 | LLVMDisassembler_Option_PrintImmHex* {.importc, header: "".}: cint 186 | ## The option to print immediates as hex. 187 | 188 | LLVMDisassembler_Option_AsmPrinterVariant* {.importc, header: "".}: cint 189 | ## The option use the other assembler printer variant 190 | 191 | LLVMDisassembler_Option_SetInstrComments* {.importc, header: "".}: cint 192 | ## The option to set comment on instructions 193 | 194 | LLVMDisassembler_Option_PrintLatency* {.importc, header: "".}: cint 195 | ## The option to print latency information alongside instructions 196 | 197 | proc disasmDispose*(dc: DisasmContextRef) {.importc: "LLVMDisasmDispose", libllvm.} 198 | ## Dispose of a disassembler context. 199 | 200 | proc disasmInstruction*(dc: DisasmContextRef, bytes: ptr cuchar, 201 | bytesSize: culonglong, pc: culonglong, 202 | outString: cstring, outStringSize: csize): csize {. 203 | importc: "LLVMDisasmInstruction", libllvm.} 204 | ## Disassemble a single instruction using the disassembler context specified in 205 | ## the parameter DC. The bytes of the instruction are specified in the 206 | ## parameter Bytes, and contains at least BytesSize number of bytes. The 207 | ## instruction is at the address specified by the PC parameter. If a valid 208 | ## instruction can be disassembled, its string is returned indirectly in 209 | ## OutString whose size is specified in the parameter OutStringSize. This 210 | ## function returns the number of bytes in the instruction or zero if there was 211 | ## no valid instruction. 212 | -------------------------------------------------------------------------------- /src/llvm_core.nim: -------------------------------------------------------------------------------- 1 | ## This module provides an interface to libLLVMCore, which implements 2 | ## the LLVM intermediate representation as well as other related types 3 | ## and utilities. 4 | ## 5 | ## LLVM uses a polymorphic type hierarchy which C cannot represent, therefore 6 | ## parameters must be passed as base types. Despite the declared types, most 7 | ## of the functions provided operate only on branches of the type hierarchy. 8 | ## The declared parameter names are descriptive and specify which type is 9 | ## required. Additionally, each type hierarchy is documented along with the 10 | ## functions that operate upon it. For more detail, refer to LLVM's C++ code. 11 | ## If in doubt, refer to Core.cpp, which performs parameter downcasts in the 12 | ## form unwrap(Param). 13 | ## 14 | ## Many exotic languages can interoperate with C code but have a harder time 15 | ## with C++ due to name mangling. So in addition to C, this interface enables 16 | ## tools written in such languages. 17 | 18 | import llvm_support 19 | export Bool, MemoryBufferRef 20 | 21 | include llvm_lib 22 | 23 | # Opaque types. 24 | type 25 | ContextRef* = ptr object 26 | ## The top-level container for all LLVM global data. See the LLVMContext 27 | ## class. 28 | ModuleRef* = ptr object 29 | ## The top-level container for all other LLVM Intermediate Representation 30 | ## (IR) objects. 31 | TypeRef* = ptr object 32 | ## Each value in the LLVM IR has a type, an LLVMTypeRef. 33 | ValueRef* = ptr object 34 | ## Represents an individual value in LLVM IR. 35 | BasicBlockRef* = ptr object 36 | ## Represents a basic block of instructions in LLVM IR. 37 | BuilderRef* = ptr object 38 | ## Represents an LLVM basic block builder 39 | ModuleProviderRef* = ptr object 40 | ## Interface used to provide a module to JIT or interpreter. 41 | ## This is now just a synonym for llvm::Module, but we have to keep using 42 | ## the different type to keep binary compatibility. 43 | PassManagerRef* = ptr object 44 | PassRegistryRef* = ptr object 45 | UseRef* = ptr object 46 | ## Used to get the users and usees of a Value. 47 | DiagnosticInfoRef* = ptr object 48 | 49 | type 50 | Attribute* = enum 51 | ZExtAttribute = 1 shl 0 52 | SExtAttribute = 1 shl 1 53 | NoReturnAttribute = 1 shl 2 54 | InRegAttribute = 1 shl 3 55 | StructRetAttribute = 1 shl 4 56 | NoUnwindAttribute = 1 shl 5 57 | NoAliasAttribute = 1 shl 6 58 | ByValAttribute = 1 shl 7 59 | NestAttribute = 1 shl 8 60 | ReadNoneAttribute = 1 shl 9 61 | ReadOnlyAttribute = 1 shl 10 62 | NoInlineAttribute = 1 shl 11 63 | AlwaysInlineAttribute = 1 shl 12 64 | OptimizeForSizeAttribute = 1 shl 13 65 | StackProtectAttribute = 1 shl 14 66 | StackProtectReqAttribute = 1 shl 15 67 | Alignment = 31 shl 16 68 | NoCaptureAttribute = 1 shl 21 69 | NoRedZoneAttribute = 1 shl 22 70 | NoImplicitFloatAttribute = 1 shl 23 71 | NakedAttribute = 1 shl 24 72 | InlineHintAttribute = 1 shl 25 73 | StackAlignment = 7 shl 26 74 | ReturnsTwice = 1 shl 29 75 | UWTable = 1 shl 30 76 | NonLazyBind = 1 shl 31 77 | 78 | Opcode* = enum 79 | # Terminator Instructions 80 | Ret = 1 81 | Br = 2 82 | Switch = 3 83 | IndirectBr = 4 84 | Invoke = 5 85 | # removed 6 due to API changes 86 | Unreachable = 7 87 | 88 | # Standard Binary Operators 89 | Add = 8 90 | FAdd = 9 91 | Sub = 10 92 | FSub = 11 93 | Mul = 12 94 | FMul = 13 95 | UDiv = 14 96 | SDiv = 15 97 | FDiv = 16 98 | URem = 17 99 | SRem = 18 100 | FRem = 19 101 | 102 | # Logical Operators 103 | Shl = 20 104 | LShr = 21 105 | AShr = 22 106 | And = 23 107 | Or = 24 108 | Xor = 25 109 | 110 | # Memory Operators 111 | Alloca = 26 112 | Load = 27 113 | Store = 28 114 | GetElementPtr = 29 115 | 116 | # Cast Operators 117 | Trunc = 30 118 | ZExt = 31 119 | SExt = 32 120 | FPToUI = 33 121 | FPToSI = 34 122 | UIToFP = 35 123 | SIToFP = 36 124 | FPTrunc = 37 125 | FPExt = 38 126 | PtrToInt = 39 127 | IntToPtr = 40 128 | BitCast = 41 129 | 130 | # Other Operators 131 | ICmp = 42 132 | FCmp = 43 133 | PHI = 44 134 | Call = 45 135 | Select = 46 136 | UserOp1 = 47 137 | UserOp2 = 48 138 | VAArg = 49 139 | ExtractElement = 50 140 | InsertElement = 51 141 | ShuffleVector = 52 142 | ExtractValue = 53 143 | InsertValue = 54 144 | 145 | # Atomic operators 146 | Fence = 55 147 | AtomicCmpXchg = 56 148 | AtomicRMW = 57 149 | 150 | # Exception Handling Operators 151 | Resume = 58 152 | LandingPad = 59 153 | 154 | # Cast Operators 155 | AddrSpaceCast = 60 156 | 157 | TypeKind* = enum ## Type kind. 158 | VoidTypeKind ## type with no size 159 | HalfTypeKind ## 16 bit floating point type 160 | FloatTypeKind ## 32 bit floating point type 161 | DoubleTypeKind ## 64 bit floating point type 162 | X86_FP80TypeKind ## 80 bit floating point type (X87) 163 | FP128TypeKind ## 128 bit floating point type (112-bit mantissa)*/ 164 | PPC_FP128TypeKind ## 128 bit floating point type (two 64-bits) 165 | LabelTypeKind ## Labels 166 | IntegerTypeKind ## Arbitrary bit width integers 167 | FunctionTypeKind ## Functions 168 | StructTypeKind ## Structures 169 | ArrayTypeKind ## Arrays 170 | PointerTypeKind ## Pointers 171 | VectorTypeKind ## SIMD 'packed' format or other vector type 172 | MetadataTypeKind ## Metadata 173 | X86_MMXTypeKind ## X86 MMX 174 | 175 | Linkage* = enum ## Linkage. 176 | ExternalLinkage ## Externally visible function 177 | AvailableExternallyLinkage ## 178 | LinkOnceAnyLinkage ## Keep one copy of function when linking (inline) 179 | LinkOnceODRLinkage ## Same but only replaced by something equivalent. 180 | LinkOnceODRAutoHideLinkage ## Obsolete 181 | WeakAnyLinkage ## Keep one copy of function when linking (weak) 182 | WeakODRLinkage ## Same but only replaced by something equivalent. 183 | AppendingLinkage ## Special purpose only applies to global arrays 184 | InternalLinkage ## Rename collisions when linking (static functions) 185 | PrivateLinkage ## Like Internal but omit from symbol table 186 | DLLImportLinkage ## Obsolete 187 | DLLExportLinkage ## Obsolete 188 | ExternalWeakLinkage ## ExternalWeak linkage description 189 | GhostLinkage ## Obsolete 190 | CommonLinkage ## Tentative definitions 191 | LinkerPrivateLinkage ## Like Private but linker removes. 192 | LinkerPrivateWeakLinkage ## Like LinkerPrivate but is weak. 193 | 194 | Visibility* = enum ## Visibility. 195 | DefaultVisibility ## The GV is visible 196 | HiddenVisibility ## The GV is hidden 197 | ProtectedVisibility ## The GV is protected 198 | 199 | DLLStorageClass* = enum ## DLL storage class. 200 | DefaultStorageClass = 0 ## 201 | DLLImportStorageClass = 1 ## Function to be imported from DLL. 202 | DLLExportStorageClass = 2 ## Function to be accessible from DLL. 203 | 204 | CallConv* = enum 205 | CCallConv = 0 206 | FastCallConv = 8 207 | ColdCallConv = 9 208 | WebKitJSCallConv = 12 209 | AnyRegCallConv = 13 210 | X86StdcallCallConv = 64 211 | X86FastcallCallConv = 65 212 | 213 | IntPredicate* = enum ## Integer predicate. 214 | IntEQ = 32 ## equal 215 | IntNE ## not equal 216 | IntUGT ## unsigned greater than 217 | IntUGE ## unsigned greater or equal 218 | IntULT ## unsigned less than 219 | IntULE ## unsigned less or equal 220 | IntSGT ## signed greater than 221 | IntSGE ## signed greater or equal 222 | IntSLT ## signed less than 223 | IntSLE ## signed less or equal 224 | 225 | RealPredicate* = enum ## Real predicate. 226 | RealPredicateFalse ## Always false (always folded) 227 | RealOEQ ## True if ordered and equal 228 | RealOGT ## True if ordered and greater than 229 | RealOGE ## True if ordered and greater than or equal 230 | RealOLT ## True if ordered and less than 231 | RealOLE ## True if ordered and less than or equal 232 | RealONE ## True if ordered and operands are unequal 233 | RealORD ## True if ordered (no nans) 234 | RealUNO ## True if unordered: isnan(X) | isnan(Y) 235 | RealUEQ ## True if unordered or equal 236 | RealUGT ## True if unordered or greater than 237 | RealUGE ## True if unordered greater than or equal 238 | RealULT ## True if unordered or less than 239 | RealULE ## True if unordered less than or equal 240 | RealUNE ## True if unordered or not equal 241 | RealPredicateTrue ## Always true (always folded) 242 | 243 | LandingPadClauseTy* = enum ## Landing pad clause type. 244 | LandingPadCatch ## A catch clause 245 | LandingPadFilter ## A filter clause 246 | 247 | ThreadLocalMode* = enum 248 | NotThreadLocal = 0 249 | GeneralDynamicTLSModel 250 | LocalDynamicTLSModel 251 | InitialExecTLSModel 252 | LocalExecTLSModel 253 | 254 | AtomicOrdering* = enum ## Atomic ordering. 255 | AtomicOrderingNotAtomic = 0 ## A load or store which is not atomic 256 | AtomicOrderingUnordered = 1 ## Lowest level of atomicity guarantees 257 | ## somewhat sane results lock free. 258 | AtomicOrderingMonotonic = 2 ## Guarantees that if you take all the 259 | ## operations affecting a specific address 260 | ## a consistent ordering exists 261 | AtomicOrderingAcquire = 4 ## Acquire provides a barrier of the sort 262 | ## necessary to acquire a lock to access other 263 | ## memory with normal loads and stores. 264 | AtomicOrderingRelease = 5 ## Release is similar to Acquire but with 265 | ## a barrier of the sort necessary to 266 | ## release a lock. 267 | AtomicOrderingAcquireRelease = 6 ## Provides both an Acquire and a Release 268 | ## barrier (for fences and operations 269 | ## which both read and write memory). 270 | AtomicOrderingSequentiallyConsistent = 7 ## Provides Acquire semantics for 271 | ## loads and Release semantics for 272 | ## stores. Additionally it guarantees 273 | ## that a total ordering exists 274 | ## between all SequentiallyConsistent 275 | ## operations. 276 | 277 | AtomicRMWBinOp* = enum ## Atomic R/W binary operation. 278 | AtomicRMWBinOpXchg ## Set the new value and return the one old 279 | AtomicRMWBinOpAdd ## Add a value and return the old one 280 | AtomicRMWBinOpSub ## Subtract a value and return the old one 281 | AtomicRMWBinOpAnd ## And a value and return the old one 282 | AtomicRMWBinOpNand ## Not-And a value and return the old one 283 | AtomicRMWBinOpOr ## OR a value and return the old one 284 | AtomicRMWBinOpXor ## Xor a value and return the old one 285 | AtomicRMWBinOpMax ## Sets the value if it's greater than the original 286 | ## using a signed comparison and return the old one 287 | AtomicRMWBinOpMin ## Sets the value if it's Smaller than the original 288 | ## using a signed comparison and return the old one 289 | AtomicRMWBinOpUMax ## Sets the value if it's greater than the original 290 | ## using an unsigned comparison and return the old one 291 | AtomicRMWBinOpUMin ## Sets the value if it's smaller than the original 292 | ## using an unsigned comparison and return the old one 293 | 294 | DiagnosticSeverity* = enum 295 | DSError 296 | DSWarning 297 | DSRemark 298 | DSNote 299 | 300 | proc initializeCore*(r: PassRegistryRef) {.importc: "LLVMInitializeCore", 301 | libllvm.} 302 | 303 | proc shutdown* {.importc: "LLVMShutdown", libllvm.} 304 | ## Deallocate and destroy all ManagedStatic variables. 305 | 306 | # Error handling 307 | proc createMessage*(message: cstring): cstring {.importc: "LLVMCreateMessage", 308 | libllvm.} 309 | 310 | proc disposeMessage*(message: cstring) {.importc: "LLVMDisposeMessage", 311 | libllvm.} 312 | 313 | type FatalErrorHandler* = proc (reason: cstring) {.cdecl.} 314 | 315 | proc installFatalErrorHandler*(handler: FatalErrorHandler) {. 316 | importc: "LLVMInstallFatalErrorHandler", libllvm.} 317 | ## Install a fatal error handler. By default, if LLVM detects a fatal error, 318 | ## it will call exit(1). This may not be appropriate in many contexts. For 319 | ## example, doing exit(1) will bypass many crash reporting/tracing system 320 | ## tools. This function allows you to install a callback that will be invoked 321 | ## prior to the call to exit(1). 322 | 323 | proc resetFatalErrorHandler* {.importc: "LLVMResetFatalErrorHandler", libllvm.} 324 | ## Reset the fatal error handler. This resets LLVM's fatal error handling 325 | ## behavior to the default. 326 | 327 | proc enablePrettyStackTrace* {.importc: "LLVMEnablePrettyStackTrace", libllvm.} 328 | ## Enable LLVM's built-in stack trace code. This intercepts the OS's crash 329 | ## signals and prints which component of LLVM you were in at the time if the 330 | ## crash. 331 | 332 | # Contexts are execution states for the core LLVM IR system. 333 | # 334 | # Most types are tied to a context instance. Multiple contexts can exist 335 | # simultaneously. A single context is not thread safe. However, different 336 | # contexts can execute on different threads simultaneously. 337 | 338 | type 339 | DiagnosticHandler* = proc (di: DiagnosticInfoRef, p: pointer) {.cdecl.} 340 | YieldCallback* = proc (c: ContextRef, p: pointer) {.cdecl.} 341 | 342 | proc contextCreate*: ContextRef {.importc: "LLVMContextCreate", libllvm.} 343 | ## Create a new context. 344 | ## 345 | ## Every call to this function should be paired with a call to 346 | ## LLVMContextDispose() or the context will leak memory. 347 | 348 | proc getGlobalContext*: ContextRef {.importc: "LLVMGetGlobalContext", libllvm.} 349 | ## Obtain the global context instance. 350 | 351 | proc contextSetDiagnosticHandler*(c: ContextRef, handler: DiagnosticHandler, 352 | diagnosticContext: pointer) {. 353 | importc: "LLVMContextSetDiagnosticHandler", 354 | libllvm.} 355 | ## Set the diagnostic handler for this context. 356 | 357 | proc contextSetYieldCallback*(c: ContextRef, callback: YieldCallback, 358 | opaqueHandle: pointer) {. 359 | importc: "LLVMContextSetYieldCallback", libllvm.} 360 | ## Set the yield callback function for this context. 361 | 362 | proc contextDispose*(c: ContextRef) {.importc: "LLVMContextDispose", libllvm.} 363 | ## Destroy a context instance. 364 | ## 365 | ## This should be called for every call to LLVMContextCreate() or memory will 366 | ## be leaked. 367 | 368 | proc getDiagInfoDescription*(di: DiagnosticInfoRef): cstring {. 369 | importc: "LLVMGetDiagInfoDescription", libllvm.} 370 | ## Return a string representation of the DiagnosticInfo. Use LLVMDisposeMessage 371 | ## to free the string. 372 | 373 | proc getDiagInfoSeverity*(di: DiagnosticInfoRef): DiagnosticSeverity {. 374 | importc: "LLVMGetDiagInfoSeverity", libllvm.} 375 | ## Return an enum LLVMDiagnosticSeverity. 376 | 377 | proc getMDKindIDInContex*(c: ContextRef, name: cstring, sLen: cuint): cuint {. 378 | importc: "LLVMGetMDKindIDInContext", libllvm.} 379 | 380 | proc getMDKindID*(name: cstring, sLen: cuint): cuint {. 381 | importc: "LLVMGetMDKindID", libllvm.} 382 | 383 | # Modules represent the top-level structure in an LLVM program. An LLVM module 384 | # is effectively a translation unit or a collection of translation units merged 385 | # together. 386 | 387 | proc moduleCreateWithName*(moduleID: cstring): ModuleRef {. 388 | importc: "LLVMModuleCreateWithName", libllvm.} 389 | ## Create a new, empty module in the global context. 390 | ## 391 | ## This is equivalent to calling LLVMModuleCreateWithNameInContext with 392 | ## LLVMGetGlobalContext() as the context parameter. 393 | ## 394 | ## Every invocation should be paired with LLVMDisposeModule() or memory will 395 | ## be leaked. 396 | 397 | proc moduleCreateWithNameInContext*(moduleID: cstring, c: ContextRef): ModuleRef 398 | {.importc: "LLVMModuleCreateWithNameInContext", libllvm.} 399 | ## Create a new, empty module in a specific context. 400 | ## 401 | ## Every invocation should be paired with LLVMDisposeModule() or memory will 402 | ## be leaked. 403 | 404 | proc disposeModule*(m: ModuleRef) {.importc: "LLVMDisposeModule", libllvm.} 405 | ## Destroy a module instance. 406 | ## 407 | ## This must be called for every created module or memory will be 408 | ## leaked. 409 | 410 | proc getDataLayout*(m: ModuleRef): cstring {.importc: "LLVMGetDataLayout", 411 | libllvm.} 412 | ## Obtain the data layout for a module. 413 | 414 | proc setDataLayout*(m: ModuleRef, triple: cstring) {. 415 | importc: "LLVMSetDataLayout", libllvm.} 416 | ## Set the data layout for a module. 417 | 418 | proc getTarget*(m: ModuleRef): cstring {.importc: "LLVMGetTarget", libllvm.} 419 | ## Obtain the target triple for a module. 420 | 421 | proc setTarget*(m: ModuleRef, triple: cstring) {.importc: "LLVMSetTarget", 422 | libllvm.} 423 | ## Set the target triple for a module. 424 | 425 | proc dumpModule*(m: ModuleRef) {.importc: "LLVMDumpModule", libllvm.} 426 | ## Dump a representation of a module to stderr. 427 | 428 | proc printModuleToFile*(m: ModuleRef, filename: cstring, 429 | errorMessage: ptr cstring): Bool {.importc: "LLVMPrintModuleToFile", libllvm.} 430 | ## Print a representation of a module to a file. The ErrorMessage needs to be 431 | ## disposed with LLVMDisposeMessage. Returns 0 on success, 1 otherwise. 432 | 433 | proc printModuleToString*(m: ModuleRef): cstring {. 434 | importc: "LLVMPrintModuleToString", libllvm.} 435 | ## Return a string representation of the module. Use LLVMDisposeMessage to 436 | ## free the string. 437 | 438 | proc setModuleInlineAsm*(m: ModuleRef, asmStr: cstring) {. 439 | importc: "LLVMSetModuleInlineAsm", libllvm.} 440 | ## Set inline assembly for a module. 441 | 442 | proc getModuleContext*(m: ModuleRef): ContextRef {. 443 | importc: "LLVMGetModuleContext", libllvm.} 444 | ## Obtain the context to which this module is associated. 445 | 446 | proc getTypeByName*(m: ModuleRef, name: cstring): TypeRef {. 447 | importc: "LLVMGetTypeByName", libllvm.} 448 | ## Obtain a Type from a module by its registered name. 449 | 450 | proc getNamedMetadataNumOperands*(m: ModuleRef, name: cstring): cuint {. 451 | importc: "LLVMGetNamedMetadataNumOperands", libllvm.} 452 | ## Obtain the number of operands for named metadata in a module. 453 | 454 | proc getNamedMetadataOperands*(m: ModuleRef, name: cstring, dest: ValueRef) {. 455 | importc: "LLVMGetNamedMetadataOperands", libllvm.} 456 | ## Obtain the named metadata operands for a module. 457 | ## 458 | ## The passed LLVMValueRef pointer should refer to an array of LLVMValueRef at 459 | ## least LLVMGetNamedMetadataNumOperands long. This array will be populated 460 | ## with the LLVMValueRef instances. Each instance corresponds to a llvm::MDNode. 461 | 462 | proc addNamedMetadataOperand*(m: ModuleRef, name: cstring, val: ValueRef) {. 463 | importc: "LLVMAddNamedMetadataOperand", libllvm.} 464 | ## Add an operand to named metadata. 465 | 466 | proc addFunction*(m: ModuleRef, name: cstring, functionType: TypeRef): 467 | ValueRef {.importc: "LLVMAddFunction", libllvm.} 468 | ## Add a function to a module under a specified name. 469 | 470 | proc getNamedFunction*(m: ModuleRef, name: cstring): ValueRef {. 471 | importc: "LLVMGetNamedFunction", libllvm.} 472 | ## Obtain a Function value from a Module by its name. 473 | ## 474 | ## The returned value corresponds to a llvm::Function value. 475 | 476 | proc getFirstFunction*(m: ModuleRef): ValueRef {. 477 | importc: "LLVMGetFirstFunction", libllvm.} 478 | ## Obtain an iterator to the first Function in a Module. 479 | 480 | proc getLastFunction*(m: ModuleRef): ValueRef {.importc: "LLVMGetLastFunction", 481 | libllvm.} 482 | ## Obtain an iterator to the last Function in a Module. 483 | 484 | proc getNextFunction*(fn: ValueRef): ValueRef {.importc: "LLVMGetNextFunction", 485 | libllvm.} 486 | ## Advance a Function iterator to the next Function. 487 | ## 488 | ## Returns NULL if the iterator was already at the end and there are no more 489 | ## functions. 490 | 491 | proc getPreviousFunction*(fn: ValueRef): ValueRef {. 492 | importc: "LLVMGetPreviousFunction", libllvm.} 493 | ## Decrement a Function iterator to the previous Function. 494 | ## 495 | ## Returns NULL if the iterator was already at the beginning and there are no 496 | ## previous functions. 497 | 498 | # Types represent the type of a value. 499 | # 500 | # Types are associated with a context instance. The context internally 501 | # deduplicates types so there is only 1 instance of a specific type alive at a 502 | # time. In other words, a unique type is shared among all consumers within a 503 | # context. 504 | # 505 | # A Type in the C API corresponds to llvm::Type. 506 | # 507 | # Types have the following hierarchy: 508 | # 509 | # types: 510 | # integer type 511 | # real type 512 | # function type 513 | # sequence types: 514 | # array type 515 | # pointer type 516 | # vector type 517 | # void type 518 | # label type 519 | # opaque type 520 | 521 | proc getTypeKind*(ty: TypeRef): TypeKind {.importc: "LLVMGetTypeKind", 522 | libllvm.} 523 | ## Obtain the enumerated type of a Type instance. 524 | 525 | proc typeIsSized*(ty: TypeRef): Bool {.importc: "LLVMTypeIsSized", libllvm.} 526 | ## Whether the type has a known size. 527 | ## 528 | ## Things that don't have a size are abstract types, labels, and void.a 529 | 530 | proc getTypeContext*(ty: TypeRef): ContextRef {. 531 | importc: "LLVMGetTypeContext", libllvm.} 532 | ## Obtain the context to which this type instance is associated. 533 | 534 | proc dumpType*(val: TypeRef) {.importc: "LLVMDumpType", libllvm.} 535 | ## Dump a representation of a type to stderr. 536 | 537 | proc printTypeToString*(val: TypeRef): cstring {. 538 | importc: "LLVMPrintTypeToString", libllvm.} 539 | ## Return a string representation of the type. Use LLVMDisposeMessage to free 540 | ## the string. 541 | 542 | # Functions in this section operate on integer types. 543 | 544 | proc int1TypeInContext*(c: ContextRef): TypeRef {. 545 | importc: "LLVMInt1TypeInContext", libllvm.} 546 | ## Obtain a 1-bit integer type from a context. 547 | 548 | proc int8TypeInContext*(c: ContextRef): TypeRef {. 549 | importc: "LLVMInt8TypeInContext", libllvm.} 550 | ## Obtain a 8-bit integer type from a context. 551 | 552 | proc int16TypeInContext*(c: ContextRef): TypeRef {. 553 | importc: "LLVMInt16TypeInContext", libllvm.} 554 | ## Obtain a 16-bit integer type from a context. 555 | 556 | proc int32TypeInContext*(c: ContextRef): TypeRef {. 557 | importc: "LLVMInt32TypeInContext", libllvm.} 558 | ## Obtain a 32-bit integer type from a context. 559 | 560 | proc int64TypeInContext*(c: ContextRef): TypeRef {. 561 | importc: "LLVMInt64TypeInContext", libllvm.} 562 | ## Obtain a 64-bit integer type from a context. 563 | 564 | proc intTypeInContext*(c: ContextRef, numBits: cuint): TypeRef {. 565 | importc: "LLVMIntTypeInContext", libllvm.} 566 | ## Obtain an integer type from a context with specified bit width. 567 | 568 | proc int1Type*: TypeRef {.importc: "LLVMInt1Type", libllvm.} 569 | ## Obtain a 1-bit integer type from the global context. 570 | 571 | proc int8Type*: TypeRef {.importc: "LLVMInt8Type", libllvm.} 572 | ## Obtain a 8-bit integer type from the global context. 573 | 574 | proc int16Type*: TypeRef {.importc: "LLVMInt16Type", libllvm.} 575 | ## Obtain a 16-bit integer type from the global context. 576 | 577 | proc int32Type*: TypeRef {.importc: "LLVMInt32Type", libllvm.} 578 | ## Obtain a 32-bit integer type from the global context. 579 | 580 | proc int64Type*: TypeRef {.importc: "LLVMInt64Type", libllvm.} 581 | ## Obtain a 64-bit integer type from the global context. 582 | 583 | proc intType*(numBits: cuint): TypeRef {.importc: "LLVMIntType", libllvm.} 584 | ## Obtain an integer type from the global context with a specified bit width. 585 | 586 | proc getIntTypeWidth*(integerType: TypeRef): cuint {. 587 | importc: "LLVMGetIntTypeWidth", libllvm.} 588 | 589 | # Functions in this section operate on Floating Point types. 590 | 591 | proc halfTypeInContext*(c: ContextRef): TypeRef {. 592 | importc: "LLVMHalfTypeInContext", libllvm.} 593 | ## Obtain a 16-bit floating point type from a context. 594 | 595 | proc floatTypeInContext*(c: ContextRef): TypeRef {. 596 | importc: "LLVMFloatTypeInContext", libllvm.} 597 | ## Obtain a 32-bit floating point type from a context. 598 | 599 | proc doubleTypeInContext*(c: ContextRef): TypeRef {. 600 | importc: "LLVMDoubleTypeInContext", libllvm.} 601 | ## Obtain a 64-bit floating point type from a context. 602 | 603 | proc x86FP80TypeInContext*(c: ContextRef): TypeRef {. 604 | importc: "LLVMX86FP80TypeInContext", libllvm.} 605 | ## Obtain a 80-bit floating point type (X87) from a context. 606 | 607 | proc fp128TypeInContext*(c: ContextRef): TypeRef {. 608 | importc: "LLVMFP128TypeInContext", libllvm.} 609 | ## Obtain a 128-bit floating point type (112-bit mantissa) from a context. 610 | 611 | proc ppcFP128TypeInContext*(c: ContextRef): TypeRef {. 612 | importc: "LLVMPPCFP128TypeInContext", libllvm.} 613 | ## Obtain a 128-bit floating point type (two 64-bits) from a context. 614 | 615 | proc halfType*: TypeRef {.importc: "LLVMHalfType", libllvm.} 616 | ## Obtain a 16-bit floating point type from the global context. 617 | 618 | proc floatType*: TypeRef {.importc: "LLVMFloatType", libllvm.} 619 | ## Obtain a 32-bit floating point type from the global context. 620 | 621 | proc doubleType*: TypeRef {.importc: "LLVMDoubleType", libllvm.} 622 | ## Obtain a 64-bit floating point type from the global context. 623 | 624 | proc x86FP80Type*: TypeRef {.importc: "LLVMX86FP80Type", libllvm.} 625 | ## Obtain a 80-bit floating point type from the global context. 626 | 627 | proc fp128Type*: TypeRef {.importc: "LLVMFP128Type", libllvm.} 628 | ## Obtain a 128-bit floating point type from the global context. 629 | 630 | proc ppcFP128Type*: TypeRef {.importc: "LLVMPPCFP128Type", libllvm.} 631 | ## Obtain a 128-bit floating point type from the global context. 632 | 633 | # Function Types 634 | 635 | proc functionType*(returnType: TypeRef, paramTypes: ptr TypeRef, paramCount: cuint, 636 | isVarArg: Bool): TypeRef {.importc: "LLVMFunctionType", 637 | libllvm.} 638 | ## Obtain a function type consisting of a specified signature. 639 | ## 640 | ## The function is defined as a tuple of a return Type, a list of parameter 641 | ## types, and whether the function is variadic. 642 | 643 | proc isFunctionVarArg*(functionType: TypeRef): Bool {. 644 | importc: "LLVMIsFunctionVarArg", libllvm.} 645 | ## Returns whether a function type is variadic. 646 | 647 | proc getReturnType*(functionType: TypeRef): TypeRef {. 648 | importc: "LLVMGetReturnType", libllvm.} 649 | ## Obtain the Type this function Type returns. 650 | 651 | proc countParamTypes*(functionType: TypeRef): cuint {. 652 | importc: "LLVMCountParamTypes", libllvm.} 653 | ## Obtain the number of parameters this function accepts. 654 | 655 | proc getParamTypes*(functionType: TypeRef, dest: ptr TypeRef) {. 656 | importc: "LLVMGetParamTypes", libllvm.} 657 | ## Obtain the types of a function's parameters. 658 | ## 659 | ## The Dest parameter should point to a pre-allocated array of LLVMTypeRef at 660 | ## least LLVMCountParamTypes() large. On return, the first LLVMCountParamTypes() 661 | ## entries in the array will be populated with LLVMTypeRef instances. 662 | 663 | # These functions relate to LLVMTypeRef instances. 664 | 665 | proc structTypeInContext*(c: ContextRef, elementTypes: ptr TypeRef, 666 | elementCount: cuint, packed: Bool): TypeRef {. 667 | importc: "LLVMStructTypeInContext", libllvm.} 668 | ## Create a new structure type in a context. 669 | ## 670 | ## A structure is specified by a list of inner elements/types and whether 671 | ## these can be packed together. 672 | 673 | proc structType*(elementTypes: ptr TypeRef, elementCount: cuint, 674 | packed: Bool): TypeRef {.importc: "LLVMStructType", libllvm.} 675 | ## Create a new structure type in the global context. 676 | 677 | proc structCreateNamed*(c: ContextRef, name: cstring): TypeRef {. 678 | importc: "LLVMStructCreateNamed", libllvm.} 679 | ## Create an empty structure in a context having a specified name. 680 | 681 | proc getStructName*(ty: TypeRef): cstring {.importc: "LLVMGetStructName", 682 | libllvm.} 683 | ## Obtain the name of a structure. 684 | 685 | proc structSetBody*(structType: TypeRef, elementTypes: ptr TypeRef, 686 | elementCount: cuint, packed: Bool) {. 687 | importc: "LLVMStructSetBody", libllvm.} 688 | ## Set the contents of a structure type. 689 | 690 | proc countStructElementTypes*(structType: TypeRef): cuint {. 691 | importc: "LLVMCountStructElementTypes", libllvm.} 692 | ## Get the number of elements defined inside the structure. 693 | 694 | proc getStructElementTypes*(structType: TypeRef, dest: ptr TypeRef) {. 695 | importc: "LLVMGetStructElementTypes", libllvm.} 696 | ## Get the elements within a structure. 697 | ## 698 | ## The function is passed the address of a pre-allocated array of LLVMTypeRef 699 | ## at least LLVMCountStructElementTypes() long. After invocation, this array 700 | ## will be populated with the structure's elements. The objects in the 701 | ## destination array will have a lifetime of the structure type itself, which 702 | ## is the lifetime of the context it is contained in. 703 | 704 | proc isPackedStruct*(structType: TypeRef): Bool {. 705 | importc: "LLVMIsPackedStruct", libllvm.} 706 | ## Determine whether a structure is packed. 707 | 708 | proc isOpaqueStruct*(structType: TypeRef): Bool {. 709 | importc: "LLVMIsOpaqueStruct", libllvm.} 710 | ## Determine whether a structure is opaque. 711 | 712 | # Sequential types represents "arrays" of types. This is a super class for 713 | # array, vector, and pointer types. 714 | 715 | proc getElementType*(ty: TypeRef): TypeRef {.importc: "LLVMGetElementType", 716 | libllvm.} 717 | ## Obtain the type of elements within a sequential type. 718 | ## 719 | ## This works on array, vector, and pointer types. 720 | 721 | proc arrayType*(elementType: TypeRef, elementCount: cuint): TypeRef {. 722 | importc: "LLVMArrayType", libllvm.} 723 | ## Create a fixed size array type that refers to a specific type. 724 | ## 725 | ## The created type will exist in the context that its element type exists in. 726 | 727 | proc getArrayLength*(arrayType: TypeRef): cuint {. 728 | importc: "LLVMGetArrayLength", libllvm.} 729 | ## Obtain the length of an array type. 730 | ## 731 | ## This only works on types that represent arrays. 732 | 733 | proc pointerType*(elementType: TypeRef, addressSpace: cuint): TypeRef {. 734 | importc: "LLVMPointerType", libllvm.} 735 | ## Create a pointer type that points to a defined type. 736 | ## 737 | ## The created type will exist in the context that its pointee type exists in. 738 | 739 | proc getPointerAddressSpace*(pointerType: TypeRef): cuint {. 740 | importc: "LLVMGetPointerAddressSpace", libllvm.} 741 | ## Obtain the address space of a pointer type. 742 | ## 743 | ## This only works on types that represent pointers. 744 | 745 | proc vectorType*(elementType: TypeRef, elementCount: cuint): TypeRef {. 746 | importc: "LLVMVectorType", libllvm.} 747 | ## Create a vector type that contains a defined type and has a specific number 748 | ## of elements. 749 | ## 750 | ## The created type will exist in the context that its element type exists in. 751 | 752 | proc getVectorSize*(vectorType: TypeRef): cuint {.importc: "LLVMGetVectorSize", 753 | libllvm.} 754 | ## Obtain the number of elements in a vector type. 755 | ## 756 | ## This only works on types that represent vectors. 757 | 758 | # Other Types 759 | 760 | proc voidTypeInContext*(c: ContextRef): TypeRef {. 761 | importc: "LLVMVoidTypeInContext", libllvm.} 762 | ## Create a void type in a context. 763 | 764 | proc labelTypeInContext*(c: ContextRef): TypeRef {. 765 | importc: "LLVMLabelTypeInContext", libllvm.} 766 | ## Create a label type in a context. 767 | 768 | proc x86MMXTypeInContext*(c: ContextRef): TypeRef {. 769 | importc: "LLVMX86MMXTypeInContext", libllvm.} 770 | ## Create a X86 MMX type in a context. 771 | 772 | proc voidType*(): TypeRef {.importc: "LLVMVoidType", libllvm.} 773 | ## Create a void type in the global context. 774 | 775 | proc labelType*(): TypeRef {.importc: "LLVMLabelType", libllvm.} 776 | ## Create a label type in the global context. 777 | 778 | proc x86MMXType*(): TypeRef {.importc: "LLVMX86MMXType", libllvm.} 779 | ## Create a X86 MMX type in the global context. 780 | 781 | # The bulk of LLVM's object model consists of values, which comprise a very 782 | # rich type hierarchy. 783 | # 784 | # LLVMValueRef essentially represents llvm::Value. There is a rich 785 | # hierarchy of classes within this type. Depending on the instance 786 | # obtained, not all APIs are available. 787 | # 788 | # Callers can determine the type of an LLVMValueRef by calling the 789 | # LLVMIsA* family of functions (e.g. LLVMIsAArgument()). These 790 | # functions are defined by a macro, so it isn't obvious which are 791 | # available by looking at the Doxygen source code. Instead, look at the 792 | # source definition of LLVM_FOR_EACH_VALUE_SUBCLASS and note the list 793 | # of value names given. These value names also correspond to classes in 794 | # the llvm::Value hierarchy. 795 | 796 | proc isAArgument*(val: ValueRef): ValueRef {.importc: "LLVMIsAArgument", 797 | libllvm.} 798 | 799 | proc isABasicBlock*(val: ValueRef): ValueRef {.importc: "LLVMIsABasicBlock", 800 | libllvm.} 801 | 802 | proc isAInlineAsm*(val: ValueRef): ValueRef {.importc: "LLVMIsAInlineAsm", 803 | libllvm.} 804 | 805 | proc isAMDNode*(val: ValueRef): ValueRef {.importc: "LLVMIsAMDNode", 806 | libllvm.} 807 | 808 | proc isAMDString*(val: ValueRef): ValueRef {.importc: "LLVMIsAMDString", 809 | libllvm.} 810 | 811 | proc isAUser*(val: ValueRef): ValueRef {.importc: "LLVMIsAUser", libllvm.} 812 | 813 | proc isAConstant*(val: ValueRef): ValueRef {.importc: "LLVMIsAConstant", 814 | libllvm.} 815 | 816 | proc isABlockAddress*(val: ValueRef): ValueRef {.importc: "LLVMIsABlockAddress", 817 | libllvm.} 818 | 819 | proc isAConstantAggregateZero*(val: ValueRef): ValueRef {. 820 | importc: "LLVMIsAConstantAggregateZero", libllvm.} 821 | 822 | proc isAConstantArray*(val: ValueRef): ValueRef {. 823 | importc: "LLVMIsAConstantArray", libllvm.} 824 | 825 | proc isAConstantDataSequential*(val: ValueRef): ValueRef {. 826 | importc: "LLVMIsAConstantDataSequential", libllvm.} 827 | 828 | proc isAConstantDataArray*(val: ValueRef): ValueRef {. 829 | importc: "LLVMIsAConstantDataArray", libllvm.} 830 | 831 | proc isAConstantDataVector*(val: ValueRef): ValueRef {. 832 | importc: "LLVMIsAConstantDataVector", libllvm.} 833 | 834 | proc isAConstantExpr*(val: ValueRef): ValueRef {.importc: "LLVMIsAConstantExpr", 835 | libllvm.} 836 | 837 | proc isAConstantFP*(val: ValueRef): ValueRef {.importc: "LLVMIsAConstantFP", 838 | libllvm.} 839 | 840 | proc isAConstantInt*(val: ValueRef): ValueRef {.importc: "LLVMIsAConstantInt", 841 | libllvm.} 842 | 843 | proc isAConstantPointerNull*(val: ValueRef): ValueRef {. 844 | importc: "LLVMIsAConstantPointerNull", libllvm.} 845 | 846 | proc isAConstantStruct*(val: ValueRef): ValueRef {. 847 | importc: "LLVMIsAConstantStruct", libllvm.} 848 | 849 | proc isAConstantVector*(val: ValueRef): ValueRef {. 850 | importc: "LLVMIsAConstantVector", libllvm.} 851 | 852 | proc isAGlobalValue*(val: ValueRef): ValueRef {.importc: "LLVMIsAGlobalValue", 853 | libllvm.} 854 | 855 | proc isAGlobalAlias*(val: ValueRef): ValueRef {.importc: "LLVMIsAGlobalAlias", 856 | libllvm.} 857 | 858 | proc isAGlobalObject*(val: ValueRef): ValueRef {.importc: "LLVMIsAGlobalObject", 859 | libllvm.} 860 | 861 | proc isAFunction*(val: ValueRef): ValueRef {.importc: "LLVMIsAFunction", 862 | libllvm.} 863 | 864 | proc isAGlobalVariable*(val: ValueRef): ValueRef {. 865 | importc: "LLVMIsAGlobalVariable", libllvm.} 866 | 867 | proc isAUndefValue*(val: ValueRef): ValueRef {.importc: "LLVMIsAUndefValue", 868 | libllvm.} 869 | 870 | proc isAInstruction*(val: ValueRef): ValueRef {.importc: "LLVMIsAInstruction", 871 | libllvm.} 872 | 873 | proc isABinaryOperator*(val: ValueRef): ValueRef {. 874 | importc: "LLVMIsABinaryOperator", libllvm.} 875 | 876 | proc isACallInst*(val: ValueRef): ValueRef {.importc: "LLVMIsACallInst", 877 | libllvm.} 878 | 879 | proc isAAIntrinsicInst*(val: ValueRef): ValueRef {. 880 | importc: "LLVMIsAIntrinsicInst", libllvm.} 881 | 882 | proc isADbgInfoIntrinsic*(val: ValueRef): ValueRef {. 883 | importc: "LLVMIsADbgInfoIntrinsic", libllvm.} 884 | 885 | proc isADbgDeclareInst*(val: ValueRef): ValueRef {. 886 | importc: "LLVMIsADbgDeclareInst", libllvm.} 887 | 888 | proc isAMemIntrinsic*(val: ValueRef): ValueRef {.importc: "LLVMIsAMemIntrinsic", 889 | libllvm.} 890 | 891 | proc isAMemCpyInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAMemCpyInst", 892 | libllvm.} 893 | 894 | proc isAMemMoveInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAMemMoveInst", 895 | libllvm.} 896 | 897 | proc isAMemSetInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAMemSetInst", 898 | libllvm.} 899 | 900 | proc isACmpInst*(val: ValueRef): ValueRef {.importc: "LLVMIsACmpInst", 901 | libllvm.} 902 | 903 | proc isAFCmpInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAFCmpInst", 904 | libllvm.} 905 | 906 | proc isAICmpInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAICmpInst", 907 | libllvm.} 908 | 909 | proc isAExtractElementInst*(val: ValueRef): ValueRef {. 910 | importc: "LLVMIsAExtractElementInst", libllvm.} 911 | 912 | proc isAGetElementPtrInst*(val: ValueRef): ValueRef {. 913 | importc: "LLVMIsAGetElementPtrInst", libllvm.} 914 | 915 | proc isAInsertElementInst*(val: ValueRef): ValueRef {. 916 | importc: "LLVMIsAInsertElementInst", libllvm.} 917 | 918 | proc isAInsertValueInst*(val: ValueRef): ValueRef {. 919 | importc: "LLVMIsAInsertValueInst", libllvm.} 920 | 921 | proc isALandingPadInst*(val: ValueRef): ValueRef {. 922 | importc: "LLVMIsALandingPadInst", libllvm.} 923 | 924 | proc isAPHINode*(val: ValueRef): ValueRef {.importc: "LLVMIsAPHINode", 925 | libllvm.} 926 | 927 | proc isASelectInst*(val: ValueRef): ValueRef {.importc: "LLVMIsASelectInst", 928 | libllvm.} 929 | 930 | proc isAShuffleVectorInst*(val: ValueRef): ValueRef {. 931 | importc: "LLVMIsAShuffleVectorInst", libllvm.} 932 | 933 | proc isAStoreInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAStoreInst", 934 | libllvm.} 935 | 936 | proc isATerminatorInst*(val: ValueRef): ValueRef {. 937 | importc: "LLVMIsATerminatorInst", libllvm.} 938 | 939 | proc isABranchInst*(val: ValueRef): ValueRef {.importc: "LLVMIsABranchInst", 940 | libllvm.} 941 | 942 | proc isAIndirectBrInst*(val: ValueRef): ValueRef {. 943 | importc: "LLVMIsAIndirectBrInst", libllvm.} 944 | 945 | proc isAInvokeInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAInvokeInst", 946 | libllvm.} 947 | 948 | proc isAReturnInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAReturnInst", 949 | libllvm.} 950 | 951 | proc isASwitchInst*(val: ValueRef): ValueRef {.importc: "LLVMIsASwitchInst", 952 | libllvm.} 953 | 954 | proc isAUnreachableInst*(val: ValueRef): ValueRef {. 955 | importc: "LLVMIsAUnreachableInst", libllvm.} 956 | 957 | proc isAResumeInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAResumeInst", 958 | libllvm.} 959 | 960 | proc isAUnaryInstruction*(val: ValueRef): ValueRef {. 961 | importc: "LLVMIsAUnaryInstruction", libllvm.} 962 | 963 | proc isAAllocaInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAAllocaInst", 964 | libllvm.} 965 | 966 | proc isACastInst*(val: ValueRef): ValueRef {.importc: "LLVMIsACastInst", 967 | libllvm.} 968 | 969 | proc isAAddrSpaceCastInst*(val: ValueRef): ValueRef {. 970 | importc: "LLVMIsAAddrSpaceCastInst", libllvm.} 971 | 972 | proc isABitCastInst*(val: ValueRef): ValueRef {.importc: "LLVMIsABitCastInst", 973 | libllvm.} 974 | 975 | proc isAFPExtInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAFPExtInst", 976 | libllvm.} 977 | 978 | proc isAFPToSIInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAFPToSIInst", 979 | libllvm.} 980 | 981 | proc isAFPToUIInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAFPToUIInst", 982 | libllvm.} 983 | 984 | proc isAFPTruncInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAFPTruncInst", 985 | libllvm.} 986 | 987 | proc isAIntToPtrInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAIntToPtrInst", 988 | libllvm.} 989 | 990 | proc isAPtrToIntInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAPtrToIntInst", 991 | libllvm.} 992 | 993 | proc isASExtInst*(val: ValueRef): ValueRef {.importc: "LLVMIsASExtInst", 994 | libllvm.} 995 | 996 | proc isASIToFPInst*(val: ValueRef): ValueRef {.importc: "LLVMIsASIToFPInst", 997 | libllvm.} 998 | 999 | proc isATruncInst*(val: ValueRef): ValueRef {.importc: "LLVMIsATruncInst", 1000 | libllvm.} 1001 | 1002 | proc isAUIToFPInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAUIToFPInst", 1003 | libllvm.} 1004 | 1005 | proc isAZExtInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAZExtInst", 1006 | libllvm.} 1007 | 1008 | proc isAExtractValueInst*(val: ValueRef): ValueRef {. 1009 | importc: "LLVMIsAExtractValueInst", libllvm.} 1010 | 1011 | proc isALoadInst*(val: ValueRef): ValueRef {.importc: "LLVMIsALoadInst", 1012 | libllvm.} 1013 | 1014 | proc isAVAArgInst*(val: ValueRef): ValueRef {.importc: "LLVMIsAVAArgInst", 1015 | libllvm.} 1016 | 1017 | # Functions in this section work on all LLVMValueRef instances, 1018 | # regardless of their sub-type. They correspond to functions available 1019 | # on llvm::Value. 1020 | 1021 | proc typeOf*(val: ValueRef): TypeRef {.importc: "LLVMTypeOf", libllvm.} 1022 | ## Obtain the type of a value. 1023 | 1024 | proc getValueName*(val: ValueRef): cstring {.importc: "LLVMGetValueName", 1025 | libllvm.} 1026 | ## Obtain the string name of a value. 1027 | 1028 | proc setValueName*(val: ValueRef, name: cstring) {.importc: "LLVMSetValueName", 1029 | libllvm.} 1030 | ## Set the string name of a value. 1031 | 1032 | proc dumpValue*(val: ValueRef) {.importc: "LLVMDumpValue", libllvm.} 1033 | ## Dump a representation of a value to stderr. 1034 | 1035 | proc printValueToString*(val: ValueRef): cstring {. 1036 | importc: "LLVMPrintValueToString", libllvm.} 1037 | ## Return a string representation of the value. Use LLVMDisposeMessage to free 1038 | ## the string. 1039 | 1040 | proc replaceAllUsesWith*(oldVal: ValueRef, newVal: ValueRef) {. 1041 | importc: "LLVMReplaceAllUsesWith", libllvm.} 1042 | ## Replace all uses of a value with another one. 1043 | 1044 | proc isConstant*(val: ValueRef): Bool {.importc: "LLVMIsConstant", libllvm.} 1045 | ## Determine whether the specified constant instance is constant. 1046 | 1047 | proc isUndef*(val: ValueRef): Bool {.importc: "LLVMIsUndef", libllvm.} 1048 | ## Determine whether a value instance is undefined. 1049 | 1050 | # This module defines functions that allow you to inspect the uses of a 1051 | # LLVMValueRef. 1052 | # 1053 | # It is possible to obtain an LLVMUseRef for any LLVMValueRef instance. 1054 | # Each LLVMUseRef (which corresponds to a llvm::Use instance) holds a 1055 | # llvm::User and llvm::Value. 1056 | 1057 | proc getFirstUse*(val: ValueRef): UseRef {.importc: "LLVMGetFirstUse", libllvm.} 1058 | ## Obtain the first use of a value. 1059 | ## 1060 | ## Uses are obtained in an iterator fashion. First, call this function 1061 | ## to obtain a reference to the first use. Then, call LLVMGetNextUse() 1062 | ## on that instance and all subsequently obtained instances until 1063 | ## LLVMGetNextUse() returns NULL. 1064 | 1065 | proc getNextUse*(u: UseRef): UseRef {.importc: "LLVMGetNextUse", libllvm.} 1066 | ## Obtain the next use of a value. 1067 | ## 1068 | ## This effectively advances the iterator. It returns NULL if you are on 1069 | ## the final use and no more are available. 1070 | 1071 | proc getUser*(u: UseRef): ValueRef {.importc: "LLVMGetUser", libllvm.} 1072 | ## Obtain the user value for a use. 1073 | ## 1074 | ## The returned value corresponds to a llvm::User type. 1075 | 1076 | proc getUsedValue*(u: UseRef): ValueRef {.importc: "LLVMGetUsedValue", libllvm.} 1077 | ## Obtain the value this use corresponds to. 1078 | 1079 | # Function in this group pertain to LLVMValueRef instances that descent 1080 | # from llvm::User. This includes constants, instructions, and 1081 | # operators. 1082 | 1083 | proc getOperand*(val: ValueRef, index: cuint): ValueRef {. 1084 | importc: "LLVMGetOperand", libllvm.} 1085 | ## Obtain an operand at a specific index in a llvm::User value. 1086 | 1087 | proc setOperand*(user: ValueRef, index: cuint, val: ValueRef) {. 1088 | importc: "LLVMSetOperand", libllvm.} 1089 | ## Set an operand at a specific index in a llvm::User value. 1090 | 1091 | proc getNumOperands*(val: ValueRef): cint {.importc: "LLVMGetNumOperands", 1092 | libllvm.} 1093 | ## Obtain the number of operands in a llvm::User value. 1094 | 1095 | # This section contains APIs for interacting with LLVMValueRef that 1096 | # correspond to llvm::Constant instances. 1097 | # 1098 | # These functions will work for any LLVMValueRef in the llvm::Constant 1099 | # class hierarchy. 1100 | 1101 | proc constNull*(ty: TypeRef): ValueRef {.importc: "LLVMConstNull", libllvm.} 1102 | ## Obtain a constant value referring to the null instance of a type. 1103 | 1104 | proc constAllOnes*(ty: TypeRef): ValueRef {.importc: "LLVMConstAllOnes", 1105 | libllvm.} 1106 | ## Obtain a constant value referring to the instance of a type 1107 | ## consisting of all ones. 1108 | ## 1109 | ## This is only valid for integer types. 1110 | 1111 | proc getUndef*(ty: TypeRef): ValueRef {.importc: "LLVMGetUndef", libllvm.} 1112 | ## Obtain a constant value referring to an undefined value of a type. 1113 | 1114 | proc isNull*(val: ValueRef): Bool {.importc: "LLVMIsNull", libllvm.} 1115 | ## Determine whether a value instance is null. 1116 | 1117 | proc constPointerNull*(ty: TypeRef): ValueRef {. 1118 | importc: "LLVMConstPointerNull", libllvm.} 1119 | ## Obtain a constant that is a constant pointer pointing to NULL for a 1120 | ## specified type. 1121 | 1122 | # Functions in this group model LLVMValueRef instances that correspond 1123 | # to constants referring to scalar types. 1124 | # 1125 | # For integer types, the LLVMTypeRef parameter should correspond to a 1126 | # llvm::IntegerType instance and the returned LLVMValueRef will 1127 | # correspond to a llvm::ConstantInt. 1128 | # 1129 | # For floating point types, the LLVMTypeRef returned corresponds to a 1130 | # llvm::ConstantFP. 1131 | 1132 | proc constInt*(intType: TypeRef, n: culonglong, signExtend: Bool): ValueRef {. 1133 | importc: "LLVMConstInt", libllvm.} 1134 | ## Obtain a constant value for an integer type. 1135 | ## 1136 | ## The returned value corresponds to a llvm::ConstantInt. 1137 | 1138 | proc constIntOfArbitraryPrecision*(intType: TypeRef, numWords: cuint, 1139 | words: ptr culonglong): ValueRef {. 1140 | importc: "LLVMConstIntOfArbitraryPrecision", libllvm.} 1141 | ## Obtain a constant value for an integer of arbitrary precision. 1142 | 1143 | proc constIntOfString*(intType: TypeRef, text: cstring, radix: cuchar): ValueRef 1144 | {.importc: "LLVMConstIntOfString", libllvm.} 1145 | ## Obtain a constant value for an integer parsed from a string. 1146 | ## 1147 | ## A similar API, LLVMConstIntOfStringAndSize is also available. If the 1148 | ## string's length is available, it is preferred to call that function 1149 | ## instead. 1150 | 1151 | proc constIntOfStringAndSize*(intType: TypeRef, text: cstring, sLen: cuint, 1152 | radix: cuchar): ValueRef {. 1153 | importc: "LLVMConstIntOfStringAndSize", libllvm.} 1154 | ## Obtain a constant value for an integer parsed from a string with 1155 | ## specified length. 1156 | 1157 | proc constReal*(realType: TypeRef, n: cdouble): ValueRef {. 1158 | importc: "LLVMConstReal", libllvm.} 1159 | ## Obtain a constant value referring to a double floating point value. 1160 | 1161 | proc constRealOfString*(realType: TypeRef, text: cstring): ValueRef {. 1162 | importc: "LLVMConstRealOfString", libllvm.} 1163 | ## Obtain a constant for a floating point value parsed from a string. 1164 | ## 1165 | ## A similar API, LLVMConstRealOfStringAndSize is also available. It 1166 | ## should be used if the input string's length is known. 1167 | 1168 | proc constRealOfStringAndSize*(realType: TypeRef, text: cstring, sLen: cuint): 1169 | ValueRef {. 1170 | importc: "LLVMConstRealOfStringAndSize", libllvm.} 1171 | ## Obtain a constant for a floating point value parsed from a string. 1172 | 1173 | proc constIntGetZExtValue*(constantVal: ValueRef): culonglong {. 1174 | importc: "LLVMConstIntGetZExtValue", libllvm.} 1175 | ## Obtain the zero extended value for an integer constant value. 1176 | 1177 | proc constIntGetSExtValue*(constantVal: ValueRef): clonglong {. 1178 | importc: "LLVMConstIntGetSExtValue", libllvm.} 1179 | ## Obtain the sign extended value for an integer constant value. 1180 | 1181 | # Functions in this group operate on composite constants. 1182 | 1183 | proc constStringInContext*(c: ContextRef, str: cstring, length: cuint, 1184 | dontNullTerminate: Bool): ValueRef {. 1185 | importc: "LLVMConstStringInContext", libllvm.} 1186 | ## Create a ConstantDataSequential and initialize it with a string. 1187 | 1188 | proc constString*(str: cstring, length: cuint, dontNullTerminate: Bool): 1189 | ValueRef {.importc: "LLVMConstString", libllvm.} 1190 | ## Create a ConstantDataSequential with string content in the global context. 1191 | ## 1192 | ## This is the same as LLVMConstStringInContext except it operates on the 1193 | ## global context. 1194 | 1195 | proc constStructInContext*(c: ContextRef, constantVals: ptr ValueRef, 1196 | count: cuint, packed: Bool): ValueRef {. 1197 | importc: "LLVMConstStructInContext", libllvm.} 1198 | ## Create an anonymous ConstantStruct with the specified values. 1199 | 1200 | proc constStruct*(constantVals: ptr ValueRef, count: cuint, packed: Bool): 1201 | ValueRef {.importc: "LLVMConstStruct", libllvm.} 1202 | ## Create a ConstantStruct in the global Context. 1203 | ## 1204 | ## This is the same as LLVMConstStructInContext except it operates on the 1205 | ## global Context. 1206 | 1207 | proc constArray*(elementType: TypeRef, constantVals: ptr ValueRef, 1208 | length: cuint): ValueRef {.importc: "LLVMConstArray", libllvm.} 1209 | ## Create a ConstantArray from values. 1210 | 1211 | proc constNamedStruct*(structType: TypeRef, constantVals: ptr ValueRef, 1212 | count: cuint): ValueRef {. 1213 | importc: "LLVMConstNamedStruct", libllvm.} 1214 | ## Create a non-anonymous ConstantStruct from values. 1215 | 1216 | proc constVector*(scalarConstantVals: ptr ValueRef, size: cuint): ValueRef {. 1217 | importc: "LLVMConstVector", libllvm.} 1218 | ## Create a ConstantVector from values. 1219 | 1220 | # Functions in this group correspond to APIs on llvm::ConstantExpr. 1221 | 1222 | proc getConstOpcode*(constantVal: ValueRef): Opcode {. 1223 | importc: "LLVMGetConstOpcode", libllvm.} 1224 | 1225 | proc alignOf*(ty: TypeRef): ValueRef {.importc: "LLVMAlignOf", libllvm.} 1226 | 1227 | proc sizeOf*(ty: TypeRef): ValueRef {.importc: "LLVMSizeOf", libllvm.} 1228 | 1229 | proc constNeg*(constantVal: ValueRef): ValueRef {.importc: "LLVMConstNeg", 1230 | libllvm.} 1231 | 1232 | proc constNSWNeg*(constantVal: ValueRef): ValueRef {.importc: "LLVMConstNSWNeg", 1233 | libllvm.} 1234 | 1235 | proc constNUWNeg*(constantVal: ValueRef): ValueRef {.importc: "LLVMConstNUWNeg", 1236 | libllvm.} 1237 | 1238 | proc constFNeg*(constantVal: ValueRef): ValueRef {.importc: "LLVMConstFNeg", 1239 | libllvm.} 1240 | 1241 | proc constNot*(constantVal: ValueRef): ValueRef {.importc: "LLVMConstNot", 1242 | libllvm.} 1243 | 1244 | proc constAdd*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1245 | importc: "LLVMConstAdd", libllvm.} 1246 | 1247 | proc ConstNSWAdd*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1248 | importc: "LLVMConstNSWAdd", libllvm.} 1249 | 1250 | proc constNUWAdd*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1251 | importc: "LLVMConstNUWAdd", libllvm.} 1252 | 1253 | proc constFAdd*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1254 | importc: "LLVMConstFAdd", libllvm.} 1255 | 1256 | proc constSub*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1257 | importc: "LLVMConstSub", libllvm.} 1258 | 1259 | proc constNSWSub*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1260 | importc: "LLVMConstNSWSub", libllvm.} 1261 | 1262 | proc constNUWSub*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1263 | importc: "LLVMConstNUWSub", libllvm.} 1264 | 1265 | proc constFSub*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1266 | importc: "LLVMConstFSub", libllvm.} 1267 | 1268 | proc constMul*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1269 | importc: "LLVMConstMul", libllvm.} 1270 | 1271 | proc constNSWMul*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1272 | importc: "LLVMConstNSWMul", libllvm.} 1273 | 1274 | proc constNUWMul*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1275 | importc: "LLVMConstNUWMul", libllvm.} 1276 | 1277 | proc constFMul*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1278 | importc: "LLVMConstFMul", libllvm.} 1279 | 1280 | proc constUDiv*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1281 | importc: "LLVMConstUDiv", libllvm.} 1282 | 1283 | proc constSDiv*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1284 | importc: "LLVMConstSDiv", libllvm.} 1285 | 1286 | proc constExactSDiv*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1287 | importc: "LLVMConstExactSDiv", libllvm.} 1288 | 1289 | proc constFDiv*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1290 | importc: "LLVMConstFDiv", libllvm.} 1291 | 1292 | proc constURem*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1293 | importc: "LLVMConstURem", libllvm.} 1294 | 1295 | proc constSRem*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1296 | importc: "LLVMConstSRem", libllvm.} 1297 | 1298 | proc constFRem*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1299 | importc: "LLVMConstFRem", libllvm.} 1300 | 1301 | proc constAnd*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1302 | importc: "LLVMConstAnd", libllvm.} 1303 | 1304 | proc constOr*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1305 | importc: "LLVMConstOr", libllvm.} 1306 | 1307 | proc constXor*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1308 | importc: "LLVMConstXor", libllvm.} 1309 | 1310 | proc constICmp*(predicate: IntPredicate, lhsConstant: ValueRef, 1311 | rhsConstant: ValueRef): ValueRef {.importc: "LLVMConstICmp", 1312 | libllvm.} 1313 | 1314 | proc constFCmp*(predicate: RealPredicate, lhsConstant: ValueRef, 1315 | rhsConstant: ValueRef): ValueRef {.importc: "LLVMConstFCmp", 1316 | libllvm.} 1317 | 1318 | proc constShl*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1319 | importc: "LLVMConstShl", libllvm.} 1320 | 1321 | proc constLShr*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1322 | importc: "LLVMConstLShr", libllvm.} 1323 | 1324 | proc constAShr*(lhsConstant: ValueRef, rhsConstant: ValueRef): ValueRef {. 1325 | importc: "LLVMConstAShr", libllvm.} 1326 | 1327 | proc constGEP*(constantVal: ValueRef, constantIndices: ptr ValueRef, 1328 | numIndices: cuint): ValueRef {.importc: "LLVMConstGEP", libllvm.} 1329 | 1330 | proc constInBoundsGEP*(constantVal: ValueRef, constantIndices: ptr ValueRef, 1331 | numIndices: cuint): ValueRef {. 1332 | importc: "LLVMConstInBoundsGEP", libllvm.} 1333 | 1334 | proc constTrunc*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1335 | importc: "LLVMConstTrunc", libllvm.} 1336 | 1337 | proc constSExt*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1338 | importc: "LLVMConstSExt", libllvm.} 1339 | 1340 | proc constZExt*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1341 | importc: "LLVMConstZExt", libllvm.} 1342 | 1343 | proc constFPTrunc*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1344 | importc: "LLVMConstFPTrunc", libllvm.} 1345 | 1346 | proc constFPExt*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1347 | importc: "LLVMConstFPExt", libllvm.} 1348 | 1349 | proc constUIToFP*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1350 | importc: "LLVMConstUIToFP", libllvm.} 1351 | 1352 | proc constSIToFP*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1353 | importc: "LLVMConstSIToFP", libllvm.} 1354 | 1355 | proc constFPToUI*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1356 | importc: "LLVMConstFPToUI", libllvm.} 1357 | 1358 | proc constFPToSI*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1359 | importc: "LLVMConstFPToSI", libllvm.} 1360 | 1361 | proc constPtrToInt*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1362 | importc: "LLVMConstPtrToInt", libllvm.} 1363 | 1364 | proc constIntToPtr*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1365 | importc: "LLVMConstIntToPtr", libllvm.} 1366 | 1367 | proc constBitCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1368 | importc: "LLVMConstBitCast", libllvm.} 1369 | 1370 | proc constAddrSpaceCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1371 | importc: "LLVMConstAddrSpaceCast", libllvm.} 1372 | 1373 | proc constZExtOrBitCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1374 | importc: "LLVMConstZExtOrBitCast", libllvm.} 1375 | 1376 | proc constSExtOrBitCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1377 | importc: "LLVMConstSExtOrBitCast", libllvm.} 1378 | 1379 | proc constTruncOrBitCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1380 | importc: "LLVMConstTruncOrBitCast", libllvm.} 1381 | 1382 | proc constPointerCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1383 | importc: "LLVMConstPointerCast", libllvm.} 1384 | 1385 | proc constIntCast*(constantVal: ValueRef, toType: TypeRef, isSigned: Bool): 1386 | ValueRef {.importc: "LLVMConstIntCast", libllvm.} 1387 | 1388 | proc constFPCast*(constantVal: ValueRef, toType: TypeRef): ValueRef {. 1389 | importc: "LLVMConstFPCast", libllvm.} 1390 | 1391 | proc constSelect*(constantCondition: ValueRef, constantIfTrue: ValueRef, 1392 | constantIfFalse: ValueRef): ValueRef {. 1393 | importc: "LLVMConstSelect", libllvm.} 1394 | 1395 | proc constExtractElement*(vectorConstant: ValueRef, indexConstant: ValueRef): 1396 | ValueRef {.importc: "LLVMConstExtractElement", 1397 | libllvm.} 1398 | 1399 | proc constInsertElement*(vectorConstant: ValueRef, 1400 | elementValueConstant: ValueRef, 1401 | indexConstant: ValueRef): ValueRef {. 1402 | importc: "LLVMConstInsertElement", libllvm.} 1403 | 1404 | proc constShuffleVector*(vectorAConstant: ValueRef, vectorBConstant: ValueRef, 1405 | maskConstant: ValueRef): ValueRef {. 1406 | importc: "LLVMConstShuffleVector", libllvm.} 1407 | 1408 | proc constExtractValue*(aggConstant: ValueRef, idxList: ptr cuint, 1409 | numIdx: cuint): ValueRef {. 1410 | importc: "LLVMConstExtractValue", libllvm.} 1411 | 1412 | proc constInsertValue*(aggConstant: ValueRef, elementValueConstant: ValueRef, 1413 | idxList: ptr cuint, numIdx: cuint): ValueRef {. 1414 | importc: "LLVMConstInsertValue", libllvm.} 1415 | 1416 | proc constInlineAsm*(ty: TypeRef, asmString: cstring, constraints: cstring, 1417 | hasSideEffects: Bool, isAlignStack: Bool): ValueRef {. 1418 | importc: "LLVMConstInlineAsm", libllvm.} 1419 | 1420 | proc BlockAddress*(f: ValueRef, bb: BasicBlockRef): ValueRef {. 1421 | importc: "LLVMBlockAddress", libllvm.} 1422 | 1423 | # This group contains functions that operate on global values. Functions in 1424 | # this group relate to functions in the llvm::GlobalValue class tree. 1425 | 1426 | proc getGlobalParent*(global: ValueRef): ModuleRef {. 1427 | importc: "LLVMGetGlobalParent", libllvm.} 1428 | 1429 | proc isDeclaration*(global: ValueRef): Bool {.importc: "LLVMIsDeclaration", 1430 | libllvm.} 1431 | 1432 | proc getLinkage*(global: ValueRef): Linkage {.importc: "LLVMGetLinkage", 1433 | libllvm.} 1434 | 1435 | proc setLinkage*(global: ValueRef, linkage: Linkage) {. 1436 | importc: "LLVMSetLinkage", libllvm.} 1437 | 1438 | proc getSection*(global: ValueRef): cstring {.importc: "LLVMGetSection", 1439 | libllvm.} 1440 | 1441 | proc setSection*(global: ValueRef, section: cstring) {. 1442 | importc: "LLVMSetSection", libllvm.} 1443 | 1444 | proc getVisibility*(global: ValueRef): Visibility {. 1445 | importc: "LLVMGetVisibility", libllvm.} 1446 | 1447 | proc setVisibility*(global: ValueRef, viz: Visibility) {. 1448 | importc: "LLVMSetVisibility", libllvm.} 1449 | 1450 | proc getDLLStorageClass*(global: ValueRef): DLLStorageClass {. 1451 | importc: "LLVMGetDLLStorageClass", libllvm.} 1452 | 1453 | proc setDLLStorageClass*(global: ValueRef, class: DLLStorageClass) {. 1454 | importc: "LLVMSetDLLStorageClass", libllvm.} 1455 | 1456 | proc hasUnnamedAddr*(global: ValueRef): Bool {.importc: "LLVMHasUnnamedAddr", 1457 | libllvm.} 1458 | 1459 | proc setUnnamedAddr*(global: ValueRef, hasUnnamedAddr: Bool) {. 1460 | importc: "LLVMSetUnnamedAddr", libllvm.} 1461 | 1462 | # Functions in this group only apply to values with alignment, i.e. 1463 | # global variables, load and store instructions. 1464 | 1465 | proc getAlignment*(v: ValueRef): cuint {.importc: "LLVMGetAlignment", libllvm.} 1466 | ## Obtain the preferred alignment of the value. 1467 | 1468 | proc setAlignment*(v: ValueRef, bytes: cuint) {.importc: "LLVMSetAlignment", 1469 | libllvm.} 1470 | ## Set the preferred alignment of the value. 1471 | 1472 | # This group contains functions that operate on global variable values. 1473 | 1474 | proc addGlobal*(m: ModuleRef, ty: TypeRef, name: cstring): ValueRef {. 1475 | importc: "LLVMAddGlobal", libllvm.} 1476 | 1477 | proc addGlobalInAddressSpace*(m: ModuleRef, ty: TypeRef, name: cstring, 1478 | addressSpace: cuint): ValueRef {. 1479 | importc: "LLVMAddGlobalInAddressSpace", libllvm.} 1480 | 1481 | proc getNamedGlobal*(m: ModuleRef, name: cstring): ValueRef {. 1482 | importc: "LLVMGetNamedGlobal", libllvm.} 1483 | 1484 | proc getFirstGlobal*(m: ModuleRef): ValueRef {.importc: "LLVMGetFirstGlobal", 1485 | libllvm.} 1486 | 1487 | proc getLastGlobal*(m: ModuleRef): ValueRef {.importc: "LLVMGetLastGlobal", 1488 | libllvm.} 1489 | 1490 | proc getNextGlobal*(globalVar: ValueRef): ValueRef {. 1491 | importc: "LLVMGetNextGlobal", libllvm.} 1492 | 1493 | proc getPreviousGlobal*(globalVar: ValueRef): ValueRef {. 1494 | importc: "LLVMGetPreviousGlobal", libllvm.} 1495 | 1496 | proc deleteGlobal*(globalVar: ValueRef) {.importc: "LLVMDeleteGlobal", libllvm.} 1497 | 1498 | proc getInitializer*(globalVar: ValueRef): ValueRef {. 1499 | importc: "LLVMGetInitializer", libllvm.} 1500 | 1501 | proc setInitializer*(globalVar: ValueRef, constantVal: ValueRef) {. 1502 | importc: "LLVMSetInitializer", libllvm.} 1503 | 1504 | proc isThreadLocal*(globalVar: ValueRef): Bool {.importc: "LLVMIsThreadLocal", 1505 | libllvm.} 1506 | 1507 | proc setThreadLocal*(globalVar: ValueRef, isThreadLocal: Bool) {. 1508 | importc: "LLVMSetThreadLocal", libllvm.} 1509 | 1510 | proc isGlobalConstant*(globalVar: ValueRef): Bool {. 1511 | importc: "LLVMIsGlobalConstant", libllvm.} 1512 | 1513 | proc setGlobalConstant*(globalVar: ValueRef, isConstant: Bool) {. 1514 | importc: "LLVMSetGlobalConstant", libllvm.} 1515 | 1516 | proc getThreadLocalMode*(globalVar: ValueRef): ThreadLocalMode {. 1517 | importc: "LLVMGetThreadLocalMode", libllvm.} 1518 | 1519 | proc setThreadLocalMode*(globalVar: ValueRef, mode: ThreadLocalMode) {. 1520 | importc: "LLVMSetThreadLocalMode", libllvm.} 1521 | 1522 | proc isExternallyInitialized*(globalVar: ValueRef): Bool {. 1523 | importc: "LLVMIsExternallyInitialized", libllvm.} 1524 | 1525 | proc setExternallyInitialized*(globalVar: ValueRef, isExtInit: Bool) {. 1526 | importc: "LLVMSetExternallyInitialized", libllvm.} 1527 | 1528 | # This group contains function that operate on global alias values. 1529 | 1530 | proc addAlias*(m: ModuleRef, ty: TypeRef, aliasee: ValueRef, name: cstring): 1531 | ValueRef {.importc: "LLVMAddAlias", libllvm.} 1532 | 1533 | # Functions in this group operate on LLVMValueRef instances that 1534 | # correspond to llvm::Function instances. 1535 | 1536 | proc deleteFunction*(fn: ValueRef) {.importc: "LLVMDeleteFunction", libllvm.} 1537 | ## Remove a function from its containing module and deletes it. 1538 | 1539 | proc getIntrinsicID*(fn: ValueRef): cuint {.importc: "LLVMGetIntrinsicID", 1540 | libllvm.} 1541 | ## Obtain the ID number from a function instance. 1542 | 1543 | proc getFunctionCallConv*(fn: ValueRef): cuint {. 1544 | importc: "LLVMGetFunctionCallConv", libllvm.} 1545 | ## Obtain the calling function of a function. 1546 | ## 1547 | ## The returned value corresponds to the LLVMCallConv enumeration. 1548 | 1549 | proc setFunctionCallConv*(fn: ValueRef, cc: CallConv) {. 1550 | importc: "LLVMSetFunctionCallConv", libllvm.} 1551 | ## Set the calling convention of a function. 1552 | 1553 | proc getGC*(fn: ValueRef): cstring {.importc: "LLVMGetGC", libllvm.} 1554 | ## Obtain the name of the garbage collector to use during code 1555 | ## generation. 1556 | 1557 | proc setGC*(fn: ValueRef, name: cstring) {.importc: "LLVMSetGC", libllvm.} 1558 | ## Define the garbage collector to use during code generation. 1559 | 1560 | proc addFunctionAttr*(fn: ValueRef, pa: Attribute) {. 1561 | importc: "LLVMAddFunctionAttr", libllvm.} 1562 | ## Add an attribute to a function. 1563 | 1564 | proc addTargetDependentFunctionAttr*(fn: ValueRef, a: cstring, v: cstring) {. 1565 | importc: "LLVMAddTargetDependentFunctionAttr", libllvm.} 1566 | ## Add a target-dependent attribute to a fuction 1567 | 1568 | proc getFunctionAttr*(fn: ValueRef): Attribute {.importc: "LLVMGetFunctionAttr", 1569 | libllvm.} 1570 | ## Obtain an attribute from a function. 1571 | 1572 | proc removeFunctionAttr*(fn: ValueRef, pa: Attribute) {. 1573 | importc: "LLVMRemoveFunctionAttr", libllvm.} 1574 | ## Remove an attribute from a function. 1575 | 1576 | # Functions in this group relate to arguments/parameters on functions. 1577 | # 1578 | # Functions in this group expect LLVMValueRef instances that correspond 1579 | # to llvm::Function instances. 1580 | 1581 | proc countParams*(fn: ValueRef): cuint {.importc: "LLVMCountParams", libllvm.} 1582 | ## Obtain the number of parameters in a function. 1583 | 1584 | proc getParams*(fn: ValueRef, params: ptr ValueRef) {.importc: "LLVMGetParams", 1585 | libllvm.} 1586 | ## Obtain the parameters in a function. 1587 | ## 1588 | ## The takes a pointer to a pre-allocated array of LLVMValueRef that is 1589 | ## at least LLVMCountParams() long. This array will be filled with 1590 | ## LLVMValueRef instances which correspond to the parameters the 1591 | ## function receives. Each LLVMValueRef corresponds to a llvm::Argument 1592 | ## instance. 1593 | 1594 | proc getParam*(fn: ValueRef, index: cuint): ValueRef {.importc: "LLVMGetParam", 1595 | libllvm.} 1596 | ## Obtain the parameter at the specified index. 1597 | ## 1598 | ## Parameters are indexed from 0. 1599 | 1600 | proc getParamParent*(inst: ValueRef): ValueRef {.importc: "LLVMGetParamParent", 1601 | libllvm.} 1602 | ## Obtain the function to which this argument belongs. 1603 | ## 1604 | ## Unlike other functions in this group, this one takes an LLVMValueRef 1605 | ## that corresponds to a llvm::Attribute. 1606 | ## 1607 | ## The returned LLVMValueRef is the llvm::Function to which this 1608 | ## argument belongs. 1609 | 1610 | proc getFirstParam*(fn: ValueRef): ValueRef {.importc: "LLVMGetFirstParam", 1611 | libllvm.} 1612 | ## Obtain the first parameter to a function. 1613 | 1614 | proc getLastParam*(fn: ValueRef): ValueRef {.importc: "LLVMGetLastParam", 1615 | libllvm.} 1616 | ## Obtain the last parameter to a function. 1617 | 1618 | proc getNextParam*(arg: ValueRef): ValueRef {.importc: "LLVMGetNextParam", 1619 | libllvm.} 1620 | ## Obtain the next parameter to a function. 1621 | ## 1622 | ## This takes an LLVMValueRef obtained from LLVMGetFirstParam() (which is 1623 | ## actually a wrapped iterator) and obtains the next parameter from the 1624 | ## underlying iterator. 1625 | 1626 | proc getPreviousParam*(arg: ValueRef): ValueRef {. 1627 | importc: "LLVMGetPreviousParam", libllvm.} 1628 | ## Obtain the previous parameter to a function. 1629 | ## 1630 | ## This is the opposite of LLVMGetNextParam(). 1631 | 1632 | proc addAttribute*(arg: ValueRef, pa: Attribute) {.importc: "LLVMAddAttribute", 1633 | libllvm.} 1634 | ## Add an attribute to a function argument. 1635 | 1636 | proc removeAttribute*(arg: ValueRef, pa: Attribute) {. 1637 | importc: "LLVMRemoveAttribute", libllvm.} 1638 | ## Remove an attribute from a function argument. 1639 | 1640 | proc getAttribute*(arg: ValueRef): Attribute {.importc: "LLVMGetAttribute", 1641 | libllvm.} 1642 | ## Get an attribute from a function argument. 1643 | 1644 | proc setParamAlignment*(arg: ValueRef, align: cuint) {. 1645 | importc: "LLVMSetParamAlignment", libllvm.} 1646 | ## Set the alignment for a function parameter. 1647 | 1648 | # Metadata 1649 | 1650 | proc mdStringInContext*(c: ContextRef, str: cstring, sLen: cuint): ValueRef {. 1651 | importc: "LLVMMDStringInContext", libllvm.} 1652 | ## Obtain a MDString value from a context. 1653 | ## 1654 | ## The returned instance corresponds to the llvm::MDString class. 1655 | ## 1656 | ## The instance is specified by string data of a specified length. The 1657 | ## string content is copied, so the backing memory can be freed after 1658 | ## this function returns. 1659 | 1660 | proc mdString*(str: cstring, sLen: cuint): ValueRef {.importc: "LLVMMDString", 1661 | libllvm.} 1662 | ## Obtain a MDString value from the global context. 1663 | 1664 | proc mdNodeInContext*(c: ContextRef, vals: ptr ValueRef, count: cuint): ValueRef 1665 | {.importc: "LLVMMDNodeInContext", libllvm.} 1666 | ## Obtain a MDNode value from a context. 1667 | ## 1668 | ## The returned value corresponds to the llvm::MDNode class. 1669 | 1670 | proc mdNode*(vals: ptr ValueRef, count: cuint): ValueRef {. 1671 | importc: "LLVMMDNode", libllvm.} 1672 | ## Obtain a MDNode value from the global context. 1673 | 1674 | proc getMDString*(v: ValueRef, len: ptr cuint): cstring {. 1675 | importc: "LLVMGetMDString", libllvm.} 1676 | ## Obtain the underlying string from a MDString value. 1677 | 1678 | proc getMDNodeNumOperands*(v: ValueRef): cuint {. 1679 | importc: "LLVMGetMDNodeNumOperands", libllvm.} 1680 | ## Obtain the number of operands from an MDNode value. 1681 | 1682 | proc getMDNodeOperands*(v: ValueRef, dest: ptr ValueRef) {. 1683 | importc: "LLVMGetMDNodeOperands", libllvm.} 1684 | ## Obtain the given MDNode's operands. 1685 | ## 1686 | ## The passed LLVMValueRef pointer should point to enough memory to hold all of 1687 | ## the operands of the given MDNode (see LLVMGetMDNodeNumOperands) as 1688 | ## LLVMValueRefs. This memory will be populated with the LLVMValueRefs of the 1689 | ## MDNode's operands. 1690 | 1691 | # A basic block represents a single entry single exit section of code. 1692 | # Basic blocks contain a list of instructions which form the body of 1693 | # the block. 1694 | # 1695 | # Basic blocks belong to functions. They have the type of label. 1696 | # 1697 | # Basic blocks are themselves values. However, the C API models them as 1698 | # LLVMBasicBlockRef. 1699 | 1700 | proc basicBlockAsValue*(bb: BasicBlockRef): ValueRef {. 1701 | importc: "LLVMBasicBlockAsValue", libllvm.} 1702 | ## Convert a basic block instance to a value type. 1703 | 1704 | proc valueIsBasicBlock*(val: ValueRef): Bool {.importc: "LLVMValueIsBasicBlock", 1705 | libllvm.} 1706 | ## Determine whether an LLVMValueRef is itself a basic block. 1707 | 1708 | proc valueAsBasicBlock*(val: ValueRef): BasicBlockRef {. 1709 | importc: "LLVMValueAsBasicBlock", libllvm.} 1710 | ## Convert an LLVMValueRef to an LLVMBasicBlockRef instance. 1711 | 1712 | proc getBasicBlockParent*(bb: BasicBlockRef): ValueRef {. 1713 | importc: "LLVMGetBasicBlockParent", libllvm.} 1714 | ## Obtain the function to which a basic block belongs. 1715 | 1716 | proc getBasicBlockTerminator*(bb: BasicBlockRef): ValueRef {. 1717 | importc: "LLVMGetBasicBlockTerminator", libllvm.} 1718 | ## Obtain the terminator instruction for a basic block. 1719 | ## 1720 | ## If the basic block does not have a terminator (it is not well-formed 1721 | ## if it doesn't), then NULL is returned. 1722 | ## 1723 | ## The returned LLVMValueRef corresponds to a llvm::TerminatorInst. 1724 | 1725 | proc countBasicBlocks*(fn: ValueRef): cuint {.importc: "LLVMCountBasicBlocks", 1726 | libllvm.} 1727 | ## Obtain the number of basic blocks in a function. 1728 | 1729 | proc getBasicBlocks*(fn: ValueRef, basicBlocks: ptr BasicBlockRef) {. 1730 | importc: "LLVMGetBasicBlocks", libllvm.} 1731 | ## Obtain all of the basic blocks in a function. 1732 | ## 1733 | ## This operates on a function value. The BasicBlocks parameter is a 1734 | ## pointer to a pre-allocated array of LLVMBasicBlockRef of at least 1735 | ## LLVMCountBasicBlocks() in length. This array is populated with 1736 | ## LLVMBasicBlockRef instances. 1737 | 1738 | proc getFirstBasicBlock*(fn: ValueRef): BasicBlockRef {. 1739 | importc: "LLVMGetFirstBasicBlock", libllvm.} 1740 | ## Obtain the first basic block in a function. 1741 | ## 1742 | ## The returned basic block can be used as an iterator. You will likely 1743 | ## eventually call into LLVMGetNextBasicBlock() with it. 1744 | 1745 | proc getLastBasicBlock*(fn: ValueRef): BasicBlockRef {. 1746 | importc: "LLVMGetLastBasicBlock", libllvm.} 1747 | ## Obtain the last basic block in a function. 1748 | 1749 | proc getNextBasicBlock*(bb: BasicBlockRef): BasicBlockRef {. 1750 | importc: "LLVMGetNextBasicBlock", libllvm.} 1751 | ## Advance a basic block iterator. 1752 | 1753 | proc getPreviousBasicBlock*(bb: BasicBlockRef): BasicBlockRef {. 1754 | importc: "LLVMGetPreviousBasicBlock", libllvm.} 1755 | ## Go backwards in a basic block iterator. 1756 | 1757 | proc getEntryBasicBlock*(fn: ValueRef): BasicBlockRef {. 1758 | importc: "LLVMGetEntryBasicBlock", libllvm.} 1759 | ## Obtain the basic block that corresponds to the entry point of a 1760 | ## function. 1761 | 1762 | proc appendBasicBlockInContext*(c: ContextRef, fn: ValueRef, name: cstring): 1763 | BasicBlockRef {. 1764 | importc: "LLVMAppendBasicBlockInContext", libllvm.} 1765 | ## Append a basic block to the end of a function. 1766 | 1767 | proc appendBasicBlock*(fn: ValueRef, name: cstring): BasicBlockRef {. 1768 | importc: "LLVMAppendBasicBlock", libllvm.} 1769 | ## Append a basic block to the end of a function using the global 1770 | ## context. 1771 | 1772 | proc insertBasicBlockInContext*(c: ContextRef, bb: BasicBlockRef, name: cstring): 1773 | BasicBlockRef {. 1774 | importc: "LLVMInsertBasicBlockInContext", libllvm.} 1775 | ## Insert a basic block in a function before another basic block. 1776 | ## 1777 | ## The function to add to is determined by the function of the 1778 | ## passed basic block. 1779 | 1780 | proc insertBasicBlock*(insertBeforeBB: BasicBlockRef, name: cstring): 1781 | BasicBlockRef {.importc: "LLVMInsertBasicBlock", libllvm.} 1782 | ## Insert a basic block in a function using the global context. 1783 | 1784 | proc deleteBasicBlock*(bb: BasicBlockRef) {.importc: "LLVMDeleteBasicBlock", 1785 | libllvm.} 1786 | ## Remove a basic block from a function and delete it. 1787 | ## 1788 | ## This deletes the basic block from its containing function and deletes 1789 | ## the basic block itself. 1790 | 1791 | proc removeBasicBlockFromParent*(bb: BasicBlockRef) {. 1792 | importc: "LLVMRemoveBasicBlockFromParent", libllvm.} 1793 | ## Remove a basic block from a function. 1794 | ## 1795 | ## This deletes the basic block from its containing function but keep 1796 | ## the basic block alive. 1797 | 1798 | proc moveBasicBlockBefore*(bb: BasicBlockRef, movePos: BasicBlockRef) {. 1799 | importc: "LLVMMoveBasicBlockBefore", libllvm.} 1800 | ## Move a basic block to before another one. 1801 | 1802 | proc moveBasicBlockAfter*(bb: BasicBlockRef, movePos: BasicBlockRef) {. 1803 | importc: "LLVMMoveBasicBlockAfter", libllvm.} 1804 | ## Move a basic block to after another one. 1805 | 1806 | proc getFirstInstruction*(bb: BasicBlockRef): ValueRef {. 1807 | importc: "LLVMGetFirstInstruction", libllvm.} 1808 | ## Obtain the first instruction in a basic block. 1809 | ## 1810 | ## The returned LLVMValueRef corresponds to a llvm::Instruction 1811 | ## instance. 1812 | 1813 | proc GetLastInstruction*(bb: BasicBlockRef): ValueRef {. 1814 | importc: "LLVMGetLastInstruction", libllvm.} 1815 | ## Obtain the last instruction in a basic block. 1816 | ## 1817 | ## The returned LLVMValueRef corresponds to an LLVM:Instruction. 1818 | 1819 | # Functions in this group relate to the inspection and manipulation of 1820 | # individual instructions. 1821 | # 1822 | # In the C++ API, an instruction is modeled by llvm::Instruction. This 1823 | # class has a large number of descendents. llvm::Instruction is a 1824 | # llvm::Value and in the C API, instructions are modeled by 1825 | # LLVMValueRef. 1826 | # 1827 | # This group also contains sub-groups which operate on specific 1828 | # llvm::Instruction types, e.g. llvm::CallInst. 1829 | 1830 | proc hasMetadata*(val: ValueRef): cint {.importc: "LLVMHasMetadata", libllvm.} 1831 | ## Determine whether an instruction has any metadata attached. 1832 | 1833 | proc getMetadata*(val: ValueRef, kindID: cuint): ValueRef {. 1834 | importc: "LLVMGetMetadata", libllvm.} 1835 | ## Return metadata associated with an instruction value. 1836 | 1837 | proc setMetadata*(val: ValueRef, kindID: cuint, node: ValueRef) {. 1838 | importc: "LLVMSetMetadata", libllvm.} 1839 | ## Set metadata associated with an instruction value. 1840 | 1841 | proc getInstructionParent*(inst: ValueRef): BasicBlockRef {. 1842 | importc: "LLVMGetInstructionParent", libllvm.} 1843 | ## Obtain the basic block to which an instruction belongs. 1844 | 1845 | proc getNextInstruction*(inst: ValueRef): ValueRef {. 1846 | importc: "LLVMGetNextInstruction", libllvm.} 1847 | ## Obtain the instruction that occurs after the one specified. 1848 | ## 1849 | ## The next instruction will be from the same basic block. 1850 | ## 1851 | ## If this is the last instruction in a basic block, NULL will be 1852 | ## returned. 1853 | 1854 | proc getPreviousInstruction*(inst: ValueRef): ValueRef {. 1855 | importc: "LLVMGetPreviousInstruction", libllvm.} 1856 | ## Obtain the instruction that occurred before this one. 1857 | ## 1858 | ## If the instruction is the first instruction in a basic block, NULL 1859 | ## will be returned. 1860 | 1861 | proc instructionEraseFromParent*(inst: ValueRef) {. 1862 | importc: "LLVMInstructionEraseFromParent", libllvm.} 1863 | ## Remove and delete an instruction. 1864 | ## 1865 | ## The instruction specified is removed from its containing building 1866 | ## block and then deleted. 1867 | 1868 | proc getInstructionOpcode*(inst: ValueRef): Opcode {. 1869 | importc: "LLVMGetInstructionOpcode", libllvm.} 1870 | ## Obtain the code opcode for an individual instruction. 1871 | 1872 | proc getICmpPredicate*(inst: ValueRef): IntPredicate {. 1873 | importc: "LLVMGetICmpPredicate", libllvm.} 1874 | ## Obtain the predicate of an instruction. 1875 | ## 1876 | ## This is only valid for instructions that correspond to llvm::ICmpInst 1877 | ## or llvm::ConstantExpr whose opcode is llvm::Instruction::ICmp. 1878 | 1879 | # Functions in this group apply to instructions that refer to call 1880 | # sites and invocations. These correspond to C++ types in the 1881 | # llvm::CallInst class tree. 1882 | 1883 | proc setInstructionCallConv*(instr: ValueRef, cc: cuint) {. 1884 | importc: "LLVMSetInstructionCallConv", libllvm.} 1885 | ## Set the calling convention for a call instruction. 1886 | ## 1887 | ## This expects an LLVMValueRef that corresponds to a llvm::CallInst or 1888 | ## llvm::InvokeInst. 1889 | 1890 | proc getInstructionCallConv*(instr: ValueRef): cuint {. 1891 | importc: "LLVMGetInstructionCallConv", libllvm.} 1892 | ## Obtain the calling convention for a call instruction. 1893 | ## 1894 | ## This is the opposite of LLVMSetInstructionCallConv(). Reads its 1895 | ## usage. 1896 | 1897 | proc addInstrAttribute*(instr: ValueRef, index: cuint, attr: Attribute) {. 1898 | importc: "LLVMAddInstrAttribute", libllvm.} 1899 | 1900 | proc removeInstrAttribute*(instr: ValueRef, index: cuint, attr: Attribute) {. 1901 | importc: "LLVMRemoveInstrAttribute", libllvm.} 1902 | 1903 | proc setInstrParamAlignment*(instr: ValueRef, index: cuint, align: cuint) {. 1904 | importc: "LLVMSetInstrParamAlignment", libllvm.} 1905 | 1906 | proc isTailCall*(callInst: ValueRef): Bool {.importc: "LLVMIsTailCall", libllvm.} 1907 | ## Obtain whether a call instruction is a tail call. 1908 | ## 1909 | ## This only works on llvm::CallInst instructions. 1910 | 1911 | proc setTailCall*(callInst: ValueRef, isTailCall: Bool) {. 1912 | importc: "LLVMSetTailCall", libllvm.} 1913 | ## Set whether a call instruction is a tail call. 1914 | ## 1915 | ## This only works on llvm::CallInst instructions. 1916 | 1917 | proc getSwitchDefaultDest*(SwitchInstr: ValueRef): BasicBlockRef {. 1918 | importc: "LLVMGetSwitchDefaultDest", libllvm.} 1919 | ## Obtain the default destination basic block of a switch instruction. 1920 | ## 1921 | ## This only works on llvm::SwitchInst instructions. 1922 | 1923 | # Functions in this group only apply to instructions that map to 1924 | # llvm::PHINode instances. 1925 | 1926 | proc addIncoming*(phiNode: ValueRef, incomingValues: ptr ValueRef, 1927 | incomingBlocks: ptr BasicBlockRef, count: cuint) {. 1928 | importc: "LLVMAddIncoming", libllvm.} 1929 | ## Add an incoming value to the end of a PHI list. 1930 | 1931 | proc countIncoming*(phiNode: ValueRef): cuint {.importc: "LLVMCountIncoming", 1932 | libllvm.} 1933 | ## Obtain the number of incoming basic blocks to a PHI node. 1934 | 1935 | proc getIncomingValue*(phiNode: ValueRef, index: cuint): ValueRef {. 1936 | importc: "LLVMGetIncomingValue", libllvm.} 1937 | ## Obtain an incoming value to a PHI node as an LLVMValueRef. 1938 | 1939 | proc getIncomingBlock*(phiNode: ValueRef, index: cuint): BasicBlockRef {. 1940 | importc: "LLVMGetIncomingBlock", libllvm.} 1941 | ## Obtain an incoming value to a PHI node as an LLVMBasicBlockRef. 1942 | 1943 | # An instruction builder represents a point within a basic block and is 1944 | # the exclusive means of building instructions using the C interface. 1945 | 1946 | proc createBuilderInContext*(c: ContextRef): BuilderRef {. 1947 | importc: "LLVMCreateBuilderInContext", libllvm.} 1948 | 1949 | proc createBuilder*: BuilderRef {.importc: "LLVMCreateBuilder", libllvm.} 1950 | 1951 | proc positionBuilder*(builder: BuilderRef, bb: BasicBlockRef, instr: ValueRef) {. 1952 | importc: "LLVMPositionBuilder", libllvm.} 1953 | 1954 | proc positionBuilderBefore*(builder: BuilderRef, instr: ValueRef) {. 1955 | importc: "LLVMPositionBuilderBefore", libllvm.} 1956 | 1957 | proc positionBuilderAtEnd*(builder: BuilderRef, bb: BasicBlockRef) {. 1958 | importc: "LLVMPositionBuilderAtEnd", libllvm.} 1959 | 1960 | proc getInsertBlock*(builder: BuilderRef): BasicBlockRef {. 1961 | importc: "LLVMGetInsertBlock", libllvm.} 1962 | 1963 | proc clearInsertionPosition*(builder: BuilderRef) {. 1964 | importc: "LLVMClearInsertionPosition", libllvm.} 1965 | 1966 | proc insertIntoBuilder*(builder: BuilderRef, instr: ValueRef) {. 1967 | importc: "LLVMInsertIntoBuilder", libllvm.} 1968 | 1969 | proc insertIntoBuilderWithName*(builder: BuilderRef, instr: ValueRef, 1970 | name: cstring) {. 1971 | importc: "LLVMInsertIntoBuilderWithName", libllvm.} 1972 | 1973 | proc disposeBuilder*(builder: BuilderRef) {.importc: "LLVMDisposeBuilder", 1974 | libllvm.} 1975 | 1976 | # Metadata 1977 | 1978 | proc setCurrentDebugLocation*(builder: BuilderRef, location: ValueRef) {. 1979 | importc: "LLVMSetCurrentDebugLocation", libllvm.} 1980 | 1981 | proc getCurrentDebugLocation*(builder: BuilderRef): ValueRef {. 1982 | importc: "LLVMGetCurrentDebugLocation", libllvm.} 1983 | 1984 | proc setInstDebugLocation*(builder: BuilderRef, inst: ValueRef) {. 1985 | importc: "LLVMSetInstDebugLocation", libllvm.} 1986 | 1987 | # Terminators 1988 | 1989 | proc buildRetVoid*(builder: BuilderRef): ValueRef {.importc: "LLVMBuildRetVoid", 1990 | libllvm.} 1991 | 1992 | proc buildRet*(builder: BuilderRef, v: ValueRef): ValueRef {. 1993 | importc: "LLVMBuildRet", libllvm.} 1994 | 1995 | proc buildAggregateRet*(builder: BuilderRef, retVals: ptr ValueRef, n: cuint): 1996 | ValueRef {.importc: "LLVMBuildAggregateRet", libllvm.} 1997 | 1998 | proc buildBr*(builder: BuilderRef, dest: BasicBlockRef): ValueRef {. 1999 | importc: "LLVMBuildBr", libllvm.} 2000 | 2001 | proc buildCondBr*(builder: BuilderRef, ifCond: ValueRef, then: BasicBlockRef, 2002 | elseBranch: BasicBlockRef): ValueRef {. 2003 | importc: "LLVMBuildCondBr", libllvm.} 2004 | 2005 | proc buildSwitch*(builder: BuilderRef, v: ValueRef, elseBranch: BasicBlockRef, 2006 | numCases: cuint): ValueRef {.importc: "LLVMBuildSwitch", 2007 | libllvm.} 2008 | 2009 | proc buildIndirectBr*(builder: BuilderRef, address: ValueRef, numDests: cuint): 2010 | ValueRef {.importc: "LLVMBuildIndirectBr", libllvm.} 2011 | 2012 | proc buildInvoke*(builder: BuilderRef, fn: ValueRef, args: ptr ValueRef, 2013 | numArgs: cuint, then: BasicBlockRef, catch: BasicBlockRef, 2014 | name: cstring): ValueRef {.importc: "LLVMBuildInvoke", libllvm.} 2015 | 2016 | proc buildLandingPad*(builder: BuilderRef, ty: TypeRef, persFn: ValueRef, 2017 | numClauses: cuint, name: cstring): ValueRef {. 2018 | importc: "LLVMBuildLandingPad", libllvm.} 2019 | 2020 | proc buildResume*(builder: BuilderRef, exn: ValueRef): ValueRef {. 2021 | importc: "LLVMBuildResume", libllvm.} 2022 | 2023 | proc buildUnreachable*(builder: BuilderRef): ValueRef {. 2024 | importc: "LLVMBuildUnreachable", libllvm.} 2025 | 2026 | proc addCase*(switch: ValueRef, onVal: ValueRef, dest: BasicBlockRef) {. 2027 | importc: "LLVMAddCase", libllvm.} 2028 | ## Add a case to the switch instruction 2029 | 2030 | proc addDestination*(indirectBr: ValueRef, dest: BasicBlockRef) {. 2031 | importc: "LLVMAddDestination", libllvm.} 2032 | ## Add a destination to the indirectbr instruction 2033 | 2034 | proc addClause*(landingPad: ValueRef, clauseVal: ValueRef) {. 2035 | importc: "LLVMAddClause", libllvm.} 2036 | ## Add a catch or filter clause to the landingpad instruction 2037 | 2038 | proc setCleanup*(landingPad: ValueRef, val: Bool) {.importc: "LLVMAddClause", 2039 | libllvm.} 2040 | ## Set the 'cleanup' flag in the landingpad instruction 2041 | 2042 | # Arithmetic 2043 | 2044 | proc buildAdd*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2045 | ValueRef {.importc: "LLVMBuildAdd", libllvm.} 2046 | 2047 | proc buildNSWAdd*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2048 | name: cstring): ValueRef {.importc: "LLVMBuildNSWAdd", libllvm.} 2049 | 2050 | proc buildNUWAdd*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2051 | name: cstring): ValueRef {.importc: "LLVMBuildNUWAdd", libllvm.} 2052 | 2053 | proc buildFAdd*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2054 | ValueRef {.importc: "LLVMBuildFAdd", libllvm.} 2055 | 2056 | proc buildSub*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2057 | ValueRef {.importc: "LLVMBuildSub", libllvm.} 2058 | 2059 | proc buildNSWSub*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2060 | name: cstring): ValueRef {.importc: "LLVMBuildNSWSub", libllvm.} 2061 | 2062 | proc buildNUWSub*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2063 | name: cstring): ValueRef {.importc: "LLVMBuildNUWSub", libllvm.} 2064 | 2065 | proc buildFSub*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2066 | ValueRef {.importc: "LLVMBuildFSub", libllvm.} 2067 | 2068 | proc buildMul*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2069 | ValueRef {.importc: "LLVMBuildMul", libllvm.} 2070 | 2071 | proc buildNSWMul*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2072 | name: cstring): ValueRef {.importc: "LLVMBuildNSWMul", libllvm.} 2073 | 2074 | proc buildNUWMul*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2075 | name: cstring): ValueRef {.importc: "LLVMBuildNUWMul", libllvm.} 2076 | 2077 | proc buildFMul*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2078 | ValueRef {.importc: "LLVMBuildFMul", libllvm.} 2079 | 2080 | proc buildUDiv*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2081 | ValueRef {.importc: "LLVMBuildUDiv", libllvm.} 2082 | 2083 | proc buildSDiv*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2084 | ValueRef {.importc: "LLVMBuildSDiv", libllvm.} 2085 | 2086 | proc buildExactSDiv*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2087 | name: cstring): ValueRef {.importc: "LLVMBuildExactSDiv", 2088 | libllvm.} 2089 | 2090 | proc buildFDiv*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2091 | ValueRef {.importc: "LLVMBuildFDiv", libllvm.} 2092 | 2093 | proc buildURem*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2094 | ValueRef {.importc: "LLVMBuildURem", libllvm.} 2095 | 2096 | proc buildSRem*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2097 | ValueRef {.importc: "LLVMBuildSRem", libllvm.} 2098 | 2099 | proc buildFRem*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2100 | ValueRef {.importc: "LLVMBuildFRem", libllvm.} 2101 | 2102 | proc buildShl*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2103 | ValueRef {.importc: "LLVMBuildShl", libllvm.} 2104 | 2105 | proc buildLShr*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2106 | ValueRef {.importc: "LLVMBuildLShr", libllvm.} 2107 | 2108 | proc buildAShr*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2109 | ValueRef {.importc: "LLVMBuildAShr", libllvm.} 2110 | 2111 | proc buildAnd*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2112 | ValueRef {.importc: "LLVMBuildAnd", libllvm.} 2113 | 2114 | proc buildOr*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2115 | ValueRef {.importc: "LLVMBuildOr", libllvm.} 2116 | 2117 | proc buildXor*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, name: cstring): 2118 | ValueRef {.importc: "LLVMBuildXor", libllvm.} 2119 | 2120 | proc buildBinOp*(builder: BuilderRef, op: Opcode, lhs: ValueRef, rhs: ValueRef, 2121 | name: cstring): ValueRef {.importc: "LLVMBuildBinOp", libllvm.} 2122 | 2123 | proc buildNeg*(builder: BuilderRef, v: ValueRef, name: cstring): ValueRef {. 2124 | importc: "LLVMBuildNeg", libllvm.} 2125 | 2126 | proc buildNSWNeg*(builder: BuilderRef, v: ValueRef, name: cstring): ValueRef {. 2127 | importc: "LLVMBuildNSWNeg", libllvm.} 2128 | 2129 | proc buildNUWNeg*(builder: BuilderRef, v: ValueRef, name: cstring): ValueRef {. 2130 | importc: "LLVMBuildNUWNeg", libllvm.} 2131 | 2132 | proc buildFNeg*(builder: BuilderRef, v: ValueRef, name: cstring): ValueRef {. 2133 | importc: "LLVMBuildFNeg", libllvm.} 2134 | 2135 | proc buildNot*(builder: BuilderRef, v: ValueRef, name: cstring): ValueRef {. 2136 | importc: "LLVMBuildNot", libllvm.} 2137 | 2138 | # Memory 2139 | 2140 | proc buildMalloc*(builder: BuilderRef, ty: TypeRef, name: cstring): ValueRef {. 2141 | importc: "LLVMBuildMalloc", libllvm.} 2142 | 2143 | proc buildArrayMalloc*(builder: BuilderRef, ty: TypeRef, val: ValueRef, 2144 | name: cstring): ValueRef {. 2145 | importc: "LLVMBuildArrayMalloc", libllvm.} 2146 | 2147 | proc buildAlloca*(builder: BuilderRef, ty: TypeRef, name: cstring): ValueRef {. 2148 | importc: "LLVMBuildAlloca", libllvm.} 2149 | 2150 | proc buildArrayAlloca*(builder: BuilderRef, ty: TypeRef, val: ValueRef, 2151 | name: cstring): ValueRef {. 2152 | importc: "LLVMBuildArrayAlloca", libllvm.} 2153 | 2154 | proc buildFree*(builder: BuilderRef, pointerVal: ValueRef): ValueRef {. 2155 | importc: "LLVMBuildFree", libllvm.} 2156 | 2157 | proc buildLoad*(builder: BuilderRef, pointerVal: ValueRef, name: cstring): 2158 | ValueRef {.importc: "LLVMBuildLoad", libllvm.} 2159 | 2160 | proc buildStore*(builder: BuilderRef, val: ValueRef, address: ValueRef): 2161 | ValueRef {.importc: "LLVMBuildStore", libllvm.} 2162 | 2163 | proc buildGEP*(builder: BuilderRef, pointer: ValueRef, indices: ptr ValueRef, 2164 | numIndices: cuint, name: cstring): ValueRef {. 2165 | importc: "LLVMBuildGEP", libllvm.} 2166 | 2167 | proc buildInBoundsGEP*(builder: BuilderRef, pointer: ValueRef, 2168 | indices: ptr ValueRef, numIndices: cuint, name: cstring): 2169 | ValueRef {.importc: "LLVMBuildInBoundsGEP", libllvm.} 2170 | 2171 | proc buildStructGEP*(builder: BuilderRef, pointer: ValueRef, idx: cuint, 2172 | name: cstring): ValueRef {.importc: "LLVMBuildStructGEP", 2173 | libllvm.} 2174 | 2175 | proc buildGlobalString*(builder: BuilderRef, str: cstring, name: cstring): 2176 | ValueRef {.importc: "LLVMBuildGlobalString", libllvm.} 2177 | 2178 | proc buildGlobalStringPtr*(builder: BuilderRef, str: cstring, name: cstring): 2179 | ValueRef {.importc: "LLVMBuildGlobalStringPtr", 2180 | libllvm.} 2181 | 2182 | proc getVolatile*(memoryAccessInst: ValueRef): Bool {.importc: "LLVMGetVolatile", 2183 | libllvm.} 2184 | 2185 | proc setVolatile*(memoryAccessInst: ValueRef, isVolatile: Bool) {. 2186 | importc: "LLVMSetVolatile", libllvm.} 2187 | 2188 | # Casts 2189 | 2190 | proc buildTrunc*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2191 | name: cstring): ValueRef {.importc: "LLVMBuildTrunc", libllvm.} 2192 | 2193 | proc buildZExt*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2194 | name: cstring): ValueRef {.importc: "LLVMBuildZExt", libllvm.} 2195 | 2196 | proc buildSExt*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2197 | name: cstring): ValueRef {.importc: "LLVMBuildSExt", libllvm.} 2198 | 2199 | proc buildFPToUI*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2200 | name: cstring): ValueRef {.importc: "LLVMBuildFPToUI", libllvm.} 2201 | 2202 | proc buildFPToSI*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2203 | name: cstring): ValueRef {.importc: "LLVMBuildFPToSI", libllvm.} 2204 | 2205 | proc buildUIToFP*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2206 | name: cstring): ValueRef {.importc: "LLVMBuildUIToFP", libllvm.} 2207 | 2208 | proc buildSIToFP*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2209 | name: cstring): ValueRef {.importc: "LLVMBuildSIToFP", libllvm.} 2210 | 2211 | proc buildFPTrunc*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2212 | name: cstring): ValueRef {.importc: "LLVMBuildFPTrunc", 2213 | libllvm.} 2214 | 2215 | proc buildFPExt*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2216 | name: cstring): ValueRef {.importc: "LLVMBuildFPExt", libllvm.} 2217 | 2218 | proc buildPtrToInt*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2219 | name: cstring): ValueRef {.importc: "LLVMBuildPtrToInt", 2220 | libllvm.} 2221 | 2222 | proc buildIntToPtr*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2223 | name: cstring): ValueRef {.importc: "LLVMBuildIntToPtr", 2224 | libllvm.} 2225 | 2226 | proc buildBitCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2227 | name: cstring): ValueRef {.importc: "LLVMBuildBitCast", 2228 | libllvm.} 2229 | 2230 | proc buildAddrSpaceCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2231 | name: cstring): ValueRef {. 2232 | importc: "LLVMBuildAddrSpaceCast", libllvm.} 2233 | 2234 | proc buildZExtOrBitCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2235 | name: cstring): ValueRef {. 2236 | importc: "LLVMBuildZExtOrBitCast", libllvm.} 2237 | 2238 | proc buildSExtOrBitCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2239 | name: cstring): ValueRef {. 2240 | importc: "LLVMBuildSExtOrBitCast", libllvm.} 2241 | 2242 | proc buildTruncOrBitCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2243 | name: cstring): ValueRef {. 2244 | importc: "LLVMBuildTruncOrBitCast", libllvm.} 2245 | 2246 | proc buildCast*(builder: BuilderRef, op: Opcode, val: ValueRef, destTy: TypeRef, 2247 | name: cstring): ValueRef {.importc: "LLVMBuildCast", libllvm.} 2248 | 2249 | proc buildPointerCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2250 | name: cstring): ValueRef {. 2251 | importc: "LLVMBuildPointerCast", libllvm.} 2252 | 2253 | proc buildIntCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2254 | name: cstring): ValueRef {.importc: "LLVMBuildIntCast", 2255 | libllvm.} 2256 | 2257 | proc buildFPCast*(builder: BuilderRef, val: ValueRef, destTy: TypeRef, 2258 | name: cstring): ValueRef {.importc: "LLVMBuildFPCast", libllvm.} 2259 | 2260 | # Comparisons 2261 | 2262 | proc buildICmp*(builder: BuilderRef, op: IntPredicate, lhs: ValueRef, 2263 | rhs: ValueRef, name: cstring): ValueRef {. 2264 | importc: "LLVMBuildICmp", libllvm.} 2265 | 2266 | proc buildFCmp*(builder: BuilderRef, op: IntPredicate, lhs: ValueRef, 2267 | rhs: ValueRef, name: cstring): ValueRef {. 2268 | importc: "LLVMBuildFCmp", libllvm.} 2269 | 2270 | # Miscellaneous instructions 2271 | 2272 | proc buildPhi*(builder: BuilderRef, ty: TypeRef, name: cstring): ValueRef {. 2273 | importc: "LLVMBuildPhi", libllvm.} 2274 | 2275 | proc buildCall*(builder: BuilderRef, fn: ValueRef, args: ptr ValueRef, 2276 | numArgs: cuint, name: cstring): ValueRef {. 2277 | importc: "LLVMBuildCall", libllvm.} 2278 | 2279 | proc buildSelect*(builder: BuilderRef, ifCond: ValueRef, then: ValueRef, 2280 | elseBranch: ValueRef, name: cstring): ValueRef {. 2281 | importc: "LLVMBuildSelect", libllvm.} 2282 | 2283 | proc buildVAArg*(builder: BuilderRef, list: ValueRef, ty: TypeRef, name: cstring): 2284 | ValueRef {.importc: "LLVMBuildVAArg", libllvm.} 2285 | 2286 | proc buildExtractElement*(builder: BuilderRef, vecVal: ValueRef, index: ValueRef, 2287 | name: cstring): ValueRef {. 2288 | importc: "LLVMBuildExtractElement", libllvm.} 2289 | 2290 | proc buildInsertElement*(builder: BuilderRef, vecVal: ValueRef, eltVal: ValueRef, 2291 | index: ValueRef, name: cstring): ValueRef {. 2292 | importc: "LLVMBuildInsertElement", libllvm.} 2293 | 2294 | proc buildShuffleVector*(builder: BuilderRef, v1: ValueRef, v2: ValueRef, 2295 | mask: ValueRef, name: cstring): ValueRef {. 2296 | importc: "LLVMBuildShuffleVector", libllvm.} 2297 | 2298 | proc buildExtractValue*(builder: BuilderRef, aggVal: ValueRef, index: cuint, 2299 | name: cstring): ValueRef {. 2300 | importc: "LLVMBuildExtractValue", libllvm.} 2301 | 2302 | proc BuildInsertValue*(builder: BuilderRef, aggVal: ValueRef, eltVal: ValueRef, 2303 | index: cuint, name: cstring): ValueRef {. 2304 | importc: "LLVMBuildInsertValue", libllvm.} 2305 | 2306 | proc buildIsNull*(builder: BuilderRef, val: ValueRef, name: cstring): ValueRef {. 2307 | importc: "LLVMBuildIsNull", libllvm.} 2308 | 2309 | proc buildIsNotNull*(builder: BuilderRef, val: ValueRef, name: cstring): 2310 | ValueRef {.importc: "LLVMBuildIsNotNull", libllvm.} 2311 | 2312 | proc buildPtrDiff*(builder: BuilderRef, lhs: ValueRef, rhs: ValueRef, 2313 | name: cstring): ValueRef {.importc: "LLVMBuildPtrDiff", 2314 | libllvm.} 2315 | 2316 | proc buildFence*(builder: BuilderRef, ordering: AtomicOrdering, 2317 | singleThread: Bool, name: cstring): ValueRef {. 2318 | importc: "LLVMBuildFence", libllvm.} 2319 | 2320 | proc buildAtomicRMW*(builder: BuilderRef, op: AtomicRMWBinOp, address: ValueRef, 2321 | val: ValueRef, ordering: AtomicOrdering, singleThread: Bool): 2322 | ValueRef {.importc: "LLVMBuildAtomicRMW", libllvm.} 2323 | 2324 | # Module Providers 2325 | 2326 | proc createModuleProviderForExistingModule*(m: ModuleRef): ModuleProviderRef {. 2327 | importc: "LLVMCreateModuleProviderForExistingModule", libllvm.} 2328 | ## Changes the type of M so it can be passed to FunctionPassManagers and the 2329 | ## JIT. They take ModuleProviders for historical reasons. 2330 | 2331 | proc disposeModuleProvider*(m: ModuleProviderRef) {. 2332 | importc: "LLVMDisposeModuleProvider", libllvm.} 2333 | ## Destroys the module M. 2334 | 2335 | # Memory Buffers 2336 | 2337 | proc createMemoryBufferWithContentsOfFile*(path: cstring, 2338 | outMemBuf: ptr MemoryBufferRef, 2339 | outMessage: cstringArray): Bool {. 2340 | importc: "LLVMCreateMemoryBufferWithContentsOfFile", libllvm.} 2341 | 2342 | proc createMemoryBufferWithSTDIN*(outMemBuf: ptr MemoryBufferRef, 2343 | outMessage: cstringArray): Bool {. 2344 | importc: "LLVMCreateMemoryBufferWithSTDIN", libllvm.} 2345 | 2346 | proc createMemoryBufferWithMemoryRange*(inputData: cstring, 2347 | inputDataLength: csize, 2348 | bufferName: cstring, 2349 | requiresNullTerminator: Bool): 2350 | MemoryBufferRef {. 2351 | importc: "LLVMCreateMemoryBufferWithMemoryRange", libllvm.} 2352 | 2353 | proc createMemoryBufferWithMemoryRangeCopy*(InputData: cstring, 2354 | InputDataLength: csize, 2355 | BufferName: cstring): 2356 | MemoryBufferRef {. 2357 | importc: "LLVMCreateMemoryBufferWithMemoryRangeCopy", libllvm.} 2358 | 2359 | proc getBufferStart*(memBuf: MemoryBufferRef): cstring {. 2360 | importc: "LLVMGetBufferStart", libllvm.} 2361 | 2362 | proc getBufferSize*(memBuf: MemoryBufferRef): csize {. 2363 | importc: "LLVMGetBufferSize", libllvm.} 2364 | 2365 | proc disposeMemoryBuffer*(memBuf: MemoryBufferRef) {. 2366 | importc: "LLVMDisposeMemoryBuffer", libllvm.} 2367 | 2368 | # Pass Registry 2369 | 2370 | proc getGlobalPassRegistry*: PassRegistryRef {. 2371 | importc: "LLVMGetGlobalPassRegistry", libllvm.} 2372 | ## Return the global pass registry, for use with initialization functions. 2373 | 2374 | # Pass Managers 2375 | 2376 | proc createPassManager*: PassManagerRef {.importc: "LLVMCreatePassManager", 2377 | libllvm.} 2378 | ## Constructs a new whole-module pass pipeline. This type of pipeline is 2379 | ## suitable for link-time optimization and whole-module transformations. 2380 | 2381 | proc createFunctionPassManagerForModule*(m: ModuleRef): PassManagerRef {. 2382 | importc: "LLVMCreateFunctionPassManagerForModule", libllvm.} 2383 | ## Constructs a new function-by-function pass pipeline over the module 2384 | ## provider. It does not take ownership of the module provider. This type of 2385 | ## pipeline is suitable for code generation and JIT compilation tasks. 2386 | 2387 | proc createFunctionPassManager*(mp: ModuleProviderRef): PassManagerRef {. 2388 | deprecated, importc: "LLVMCreateFunctionPassManager", libllvm.} 2389 | ## Deprecated: Use LLVMCreateFunctionPassManagerForModule instead. 2390 | 2391 | proc runPassManager*(pm: PassManagerRef, m: ModuleRef): Bool {. 2392 | importc: "LLVMRunPassManager", libllvm.} 2393 | ## Initializes, executes on the provided module, and finalizes all of the 2394 | ## passes scheduled in the pass manager. Returns 1 if any of the passes 2395 | ## modified the module, 0 otherwise. 2396 | 2397 | proc initializeFunctionPassManager*(fpm: PassManagerRef): Bool {. 2398 | importc: "LLVMInitializeFunctionPassManager", libllvm.} 2399 | ## Initializes all of the function passes scheduled in the function pass 2400 | ## manager. Returns 1 if any of the passes modified the module, 0 otherwise. 2401 | 2402 | proc runFunctionPassManager*(fpm: PassManagerRef, f: ValueRef): Bool {. 2403 | importc: "LLVMRunFunctionPassManager", libllvm.} 2404 | ## Executes all of the function passes scheduled in the function pass manager 2405 | ## on the provided function. Returns 1 if any of the passes modified the 2406 | ## function, false otherwise. 2407 | 2408 | proc finalizeFunctionPassManager*(fpm: PassManagerRef): Bool {. 2409 | importc: "LLVMFinalizeFunctionPassManager", libllvm.} 2410 | ## Finalizes all of the function passes scheduled in in the function pass 2411 | ## manager. Returns 1 if any of the passes modified the module, 0 otherwise. 2412 | 2413 | proc disposePassManager*(pm: PassManagerRef) {.importc: "LLVMDisposePassManager", 2414 | libllvm.} 2415 | ## Frees the memory of a pass pipeline. For function pipelines, does not free 2416 | ## the module provider. 2417 | 2418 | # Handle the structures needed to make LLVM safe for multithreading. 2419 | 2420 | proc startMultithreaded*: Bool {.deprecated, importc: "LLVMStartMultithreaded", 2421 | libllvm.} 2422 | ## Deprecated: Multi-threading can only be enabled/disabled with the compile 2423 | ## time define LLVM_ENABLE_THREADS. This function always returns 2424 | ## LLVMIsMultithreaded(). 2425 | 2426 | proc stopMultithreaded* {.deprecated, importc: "LLVMStopMultithreaded", libllvm.} 2427 | ## Deprecated: Multi-threading can only be enabled/disabled with the compile 2428 | ## time define LLVM_ENABLE_THREADS. 2429 | 2430 | proc isMultithreaded*: Bool {.importc: "LLVMIsMultithreaded", libllvm.} 2431 | ## Check whether LLVM is executing in thread-safe mode or not. 2432 | --------------------------------------------------------------------------------