1 #===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
3 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 # See https://llvm.org/LICENSE.txt for license information.
5 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 #===------------------------------------------------------------------------===#
8 from __future__
import print_function
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
40 class LLVMEnumeration(object):
41 """Represents an individual LLVM enumeration."""
43 def __init__(self
, name
, value
):
48 return '%s.%s' % (self
.__class
__.__name
__,
52 def from_value(cls
, value
):
53 """Obtain an enumeration instance from a numeric value."""
54 result
= cls
._value
_map
.get(value
, None)
57 raise ValueError('Unknown %s: %d' % (cls
.__name
__,
63 def register(cls
, name
, value
):
64 """Registers a new enumeration.
66 This is called by this module for each enumeration defined in
67 enumerations. You should not need to call this outside this module.
69 if value
in cls
._value
_map
:
70 raise ValueError('%s value already registered: %d' % (cls
.__name
__,
72 enum
= cls(name
, value
)
73 cls
._value
_map
[value
] = enum
74 setattr(cls
, name
, enum
)
76 class Attribute(LLVMEnumeration
):
77 """Represents an individual Attribute enumeration."""
81 def __init__(self
, name
, value
):
82 super(Attribute
, self
).__init
__(name
, value
)
84 class OpCode(LLVMEnumeration
):
85 """Represents an individual OpCode enumeration."""
89 def __init__(self
, name
, value
):
90 super(OpCode
, self
).__init
__(name
, value
)
92 class TypeKind(LLVMEnumeration
):
93 """Represents an individual TypeKind enumeration."""
97 def __init__(self
, name
, value
):
98 super(TypeKind
, self
).__init
__(name
, value
)
100 class Linkage(LLVMEnumeration
):
101 """Represents an individual Linkage enumeration."""
105 def __init__(self
, name
, value
):
106 super(Linkage
, self
).__init
__(name
, value
)
108 class Visibility(LLVMEnumeration
):
109 """Represents an individual visibility enumeration."""
113 def __init__(self
, name
, value
):
114 super(Visibility
, self
).__init
__(name
, value
)
116 class CallConv(LLVMEnumeration
):
117 """Represents an individual calling convention enumeration."""
121 def __init__(self
, name
, value
):
122 super(CallConv
, self
).__init
__(name
, value
)
124 class IntPredicate(LLVMEnumeration
):
125 """Represents an individual IntPredicate enumeration."""
129 def __init__(self
, name
, value
):
130 super(IntPredicate
, self
).__init
__(name
, value
)
132 class RealPredicate(LLVMEnumeration
):
133 """Represents an individual RealPredicate enumeration."""
137 def __init__(self
, name
, value
):
138 super(RealPredicate
, self
).__init
__(name
, value
)
140 class LandingPadClauseTy(LLVMEnumeration
):
141 """Represents an individual LandingPadClauseTy enumeration."""
145 def __init__(self
, name
, value
):
146 super(LandingPadClauseTy
, self
).__init
__(name
, value
)
148 class MemoryBuffer(LLVMObject
):
149 """Represents an opaque memory buffer."""
151 def __init__(self
, filename
=None):
152 """Create a new memory buffer.
154 Currently, we support creating from the contents of a file at the
158 raise Exception("filename argument must be defined")
160 memory
= c_object_p()
163 result
= lib
.LLVMCreateMemoryBufferWithContentsOfFile(filename
,
164 byref(memory
), byref(out
))
167 raise Exception("Could not create memory buffer: %s" % out
.value
)
169 LLVMObject
.__init
__(self
, memory
, disposer
=lib
.LLVMDisposeMemoryBuffer
)
172 return lib
.LLVMGetBufferSize(self
)
174 class Value(LLVMObject
):
176 def __init__(self
, value
):
177 LLVMObject
.__init
__(self
, value
)
181 return lib
.LLVMGetValueName(self
)
184 lib
.LLVMDumpValue(self
)
186 def get_operand(self
, i
):
187 return Value(lib
.LLVMGetOperand(self
, i
))
189 def set_operand(self
, i
, v
):
190 return lib
.LLVMSetOperand(self
, i
, v
)
193 return lib
.LLVMGetNumOperands(self
)
195 class Module(LLVMObject
):
196 """Represents the top-level structure of an llvm program in an opaque object."""
198 def __init__(self
, module
, name
=None, context
=None):
199 LLVMObject
.__init
__(self
, module
, disposer
=lib
.LLVMDisposeModule
)
202 def CreateWithName(cls
, module_id
):
203 m
= Module(lib
.LLVMModuleCreateWithName(module_id
))
204 Context
.GetGlobalContext().take_ownership(m
)
208 def datalayout(self
):
209 return lib
.LLVMGetDataLayout(self
)
212 def datalayout(self
, new_data_layout
):
213 """new_data_layout is a string."""
214 lib
.LLVMSetDataLayout(self
, new_data_layout
)
218 return lib
.LLVMGetTarget(self
)
221 def target(self
, new_target
):
222 """new_target is a string."""
223 lib
.LLVMSetTarget(self
, new_target
)
226 lib
.LLVMDumpModule(self
)
228 class __function_iterator(object):
229 def __init__(self
, module
, reverse
=False):
231 self
.reverse
= reverse
233 self
.function
= self
.module
.last
235 self
.function
= self
.module
.first
241 if not isinstance(self
.function
, Function
):
242 raise StopIteration("")
243 result
= self
.function
245 self
.function
= self
.function
.prev
247 self
.function
= self
.function
.next
250 if sys
.version_info
.major
== 2:
254 return Module
.__function
_iterator
(self
)
256 def __reversed__(self
):
257 return Module
.__function
_iterator
(self
, reverse
=True)
261 return Function(lib
.LLVMGetFirstFunction(self
))
265 return Function(lib
.LLVMGetLastFunction(self
))
267 def print_module_to_file(self
, filename
):
269 # Result is inverted so 0 means everything was ok.
270 result
= lib
.LLVMPrintModuleToFile(self
, filename
, byref(out
))
272 raise RuntimeError("LLVM Error: %s" % out
.value
)
274 class Function(Value
):
276 def __init__(self
, value
):
277 Value
.__init
__(self
, value
)
281 f
= lib
.LLVMGetNextFunction(self
)
282 return f
and Function(f
)
286 f
= lib
.LLVMGetPreviousFunction(self
)
287 return f
and Function(f
)
291 b
= lib
.LLVMGetFirstBasicBlock(self
)
292 return b
and BasicBlock(b
)
296 b
= lib
.LLVMGetLastBasicBlock(self
)
297 return b
and BasicBlock(b
)
299 class __bb_iterator(object):
300 def __init__(self
, function
, reverse
=False):
301 self
.function
= function
302 self
.reverse
= reverse
304 self
.bb
= function
.last
306 self
.bb
= function
.first
312 if not isinstance(self
.bb
, BasicBlock
):
313 raise StopIteration("")
316 self
.bb
= self
.bb
.prev
318 self
.bb
= self
.bb
.next
321 if sys
.version_info
.major
== 2:
325 return Function
.__bb
_iterator
(self
)
327 def __reversed__(self
):
328 return Function
.__bb
_iterator
(self
, reverse
=True)
331 return lib
.LLVMCountBasicBlocks(self
)
333 class BasicBlock(LLVMObject
):
335 def __init__(self
, value
):
336 LLVMObject
.__init
__(self
, value
)
340 b
= lib
.LLVMGetNextBasicBlock(self
)
341 return b
and BasicBlock(b
)
345 b
= lib
.LLVMGetPreviousBasicBlock(self
)
346 return b
and BasicBlock(b
)
350 i
= lib
.LLVMGetFirstInstruction(self
)
351 return i
and Instruction(i
)
355 i
= lib
.LLVMGetLastInstruction(self
)
356 return i
and Instruction(i
)
358 def __as_value(self
):
359 return Value(lib
.LLVMBasicBlockAsValue(self
))
363 return lib
.LLVMGetValueName(self
.__as
_value
())
366 lib
.LLVMDumpValue(self
.__as
_value
())
368 def get_operand(self
, i
):
369 return Value(lib
.LLVMGetOperand(self
.__as
_value
(),
372 def set_operand(self
, i
, v
):
373 return lib
.LLVMSetOperand(self
.__as
_value
(),
377 return lib
.LLVMGetNumOperands(self
.__as
_value
())
379 class __inst_iterator(object):
380 def __init__(self
, bb
, reverse
=False):
382 self
.reverse
= reverse
384 self
.inst
= self
.bb
.last
386 self
.inst
= self
.bb
.first
392 if not isinstance(self
.inst
, Instruction
):
393 raise StopIteration("")
396 self
.inst
= self
.inst
.prev
398 self
.inst
= self
.inst
.next
401 if sys
.version_info
.major
== 2:
405 return BasicBlock
.__inst
_iterator
(self
)
407 def __reversed__(self
):
408 return BasicBlock
.__inst
_iterator
(self
, reverse
=True)
411 class Instruction(Value
):
413 def __init__(self
, value
):
414 Value
.__init
__(self
, value
)
418 i
= lib
.LLVMGetNextInstruction(self
)
419 return i
and Instruction(i
)
423 i
= lib
.LLVMGetPreviousInstruction(self
)
424 return i
and Instruction(i
)
428 return OpCode
.from_value(lib
.LLVMGetInstructionOpcode(self
))
430 class Context(LLVMObject
):
432 def __init__(self
, context
=None):
434 context
= lib
.LLVMContextCreate()
435 LLVMObject
.__init
__(self
, context
, disposer
=lib
.LLVMContextDispose
)
437 LLVMObject
.__init
__(self
, context
)
440 def GetGlobalContext(cls
):
441 return Context(lib
.LLVMGetGlobalContext())
443 class PassRegistry(LLVMObject
):
444 """Represents an opaque pass registry object."""
447 LLVMObject
.__init
__(self
,
448 lib
.LLVMGetGlobalPassRegistry())
450 def register_library(library
):
451 # Initialization/Shutdown declarations.
452 library
.LLVMInitializeCore
.argtypes
= [PassRegistry
]
453 library
.LLVMInitializeCore
.restype
= None
455 library
.LLVMInitializeTransformUtils
.argtypes
= [PassRegistry
]
456 library
.LLVMInitializeTransformUtils
.restype
= None
458 library
.LLVMInitializeScalarOpts
.argtypes
= [PassRegistry
]
459 library
.LLVMInitializeScalarOpts
.restype
= None
461 library
.LLVMInitializeObjCARCOpts
.argtypes
= [PassRegistry
]
462 library
.LLVMInitializeObjCARCOpts
.restype
= None
464 library
.LLVMInitializeVectorization
.argtypes
= [PassRegistry
]
465 library
.LLVMInitializeVectorization
.restype
= None
467 library
.LLVMInitializeInstCombine
.argtypes
= [PassRegistry
]
468 library
.LLVMInitializeInstCombine
.restype
= None
470 library
.LLVMInitializeAggressiveInstCombiner
.argtypes
= [PassRegistry
]
471 library
.LLVMInitializeAggressiveInstCombiner
.restype
= None
473 library
.LLVMInitializeIPO
.argtypes
= [PassRegistry
]
474 library
.LLVMInitializeIPO
.restype
= None
476 library
.LLVMInitializeInstrumentation
.argtypes
= [PassRegistry
]
477 library
.LLVMInitializeInstrumentation
.restype
= None
479 library
.LLVMInitializeAnalysis
.argtypes
= [PassRegistry
]
480 library
.LLVMInitializeAnalysis
.restype
= None
482 library
.LLVMInitializeCodeGen
.argtypes
= [PassRegistry
]
483 library
.LLVMInitializeCodeGen
.restype
= None
485 library
.LLVMInitializeTarget
.argtypes
= [PassRegistry
]
486 library
.LLVMInitializeTarget
.restype
= None
488 library
.LLVMShutdown
.argtypes
= []
489 library
.LLVMShutdown
.restype
= None
491 # Pass Registry declarations.
492 library
.LLVMGetGlobalPassRegistry
.argtypes
= []
493 library
.LLVMGetGlobalPassRegistry
.restype
= c_object_p
495 # Context declarations.
496 library
.LLVMContextCreate
.argtypes
= []
497 library
.LLVMContextCreate
.restype
= c_object_p
499 library
.LLVMContextDispose
.argtypes
= [Context
]
500 library
.LLVMContextDispose
.restype
= None
502 library
.LLVMGetGlobalContext
.argtypes
= []
503 library
.LLVMGetGlobalContext
.restype
= c_object_p
505 # Memory buffer declarations
506 library
.LLVMCreateMemoryBufferWithContentsOfFile
.argtypes
= [c_char_p
,
507 POINTER(c_object_p
), POINTER(c_char_p
)]
508 library
.LLVMCreateMemoryBufferWithContentsOfFile
.restype
= bool
510 library
.LLVMGetBufferSize
.argtypes
= [MemoryBuffer
]
512 library
.LLVMDisposeMemoryBuffer
.argtypes
= [MemoryBuffer
]
514 # Module declarations
515 library
.LLVMModuleCreateWithName
.argtypes
= [c_char_p
]
516 library
.LLVMModuleCreateWithName
.restype
= c_object_p
518 library
.LLVMDisposeModule
.argtypes
= [Module
]
519 library
.LLVMDisposeModule
.restype
= None
521 library
.LLVMGetDataLayout
.argtypes
= [Module
]
522 library
.LLVMGetDataLayout
.restype
= c_char_p
524 library
.LLVMSetDataLayout
.argtypes
= [Module
, c_char_p
]
525 library
.LLVMSetDataLayout
.restype
= None
527 library
.LLVMGetTarget
.argtypes
= [Module
]
528 library
.LLVMGetTarget
.restype
= c_char_p
530 library
.LLVMSetTarget
.argtypes
= [Module
, c_char_p
]
531 library
.LLVMSetTarget
.restype
= None
533 library
.LLVMDumpModule
.argtypes
= [Module
]
534 library
.LLVMDumpModule
.restype
= None
536 library
.LLVMPrintModuleToFile
.argtypes
= [Module
, c_char_p
,
538 library
.LLVMPrintModuleToFile
.restype
= bool
540 library
.LLVMGetFirstFunction
.argtypes
= [Module
]
541 library
.LLVMGetFirstFunction
.restype
= c_object_p
543 library
.LLVMGetLastFunction
.argtypes
= [Module
]
544 library
.LLVMGetLastFunction
.restype
= c_object_p
546 library
.LLVMGetNextFunction
.argtypes
= [Function
]
547 library
.LLVMGetNextFunction
.restype
= c_object_p
549 library
.LLVMGetPreviousFunction
.argtypes
= [Function
]
550 library
.LLVMGetPreviousFunction
.restype
= c_object_p
552 # Value declarations.
553 library
.LLVMGetValueName
.argtypes
= [Value
]
554 library
.LLVMGetValueName
.restype
= c_char_p
556 library
.LLVMDumpValue
.argtypes
= [Value
]
557 library
.LLVMDumpValue
.restype
= None
559 library
.LLVMGetOperand
.argtypes
= [Value
, c_uint
]
560 library
.LLVMGetOperand
.restype
= c_object_p
562 library
.LLVMSetOperand
.argtypes
= [Value
, Value
, c_uint
]
563 library
.LLVMSetOperand
.restype
= None
565 library
.LLVMGetNumOperands
.argtypes
= [Value
]
566 library
.LLVMGetNumOperands
.restype
= c_uint
568 # Basic Block Declarations.
569 library
.LLVMGetFirstBasicBlock
.argtypes
= [Function
]
570 library
.LLVMGetFirstBasicBlock
.restype
= c_object_p
572 library
.LLVMGetLastBasicBlock
.argtypes
= [Function
]
573 library
.LLVMGetLastBasicBlock
.restype
= c_object_p
575 library
.LLVMGetNextBasicBlock
.argtypes
= [BasicBlock
]
576 library
.LLVMGetNextBasicBlock
.restype
= c_object_p
578 library
.LLVMGetPreviousBasicBlock
.argtypes
= [BasicBlock
]
579 library
.LLVMGetPreviousBasicBlock
.restype
= c_object_p
581 library
.LLVMGetFirstInstruction
.argtypes
= [BasicBlock
]
582 library
.LLVMGetFirstInstruction
.restype
= c_object_p
584 library
.LLVMGetLastInstruction
.argtypes
= [BasicBlock
]
585 library
.LLVMGetLastInstruction
.restype
= c_object_p
587 library
.LLVMBasicBlockAsValue
.argtypes
= [BasicBlock
]
588 library
.LLVMBasicBlockAsValue
.restype
= c_object_p
590 library
.LLVMCountBasicBlocks
.argtypes
= [Function
]
591 library
.LLVMCountBasicBlocks
.restype
= c_uint
593 # Instruction Declarations.
594 library
.LLVMGetNextInstruction
.argtypes
= [Instruction
]
595 library
.LLVMGetNextInstruction
.restype
= c_object_p
597 library
.LLVMGetPreviousInstruction
.argtypes
= [Instruction
]
598 library
.LLVMGetPreviousInstruction
.restype
= c_object_p
600 library
.LLVMGetInstructionOpcode
.argtypes
= [Instruction
]
601 library
.LLVMGetInstructionOpcode
.restype
= c_uint
603 def register_enumerations():
607 (Attribute
, enumerations
.Attributes
),
608 (OpCode
, enumerations
.OpCodes
),
609 (TypeKind
, enumerations
.TypeKinds
),
610 (Linkage
, enumerations
.Linkages
),
611 (Visibility
, enumerations
.Visibility
),
612 (CallConv
, enumerations
.CallConv
),
613 (IntPredicate
, enumerations
.IntPredicate
),
614 (RealPredicate
, enumerations
.RealPredicate
),
615 (LandingPadClauseTy
, enumerations
.LandingPadClauseTy
),
617 for enum_class
, enum_spec
in enums
:
618 for name
, value
in enum_spec
:
620 enum_class
.register(name
, value
)
623 def initialize_llvm():
624 Context
.GetGlobalContext()
626 lib
.LLVMInitializeCore(p
)
627 lib
.LLVMInitializeTransformUtils(p
)
628 lib
.LLVMInitializeScalarOpts(p
)
629 lib
.LLVMInitializeObjCARCOpts(p
)
630 lib
.LLVMInitializeVectorization(p
)
631 lib
.LLVMInitializeInstCombine(p
)
632 lib
.LLVMInitializeIPO(p
)
633 lib
.LLVMInitializeInstrumentation(p
)
634 lib
.LLVMInitializeAnalysis(p
)
635 lib
.LLVMInitializeCodeGen(p
)
636 lib
.LLVMInitializeTarget(p
)
638 register_library(lib
)
639 Enums
= register_enumerations()