[pypy-svn] r48369 - in pypy/dist/pypy/translator/llvm: . module test

rxe at codespeak.net rxe at codespeak.net
Wed Nov 7 20:26:53 CET 2007


Author: rxe
Date: Wed Nov  7 20:26:51 2007
New Revision: 48369

Modified:
   pypy/dist/pypy/translator/llvm/arraynode.py
   pypy/dist/pypy/translator/llvm/buildllvm.py
   pypy/dist/pypy/translator/llvm/codewriter.py
   pypy/dist/pypy/translator/llvm/database.py
   pypy/dist/pypy/translator/llvm/externs2ll.py
   pypy/dist/pypy/translator/llvm/extfuncnode.py
   pypy/dist/pypy/translator/llvm/funcnode.py
   pypy/dist/pypy/translator/llvm/gc.py
   pypy/dist/pypy/translator/llvm/genllvm.py
   pypy/dist/pypy/translator/llvm/module/support.py
   pypy/dist/pypy/translator/llvm/modwrapper.py
   pypy/dist/pypy/translator/llvm/opwriter.py
   pypy/dist/pypy/translator/llvm/structnode.py
   pypy/dist/pypy/translator/llvm/test/runtest.py
Log:
some mindless whacking with llvm 2.0 binaries in place of 1.9 ones; it's a start and some tests are passing now

Modified: pypy/dist/pypy/translator/llvm/arraynode.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/arraynode.py	(original)
+++ pypy/dist/pypy/translator/llvm/arraynode.py	Wed Nov  7 20:26:51 2007
@@ -3,7 +3,7 @@
 
 class ArrayNode(ConstantNode):
     __slots__ = "db value arraytype".split()
-    prefix = '%arrayinstance'
+    prefix = '@arrayinstance'
     
     def __init__(self, db, value):
         assert isinstance(lltype.typeOf(value), lltype.Array)
@@ -47,7 +47,7 @@
         else:
             ref = self.db.get_childref(p, c)
 
