1 #===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
3 # The LLVM Compiler Infrastructure
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
8 #===------------------------------------------------------------------------===#
10 from .common import LLVMObject
11 from .common import c_object_p
12 from .common import get_library
14 from . import enumerations
16 from ctypes import POINTER
17 from ctypes import byref
18 from ctypes import c_char_p
19 from ctypes import c_uint
38 class LLVMEnumeration(object):
39 """Represents an individual LLVM enumeration."""
41 def __init__(self, name, value):
46 return '%s.%s' % (self.__class__.__name__,
50 def from_value(cls, value):
51 """Obtain an enumeration instance from a numeric value."""
52 result = cls._value_map.get(value, None)
55 raise ValueError('Unknown %s: %d' % (cls.__name__,
61 def register(cls, name, value):
62 """Registers a new enumeration.
64 This is called by this module for each enumeration defined in
65 enumerations. You should not need to call this outside this module.
67 if value in cls._value_map:
68 raise ValueError('%s value already registered: %d' % (cls.__name__,
70 enum = cls(name, value)
71 cls._value_map[value] = enum
72 setattr(cls, name, enum)
73 #print cls, name, value
75 class Attribute(LLVMEnumeration):
76 """Represents an individual Attribute enumeration."""
80 def __init__(self, name, value):
81 super(Attribute, self).__init__(name, value)
83 class OpCode(LLVMEnumeration):
84 """Represents an individual OpCode enumeration."""
88 def __init__(self, name, value):
89 super(OpCode, self).__init__(name, value)
91 class TypeKind(LLVMEnumeration):
92 """Represents an individual TypeKind enumeration."""
96 def __init__(self, name, value):
97 super(TypeKind, self).__init__(name, value)
99 class Linkage(LLVMEnumeration):
100 """Represents an individual Linkage enumeration."""
104 def __init__(self, name, value):
105 super(Linkage, self).__init__(name, value)
107 class Visibility(LLVMEnumeration):
108 """Represents an individual visibility enumeration."""
112 def __init__(self, name, value):
113 super(Visibility, self).__init__(name, value)
115 class CallConv(LLVMEnumeration):
116 """Represents an individual calling convention enumeration."""
120 def __init__(self, name, value):
121 super(CallConv, self).__init__(name, value)
123 class IntPredicate(LLVMEnumeration):
124 """Represents an individual IntPredicate enumeration."""
128 def __init__(self, name, value):
129 super(IntPredicate, self).__init__(name, value)
131 class RealPredicate(LLVMEnumeration):
132 """Represents an individual RealPredicate enumeration."""
136 def __init__(self, name, value):
137 super(RealPredicate, self).__init__(name, value)
139 class LandingPadClauseTy(LLVMEnumeration):
140 """Represents an individual LandingPadClauseTy enumeration."""
144 def __init__(self, name, value):
145 super(LandingPadClauseTy, self).__init__(name, value)
147 class MemoryBuffer(LLVMObject):
148 """Represents an opaque memory buffer."""
150 def __init__(self, filename=None):
151 """Create a new memory buffer.
153 Currently, we support creating from the contents of a file at the
157 raise Exception("filename argument must be defined")
159 memory = c_object_p()
162 result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
163 byref(memory), byref(out))
166 raise Exception("Could not create memory buffer: %s" % out.value)
168 LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
171 return lib.LLVMGetBufferSize(self)
173 class Value(LLVMObject):
175 def __init__(self, value):
176 LLVMObject.__init__(self, value)
180 return lib.LLVMGetValueName(self)
183 lib.LLVMDumpValue(self)
185 def get_operand(self, i):
186 return Value(lib.LLVMGetOperand(self, i))
188 def set_operand(self, i, v):
189 return lib.LLVMSetOperand(self, i, v)
192 return lib.LLVMGetNumOperands(self)
194 class Module(LLVMObject):
195 """Represents the top-level structure of an llvm program in an opaque object."""
197 def __init__(self, module, name=None, context=None):
198 LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
201 def CreateWithName(cls, module_id):
202 m = Module(lib.LLVMModuleCreateWithName(module_id))
203 c = Context.GetGlobalContext().take_ownership(m)
207 def datalayout(self):
208 return lib.LLVMGetDataLayout(self)
211 def datalayout(self, new_data_layout):
212 """new_data_layout is a string."""
213 lib.LLVMSetDataLayout(self, new_data_layout)
217 return lib.LLVMGetTarget(self)
220 def target(self, new_target):
221 """new_target is a string."""
222 lib.LLVMSetTarget(self, new_target)
225 lib.LLVMDumpModule(self)
227 class __function_iterator(object):
228 def __init__(self, module, reverse=False):
230 self.reverse = reverse
232 self.function = self.module.last
234 self.function = self.module.first
240 if not isinstance(self.function, Function):
241 raise StopIteration("")
242 result = self.function
244 self.function = self.function.prev
246 self.function = self.function.next
250 return Module.__function_iterator(self)
252 def __reversed__(self):
253 return Module.__function_iterator(self, reverse=True)
257 return Function(lib.LLVMGetFirstFunction(self))
261 return Function(lib.LLVMGetLastFunction(self))
263 def print_module_to_file(self, filename):
265 # Result is inverted so 0 means everything was ok.
266 result = lib.LLVMPrintModuleToFile(self, filename, byref(out))
268 raise RuntimeError("LLVM Error: %s" % out.value)
270 class Function(Value):
272 def __init__(self, value):
273 Value.__init__(self, value)
277 f = lib.LLVMGetNextFunction(self)
278 return f and Function(f)
282 f = lib.LLVMGetPreviousFunction(self)
283 return f and Function(f)
287 b = lib.LLVMGetFirstBasicBlock(self)
288 return b and BasicBlock(b)
292 b = lib.LLVMGetLastBasicBlock(self)
293 return b and BasicBlock(b)
295 class __bb_iterator(object):
296 def __init__(self, function, reverse=False):
297 self.function = function
298 self.reverse = reverse
300 self.bb = function.last
302 self.bb = function.first
308 if not isinstance(self.bb, BasicBlock):
309 raise StopIteration("")
312 self.bb = self.bb.prev
314 self.bb = self.bb.next
318 return Function.__bb_iterator(self)
320 def __reversed__(self):
321 return Function.__bb_iterator(self, reverse=True)
324 return lib.LLVMCountBasicBlocks(self)
326 class BasicBlock(LLVMObject):
328 def __init__(self, value):
329 LLVMObject.__init__(self, value)
333 b = lib.LLVMGetNextBasicBlock(self)
334 return b and BasicBlock(b)
338 b = lib.LLVMGetPreviousBasicBlock(self)
339 return b and BasicBlock(b)
343 i = lib.LLVMGetFirstInstruction(self)
344 return i and Instruction(i)
348 i = lib.LLVMGetLastInstruction(self)
349 return i and Instruction(i)
351 def __as_value(self):
352 return Value(lib.LLVMBasicBlockAsValue(self))
356 return lib.LLVMGetValueName(self.__as_value())
359 lib.LLVMDumpValue(self.__as_value())
361 def get_operand(self, i):
362 return Value(lib.LLVMGetOperand(self.__as_value(),
365 def set_operand(self, i, v):
366 return lib.LLVMSetOperand(self.__as_value(),
370 return lib.LLVMGetNumOperands(self.__as_value())
372 class __inst_iterator(object):
373 def __init__(self, bb, reverse=False):
375 self.reverse = reverse
377 self.inst = self.bb.last
379 self.inst = self.bb.first
385 if not isinstance(self.inst, Instruction):
386 raise StopIteration("")
389 self.inst = self.inst.prev
391 self.inst = self.inst.next
395 return BasicBlock.__inst_iterator(self)
397 def __reversed__(self):
398 return BasicBlock.__inst_iterator(self, reverse=True)
401 class Instruction(Value):
403 def __init__(self, value):
404 Value.__init__(self, value)
408 i = lib.LLVMGetNextInstruction(self)
409 return i and Instruction(i)
413 i = lib.LLVMGetPreviousInstruction(self)
414 return i and Instruction(i)
418 return OpCode.from_value(lib.LLVMGetInstructionOpcode(self))
420 class Context(LLVMObject):
422 def __init__(self, context=None):
424 context = lib.LLVMContextCreate()
425 LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
427 LLVMObject.__init__(self, context)
430 def GetGlobalContext(cls):
431 return Context(lib.LLVMGetGlobalContext())
433 class PassRegistry(LLVMObject):
434 """Represents an opaque pass registry object."""
437 LLVMObject.__init__(self,
438 lib.LLVMGetGlobalPassRegistry())
440 def register_library(library):
441 # Initialization/Shutdown declarations.
442 library.LLVMInitializeCore.argtypes = [PassRegistry]
443 library.LLVMInitializeCore.restype = None
445 library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
446 library.LLVMInitializeTransformUtils.restype = None
448 library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
449 library.LLVMInitializeScalarOpts.restype = None
451 library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
452 library.LLVMInitializeObjCARCOpts.restype = None
454 library.LLVMInitializeVectorization.argtypes = [PassRegistry]
455 library.LLVMInitializeVectorization.restype = None
457 library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
458 library.LLVMInitializeInstCombine.restype = None
460 library.LLVMInitializeIPO.argtypes = [PassRegistry]
461 library.LLVMInitializeIPO.restype = None
463 library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
464 library.LLVMInitializeInstrumentation.restype = None
466 library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
467 library.LLVMInitializeAnalysis.restype = None
469 library.LLVMInitializeIPA.argtypes = [PassRegistry]
470 library.LLVMInitializeIPA.restype = None
472 library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
473 library.LLVMInitializeCodeGen.restype = None
475 library.LLVMInitializeTarget.argtypes = [PassRegistry]
476 library.LLVMInitializeTarget.restype = None
478 library.LLVMShutdown.argtypes = []
479 library.LLVMShutdown.restype = None
481 # Pass Registry declarations.
482 library.LLVMGetGlobalPassRegistry.argtypes = []
483 library.LLVMGetGlobalPassRegistry.restype = c_object_p
485 # Context declarations.
486 library.LLVMContextCreate.argtypes = []
487 library.LLVMContextCreate.restype = c_object_p
489 library.LLVMContextDispose.argtypes = [Context]
490 library.LLVMContextDispose.restype = None
492 library.LLVMGetGlobalContext.argtypes = []
493 library.LLVMGetGlobalContext.restype = c_object_p
495 # Memory buffer declarations
496 library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
497 POINTER(c_object_p), POINTER(c_char_p)]
498 library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
500 library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
502 library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
504 # Module declarations
505 library.LLVMModuleCreateWithName.argtypes = [c_char_p]
506 library.LLVMModuleCreateWithName.restype = c_object_p
508 library.LLVMDisposeModule.argtypes = [Module]
509 library.LLVMDisposeModule.restype = None
511 library.LLVMGetDataLayout.argtypes = [Module]
512 library.LLVMGetDataLayout.restype = c_char_p
514 library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
515 library.LLVMSetDataLayout.restype = None
517 library.LLVMGetTarget.argtypes = [Module]
518 library.LLVMGetTarget.restype = c_char_p
520 library.LLVMSetTarget.argtypes = [Module, c_char_p]
521 library.LLVMSetTarget.restype = None
523 library.LLVMDumpModule.argtypes = [Module]
524 library.LLVMDumpModule.restype = None
526 library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
528 library.LLVMPrintModuleToFile.restype = bool
530 library.LLVMGetFirstFunction.argtypes = [Module]
531 library.LLVMGetFirstFunction.restype = c_object_p
533 library.LLVMGetLastFunction.argtypes = [Module]
534 library.LLVMGetLastFunction.restype = c_object_p
536 library.LLVMGetNextFunction.argtypes = [Function]
537 library.LLVMGetNextFunction.restype = c_object_p
539 library.LLVMGetPreviousFunction.argtypes = [Function]
540 library.LLVMGetPreviousFunction.restype = c_object_p
542 # Value declarations.
543 library.LLVMGetValueName.argtypes = [Value]
544 library.LLVMGetValueName.restype = c_char_p
546 library.LLVMDumpValue.argtypes = [Value]
547 library.LLVMDumpValue.restype = None
549 library.LLVMGetOperand.argtypes = [Value, c_uint]
550 library.LLVMGetOperand.restype = c_object_p
552 library.LLVMSetOperand.argtypes = [Value, Value, c_uint]
553 library.LLVMSetOperand.restype = None
555 library.LLVMGetNumOperands.argtypes = [Value]
556 library.LLVMGetNumOperands.restype = c_uint
558 # Basic Block Declarations.
559 library.LLVMGetFirstBasicBlock.argtypes = [Function]
560 library.LLVMGetFirstBasicBlock.restype = c_object_p
562 library.LLVMGetLastBasicBlock.argtypes = [Function]
563 library.LLVMGetLastBasicBlock.restype = c_object_p
565 library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
566 library.LLVMGetNextBasicBlock.restype = c_object_p
568 library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
569 library.LLVMGetPreviousBasicBlock.restype = c_object_p
571 library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
572 library.LLVMGetFirstInstruction.restype = c_object_p
574 library.LLVMGetLastInstruction.argtypes = [BasicBlock]
575 library.LLVMGetLastInstruction.restype = c_object_p
577 library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
578 library.LLVMBasicBlockAsValue.restype = c_object_p
580 library.LLVMCountBasicBlocks.argtypes = [Function]
581 library.LLVMCountBasicBlocks.restype = c_uint
583 # Instruction Declarations.
584 library.LLVMGetNextInstruction.argtypes = [Instruction]
585 library.LLVMGetNextInstruction.restype = c_object_p
587 library.LLVMGetPreviousInstruction.argtypes = [Instruction]
588 library.LLVMGetPreviousInstruction.restype = c_object_p
590 library.LLVMGetInstructionOpcode.argtypes = [Instruction]
591 library.LLVMGetInstructionOpcode.restype = c_uint
593 def register_enumerations():
597 (Attribute, enumerations.Attributes),
598 (OpCode, enumerations.OpCodes),
599 (TypeKind, enumerations.TypeKinds),
600 (Linkage, enumerations.Linkages),
601 (Visibility, enumerations.Visibility),
602 (CallConv, enumerations.CallConv),
603 (IntPredicate, enumerations.IntPredicate),
604 (RealPredicate, enumerations.RealPredicate),
605 (LandingPadClauseTy, enumerations.LandingPadClauseTy),
608 for enum_class, enum_spec in enums:
609 for name, value in enum_spec:
611 enum_class.register(name, value)
614 def initialize_llvm():
615 c = Context.GetGlobalContext()
617 lib.LLVMInitializeCore(p)
618 lib.LLVMInitializeTransformUtils(p)
619 lib.LLVMInitializeScalarOpts(p)
620 lib.LLVMInitializeObjCARCOpts(p)
621 lib.LLVMInitializeVectorization(p)
622 lib.LLVMInitializeInstCombine(p)
623 lib.LLVMInitializeIPO(p)
624 lib.LLVMInitializeInstrumentation(p)
625 lib.LLVMInitializeAnalysis(p)
626 lib.LLVMInitializeIPA(p)
627 lib.LLVMInitializeCodeGen(p)
628 lib.LLVMInitializeTarget(p)
630 register_library(lib)
631 Enums = register_enumerations()