llvm-2.9 PB Code Generator progress

Sujets variés concernant le développement en PureBasic
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9

Message par idle »

updated to 2.9, included binaries dans les fiche

llvm2.9.zip

If you want to build it your self
Grom a écrit :
Download the 2.9 version ( source code ) http://llvm.org/releases/
- Extract to your desktop
- Open Terminal and go into llvm-2.9 directories
- ./configure --enable-shared
- make
- Drink coffee 20 mins
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

Le deuxième objectif

Bonjour LLVM-PB monde :mrgreen:

suddenly I feel like kcc, very happy my code compiled! :wink:
Avatar de l’utilisateur
graph100
Messages : 1318
Inscription : sam. 21/mai/2005 17:50

Re: llvm-2.9 avec Hello LLVM-PB World

Message par graph100 »

idle a écrit :suddenly I feel like kcc, very happy my code compiled! :wink:
:lol: :lol: :lol: :lol:

@idle : remarquable work ! Even if I can't immerse myself in it, it sound very interresting. (But I have not enought time, sadlly)

---
@idle : travail remarquable ! Même si je ne peux me plonger dans son étude, il me semble vachement interressant. (Mais tristement, je n'ai pas assez de temps...)
_________________________________________________
Mon site : CeriseCode (Attention Chantier perpétuel ;))
Avatar de l’utilisateur
SPH
Messages : 4937
Inscription : mer. 09/nov./2005 9:53

Re: llvm-2.8

Message par SPH »

Kwai chang caine a écrit :Je ne sais pas à quoi ça sert, comme dab, mais quand on te fait un cadeau, faut toujours dire merci 8)

I don't know what is the function of this code, like usually :oops: , but when somebody give a present, it's important to always say thanks :roll:
Thanks a lot IDLE 8)
Moi c'est pareil. Depuis le temps, je devrais le savoir mais je ne sais toujours pas.

!i!i!i!i!i!i!i!i!i!
!i!i!i!i!i!i!
!i!i!i!
//// Informations ////
Intel Core i7 4770 64 bits - GTX 650 Ti
Version de PB : 6.12LTS- 64 bits
G-Rom
Messages : 3641
Inscription : dim. 10/janv./2010 5:29

Re: llvm-2.9 avec Hello LLVM-PB World

Message par G-Rom »

En gros la llvm te permet de fabriquer des exécutables , cette lib , te permet via ces fonctions de créer du bytecode qui sera par la suite transformé en code executable , les fonctions sont du style : 'CreateFunction(Name.s , *Args, NbArg.i)' , ensuite , via une autre fonction il te sort du bytecode. En gros , cette lib sert surtout à la création de compilateur.
Avatar de l’utilisateur
SPH
Messages : 4937
Inscription : mer. 09/nov./2005 9:53

Re: llvm-2.9 avec Hello LLVM-PB World

Message par SPH »

ok mais comme d'autre, je ne sais toujours pas utiliser des libs :oops:

!i!i!i!i!i!i!i!i!i!
!i!i!i!i!i!i!
!i!i!i!
//// Informations ////
Intel Core i7 4770 64 bits - GTX 650 Ti
Version de PB : 6.12LTS- 64 bits
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

The eventual goal is to create a PB front end for the llvm tool chain by creating a self hosting PB cross compiler
It means the wider PB community will then be able to contribute to the project easier by adding high level functions
written in PB or c like "openwindow" to support other platforms like iphone's or windows mobile ...

L'objectif final est de créer un front end PB pour la chaîne d'outils LLVM en créant une auto d'hébergement PB compilateur croisé
Cela signifie que la communauté plus large PB sera alors en mesure de contribuer au projet plus facile en ajoutant des fonctions de haut niveau
écrit en PB ou c comme "openWindow" pour soutenir d'autres plateformes comme l'iPhone ou Windows Mobile ...
G-Rom
Messages : 3641
Inscription : dim. 10/janv./2010 5:29

Re: llvm-2.9 avec Hello LLVM-PB World

Message par G-Rom »

Very good work. Do you make an explaination of how to make Simple variable , structure , Function , entry point (eg: main() ) , operation like add sub div , etc...
:mrgreen:
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

Hello world shows how to create a Main and import an external function. (llvm has all the definitions of the std c lib)
The recursive Fibonacci shows how to call an internal function
The iterative Fibonacci shows how to create local Variables and do add and sub

All expressions are in SSA (static single assignment) like this
a1 = a0 * a0
a2= a1 + b
You can't have
a0 = a0 * a0
It doesn't matter what you name them but in a compiler you would do it adding to the label name

I still need to work out how to call Functions with multiple parameters
Haven't got around to Structures, Arrays, Vectors yet
Basic Structures of First class types should be easy enough to do though

Next step is to work out how to handle functions with multiple parameters
I'm not sure how to do it yet, I'm guessing we will need to use the VarArg class since every thing you do with llvm
requires a pointer returned from it, but I'm not sure what the list pointer in the buildVarArg functions is supposed to be
it might be meaning a llvmArray or an llvmVector or maybe we can do a varArg like this

