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
37 """Represents an individual OpCode enumeration."""
41 def __init__(self, name, value):
46 return 'OpCode.%s' % self.name
49 def from_value(value):
50 """Obtain an OpCode instance from a numeric value."""
51 result = OpCode._value_map.get(value, None)
54 raise ValueError('Unknown OpCode: %d' % value)
59 def register(name, value):
60 """Registers a new OpCode enumeration.
62 This is called by this module for each enumeration defined in
63 enumerations. You should not need to call this outside this module.
65 if value in OpCode._value_map:
66 raise ValueError('OpCode value already registered: %d' % value)
68 opcode = OpCode(name, value)
69 OpCode._value_map[value] = opcode
70 setattr(OpCode, name, opcode)
72 class MemoryBuffer(LLVMObject):
73 """Represents an opaque memory buffer."""
75 def __init__(self, filename=None):
76 """Create a new memory buffer.
78 Currently, we support creating from the contents of a file at the
82 raise Exception("filename argument must be defined")
87 result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
88 byref(memory), byref(out))
91 raise Exception("Could not create memory buffer: %s" % out.value)
93 LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
96 return lib.LLVMGetBufferSize(self)
98 class Value(LLVMObject):
100 def __init__(self, value):
101 LLVMObject.__init__(self, value)
105 return lib.LLVMGetValueName(self)
108 lib.LLVMDumpValue(self)
110 def get_operand(self, i):
111 return Value(lib.LLVMGetOperand(self, i))
113 def set_operand(self, i, v):
114 return lib.LLVMSetOperand(self, i, v)
117 return lib.LLVMGetNumOperands(self)
119 class Module(LLVMObject):
120 """Represents the top-level structure of an llvm program in an opaque object."""
122 def __init__(self, module, name=None, context=None):
123 LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
126 def CreateWithName(cls, module_id):
127 m = Module(lib.LLVMModuleCreateWithName(module_id))
128 c = Context.GetGlobalContext().take_ownership(m)
132 def datalayout(self):
133 return lib.LLVMGetDataLayout(self)
136 def datalayout(self, new_data_layout):
137 """new_data_layout is a string."""
138 lib.LLVMSetDataLayout(self, new_data_layout)
142 return lib.LLVMGetTarget(self)
145 def target(self, new_target):
146 """new_target is a string."""
147 lib.LLVMSetTarget(self, new_target)
150 lib.LLVMDumpModule(self)
152 class __function_iterator(object):
153 def __init__(self, module, reverse=False):
155 self.reverse = reverse
157 self.function = self.module.last
159 self.function = self.module.first
165 if not isinstance(self.function, Function):
166 raise StopIteration("")
167 result = self.function
169 self.function = self.function.prev
171 self.function = self.function.next
175 return Module.__function_iterator(self)
177 def __reversed__(self):
178 return Module.__function_iterator(self, reverse=True)
182 return Function(lib.LLVMGetFirstFunction(self))
186 return Function(lib.LLVMGetLastFunction(self))
188 def print_module_to_file(self, filename):
190 # Result is inverted so 0 means everything was ok.
191 result = lib.LLVMPrintModuleToFile(self, filename, byref(out))
193 raise RuntimeError("LLVM Error: %s" % out.value)
195 class Function(Value):
197 def __init__(self, value):
198 Value.__init__(self, value)
202 f = lib.LLVMGetNextFunction(self)
203 return f and Function(f)
207 f = lib.LLVMGetPreviousFunction(self)
208 return f and Function(f)
212 b = lib.LLVMGetFirstBasicBlock(self)
213 return b and BasicBlock(b)
217 b = lib.LLVMGetLastBasicBlock(self)
218 return b and BasicBlock(b)
220 class __bb_iterator(object):
221 def __init__(self, function, reverse=False):
222 self.function = function
223 self.reverse = reverse
225 self.bb = function.last
227 self.bb = function.first
233 if not isinstance(self.bb, BasicBlock):
234 raise StopIteration("")
237 self.bb = self.bb.prev
239 self.bb = self.bb.next
243 return Function.__bb_iterator(self)
245 def __reversed__(self):
246 return Function.__bb_iterator(self, reverse=True)
249 return lib.LLVMCountBasicBlocks(self)
251 class BasicBlock(LLVMObject):
253 def __init__(self, value):
254 LLVMObject.__init__(self, value)
258 b = lib.LLVMGetNextBasicBlock(self)
259 return b and BasicBlock(b)
263 b = lib.LLVMGetPreviousBasicBlock(self)
264 return b and BasicBlock(b)
268 i = lib.LLVMGetFirstInstruction(self)
269 return i and Instruction(i)
273 i = lib.LLVMGetLastInstruction(self)
274 return i and Instruction(i)
276 def __as_value(self):
277 return Value(lib.LLVMBasicBlockAsValue(self))
281 return lib.LLVMGetValueName(self.__as_value())
284 lib.LLVMDumpValue(self.__as_value())
286 def get_operand(self, i):
287 return Value(lib.LLVMGetOperand(self.__as_value(),
290 def set_operand(self, i, v):
291 return lib.LLVMSetOperand(self.__as_value(),
295 return lib.LLVMGetNumOperands(self.__as_value())
297 class __inst_iterator(object):
298 def __init__(self, bb, reverse=False):
300 self.reverse = reverse
302 self.inst = self.bb.last
304 self.inst = self.bb.first
310 if not isinstance(self.inst, Instruction):
311 raise StopIteration("")
314 self.inst = self.inst.prev
316 self.inst = self.inst.next
320 return BasicBlock.__inst_iterator(self)
322 def __reversed__(self):
323 return BasicBlock.__inst_iterator(self, reverse=True)
326 class Instruction(Value):
328 def __init__(self, value):
329 Value.__init__(self, value)
333 i = lib.LLVMGetNextInstruction(self)
334 return i and Instruction(i)
338 i = lib.LLVMGetPreviousInstruction(self)
339 return i and Instruction(i)
343 return OpCode.from_value(lib.LLVMGetInstructionOpcode(self))
345 class Context(LLVMObject):
347 def __init__(self, context=None):
349 context = lib.LLVMContextCreate()
350 LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
352 LLVMObject.__init__(self, context)
355 def GetGlobalContext(cls):
356 return Context(lib.LLVMGetGlobalContext())
358 class PassRegistry(LLVMObject):
359 """Represents an opaque pass registry object."""
362 LLVMObject.__init__(self,
363 lib.LLVMGetGlobalPassRegistry())
365 def register_library(library):
366 # Initialization/Shutdown declarations.
367 library.LLVMInitializeCore.argtypes = [PassRegistry]
368 library.LLVMInitializeCore.restype = None
370 library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
371 library.LLVMInitializeTransformUtils.restype = None
373 library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
374 library.LLVMInitializeScalarOpts.restype = None
376 library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
377 library.LLVMInitializeObjCARCOpts.restype = None
379 library.LLVMInitializeVectorization.argtypes = [PassRegistry]
380 library.LLVMInitializeVectorization.restype = None
382 library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
383 library.LLVMInitializeInstCombine.restype = None
385 library.LLVMInitializeIPO.argtypes = [PassRegistry]
386 library.LLVMInitializeIPO.restype = None
388 library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
389 library.LLVMInitializeInstrumentation.restype = None
391 library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
392 library.LLVMInitializeAnalysis.restype = None
394 library.LLVMInitializeIPA.argtypes = [PassRegistry]
395 library.LLVMInitializeIPA.restype = None
397 library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
398 library.LLVMInitializeCodeGen.restype = None
400 library.LLVMInitializeTarget.argtypes = [PassRegistry]
401 library.LLVMInitializeTarget.restype = None
403 library.LLVMShutdown.argtypes = []
404 library.LLVMShutdown.restype = None
406 # Pass Registry declarations.
407 library.LLVMGetGlobalPassRegistry.argtypes = []
408 library.LLVMGetGlobalPassRegistry.restype = c_object_p
410 # Context declarations.
411 library.LLVMContextCreate.argtypes = []
412 library.LLVMContextCreate.restype = c_object_p
414 library.LLVMContextDispose.argtypes = [Context]
415 library.LLVMContextDispose.restype = None
417 library.LLVMGetGlobalContext.argtypes = []
418 library.LLVMGetGlobalContext.restype = c_object_p
420 # Memory buffer declarations
421 library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
422 POINTER(c_object_p), POINTER(c_char_p)]
423 library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
425 library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
427 library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
429 # Module declarations
430 library.LLVMModuleCreateWithName.argtypes = [c_char_p]
431 library.LLVMModuleCreateWithName.restype = c_object_p
433 library.LLVMDisposeModule.argtypes = [Module]
434 library.LLVMDisposeModule.restype = None
436 library.LLVMGetDataLayout.argtypes = [Module]
437 library.LLVMGetDataLayout.restype = c_char_p
439 library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
440 library.LLVMSetDataLayout.restype = None
442 library.LLVMGetTarget.argtypes = [Module]
443 library.LLVMGetTarget.restype = c_char_p
445 library.LLVMSetTarget.argtypes = [Module, c_char_p]
446 library.LLVMSetTarget.restype = None
448 library.LLVMDumpModule.argtypes = [Module]
449 library.LLVMDumpModule.restype = None
451 library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
453 library.LLVMPrintModuleToFile.restype = bool
455 library.LLVMGetFirstFunction.argtypes = [Module]
456 library.LLVMGetFirstFunction.restype = c_object_p
458 library.LLVMGetLastFunction.argtypes = [Module]
459 library.LLVMGetLastFunction.restype = c_object_p
461 library.LLVMGetNextFunction.argtypes = [Function]
462 library.LLVMGetNextFunction.restype = c_object_p
464 library.LLVMGetPreviousFunction.argtypes = [Function]
465 library.LLVMGetPreviousFunction.restype = c_object_p
467 # Value declarations.
468 library.LLVMGetValueName.argtypes = [Value]
469 library.LLVMGetValueName.restype = c_char_p
471 library.LLVMDumpValue.argtypes = [Value]
472 library.LLVMDumpValue.restype = None
474 library.LLVMGetOperand.argtypes = [Value, c_uint]
475 library.LLVMGetOperand.restype = c_object_p
477 library.LLVMSetOperand.argtypes = [Value, Value, c_uint]
478 library.LLVMSetOperand.restype = None
480 library.LLVMGetNumOperands.argtypes = [Value]
481 library.LLVMGetNumOperands.restype = c_uint
483 # Basic Block Declarations.
484 library.LLVMGetFirstBasicBlock.argtypes = [Function]
485 library.LLVMGetFirstBasicBlock.restype = c_object_p
487 library.LLVMGetLastBasicBlock.argtypes = [Function]
488 library.LLVMGetLastBasicBlock.restype = c_object_p
490 library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
491 library.LLVMGetNextBasicBlock.restype = c_object_p
493 library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
494 library.LLVMGetPreviousBasicBlock.restype = c_object_p
496 library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
497 library.LLVMGetFirstInstruction.restype = c_object_p
499 library.LLVMGetLastInstruction.argtypes = [BasicBlock]
500 library.LLVMGetLastInstruction.restype = c_object_p
502 library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
503 library.LLVMBasicBlockAsValue.restype = c_object_p
505 library.LLVMCountBasicBlocks.argtypes = [Function]
506 library.LLVMCountBasicBlocks.restype = c_uint
508 # Instruction Declarations.
509 library.LLVMGetNextInstruction.argtypes = [Instruction]
510 library.LLVMGetNextInstruction.restype = c_object_p
512 library.LLVMGetPreviousInstruction.argtypes = [Instruction]
513 library.LLVMGetPreviousInstruction.restype = c_object_p
515 library.LLVMGetInstructionOpcode.argtypes = [Instruction]
516 library.LLVMGetInstructionOpcode.restype = c_uint
518 def register_enumerations():
519 for name, value in enumerations.OpCodes:
520 OpCode.register(name, value)
522 def initialize_llvm():
523 c = Context.GetGlobalContext()
525 lib.LLVMInitializeCore(p)
526 lib.LLVMInitializeTransformUtils(p)
527 lib.LLVMInitializeScalarOpts(p)
528 lib.LLVMInitializeObjCARCOpts(p)
529 lib.LLVMInitializeVectorization(p)
530 lib.LLVMInitializeInstCombine(p)
531 lib.LLVMInitializeIPO(p)
532 lib.LLVMInitializeInstrumentation(p)
533 lib.LLVMInitializeAnalysis(p)
534 lib.LLVMInitializeIPA(p)
535 lib.LLVMInitializeCodeGen(p)
536 lib.LLVMInitializeTarget(p)
538 register_library(lib)
539 register_enumerations()