-        ref = "cast(%s* %s to %s*)" % (self.get_typerepr(),
+        ref = "bitcast(%s* %s to %s*)" % (self.get_typerepr(),
                                        ref,
                                        typeval)
         return ref
@@ -57,11 +57,11 @@
         assert p is None, "child PBC arrays are NOT needed by rtyper"
 
         fromptr = "%s*" % self.get_typerepr()
-        ref = "cast(%s %s to %s)" % (fromptr, self.name, toptr)
+        ref = "bitcast(%s %s to %s)" % (fromptr, self.name, toptr)
         return ref
 
     def get_childref(self, index):
-        return "getelementptr(%s* %s, int 0, uint 1, int %s)" % (
+        return "getelementptr(%s* %s, i32 0, i32 1, i32 %s)" % (
             self.get_typerepr(),
             self.name,
             index)
@@ -87,7 +87,7 @@
         return "[%s x %s]" % (arraylen, typeval)
     
     def get_childref(self, index):
-        return "getelementptr(%s* %s, int 0, int %s)" %(
+        return "getelementptr(%s* %s, i32 0, i32 %s)" %(
             self.get_typerepr(),
             self.name,
             index)
@@ -124,7 +124,7 @@
 
 class VoidArrayNode(ConstantNode):
     __slots__ = "db value".split()
-    prefix = '%voidarrayinstance'
+    prefix = '@voidarrayinstance'
 
     def __init__(self, db, value):
         assert isinstance(lltype.typeOf(value), lltype.Array)

Modified: pypy/dist/pypy/translator/llvm/buildllvm.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/buildllvm.py	(original)
+++ pypy/dist/pypy/translator/llvm/buildllvm.py	Wed Nov  7 20:26:51 2007
@@ -91,12 +91,7 @@
     def cmds_bytecode(self, base):
         # run llvm assembler and optimizer
         opts = self.optimizations()
-
-        if llvm_version() < 2.0:
-            self.cmds.append("llvm-as < %s.ll | opt %s -f -o %s.bc" % (base, opts, base))
-        else:
-            # we generate 1.x .ll files, so upgrade these first
-            self.cmds.append("llvm-upgrade < %s.ll | llvm-as | opt %s -f -o %s.bc" % (base, opts, base))
+        self.cmds.append("llvm-as < %s.ll | opt %s -f -o %s.bc" % (base, opts, base))
 
     def cmds_objects(self, base):
         # XXX why this hack???

Modified: pypy/dist/pypy/translator/llvm/codewriter.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/codewriter.py	(original)
+++ pypy/dist/pypy/translator/llvm/codewriter.py	Wed Nov  7 20:26:51 2007
@@ -88,14 +88,14 @@
 
     def startimpl(self):
         self.newline()
-        self._append("implementation")
+        #self._append("implementation")
         self.newline()
 
     def br_uncond(self, blockname): 
         self._indent("br label %%%s" %(blockname,))
 
     def br(self, cond, blockname_false, blockname_true):
-        self._indent("br bool %s, label %%%s, label %%%s"
+        self._indent("br i1 %s, label %%%s, label %%%s"
                      % (cond, blockname_true, blockname_false))
 
     def switch(self, intty, cond, defaultdest, value_labels):
@@ -111,7 +111,7 @@
         if linkage is None:
             linkage = self.linkage
         self.newline()
-        self._append("%s%s %s {" % (linkage, cconv, decl,))
+        self._append("define %s%s %s {" % (linkage, cconv, decl,))
 
     def closefunc(self): 
         self._append("}") 
@@ -138,10 +138,10 @@
         self._indent("%s = %s %s %s, ubyte %s" % (targetvar, name, type_,
                                                   ref1, ref2))
 
-    def cast(self, targetvar, fromtype, fromvar, targettype):
+    def cast(self, targetvar, fromtype, fromvar, targettype, casttype='bitcast'):
         if fromtype == 'void' and targettype == 'void':
             return
-        self._indent("%(targetvar)s = cast %(fromtype)s "
+        self._indent("%(targetvar)s = %(casttype)s %(fromtype)s "
                      "%(fromvar)s to %(targettype)s" % locals())
 
     def getelementptr(self, targetvar, type, typevar, indices, getptr=True):

Modified: pypy/dist/pypy/translator/llvm/database.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/database.py	(original)
+++ pypy/dist/pypy/translator/llvm/database.py	Wed Nov  7 20:26:51 2007
@@ -347,29 +347,29 @@
     def __init__(self, database):        
         self.database = database
         self.types = {
-            lltype.Char: "sbyte",
-            lltype.Bool: "bool",
+            lltype.Char: "i8",
+            lltype.Bool: "i1",
             lltype.SingleFloat: "float",
             lltype.Float: "double",
-            lltype.UniChar: "uint",
+            lltype.UniChar: "i8",
             lltype.Void: "void",
-            lltype.UnsignedLongLong: "ulong",
-            lltype.SignedLongLong: "long",
-            llmemory.Address: "sbyte*",
+            lltype.UnsignedLongLong: "i64",
+            lltype.SignedLongLong: "i64",
+            llmemory.Address: "i8*",
             #llmemory.WeakGcAddress: "sbyte*",
             }
 
         # 32 bit platform
         if sys.maxint == 2**31-1:
             self.types.update({
-                lltype.Signed: "int",
-                lltype.Unsigned: "uint" })
+                lltype.Signed: "i32",
+                lltype.Unsigned: "i32" })
             
         # 64 bit platform
         elif sys.maxint == 2**63-1:        
             self.types.update({
-                lltype.Signed: "long",
-                lltype.Unsigned: "ulong" })            
+                lltype.Signed: "i64",
+                lltype.Unsigned: "i64" })            
         else:
             raise Exception("Unsupported platform - unknown word size")
 
@@ -553,9 +553,9 @@
 
         r = self.database.repr_type
         indices_as_str = ", ".join("%s %s" % (w, i) for w, i in indices)
-        return "cast(%s* getelementptr(%s* null, %s) to int)" % (r(to),
-                                                                 r(from_),
-                                                                 indices_as_str)
+        return "ptrtoint(%s* getelementptr(%s* null, %s) to i32)" % (r(to),
+                                                                     r(from_),
+                                                                     indices_as_str)
 
     def get_offset(self, value, initialindices=None):
         " return (from_type, (indices, ...), to_type) "

Modified: pypy/dist/pypy/translator/llvm/externs2ll.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/externs2ll.py	(original)
+++ pypy/dist/pypy/translator/llvm/externs2ll.py	Wed Nov  7 20:26:51 2007
@@ -11,17 +11,23 @@
 from pypy.tool.udir import udir
 
 support_functions = [
-    "%raisePyExc_IOError",
-    "%raisePyExc_ValueError",
-    "%raisePyExc_OverflowError",
-    "%raisePyExc_ZeroDivisionError",
-    "%raisePyExc_RuntimeError",
-    "%raisePyExc_thread_error",
-    "%RPyString_FromString",
-    "%RPyString_AsString",
-    "%RPyString_Size",
-    "%RPyExceptionOccurred",
-    "%LLVM_RPython_StartupCode",
+    "@raisePyExc_IOError",
+    "@raisePyExc_ValueError",
+    "@raisePyExc_OverflowError",
+    "@raisePyExc_ZeroDivisionError",
+    "@raisePyExc_RuntimeError",
+    "@raisePyExc_thread_error",
+    "@RPyString_FromString",
+    "@RPyString_AsString",
+    "@RPyString_Size",
+    "@RPyExceptionOccurred",
+    "@LLVM_RPython_StartupCode",
+    ]
+
+
+skip_lines = [
+    "%RPyString = type opaque",
+    "__main",
     ]
 
 def get_module_file(name):
@@ -59,14 +65,15 @@
     # strip declares that are in funcnames
     for line in llcode.split('\n'):
 
-        # For some reason gcc introduces this and then we cant resolve it
-        # XXX Get rid of this - when got more time on our hands
-        if line.find("__main") >= 1:
-           continue
-
         # get rid of any of the structs that llvm-gcc introduces to struct types
         line = line.replace("%struct.", "%")
 
+        # XXX slowwwwwww
+        for x in skip_lines:
+            if line.find(x) >= 0:
+                line = ''
+                break
+
         # strip comments
         comment = line.find(';')
         if comment >= 0:
@@ -74,18 +81,18 @@
         line = line.rstrip()
 
         # find function names, declare them with the default calling convertion
-        if '(' in  line and line[-1:] == '{':
-           returntype, s = line.split(' ', 1)
-           funcname  , s = s.split('(', 1)
-           funcnames[funcname] = True
-           if line.find("internal") == -1:
-                if funcname not in ["%main", "%ctypes_RPython_StartupCode"]:
-                    internal = 'internal '
-                    line = '%s%s %s' % (internal, default_cconv, line,)
+        #if '(' in  line and line[-1:] == '{':
+        #   returntype, s = line.split(' ', 1)
+        #   funcname  , s = s.split('(', 1)
+        #   funcnames[funcname] = True
+        #   if line.find("internal") == -1:
+        #        if funcname not in ["@main", "@ctypes_RPython_StartupCode"]:
+        #            internal = 'internal '
+        #            line = '%s%s %s' % (internal, default_cconv, line,)
         ll_lines.append(line)
 
-    # patch calls to function that we just declared with differnet cconv
-    ll_lines2, calltag, declaretag = [], 'call ', 'declare '
+    # patch calls to function that we just declared with different cconv
+    ll_lines2, calltag, declaretag, definetag = [], 'call ', 'declare ', 'define ' 
     for line in ll_lines:
         i = line.find(calltag)
         if i >= 0:
@@ -102,15 +109,24 @@
                     cconv = default_cconv
                     break
             line = "declare %s %s" % (cconv, line[len(declaretag):])
+        if line[:len(definetag)] == definetag:
+            line = line.replace("internal ", "")
+            cconv = 'ccc'
+            for funcname in funcnames.keys():
+                if line.find(funcname) >= 0:
+                    cconv = default_cconv
+                    break
+            line = "define %s %s" % (cconv, line[len(definetag):])
         ll_lines2.append(line)
 
-    ll_lines2.append("declare ccc void %abort()")
+    ll_lines2.append("declare ccc void @abort()")
 
     llcode = '\n'.join(ll_lines2)
-    try:
-        decl, impl = llcode.split('implementation')
-    except:
-        raise "Can't compile external function code (llcode.c): ERROR:", llcode
+    decl, impl = '', llcode
+    #try:
+    #    decl, impl = llcode.split('implementation')
+    #except:
+    #    raise Exception("Can't compile external function code (llcode.c)")
     return decl, impl
 
 
@@ -172,7 +188,7 @@
         
     def predeclarefn(c_name, llname):
         function_names.append(llname)
-        assert llname[0] == "%"
+        assert llname[0] == "@"
         llname = llname[1:]
         assert '\n' not in llname
         ccode.append('#define\t%s\t%s\n' % (c_name, llname))

Modified: pypy/dist/pypy/translator/llvm/extfuncnode.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/extfuncnode.py	(original)
+++ pypy/dist/pypy/translator/llvm/extfuncnode.py	Wed Nov  7 20:26:51 2007
@@ -14,11 +14,11 @@
 
 # signature of external functions differ from C's implementation
 ext_func_sigs = {
-    "%LL_stack_too_big" : ExtFuncSig("int", None),
+    "@LL_stack_too_big" : ExtFuncSig("int", None),
     }
 
 if maxint != 2**31-1:
-    ext_func_sigs["%LL_math_ldexp"] = ExtFuncSig(None, [None, "int"])
+    ext_func_sigs["@LL_math_ldexp"] = ExtFuncSig(None, [None, "int"])
 
 
 class SimplerExternalFuncNode(FuncNode):
@@ -26,7 +26,7 @@
     def __init__(self, db, value):
         self.db = db
         self.value = value
-        self.name = "%" + value._name
+        self.name = "@" + value._name
 
     def external_c_source(self):
         # return a list of unique includes and sources in C

Modified: pypy/dist/pypy/translator/llvm/funcnode.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/funcnode.py	(original)
+++ pypy/dist/pypy/translator/llvm/funcnode.py	Wed Nov  7 20:26:51 2007
@@ -11,7 +11,7 @@
     pass
 
 class FuncImplNode(FuncNode):
-    prefix = '%pypy_'
+    prefix = '@pypy_'
     __slots__ = "db value graph block_to_name bad_switch_block".split()
 
     def __init__(self, db, value):

Modified: pypy/dist/pypy/translator/llvm/gc.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/gc.py	(original)
+++ pypy/dist/pypy/translator/llvm/gc.py	Wed Nov  7 20:26:51 2007
@@ -81,7 +81,7 @@
         # malloc_size is unsigned right now
         codewriter.malloc(targetvar, "sbyte", size)
         # XXX uses own cconv
-        codewriter.call(None, 'void', '%llvm.memset' + postfix(),
+        codewriter.call(None, 'void', '@llvm.memset' + postfix(),
                         ['sbyte*', 'ubyte', uword, uword],
                         [targetvar, 0, size, boundary_size],
                         cconv='ccc')               
@@ -110,7 +110,7 @@
         word = self.db.get_machine_word()
         uword = self.db.get_machine_uword()
 
-        fnname = '%pypy_malloc' + (atomic and '_atomic' or '')
+        fnname = '@pypy_malloc' + (atomic and '_atomic' or '')
 
 ##        XXX (arigo) disabled the ring buffer for comparison purposes
 ##        XXX until we know if it's a valid optimization or not
@@ -121,20 +121,20 @@
 ##            atomic = False 
 
         # malloc_size is unsigned right now
-        sizeu = '%malloc_sizeu' + self.get_count()        
-        codewriter.cast(sizeu, word, size, uword)
-        codewriter.call(targetvar, 'sbyte*', fnname, [word], [size])
+        #sizeu = '%malloc_sizeu' + self.get_count()        
+        #codewriter.cast(sizeu, word, size, uword)
+        codewriter.call(targetvar, 'i8*', fnname, [word], [size])
 
         if atomic:
             # XXX uses own cconv
-            codewriter.call(None, 'void', '%llvm.memset' + postfix(),
-                            ['sbyte*', 'ubyte', uword, uword],
-                            [targetvar, 0, sizeu, boundary_size],
+            codewriter.call(None, 'void', '@llvm.memset' + postfix(),
+                            ['i8*', 'i8', word, word],
+                            [targetvar, 0, size, boundary_size],
                             cconv='ccc')        
 
 
     def op__collect(self, codewriter, opr):
-        codewriter.call(opr.retref, opr.rettype, "%pypy_gc__collect",
+        codewriter.call(opr.retref, opr.rettype, "@pypy_gc__collect",
                         opr.argtypes, opr.argrefs)
 
 class RefcountingGcPolicy(RawGcPolicy):

Modified: pypy/dist/pypy/translator/llvm/genllvm.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/genllvm.py	(original)
+++ pypy/dist/pypy/translator/llvm/genllvm.py	Wed Nov  7 20:26:51 2007
@@ -225,12 +225,12 @@
                 write_raise_exc(c_name, exc_repr, codewriter)
 
     def write_setup_impl(self, codewriter):
-        open_decl =  "sbyte* %LLVM_RPython_StartupCode()"
+        open_decl =  "i8* @LLVM_RPython_StartupCode()"
         codewriter.openfunc(open_decl)
         for node in self.db.getnodes():
             node.writesetupcode(codewriter)
 
-        codewriter.ret("sbyte*", "null")
+        codewriter.ret("i8*", "null")
         codewriter.closefunc()
 
     def compile_module(self):

Modified: pypy/dist/pypy/translator/llvm/module/support.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/module/support.py	(original)
+++ pypy/dist/pypy/translator/llvm/module/support.py	Wed Nov  7 20:26:51 2007
@@ -1,35 +1,45 @@
 extdeclarations = """
-declare ccc uint %strlen(sbyte*)
-declare ccc void %llvm.memsetPOSTFIX(sbyte*, ubyte, UWORD, UWORD)
-declare ccc void %llvm.memcpyPOSTFIX(sbyte*, sbyte*, UWORD, UWORD)
+declare ccc i32 @strlen(i8*)
 """
 
 extfunctions = """
-internal CC sbyte* %RPyString_AsString(%RPyString* %structstring) {
-    %source1ptr = getelementptr %RPyString* %structstring, int 0, uint 1, uint 1
-    %source1 = cast [0 x sbyte]* %source1ptr to sbyte*
-    ret sbyte* %source1
+define internal CC %RPyString* @RPyString_FromString(i8* %s) {
+    %len       = call ccc i32 @strlen(i8* %s)
+    %rpy       = call CC %RPyString* @pypy_RPyString_New__Signed(i32 %len)
+    %rpystrptr = getelementptr %RPyString* %rpy, i32 0, i32 1, i32 1
+    %rpystr    = bitcast [0 x i8]* %rpystrptr to i8*
+
+    call ccc void @llvm.memcpyPOSTFIX(i8* %rpystr, i8* %s, WORD %len, WORD 0)
+
+    ret %RPyString* %rpy
 }
 
-internal CC WORD %RPyString_Size(%RPyString* %structstring) {
-    %sizeptr = getelementptr %RPyString* %structstring, int 0, uint 1, uint 0
+define internal CC i8* @RPyString_AsString(%RPyString* %structstring) {
+    %source1ptr = getelementptr %RPyString* %structstring, i32 0, i32 1, i32 1
+    %source1 = bitcast [0 x i8]* %source1ptr to i8*
+    ret i8* %source1
+}
+
+define internal CC WORD @RPyString_Size(%RPyString* %structstring) {
+    %sizeptr = getelementptr %RPyString* %structstring, i32 0, i32 1, i32 0
     %size = load WORD* %sizeptr
     ret WORD %size
 }
 
-internal CC %RPyString* %RPyString_FromString(sbyte* %s) {
-    %lenu      = call ccc uint %strlen(sbyte* %s)
-    %lenuword  = cast uint %lenu to UWORD
-    %lenword   = cast uint %lenu to WORD
-    %rpy       = call CC %RPyString* %pypy_RPyString_New__Signed(WORD %lenword)
-    %rpystrptr = getelementptr %RPyString* %rpy, int 0, uint 1, uint 1
-    %rpystr    = cast [0 x sbyte]* %rpystrptr to sbyte*
-
-    call ccc void %llvm.memcpyPOSTFIX(sbyte* %rpystr, sbyte* %s, UWORD %lenuword, UWORD 0)
-
-    ret %RPyString* %rpy
+define internal CC double @pypyop_float_abs(double %x) {
+block0:
+    %cond1 = fcmp ugt double %x, 0.0
+    br i1 %cond1, label %return_block, label %block1
+block1:
+    %x2 = sub double 0.0, %x
+    br label %return_block
+return_block:
+    %result = phi double [%x, %block0], [%x2, %block1]
+    ret double %result
 }
 
+"""
+"""
 internal CC WORD %pypyop_int_abs(WORD %x) {
 block0:
     %cond1 = setge WORD %x, 0
@@ -54,18 +64,6 @@
     ret long %result
 }
 
-internal CC double %pypyop_float_abs(double %x) {
-block0:
-    %cond1 = setge double %x, 0.0
-    br bool %cond1, label %return_block, label %block1
-block1:
-    %x2 = sub double 0.0, %x
-    br label %return_block
-return_block:
-    %result = phi double [%x, %block0], [%x2, %block1]
-    ret double %result
-}
-
 """
 
 extfunctions_standalone = """
@@ -81,10 +79,9 @@
 
 """
 
-
 def write_raise_exc(c_name, exc_repr, codewriter):
     l = """
-internal CC void %%raise%s(sbyte* %%msg) {
+define internal CC void @raise%s(i8* %%msg) {
     ;%%exception_value = cast %s to %%RPYTHON_EXCEPTION*
     ret void
 }

Modified: pypy/dist/pypy/translator/llvm/modwrapper.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/modwrapper.py	(original)
+++ pypy/dist/pypy/translator/llvm/modwrapper.py	Wed Nov  7 20:26:51 2007
@@ -52,12 +52,6 @@
 def from_unichar(arg):
     return ord(arg)
 
-def to_bool(res):
-    return bool(res)
-
-def to_unichar(res):
-    return unichr(res)
-
 def from_str(arg):
     # XXX wont work over isolate : arg should be converted into a string first
     n = len(arg.chars)
@@ -190,10 +184,10 @@
 
     def build_lltype_to_ctypes_to_res(self, T):
         if T is lltype.Bool:
-            action = 'to_bool'
+            action = 'bool'
 
         elif T is lltype.UniChar:
-            action = 'to_unichar'
+            action = 'unichr'
 
         elif T is lltype.Unsigned:
             action = 'r_uint'

Modified: pypy/dist/pypy/translator/llvm/opwriter.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/opwriter.py	(original)
+++ pypy/dist/pypy/translator/llvm/opwriter.py	Wed Nov  7 20:26:51 2007
@@ -39,51 +39,64 @@
             self.functionref = '%pypyop_' + op.opname
 
 class OpWriter(object):            
-    
+  
+    shift_operations = {
+        # ZZZ all these 
+        'int_lshift': 'shl',
+        'int_rshift': 'shr',
+        
+        'uint_lshift': 'shl',
+        'uint_rshift': 'shr',
+        
+        'llong_lshift': 'shl',
+        'llong_rshift': 'shr',
+        }
+
     binary_operations = {
         'float_mul'     : 'mul',
         'float_add'     : 'add',
         'float_sub'     : 'sub',
-        'float_truediv' : 'div',
-        
-        'ptr_eq'        : 'seteq',
-        'ptr_ne'        : 'setne' }
+        #ZZZ'float_truediv' : 'div',
+        'ptr_eq'        : 'icmp eq',
+        'ptr_ne'        : 'icmp ne' }
 
     # generic numeric ops
     for tt in 'int llong ullong uint'.split():
         for oo in 'mul add sub and or xor'.split():
             binary_operations['%s_%s' % (tt, oo)] = oo
-        binary_operations['%s_floordiv' % tt] = 'div'
-        binary_operations['%s_mod' % tt] = 'rem'
+
+        #ZZZbinary_operations['%s_floordiv' % tt] = 'div'
+        #ZZZbinary_operations['%s_mod' % tt] = 'rem'
+
 
     # comparison ops
-    for tt in 'int llong ullong uint unichar float'.split():
-        for oo in 'lt le eq ne ge gt'.split():
-            binary_operations['%s_%s' % (tt, oo)] = 'set%s' % oo
+    for tt in 'int llong unichar'.split():
+        for oo in 'eq ne'.split():
+            binary_operations['%s_%s' % (tt, oo)] = 'icmp %s' % oo
+        for oo in 'lt le ge gt'.split():
+            binary_operations['%s_%s' % (tt, oo)] = 'icmp s%s' % oo
+            
+    for tt in 'ullong uint'.split():
+        for oo in 'eq ne'.split():
+            binary_operations['%s_%s' % (tt, oo)] = 'icmp %s' % oo
+        for oo in 'lt le ge gt'.split():
+            binary_operations['%s_s%s' % (tt, oo)] = 'icmp u%s' % oo
 
+    for tt in 'float'.split():
+        for oo in 'lt le eq ne ge gt'.split():
+            binary_operations['%s_%s' % (tt, oo)] = 'fcmp u%s' % oo
 
-    shift_operations = {'int_lshift': 'shl',
-                        'int_rshift': 'shr',
-                        
-                        'uint_lshift': 'shl',
-                        'uint_rshift': 'shr',
-                        
-                        'llong_lshift': 'shl',
-                        'llong_rshift': 'shr',
-                         }
-
-    char_operations = {'char_lt': 'setlt',
-                       'char_le': 'setle',
-                       'char_eq': 'seteq',
-                       'char_ne': 'setne',
-                       'char_ge': 'setge',
-                       'char_gt': 'setgt'}
+    char_operations = {'char_lt': 'icmp lt',
+                       'char_le': 'icmp le',
+                       'char_eq': 'icmp eq',
+                       'char_ne': 'icmp ne',
+                       'char_ge': 'icmp ge',
+                       'char_gt': 'icmp gt'}
 
     def __init__(self, db, codewriter):
         self.db = db
         self.codewriter = codewriter
         self.word = db.get_machine_word()
-        self.uword = db.get_machine_uword()
 
     def _tmp(self, count=1):
         if count == 1:
@@ -97,13 +110,15 @@
         if isinstance(ARRAYTYPE, lltype.Array):
             if not ARRAYTYPE._hints.get("nolength", False):
                 # skip the length field
-                indices.append((self.uword, 1))
+                indices.append((self.word, 1))
         else:
             assert isinstance(ARRAYTYPE, lltype.FixedSizeArray)
         return indices
 
     def write_operation(self, op):
-        #log(op)
+
+        if self.db.genllvm.config.translation.llvm.debug:
+            self.codewriter.comment(str(op))
 
         if op.opname in ("direct_call", 'indirect_call'):
             opr = OpReprCall(op, self.db)
@@ -113,12 +128,16 @@
         if op.opname.startswith('gc'):
             meth = getattr(self.db.gcpolicy, 'op' + op.opname[2:])
             meth(self.codewriter, opr)
+
         elif op.opname in self.binary_operations:
             self.binaryop(opr)
+
         elif op.opname in self.shift_operations:
             self.shiftop(opr)
+
         elif op.opname in self.char_operations:
             self.char_binaryop(opr)
+
         elif op.opname.startswith('cast_') or op.opname.startswith('truncate_'):
             if op.opname == 'cast_char_to_int':
                 self.cast_char_to_int(opr)
@@ -128,10 +147,6 @@
             meth = getattr(self, op.opname, None)
             if not meth:
                 raise Exception, "operation %s not found" % op.opname
-
-            # XXX bit unclean
-            if self.db.genllvm.config.translation.llvm.debug:
-                self.codewriter.comment(str(op))
             meth(opr)            
     
     def _generic_pow(self, opr, onestr): 
@@ -169,7 +184,7 @@
 
     def int_abs(self, opr):
         assert len(opr.argrefs) == 1
-        functionref = '%pypyop_' + opr.op.opname
+        functionref = '@pypyop_' + opr.op.opname
         self.codewriter.call(opr.retref, opr.rettype, functionref,
                              opr.argtypes, opr.argrefs)
 
@@ -234,6 +249,7 @@
 
     def cast_char_to_int(self, opr):
         " works for all casts "
+        XXX
         assert len(opr.argrefs) == 1
         intermediate = self._tmp()
         self.codewriter.cast(intermediate, opr.argtypes[0],
@@ -242,13 +258,38 @@
 
     def cast_primitive(self, opr):
         " works for all casts "
-        #assert len(opr.argrefs) == 1
+        fromtype = opr.argtypes[0]
+        totype = opr.rettype
+        casttype = "bitcast"
+        if '*' not in fromtype:
+            if fromtype[0] == 'i' and totype[0] == 'i':
+                fromsize = int(fromtype[1:])
+                tosize = int(totype[1:])
+                if tosize > fromsize:
+                    # ZZZ signed
+                    casttype = "zext" 
+                elif tosize < fromsize:
+                    casttype = "trunc"
+                else:
+                    pass
+            else:
+                if (fromtype[0] == 'i' and totype == 'double'):
+                    # ZZZ signed
+                    casttype = "sitofp"
+                elif (fromtype == 'double' and totype[0] == 'i'):
+                    # ZZZ signed
+                    casttype = "fptosi"
+                else:
+                    assert False, "this shouldtnt be possible"
+        else:
+            assert '*' in totype
+
         self.codewriter.cast(opr.retref, opr.argtypes[0],
-                             opr.argrefs[0], opr.rettype)
+                             opr.argrefs[0], opr.rettype, casttype)
     same_as = cast_primitive
 
     def int_is_true(self, opr):
-        self.codewriter.binaryop("setne", opr.retref, opr.argtypes[0],
+        self.codewriter.binaryop("icmp ne", opr.retref, opr.argtypes[0],
                                  opr.argrefs[0], "0")
     uint_is_true = int_is_true
     llong_is_true = int_is_true
@@ -258,11 +299,11 @@
                                  opr.argrefs[0], "0.0")
 
     def ptr_nonzero(self, opr):
-        self.codewriter.binaryop("setne", opr.retref, opr.argtypes[0],
+        self.codewriter.binaryop("icmp ne", opr.retref, opr.argtypes[0],
                                  opr.argrefs[0], "null")
 
     def ptr_iszero(self, opr):
-        self.codewriter.binaryop("seteq", opr.retref, opr.argtypes[0],
+        self.codewriter.binaryop("icmp eq", opr.retref, opr.argtypes[0],
                                  opr.argrefs[0], "null")
 
     def direct_call(self, opr):
@@ -284,7 +325,7 @@
 
     def call_boehm_gc_alloc(self, opr):
         word = self.db.get_machine_word()
-        self.codewriter.call(opr.retref, 'sbyte*', '%pypy_malloc',
+        self.codewriter.call(opr.retref, 'i8*', '%pypy_malloc',
                              [word], [opr.argrefs[0]])
 
     def to_getelementptr(self, TYPE, args):
@@ -302,19 +343,19 @@
                 indexref = self.db.repr_arg(arg)
 
             if isinstance(TYPE, lltype.FixedSizeArray):
-                indices.append(("int", indexref))
+                indices.append(("i32", indexref))
                 TYPE = TYPE.OF
 
             elif isinstance(TYPE, lltype.Array):
                 if not TYPE._hints.get("nolength", False):
-                    indices.append(("uint", 1))
-                indices.append(("int", indexref))
+                    indices.append(("i32", 1))
+                indices.append(("i32", indexref))
                 TYPE = TYPE.OF
 
             elif isinstance(TYPE, lltype.Struct):
                 assert name is not None
                 TYPE = getattr(TYPE, name)
-                indices.append(("uint", indexref))
+                indices.append(("i32", indexref))
 
             else:
                 raise Exception("unsupported type: %s" % TYPE)
@@ -369,7 +410,7 @@
         TYPE, indices = self.to_getelementptr(op.args[0].concretetype.TO, op.args[1:])
         if isinstance(TYPE, lltype.Array):
             # gets the length
-            indices.append(("uint", 0))
+            indices.append(("i32", 0))
             lengthref = self._tmp()
             self.codewriter.getelementptr(lengthref, opr.argtypes[0], opr.argrefs[0], indices)
         else:
@@ -393,7 +434,7 @@
         assert index != -1
         tmpvar = self._tmp()
         self.codewriter.getelementptr(tmpvar, opr.argtypes[0],
-                                      opr.argrefs[0], [(self.uword, index)])
+                                      opr.argrefs[0], [(self.word, index)])
 
         # getelementptr gets a pointer to the right type, except the generated code really expected 
         # an array of size 1... so we just cast it
@@ -435,9 +476,10 @@
 
     def _op_adr_generic(self, opr, llvm_op):
         addr, res = self._tmp(2)
-        self.codewriter.cast(addr, opr.argtypes[0], opr.argrefs[0], self.word)
+
+        self.codewriter.cast(addr, opr.argtypes[0], opr.argrefs[0], self.word, 'ptrtoint')
         self.codewriter.binaryop(llvm_op, res, self.word, addr, opr.argrefs[1])
-        self.codewriter.cast(opr.retref, self.word, res, opr.rettype)
+        self.codewriter.cast(opr.retref, self.word, res, opr.rettype, 'inttoptr')
 
     def adr_add(self, opr):
         self._op_adr_generic(opr, "add")
@@ -447,34 +489,34 @@
 
     def _op_adr_cmp(self, opr, llvm_op):
         addr1, addr2 = self._tmp(2)
-        self.codewriter.cast(addr1, opr.argtypes[0], opr.argrefs[0], self.word)
-        self.codewriter.cast(addr2, opr.argtypes[1], opr.argrefs[1], self.word)
-        assert opr.rettype == "bool"
+        self.codewriter.cast(addr1, opr.argtypes[0], opr.argrefs[0], self.word, 'ptrtoint')
+        self.codewriter.cast(addr2, opr.argtypes[1], opr.argrefs[1], self.word, 'ptrtoint')
+        assert opr.rettype == "i1"
         self.codewriter.binaryop(llvm_op, opr.retref, self.word, addr1, addr2)
 
     def adr_eq(self, opr):
-        self._op_adr_cmp(opr, "seteq")
+        self._op_adr_cmp(opr, "icmp eq")
 
     def adr_ne(self, opr):
-        self._op_adr_cmp(opr, "setne")
+        self._op_adr_cmp(opr, "icmp ne")
 
     def adr_le(self, opr):
-        self._op_adr_cmp(opr, "setle")
+        self._op_adr_cmp(opr, "icmp le")
 
     def adr_gt(self, opr):
-        self._op_adr_cmp(opr, "setgt")
+        self._op_adr_cmp(opr, "icmp gt")
 
     def adr_lt(self, opr):
-        self._op_adr_cmp(opr, "setlt")
+        self._op_adr_cmp(opr, "icmp lt")
 
     def adr_ge(self, opr):
-        self._op_adr_cmp(opr, "setge")
+        self._op_adr_cmp(opr, "icmp ge")
 
     # XXX Not sure any of this makes sense - maybe seperate policy for
     # different flavours of mallocs?  Well it depend on what happens the GC
     # developments
     def raw_malloc(self, opr):
-        self.codewriter.call(opr.retref, opr.rettype, "%raw_malloc",
+        self.codewriter.call(opr.retref, opr.rettype, "@raw_malloc",
                              opr.argtypes, opr.argrefs)
 
     def raw_malloc_usage(self, opr):
@@ -482,15 +524,15 @@
                              opr.rettype)
 
     def raw_free(self, opr):
-        self.codewriter.call(opr.retref, opr.rettype, "%raw_free",
+        self.codewriter.call(opr.retref, opr.rettype, "@raw_free",
                              opr.argtypes, opr.argrefs)
 
     def raw_memcopy(self, opr):
-        self.codewriter.call(opr.retref, opr.rettype, "%raw_memcopy",
+        self.codewriter.call(opr.retref, opr.rettype, "@raw_memcopy",
                              opr.argtypes, opr.argrefs)
 
     def raw_memclear(self, opr):
-        self.codewriter.call(opr.retref, opr.rettype, "%raw_memclear",
+        self.codewriter.call(opr.retref, opr.rettype, "@raw_memclear",
                              opr.argtypes, opr.argrefs)
 
     def raw_store(self, opr):
@@ -543,7 +585,7 @@
 
     def debug_fatalerror(self, opr):
         # XXX message?
-        self.codewriter.call(None, "void", "%abort", [], [])
+        self.codewriter.call(None, "void", "@abort", [], [])
 
     def hint(self, opr):
         self.same_as(opr)
@@ -554,7 +596,7 @@
                              'false', opr.rettype)
 
     def debug_llinterpcall(self, opr):
-        self.codewriter.call(None, "void", "%abort", [], [])
+        self.codewriter.call(None, "void", "@abort", [], [])
         # cheat llvm
         self.codewriter.cast(opr.retref, opr.rettype, 'null', opr.rettype)
 

Modified: pypy/dist/pypy/translator/llvm/structnode.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/structnode.py	(original)
+++ pypy/dist/pypy/translator/llvm/structnode.py	Wed Nov  7 20:26:51 2007
@@ -19,7 +19,7 @@
     """
     __slots__ = "db value structtype _get_ref_cache _get_types".split()
 
-    prefix = '%structinstance_'
+    prefix = '@structinstance_'
 
     def __init__(self, db, value):
         self.db = db
@@ -63,7 +63,7 @@
                 break
             pos += 1
 
-        return "getelementptr(%s* %s, int 0, uint %s)" %(
+        return "getelementptr(%s* %s, i32 0, i32 %s)" %(
             self.get_typerepr(),
             self.get_ref(),
             pos)
@@ -115,13 +115,13 @@
             ref = self.db.get_childref(p, c)
             if isinstance(self.value, lltype._subarray):
                 # ptr -> array of len 1
-                ref = "cast(%s* %s to %s*)" % (self.db.repr_type(self.arraytype),
+                ref = "bitcast(%s* %s to %s*)" % (self.db.repr_type(self.arraytype),
                                                ref,
                                                self.db.repr_type(lltype.typeOf(self.value)))
         return ref
 
     def get_childref(self, index):
-        return "getelementptr(%s* %s, int 0, int %s)" % (
+        return "getelementptr(%s* %s, i32 0, i32 %s)" % (
             self.get_typerepr(),
             self.get_ref(),
             index) 
@@ -194,7 +194,7 @@
             pos += 1
         assert found
 
-        ref = "getelementptr(%s* %s, int 0, uint %s)" %(
+        ref = "getelementptr(%s* %s, i32 0, i32 %s)" %(
             self.get_typerepr(),
             super(StructVarsizeNode, self).get_ref(),
             pos)
@@ -204,9 +204,9 @@
     def get_ref(self):
         ref = super(StructVarsizeNode, self).get_ref()
         typeval = self.db.repr_type(lltype.typeOf(self.value))
-        ref = "cast(%s* %s to %s*)" % (self.get_typerepr(),
-                                       ref,
-                                       typeval)
+        ref = "bitcast(%s* %s to %s*)" % (self.get_typerepr(),
+                                          ref,
+                                          typeval)
         return ref
     
     def get_pbcref(self, toptr):
@@ -215,6 +215,7 @@
         p, c = lltype.parentlink(self.value)
         assert p is None, "child varsize struct are NOT needed by rtyper"
         fromptr = "%s*" % self.get_typerepr()
-        refptr = "getelementptr(%s %s, int 0)" % (fromptr, ref)
-        ref = "cast(%s %s to %s)" % (fromptr, refptr, toptr)
+        refptr = "getelementptr(%s %s, i32 0)" % (fromptr, ref)
+        ref = "bitcast(%s %s to %s)" % (fromptr, refptr, toptr)
         return ref
+    

Modified: pypy/dist/pypy/translator/llvm/test/runtest.py
==============================================================================
--- pypy/dist/pypy/translator/llvm/test/runtest.py	(original)
+++ pypy/dist/pypy/translator/llvm/test/runtest.py	Wed Nov  7 20:26:51 2007
@@ -9,7 +9,7 @@
 
 optimize_tests = False
 native_llvm_backend = True
-MINIMUM_LLVM_VERSION = 1.9
+MINIMUM_LLVM_VERSION = 2.0
 FLOAT_PRECISION = 8
 
 ext_modules = []



More information about the Pypy-commit mailing list