def codegen(context, builder, signature, args): data, idx = args rawptr = cgutils.alloca_once_value(builder, value=data) ptr = builder.bitcast(rawptr, ir.IntType(bitsize).as_pointer()) ch = builder.load(builder.gep(ptr, [idx])) return builder.zext(ch, ir.IntType(32))
def lower_dist_wait(context, builder, sig, args): fnty = lir.FunctionType(lir.IntType(32), [lir.IntType(32), lir.IntType(1)]) fn = builder.module.get_or_insert_function(fnty, name="hpat_dist_wait") return builder.call(fn, args)
def _declare_print_function(self): # Declare Printf function voidptr_ty = ir.IntType(8).as_pointer() printf_ty = ir.FunctionType(ir.IntType(32), [voidptr_ty], var_arg=True) printf = ir.Function(self.module, printf_ty, name="printf") self.printf = printf
def type(): return ir.IntType(32)
def type(): return ir.IntType(128)
from llvmlite import ir import ctypes as ct import struct # indices into a box TYPE = 0 SIZE = 1 DATA = 2 ENV = 3 # sizes of things HASH_SIZE = 32 # all sorts of type aliases i8 = ir.IntType(8) i32 = ir.IntType(32) i64 = ir.IntType(64) f32 = ir.FloatType() f64 = ir.DoubleType() void = ir.VoidType() func = ir.FunctionType ptr = ir.PointerType arr = ir.ArrayType box = ir.context.global_context.get_identified_type('box') item = ir.context.global_context.get_identified_type('item') lpt = ir.context.global_context.get_identified_type('table') arg = ptr(box) lp = ir.LiteralStructType([ptr(i8), i32]) def vfunc(*args, var_arg=False):
def type(): return ir.IntType(128, False)
#!/usr/bin/env python # -*- coding: utf-8 -*- from llvmlite import ir int_type = ir.IntType(64) real_type = ir.DoubleType() bool_type = ir.IntType(1) void_type = ir.VoidType()
from enum import Enum from llvmlite import ir from .typing import DType from typing import Union global_node_id = -1 int_type = ir.IntType(32) class LRValue(Enum): """Enum class for the node, whether it is a left value or a right value """ LEFT = 1 RIGHT = 2 class BinaryOpr(Enum): """Legal Binay operator """ ADD = 1 SUB = 2 MUL = 3 IDIV = 4 FDIV = 5 class UnaryOpr(Enum): """Legal Unary operator """
""" from __future__ import print_function, absolute_import import copy import itertools import re import textwrap import unittest from . import TestCase from llvmlite import ir from llvmlite import binding as llvm from llvmlite import six int1 = ir.IntType(1) int8 = ir.IntType(8) int32 = ir.IntType(32) int64 = ir.IntType(64) flt = ir.FloatType() dbl = ir.DoubleType() class TestBase(TestCase): """ Utilities for IR tests. """ def assertInText(self, pattern, text): """Replaces whitespace sequence in `pattern` with "\s+". """ def escape(c):
def test_named_metadata(self): mod = self.module() md = mod.add_metadata([ir.Constant(ir.IntType(32), 123)]) nmd = mod.add_named_metadata("foo") nmd.add(md) self.assertInText("!foo = !{ !0 }", str(mod))
def _const_bool(cls, boolean): """Util to create constant boolean in metadata """ return ir.IntType(1)(boolean)
def _const_int(cls, num, bits=32): """Util to create constant int in metadata """ return ir.IntType(bits)(num)
int soma = (x + y); int subtracao = (x - y); int multiplicacao = (x * y); int divisao = (x / y); int modulo = (x % y); int shiftDireita = (x >> 1); int shiftEsquerda = (x << 1); return 0; } ''' # Cria o módulo. module = ir.Module('meu_modulo.bc') module.triple = binding.get_default_triple() main_ftype = ir.FunctionType(ir.IntType(32), ()) main_func = ir.Function(module, main_ftype, 'main') entry_block = main_func.append_basic_block('entry') exit_block = main_func.append_basic_block('exit') builder = ir.IRBuilder(entry_block) return_val = builder.alloca(ir.IntType(32), name='ret_val') builder.store(value=ir.Constant(ir.IntType(32), 0), ptr=return_val, align=4) x = builder.alloca(ir.IntType(32), name='x') builder.store(value=ir.Constant(ir.IntType(32), 2), ptr=x, align=4) y = builder.alloca(ir.IntType(32), name='y') builder.store(value=ir.Constant(ir.IntType(32), 1), ptr=y, align=4)
def stencil_dummy_lower(context, builder, sig, args): "lowering for dummy stencil calls" return lir.Constant(lir.IntType(types.intp.bitwidth), 0)
def emit_sentence(self, sentence, builder, consts, variables): if sentence.type == SentenceType.ASSIGN: identifier, expression = sentence.content ptr = variables.get(identifier, None) if ptr is None: try: ptr = self.module.get_global(identifier) except KeyError: raise VariableUndefinedError if ptr.global_constant: raise VariableUndefinedError expression_ptr = self.emit_expression(expression, builder, consts, variables) return builder.store(expression_ptr, ptr) elif sentence.type == SentenceType.CALL: identifier = sentence.content try: func = self.module.get_global(identifier) except KeyError: raise FunctionUndefinedError(identifier) return builder.call(func, ()) elif sentence.type == SentenceType.CONDITION: condition, sentence = sentence.content if sentence is None: return with builder.if_then( self.emit_condition(condition, builder, consts, variables)) as if_then: self.emit_sentence(sentence, builder, consts, variables) return if_then elif sentence.type == SentenceType.LOOP: condition, sentence = sentence.content while_block = builder.append_basic_block(builder.block.name + '.whilecondition') then_block = builder.append_basic_block(builder.block.name + '.whilethen') end_while_block = builder.append_basic_block(builder.block.name + '.endwhile') builder.branch(while_block) builder.position_at_start(while_block) builder.cbranch( self.emit_condition(condition, builder, consts, variables), then_block, end_while_block) builder.position_at_start(then_block) self.emit_sentence(sentence, builder, consts, variables) builder.branch(while_block) builder.position_at_start(end_while_block) elif sentence.type == SentenceType.WRITE: expressions = sentence.content format = ' '.join('%i' for _ in range(len(expressions))) + '\n\00' format_const = ir.Constant( ir.ArrayType(ir.IntType(8), len(format)), bytearray(format.encode('ascii'))) format_var = builder.alloca( ir.ArrayType(ir.IntType(8), len(format))) builder.store(format_const, format_var) format_ptr = builder.bitcast(format_var, ir.IntType(8).as_pointer()) printf = self.emit_printf() builder.call(printf, [format_ptr] + [ self.emit_expression(expression, builder, consts, variables) for expression in expressions ]) elif sentence.type == SentenceType.READ: identifiers = sentence.content format = ' '.join('%i' for _ in range(len(identifiers))) + '\00' format_const = ir.Constant( ir.ArrayType(ir.IntType(8), len(format)), bytearray(format.encode('ascii'))) format_var = builder.alloca( ir.ArrayType(ir.IntType(8), len(format))) builder.store(format_const, format_var) format_ptr = builder.bitcast(format_var, ir.IntType(8).as_pointer()) scanf = self.emit_scanf() builder.call(scanf, [format_ptr] + [ self.module.get_global(identifier) for identifier in identifiers ]) elif sentence.type == SentenceType.COMPOUND: sentences = sentence.content return [ self.emit_sentence(sub_sentence, builder, consts, variables) for sub_sentence in sentences ]
Será gerado um código em LLVM como este em C: int A[1024]; int main(){ int B[1024]; A[50] = A[49] + 5; B[0] = B[1] + 10; return 0; } ''' # Cria o módulo. module = ir.Module('meu_modulo.bc') # Array global de 1024 elementos. typeA = ir.ArrayType(ir.IntType(64), 1024) arrayA = ir.GlobalVariable(module, typeA, "A") # arrayA.initializer = ir.IntType(64) arrayA.linkage = "common" # arrayA.initializer = ir.Constant(ir.IntType(64), 0) arrayA.align = 16 # Cria um valor zero para colocar no retorno. Zero64 = ir.Constant(ir.IntType(64), 0) # Declara o tipo do retorno da função main. mainFnReturnType = ir.IntType(64) # Cria a função main. t_func_main = ir.FunctionType(mainFnReturnType, ())
def ninja_to_ir_type(t: Type): # TODO(keegan) check if values are signed or unsigned if t.type_class == TypeClass.IntegerTypeClass: return ir.IntType(t.width * 8) else: raise ValueError()
def type(): return ir.IntType(32, False)
def visit_MLIL_LOW_PART(self, expr): return self.builder.trunc(self.visit(expr.src), ir.IntType(expr.size * 8))
def type(): return ir.IntType(1, signed=False)
import llvmlite.binding as llvm import sys from ctypes import CFUNCTYPE, c_int8, c_void_p, cast try: import faulthandler faulthandler.enable() except ImportError: pass llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() i8 = ll.IntType(8) i32 = ll.IntType(32) i64 = ll.IntType(64) MEMORY_SIZE = 1 << 16 COMPILED_FN_TYPE = ll.FunctionType(ll.VoidType(), []) MEMORY_TYPE = ll.ArrayType(i8, MEMORY_SIZE) ZERO_i8 = ll.Constant(i8, 0) ZERO_i32 = ll.Constant(i8, 0) ONE_i8 = ll.Constant(i8, 1) ONE_i32 = ll.Constant(i32, 1) MEMORY_MASK_i32 = ll.Constant(i32, MEMORY_SIZE - 1)
def type(): return ir.IntType(64)
import llvmlite.ir as ir
def type(): return ir.IntType(64, False)
def generate_number(self, statement): return ll.Constant(ll.IntType(32), statement.token.value)
def dist_get_size(context, builder, sig, args): fnty = lir.FunctionType(lir.IntType(32), []) fn = builder.module.get_or_insert_function(fnty, name="hpat_dist_get_size") return builder.call(fn, [])
def box_str_arr_split_view(typ, val, c): context = c.context builder = c.builder sp_view = context.make_helper(builder, string_array_split_view_type, val) # create array of objects with num_items shape mod_name = c.context.insert_const_string(c.builder.module, "numpy") np_class_obj = c.pyapi.import_module_noblock(mod_name) dtype = c.pyapi.object_getattr_string(np_class_obj, 'object_') l_num_items = builder.sext(sp_view.num_items, c.pyapi.longlong) num_items_obj = c.pyapi.long_from_longlong(l_num_items) out_arr = c.pyapi.call_method(np_class_obj, "ndarray", (num_items_obj, dtype)) # Array setitem call arr_get_fnty = LLType.function( lir.IntType(8).as_pointer(), [c.pyapi.pyobj, c.pyapi.py_ssize_t]) arr_get_fn = c.pyapi._get_function(arr_get_fnty, name="array_getptr1") arr_setitem_fnty = LLType.function( lir.VoidType(), [c.pyapi.pyobj, lir.IntType(8).as_pointer(), c.pyapi.pyobj]) arr_setitem_fn = c.pyapi._get_function(arr_setitem_fnty, name="array_setitem") # for each string with cgutils.for_range(builder, sp_view.num_items) as loop: str_ind = loop.index # start and end offset of string's list in index_offsets # sp_view.index_offsets[str_ind] list_start_offset = builder.sext( builder.load(builder.gep(sp_view.index_offsets, [str_ind])), lir.IntType(64)) # sp_view.index_offsets[str_ind+1] list_end_offset = builder.sext( builder.load( builder.gep(sp_view.index_offsets, [builder.add(str_ind, str_ind.type(1))])), lir.IntType(64)) # cgutils.printf(builder, "%d %d\n", list_start, list_end) # Build a new Python list nitems = builder.sub(list_end_offset, list_start_offset) nitems = builder.sub(nitems, nitems.type(1)) # cgutils.printf(builder, "str %lld n %lld\n", str_ind, nitems) list_obj = c.pyapi.list_new(nitems) with c.builder.if_then(cgutils.is_not_null(c.builder, list_obj), likely=True): with cgutils.for_range(c.builder, nitems) as loop: # data_offsets of current list start_index = builder.add(list_start_offset, loop.index) data_start = builder.load( builder.gep(sp_view.data_offsets, [start_index])) # add 1 since starts from -1 data_start = builder.add(data_start, data_start.type(1)) data_end = builder.load( builder.gep( sp_view.data_offsets, [builder.add(start_index, start_index.type(1))])) # cgutils.printf(builder, "ind %lld %lld\n", data_start, data_end) data_ptr = builder.gep(builder.extract_value(sp_view.data, 0), [data_start]) str_size = builder.sext(builder.sub(data_end, data_start), lir.IntType(64)) str_obj = c.pyapi.string_from_string_and_size( data_ptr, str_size) c.pyapi.list_setitem(list_obj, loop.index, str_obj) arr_ptr = builder.call(arr_get_fn, [out_arr, str_ind]) builder.call(arr_setitem_fn, [out_arr, arr_ptr, list_obj]) c.pyapi.decref(np_class_obj) return out_arr
def lower_open_bag(context, builder, sig, args): fnty = lir.FunctionType(lir.IntType(8).as_pointer(), [lir.IntType(8).as_pointer()]) fn = builder.module.get_or_insert_function(fnty, name="open_bag") return builder.call(fn, args)
return 0; } ''' binding.initialize() binding.initialize_native_target() binding.initialize_native_asmprinter() # yes, even this one # Define o target. target = binding.Target.from_triple("x86_64-pc-linux-gnu") target_machine = target.create_target_machine() # Cria o módulo. module = ir.Module(name='meu_modulo.bc') # Cria um valor zero para colocar no retorno. Zero = ir.Constant(ir.IntType(32), 0) # Declara o tipo do retorno da função main. mainFnReturnType = ir.IntType(32) # Cria a função main. t_func_main = ir.FunctionType(mainFnReturnType, ()) # Declara a função main. main = ir.Function(module, t_func_main, name='main') # Declara o bloco de entrada. entryBlock = main.append_basic_block('entry') exitBasicBlock = main.append_basic_block('exit') # Adiciona o bloco de entrada. builder = ir.IRBuilder(entryBlock)