Code : Tout sélectionner

*mem = allocatememory(X) 
pokeI(*mem,LLVMInt32Type())
pokeI(*mem+4,#null) 
pokeI(*mem+8,LLVMInt8Type())
pokeI(*mem+12,#null)
pokeI(*mem+16,#null)  ;Don't know if you need to terminate a varArg with a null I assume you do
vArg = LLVMBuildVAArg(Builder,*mem,intType,"whatever");
G-Rom
Messages : 3641
Inscription : dim. 10/janv./2010 5:29

Re: llvm-2.9 avec Hello LLVM-PB World

Message par G-Rom »

Thank for this explaination. i will work on it the next week. i will put my work here ;)
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

I am going to try and get llvm to work on windows today
with minGW and VisualStudio (I don't know if I will have any luck)
I tried minGW with the binaries but it didn't work so I will try to build sit with shared objects instead

I just looked at functions with multiple parameters, turns out it's easy
which is all we need for PB since it doesn't have varArgs but it would still help to figure out
functions that take varArgs of an arbitrary type

Code : Tout sélectionner

;mul function  x*y 
;shows how to create a functions with more than one parameter 
;Dim paramType(2) ;Pass in a Array of llvmtypes
;paramType(0) = intType 
;parmaType(1) = intType  
;FunctionReturnType = LLVMFunctionType(IntType,@paramType(0),2,0)
;To access the parameters note how they're obtained 
;ArgX = LLVMGetFirstParam(mulf) ;  by the function pointer
;ArgY = LLVMGetNextParam(ArgX) ; by the first Argument pointer  
 

IncludeFile "llvm-2.9.pbi"

;dirty helper to read var arg strings 
Procedure.s ReadVarString(*chr)
  ;there's an odd interaction with the c lib makes a second call
  ;which results in a IMA   
  ;*chr is either 0 or some value offset from 0 like the length of the string from previous call
  ;this action only appears to comes from error messages but if your outputting to console 
  ;checking *chr > 64000 avoids the IMA (needs fixing though) 
  Protected strout.s 
  If *chr > 64000  
    strout = PeekS(*chr)
  EndIf   
  ProcedureReturn strout 
EndProcedure  

Procedure CreateMulFunction(M.i,Context.i)     
    Protected FunctionReturnType
    Protected IntType 
     
    intType = LLVMInt32Type()
    Dim paramType.i(2)
    paramType(0)=IntType 
    paramType(1)=IntType
       
    ;Function returns an int And takes two ints as parameters.
    FunctionReturnType = LLVMFunctionType(IntType,@paramType(0),2,0)
    ;Create the mul function definition And insert it into the module M. 
    mulF = LLVMAddFunction(M, "Mult",FunctionReturnType)
    ;Set the function call convention to FastCall so it can utilize tail call 
    LLVMSetFunctionCallConv(mulf,#LLVMFastCallConv)
    ;Add Entry basic block To the function.
    BB = LLVMAppendBasicBlockInContext(Context, mulF, "Entry")
    ;Get a pointer to the ArgX.i and add to function...
    ArgX = LLVMGetFirstParam(mulF) ; Get the arg from function pointer .
    LLVMSetValueName(ArgX, "ArgX") ; Give it a symbolic name.
    ;Get pointer to second argY note you pass in the pointer to the first arg 
    ArgY = LLVMGetNextParam(ArgX)  ;Get arg from first Argument pointer 
    LLVMSetValueName(ArgY, "ArgY") ;
    ;Create the intstruction Builder .
    Builder = LLVMCreateBuilderInContext(Context)
    ;Set the builder to insert at the first BasicBlock.
    LLVMPositionBuilderAtEnd(Builder, BB)
    ;Create the operation 
    Res = LLVMBuildMul(Builder,ArgX,ArgY,"x*y")
    ;Create a return block    
    RetBB = LLVMAppendBasicBlockInContext(Context, MulF, "return")
    ;build a jmp to the return block ( the optimizer will remove the jmp if it's not needed)    
    LLVMBuildBr(Builder,RetBB) 
    LLVMPositionBuilderAtEnd(Builder, RetBB)
    ;build the return instruction 
    LLVMBuildRet(Builder,Res)
    ;Don't forget to free the builder.
    LLVMDisposeBuilder(Builder)
    ;Return the function ref
    ProcedureReturn mulF
    
  EndProcedure

Procedure main(x,y)
   Protected errStr.s
   Protected EE.i
  
    LLVMLinkInJIT()
    Context = LLVMGetGlobalContext()

    ;Create a module for our function.
    M = LLVMModuleCreateWithNameInContext("test mult", Context)
    ;make mul function
    mulF = CreateMulFunction(M, Context)
     ;Create JIT engine execution
    If  LLVMCreateExecutionEngineForModule(@EE, M, pStr)
     PrintN(ReadVarString(pStr))
     LLVMDisposeMessage(pStr)
     Input()
     End 
   EndIf
   
  ;Verify module 
  PrintN("verifying module")
  If  LLVMVerifyModule(M, #LLVMPrintMessageAction,pStr)
     PrintN("Error constructing function!")
     PrintN(ReadVarString(pstr))
     LLVMDisposeMessage(pStr)
     Input()
     End
  EndIf

  PrintN("OK")
  PrintN("Test module succeded")
  PrintN("Run mul(" + Str(x) + "*" + Str(y)  + ") in JIT");

  ;Call the Mul function With the arguments x,y:
  Dim arg.i(2)
  Arg(0) = LLVMCreateGenericValueOfInt(LLVMInt32Type(), x, 1)
  Arg(1) =  LLVMCreateGenericValueOfInt(LLVMInt32Type(), y, 1)
  ;Run function 
  GV = LLVMRunFunction(EE, MulF,2,@Arg(0))
  ;convert the result
  PrintN("Jit Result: ")
  PrintN(Str(LLVMGenericValueToInt(GV, 1)))
     
  ;clean up
  LLVMDisposeGenericValue(Arg)
  LLVMDisposeGenericValue(GV)
  LLVMDisposeExecutionEngine(EE)
 
  
EndProcedure 

OpenConsole()
PrintN("enter value for x")
X = Val(Input())
PrintN("enter value for y")
Y = Val(Input())
main(x,y)
PrintN("")
PrintN("Press enter to quit") 
Input()
CloseConsole()
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

help!

spent the day building llvm for windows with minGW
[curses on] [/curses off]
Fill it in with all the swearing you want!

Anyway it built the dll but it didn't build add a lib so if anyone knows how to build import libs in minGW
please step forward and fall on your sword!

I tried
> dlltool -z llvm-2.8.def --export-all-symbol LLVM-2.8.dll ;yes def file produced
> dlltool -v -U -k -d llvm-2.8.def -l llvm-2.8.lib ;yes a 17mb lib was produces with 100's of unresolved symbols

-v = verbose : say WTF your doing
-U add _ToTheFunction
-k Remove the @size
-d the def to load
-l the lib to produce

Well I've had enough pain for the day so if any one can offer any advise, it would be appreciated

pardon mon anglais!
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

The code gen wrapper is progressing

Test code to build the iterative Fibonacci as it would be called from a parser
The trick is to use a token and op stack to handle the variable mutation.
No Phi nodes required :mrgreen:

Code : Tout sélectionner

  NewFunction("fib",#QuadType)    
  AddFunctionParam("fib",argx)
  DeclareFunction(Context,Module,"fib")     
  CreateFunction(Context,Module,"fib")     
  AddFunctionProtectedVar("fib",aa)
  AddFunctionProtectedVar("fib",bb)
  AddFunctionProtectedVar("fib",cc)
  AddFunctionCmp("fib",#LLVMIntSLE,argx,p4)
  AddFunctionReturn("fib",p5)
  AddFunctionElse("fib")
  AddFunctionWhile("fib",#LLVMIntSGT,argX,p6)
  push(lexp(),aa) 
  push(ops(),#LLVMAdd)     
  push(lexp(),bb) 
  push(ops(),#LLVMAssign) 
  push(lexp(),cc) 
  Expr()                   ;c = a + b     
  push(lexp(),bb)
  push(ops(),#LLVMAssign)
  push(lexp(),aa)
  Expr()                  ;b = a 
  push(lexp(),aa)
  push(ops(),#LLVMAssign)
  push(lexp(),cc)   
  expr()                 ;a = c  
  push(lexp(),argX)
  push(ops(),#LLVMsub)
  push(lexp(),one)
  push(lexp(),argX)
  push(ops(),#LLVMAssign)
  expr()               ; Argx - 1     
  AddfunctionWend("fib")
  AddFunctionReturn("fib",cc)
  
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 avec Hello LLVM-PB World

Message par idle »

à mi-chemin

il devrait être apte à être utilisé pour n'importe quel langage de procédure et permettra de simplifier la création de l'analyseur syntaxique, qui ne nécessitera pas la construction d'un AST ou en utilisant décent récursif avec une analyse prioritaire. Le générateur de code facilitera la source doit être analysée dans une simple évaluation de gauche à droite.

[done]
types (all PB primitive types including constant strings)
variables
constants
binary operations
If,Else,ElseIf
For While Repeat (forever/until) : Break, Continue
Procedures
Imports
Function calls
Type casting
Select
structures
arrays
pointer operations
[/done]

[todo]
Memory peek poke.
strings functions left, right, mid, + , str()
[/todo]
idle
Messages : 63
Inscription : ven. 30/juil./2010 2:31

Re: llvm-2.9 PB Code Generator progress

Message par idle »

il est temps pour le câblage du générateur de code dans l'analyseur
Debuging... ... ...
Répondre