e8bfab8445f7e0fc7aa2709b1f1b1020f854acb9
[oota-llvm.git] / bindings / python / llvm / core.py
1 #===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
2 #
3 #                     The LLVM Compiler Infrastructure
4 #
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
7 #
8 #===------------------------------------------------------------------------===#
9
10 from .common import LLVMObject
11 from .common import c_object_p
12 from .common import get_library
13
14 from . import enumerations
15
16 from ctypes import POINTER
17 from ctypes import byref
18 from ctypes import c_char_p
19 from ctypes import c_uint
20
21 __all__ = [
22     "lib",
23     "Enums",
24     "OpCode",
25     "MemoryBuffer",
26     "Module",
27     "Value",
28     "Function",
29     "BasicBlock",
30     "Instruction",
31     "Context",
32     "PassRegistry"
33 ]
34
35 lib = get_library()
36 Enums = []
37
38 class LLVMEnumeration(object):
39     """Represents an individual LLVM enumeration."""
40
41     def __init__(self, name, value):
42         self.name = name
43         self.value = value
44
45     def __repr__(self):
46         return '%s.%s' % (self.__class__.__name__,
47                           self.name)
48
49     @classmethod
50     def from_value(cls, value):
51         """Obtain an enumeration instance from a numeric value."""
52         result = cls._value_map.get(value, None)
53
54         if result is None:
55             raise ValueError('Unknown %s: %d' % (cls.__name__,
56                                                  value))
57
58         return result
59
60     @classmethod
61     def register(cls, name, value):
62         """Registers a new enumeration.
63
64         This is called by this module for each enumeration defined in
65         enumerations. You should not need to call this outside this module.
66         """
67         if value in cls._value_map:
68             raise ValueError('%s value already registered: %d' % (cls.__name__,
69                                                                   value))
70         enum = cls(name, value)
71         cls._value_map[value] = enum
72         setattr(cls, name, enum)
73         #print cls, name, value
74
75 class Attribute(LLVMEnumeration):
76     """Represents an individual Attribute enumeration."""
77
78     _value_map = {}
79
80     def __init__(self, name, value):
81         super(Attribute, self).__init__(name, value)
82
83 class OpCode(LLVMEnumeration):
84     """Represents an individual OpCode enumeration."""
85
86     _value_map = {}
87
88     def __init__(self, name, value):
89         super(OpCode, self).__init__(name, value)
90
91 class TypeKind(LLVMEnumeration):
92     """Represents an individual TypeKind enumeration."""
93
94     _value_map = {}
95
96     def __init__(self, name, value):
97         super(TypeKind, self).__init__(name, value)
98
99 class Linkage(LLVMEnumeration):
100     """Represents an individual Linkage enumeration."""
101
102     _value_map = {}
103
104     def __init__(self, name, value):
105         super(Linkage, self).__init__(name, value)
106
107 class Visibility(LLVMEnumeration):
108     """Represents an individual visibility enumeration."""
109
110     _value_map = {}
111
112     def __init__(self, name, value):
113         super(Visibility, self).__init__(name, value)
114
115 class CallConv(LLVMEnumeration):
116     """Represents an individual calling convention enumeration."""
117
118     _value_map = {}
119
120     def __init__(self, name, value):
121         super(CallConv, self).__init__(name, value)
122
123 class IntPredicate(LLVMEnumeration):
124     """Represents an individual IntPredicate enumeration."""
125
126     _value_map = {}
127
128     def __init__(self, name, value):
129         super(IntPredicate, self).__init__(name, value)
130
131 class RealPredicate(LLVMEnumeration):
132     """Represents an individual RealPredicate enumeration."""
133
134     _value_map = {}
135
136     def __init__(self, name, value):
137         super(RealPredicate, self).__init__(name, value)
138
139 class LandingPadClauseTy(LLVMEnumeration):
140     """Represents an individual LandingPadClauseTy enumeration."""
141
142     _value_map = {}
143
144     def __init__(self, name, value):
145         super(LandingPadClauseTy, self).__init__(name, value)
146
147 class MemoryBuffer(LLVMObject):
148     """Represents an opaque memory buffer."""
149
150     def __init__(self, filename=None):
151         """Create a new memory buffer.
152
153         Currently, we support creating from the contents of a file at the
154         specified filename.
155         """
156         if filename is None:
157             raise Exception("filename argument must be defined")
158
159         memory = c_object_p()
160         out = c_char_p(None)
161
162         result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
163                 byref(memory), byref(out))
164
165         if result:
166             raise Exception("Could not create memory buffer: %s" % out.value)
167
168         LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
169
170     def __len__(self):
171         return lib.LLVMGetBufferSize(self)
172
173 class Value(LLVMObject):
174     
175     def __init__(self, value):
176         LLVMObject.__init__(self, value)
177
178     @property
179     def name(self):
180         return lib.LLVMGetValueName(self)
181
182     def dump(self):
183         lib.LLVMDumpValue(self)
184     
185     def get_operand(self, i):
186         return Value(lib.LLVMGetOperand(self, i))
187     
188     def set_operand(self, i, v):
189         return lib.LLVMSetOperand(self, i, v)
190     
191     def __len__(self):
192         return lib.LLVMGetNumOperands(self)
193
194 class Module(LLVMObject):
195     """Represents the top-level structure of an llvm program in an opaque object."""
196
197     def __init__(self, module, name=None, context=None):
198         LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
199
200     @classmethod
201     def CreateWithName(cls, module_id):
202         m = Module(lib.LLVMModuleCreateWithName(module_id))
203         c = Context.GetGlobalContext().take_ownership(m)
204         return m
205
206     @property
207     def datalayout(self):
208         return lib.LLVMGetDataLayout(self)
209
210     @datalayout.setter
211     def datalayout(self, new_data_layout):
212         """new_data_layout is a string."""
213         lib.LLVMSetDataLayout(self, new_data_layout)
214
215     @property
216     def target(self):
217         return lib.LLVMGetTarget(self)
218
219     @target.setter
220     def target(self, new_target):
221         """new_target is a string."""
222         lib.LLVMSetTarget(self, new_target)
223
224     def dump(self):
225         lib.LLVMDumpModule(self)
226
227     class __function_iterator(object):
228         def __init__(self, module, reverse=False):
229             self.module = module
230             self.reverse = reverse
231             if self.reverse:
232                 self.function = self.module.last
233             else:
234                 self.function = self.module.first
235         
236         def __iter__(self):
237             return self
238         
239         def next(self):
240             if not isinstance(self.function, Function):
241                 raise StopIteration("")
242             result = self.function
243             if self.reverse:
244                 self.function = self.function.prev
245             else:
246                 self.function = self.function.next
247             return result
248     
249     def __iter__(self):
250         return Module.__function_iterator(self)
251
252     def __reversed__(self):
253         return Module.__function_iterator(self, reverse=True)
254
255     @property
256     def first(self):
257         return Function(lib.LLVMGetFirstFunction(self))
258
259     @property
260     def last(self):
261         return Function(lib.LLVMGetLastFunction(self))
262
263     def print_module_to_file(self, filename):
264         out = c_char_p(None)
265         # Result is inverted so 0 means everything was ok.
266         result = lib.LLVMPrintModuleToFile(self, filename, byref(out))        
267         if result:
268             raise RuntimeError("LLVM Error: %s" % out.value)
269
270 class Function(Value):
271
272     def __init__(self, value):
273         Value.__init__(self, value)
274     
275     @property
276     def next(self):
277         f = lib.LLVMGetNextFunction(self)
278         return f and Function(f)
279     
280     @property
281     def prev(self):
282         f = lib.LLVMGetPreviousFunction(self)
283         return f and Function(f)
284     
285     @property
286     def first(self):
287         b = lib.LLVMGetFirstBasicBlock(self)
288         return b and BasicBlock(b)
289
290     @property
291     def last(self):
292         b = lib.LLVMGetLastBasicBlock(self)
293         return b and BasicBlock(b)
294
295     class __bb_iterator(object):
296         def __init__(self, function, reverse=False):
297             self.function = function
298             self.reverse = reverse
299             if self.reverse:
300                 self.bb = function.last
301             else:
302                 self.bb = function.first
303         
304         def __iter__(self):
305             return self
306         
307         def next(self):
308             if not isinstance(self.bb, BasicBlock):
309                 raise StopIteration("")
310             result = self.bb
311             if self.reverse:
312                 self.bb = self.bb.prev
313             else:
314                 self.bb = self.bb.next
315             return result
316     
317     def __iter__(self):
318         return Function.__bb_iterator(self)
319
320     def __reversed__(self):
321         return Function.__bb_iterator(self, reverse=True)
322     
323     def __len__(self):
324         return lib.LLVMCountBasicBlocks(self)
325
326 class BasicBlock(LLVMObject):
327     
328     def __init__(self, value):
329         LLVMObject.__init__(self, value)
330
331     @property
332     def next(self):
333         b = lib.LLVMGetNextBasicBlock(self)
334         return b and BasicBlock(b)
335
336     @property
337     def prev(self):
338         b = lib.LLVMGetPreviousBasicBlock(self)
339         return b and BasicBlock(b)
340     
341     @property
342     def first(self):
343         i = lib.LLVMGetFirstInstruction(self)
344         return i and Instruction(i)
345
346     @property
347     def last(self):
348         i = lib.LLVMGetLastInstruction(self)
349         return i and Instruction(i)
350
351     def __as_value(self):
352         return Value(lib.LLVMBasicBlockAsValue(self))
353     
354     @property
355     def name(self):
356         return lib.LLVMGetValueName(self.__as_value())
357
358     def dump(self):
359         lib.LLVMDumpValue(self.__as_value())
360
361     def get_operand(self, i):
362         return Value(lib.LLVMGetOperand(self.__as_value(),
363                                         i))
364     
365     def set_operand(self, i, v):
366         return lib.LLVMSetOperand(self.__as_value(),
367                                   i, v)
368     
369     def __len__(self):
370         return lib.LLVMGetNumOperands(self.__as_value())
371
372     class __inst_iterator(object):
373         def __init__(self, bb, reverse=False):            
374             self.bb = bb
375             self.reverse = reverse
376             if self.reverse:
377                 self.inst = self.bb.last
378             else:
379                 self.inst = self.bb.first
380         
381         def __iter__(self):
382             return self
383         
384         def next(self):
385             if not isinstance(self.inst, Instruction):
386                 raise StopIteration("")
387             result = self.inst
388             if self.reverse:
389                 self.inst = self.inst.prev
390             else:
391                 self.inst = self.inst.next
392             return result
393     
394     def __iter__(self):
395         return BasicBlock.__inst_iterator(self)
396
397     def __reversed__(self):
398         return BasicBlock.__inst_iterator(self, reverse=True)
399
400
401 class Instruction(Value):
402
403     def __init__(self, value):
404         Value.__init__(self, value)
405
406     @property
407     def next(self):
408         i = lib.LLVMGetNextInstruction(self)
409         return i and Instruction(i)
410
411     @property
412     def prev(self):
413         i = lib.LLVMGetPreviousInstruction(self)
414         return i and Instruction(i)
415
416     @property
417     def opcode(self):
418         return OpCode.from_value(lib.LLVMGetInstructionOpcode(self))
419
420 class Context(LLVMObject):
421
422     def __init__(self, context=None):
423         if context is None:
424             context = lib.LLVMContextCreate()
425             LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
426         else:
427             LLVMObject.__init__(self, context)
428
429     @classmethod
430     def GetGlobalContext(cls):
431         return Context(lib.LLVMGetGlobalContext())
432
433 class PassRegistry(LLVMObject):
434     """Represents an opaque pass registry object."""
435
436     def __init__(self):
437         LLVMObject.__init__(self,
438                             lib.LLVMGetGlobalPassRegistry())
439
440 def register_library(library):
441     # Initialization/Shutdown declarations.
442     library.LLVMInitializeCore.argtypes = [PassRegistry]
443     library.LLVMInitializeCore.restype = None
444
445     library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
446     library.LLVMInitializeTransformUtils.restype = None
447
448     library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
449     library.LLVMInitializeScalarOpts.restype = None
450
451     library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
452     library.LLVMInitializeObjCARCOpts.restype = None
453
454     library.LLVMInitializeVectorization.argtypes = [PassRegistry]
455     library.LLVMInitializeVectorization.restype = None
456
457     library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
458     library.LLVMInitializeInstCombine.restype = None
459
460     library.LLVMInitializeIPO.argtypes = [PassRegistry]
461     library.LLVMInitializeIPO.restype = None
462
463     library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
464     library.LLVMInitializeInstrumentation.restype = None
465
466     library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
467     library.LLVMInitializeAnalysis.restype = None
468
469     library.LLVMInitializeIPA.argtypes = [PassRegistry]
470     library.LLVMInitializeIPA.restype = None
471
472     library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
473     library.LLVMInitializeCodeGen.restype = None
474
475     library.LLVMInitializeTarget.argtypes = [PassRegistry]
476     library.LLVMInitializeTarget.restype = None
477
478     library.LLVMShutdown.argtypes = []
479     library.LLVMShutdown.restype = None
480
481     # Pass Registry declarations.
482     library.LLVMGetGlobalPassRegistry.argtypes = []
483     library.LLVMGetGlobalPassRegistry.restype = c_object_p
484
485     # Context declarations.
486     library.LLVMContextCreate.argtypes = []
487     library.LLVMContextCreate.restype = c_object_p
488
489     library.LLVMContextDispose.argtypes = [Context]
490     library.LLVMContextDispose.restype = None
491
492     library.LLVMGetGlobalContext.argtypes = []
493     library.LLVMGetGlobalContext.restype = c_object_p
494
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
499
500     library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
501
502     library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
503
504     # Module declarations
505     library.LLVMModuleCreateWithName.argtypes = [c_char_p]
506     library.LLVMModuleCreateWithName.restype = c_object_p
507
508     library.LLVMDisposeModule.argtypes = [Module]
509     library.LLVMDisposeModule.restype = None
510
511     library.LLVMGetDataLayout.argtypes = [Module]
512     library.LLVMGetDataLayout.restype = c_char_p
513
514     library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
515     library.LLVMSetDataLayout.restype = None
516
517     library.LLVMGetTarget.argtypes = [Module]
518     library.LLVMGetTarget.restype = c_char_p
519
520     library.LLVMSetTarget.argtypes = [Module, c_char_p]
521     library.LLVMSetTarget.restype = None
522
523     library.LLVMDumpModule.argtypes = [Module]
524     library.LLVMDumpModule.restype = None
525
526     library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
527                                               POINTER(c_char_p)]
528     library.LLVMPrintModuleToFile.restype = bool
529
530     library.LLVMGetFirstFunction.argtypes = [Module]
531     library.LLVMGetFirstFunction.restype = c_object_p
532
533     library.LLVMGetLastFunction.argtypes = [Module]
534     library.LLVMGetLastFunction.restype = c_object_p
535
536     library.LLVMGetNextFunction.argtypes = [Function]
537     library.LLVMGetNextFunction.restype = c_object_p
538
539     library.LLVMGetPreviousFunction.argtypes = [Function]
540     library.LLVMGetPreviousFunction.restype = c_object_p
541
542     # Value declarations.
543     library.LLVMGetValueName.argtypes = [Value]
544     library.LLVMGetValueName.restype = c_char_p
545
546     library.LLVMDumpValue.argtypes = [Value]
547     library.LLVMDumpValue.restype = None
548
549     library.LLVMGetOperand.argtypes = [Value, c_uint]
550     library.LLVMGetOperand.restype = c_object_p
551
552     library.LLVMSetOperand.argtypes = [Value, Value, c_uint]
553     library.LLVMSetOperand.restype = None
554
555     library.LLVMGetNumOperands.argtypes = [Value]
556     library.LLVMGetNumOperands.restype = c_uint
557
558     # Basic Block Declarations.
559     library.LLVMGetFirstBasicBlock.argtypes = [Function]
560     library.LLVMGetFirstBasicBlock.restype = c_object_p
561
562     library.LLVMGetLastBasicBlock.argtypes = [Function]
563     library.LLVMGetLastBasicBlock.restype = c_object_p
564
565     library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
566     library.LLVMGetNextBasicBlock.restype = c_object_p
567
568     library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
569     library.LLVMGetPreviousBasicBlock.restype = c_object_p
570
571     library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
572     library.LLVMGetFirstInstruction.restype = c_object_p
573
574     library.LLVMGetLastInstruction.argtypes = [BasicBlock]
575     library.LLVMGetLastInstruction.restype = c_object_p
576
577     library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
578     library.LLVMBasicBlockAsValue.restype = c_object_p
579
580     library.LLVMCountBasicBlocks.argtypes = [Function]
581     library.LLVMCountBasicBlocks.restype = c_uint
582
583     # Instruction Declarations.
584     library.LLVMGetNextInstruction.argtypes = [Instruction]
585     library.LLVMGetNextInstruction.restype = c_object_p
586
587     library.LLVMGetPreviousInstruction.argtypes = [Instruction]
588     library.LLVMGetPreviousInstruction.restype = c_object_p
589
590     library.LLVMGetInstructionOpcode.argtypes = [Instruction]
591     library.LLVMGetInstructionOpcode.restype = c_uint
592
593 def register_enumerations():
594     if Enums:
595         return None
596     enums = [
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),
606     ]
607     s = set([])
608     for enum_class, enum_spec in enums:
609         for name, value in enum_spec:
610             print name, value
611             enum_class.register(name, value)
612     return enums
613
614 def initialize_llvm():
615     c = Context.GetGlobalContext()
616     p = PassRegistry()
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)
629
630 register_library(lib)
631 Enums = register_enumerations()
632 initialize_llvm()