static void Main() { LLVM.Module module = new LLVM.Module("test_type"); module.AddTypeName("int1", LLVM.Type.GetInt1()); module.AddTypeName("int8", LLVM.Type.GetInt8()); module.AddTypeName("int16", LLVM.Type.GetInt16()); module.AddTypeName("int32", LLVM.Type.GetInt32()); module.AddTypeName("int64", LLVM.Type.GetInt64()); module.AddTypeName("int24", LLVM.Type.GetIntN(24)); module.AddTypeName("int48", LLVM.IntegerType.Get(48)); LLVM.Type[] arr = new LLVM.Type[] {LLVM.Type.GetInt8(), LLVM.Type.GetInt8(), LLVM.Type.GetInt32()}; module.AddTypeName("structtype", LLVM.StructType.Get(arr)); module.AddTypeName("arraytype", LLVM.ArrayType.Get(LLVM.Type.GetInt8(), 10)); module.AddTypeName("pointertype", LLVM.PointerType.Get(LLVM.Type.GetInt8(), 0)); module.AddTypeName("opaquetype", LLVM.OpaqueType.Get()); LLVM.OpaqueType o = LLVM.OpaqueType.Get(); LLVM.TypeHandle th = new LLVM.TypeHandle(o); LLVM.StructType st = LLVM.StructType.Get(new LLVM.Type[] {LLVM.Type.GetInt32(), o}); o.RefineAbstractTypeTo(st); module.AddTypeName("refinedtype", th.Resolve()); module.Dump(); }
public Value code(IRBuilder builder) { if (primarys.Count == 1) { return(primarys[0].code(builder)); } List <Primary> tempPrimaries = new List <Primary>(); // do shallow copy foreach (Primary item in primarys) { tempPrimaries.Add(item); } // Import pow function LLVM.Type[] argTypes = new LLVM.Type[] { Parser.dbl, Parser.dbl }; FunctionType powType = new FunctionType(Parser.dbl, argTypes); Constant pow = Parser.module.GetOrInsertFunction("pow", powType); Value L = tempPrimaries[0].code(builder); tempPrimaries.RemoveAt(0); while (tempPrimaries.Count > 0) { Value R = tempPrimaries[0].code(builder); Value[] args = { L, R }; L = builder.CreateCall(pow, args); tempPrimaries.RemoveAt(0); } return(L); }
public Constant getConstantAbs() { LLVM.Type[] args = new LLVM.Type[] { Parser.i8p }; FunctionType type = new FunctionType(Parser.dbl, args); return(Parser.module.GetOrInsertFunction("abs", type)); }
static void Main() { LLVM.Module module = new LLVM.Module("test_type"); module.AddTypeName("int1", LLVM.Type.GetInt1()); module.AddTypeName("int8", LLVM.Type.GetInt8()); module.AddTypeName("int16", LLVM.Type.GetInt16()); module.AddTypeName("int32", LLVM.Type.GetInt32()); module.AddTypeName("int64", LLVM.Type.GetInt64()); module.AddTypeName("int24", LLVM.Type.GetIntN(24)); module.AddTypeName("int48", LLVM.IntegerType.Get(48)); LLVM.Type[] arr = new LLVM.Type[] { LLVM.Type.GetInt8(), LLVM.Type.GetInt8(), LLVM.Type.GetInt32() }; module.AddTypeName("structtype", LLVM.StructType.Get(arr)); module.AddTypeName("arraytype", LLVM.ArrayType.Get(LLVM.Type.GetInt8(), 10)); module.AddTypeName("pointertype", LLVM.PointerType.Get(LLVM.Type.GetInt8(), 0)); module.AddTypeName("opaquetype", LLVM.OpaqueType.Get()); LLVM.OpaqueType o = LLVM.OpaqueType.Get(); LLVM.TypeHandle th = new LLVM.TypeHandle(o); LLVM.StructType st = LLVM.StructType.Get(new LLVM.Type[] { LLVM.Type.GetInt32(), o }); o.RefineAbstractTypeTo(st); module.AddTypeName("refinedtype", th.Resolve()); module.Dump(); }
public static void Initialize(LLVM.Module module) { TargetData tgt = new TargetData("e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32"); // TargetData tgt = new TargetData(module.DataLayout); Void = LLVM.Type.GetVoid(); //module.AddTypeName("type System.Void", Void); Bool = LLVM.Type.GetInt8(); //module.AddTypeName("type System.Bool", Bool); Char = LLVM.Type.GetInt8(); //module.AddTypeName("type System.Char", Char); Int8 = LLVM.Type.GetInt8(); //module.AddTypeName("type System.Int8", Int8); Int16 = LLVM.Type.GetInt16(); //module.AddTypeName("type System.Int16", Int16); Int32 = LLVM.Type.GetInt32(); //module.AddTypeName("type System.Int32", Int32); Int64 = LLVM.Type.GetInt64(); //module.AddTypeName("type System.Int64", Int64); Native = tgt.GetIntPtrType(); //module.AddTypeName("type System.Native", Native); Ptr = Native.GetPointerTo(0); //module.AddTypeName("type System.Ptr", Ptr); Object = LLVM.StructType.Get(module.Context, "type System.Object", new LLVM.Type[2] { Int32, Int32 }, false); //module.AddTypeName("type System.Object", Object); String = LLVM.Type.GetInt8(); // FIXME, TODO //module.AddTypeName("type System.String", String); // Initialize constants // Const_0 = GetConstant(0); Const_1 = GetConstant(1); Const_2 = GetConstant(2); Const_3 = GetConstant(3); Const_4 = GetConstant(4); Const_5 = GetConstant(5); Const_6 = GetConstant(6); Const_7 = GetConstant(7); Const_8 = GetConstant(8); Const_m1 = GetConstant(-1); LLVM.FunctionType ft = LLVM.FunctionType.Get(Object.GetPointerTo(0), new LLVM.Type[1] { Native }, false); Newobj = new LLVM.Function(module, "newobj", ft); ft = LLVM.FunctionType.Get(String.GetPointerTo(0), new LLVM.Type[1] { Int8.GetPointerTo(0) }, false); Newstr = new LLVM.Function(module, "newstring", ft); ft = LLVM.FunctionType.Get(Object.GetPointerTo(0), new LLVM.Type[2] { Native, Native }, false); Newarr = new LLVM.Function(module, "newarr", ft); }
public override Value code(IRBuilder builder) { setupFunctions(); if (refType == FunctionRefType.NUMERICSUPPLIEDFUNCTION) { Constant suppliedFunction = getSuppliedFunction(numericSuppliedFunctionName); Value[] args = { }; Value input; switch (numericSuppliedFunctionName) { case NumericSuppliedFunction.RND: // Do something break; case NumericSuppliedFunction.SGN: Value one = ConstantFP.Get(Parser.context, new APFloat(1.0)); input = argument.code(builder); args = new Value[] { one, input }; break; case NumericSuppliedFunction.MOD2: Value two = ConstantFP.Get(Parser.context, new APFloat(2.0)); input = argument.code(builder); args = new Value[] { input, two }; break; default: input = argument.code(builder); args = new Value[] { input }; break; } return(builder.CreateCall(suppliedFunction, args)); } else { // Arbitrary function; LLVM.Type[] argDouble = new LLVM.Type[] { Parser.dbl }; LLVM.Type[] argVoid = new LLVM.Type[] { }; LLVM.Type[] argType = (argument == null) ? argVoid : argDouble; LLVM.Type returnType = Parser.dbl; FunctionType fnType = new FunctionType(returnType, argType); Constant fn = Parser.module.GetOrInsertFunction(numericDefinedFunctionName, fnType); Value[] args = (argument == null) ? new Value[] { } : new Value[] { argument.code(builder) }; return(builder.CreateCall(fn, args)); } }
public override BasicBlock code() { block = bb(); IRBuilder builder = new IRBuilder(block); LLVM.Type[] argTypes = new LLVM.Type[] { Parser.i8p, Parser.dblp }; FunctionType stringToInt = new FunctionType(Parser.vd, argTypes); Constant readFileToArray = Parser.module.GetOrInsertFunction("readFileToArray", stringToInt); Value arrayPointer = Parser.variables.arrayItem(builder, arrayName, Parser.zero); Value fileNamePointer = fileName.code(builder); Value[] args = { fileNamePointer, arrayPointer }; builder.CreateCall(readFileToArray, args); return(block); }
public override Value code(IRBuilder builder) { Value L = LHS.code(builder); Value R = RHS.code(builder); // import strcmp function LLVM.Type[] argTypes = new LLVM.Type[] { Parser.i8p, Parser.i8p }; FunctionType stringStringToInt = new FunctionType(Parser.i8, argTypes); Value strcmp = Parser.module.GetOrInsertFunction("strcmp", stringStringToInt); LLVM.Value[] args = new LLVM.Value[] { L, R }; Value strCmpResult = builder.CreateCall(strcmp, args); Predicate comparison = (relation == EqualityRelation.EQUAL) ? Predicate.Equal : Predicate.NotEqual; Value output = builder.CreateFCmp(comparison, strCmpResult, Parser.zero, "tempStrEqExp"); return(output); }
public override BasicBlock code() { block = bb(); builder = new IRBuilder(block); // Import printf function LLVM.Type[] argTypes = new LLVM.Type[] { Parser.i8p }; FunctionType stringToVoid = new FunctionType(Parser.vd, argTypes); printf = Parser.module.GetOrInsertFunction("printf", stringToVoid); // Import doubleprintf function argTypes = new LLVM.Type[] { Parser.i8p, Parser.dbl }; FunctionType stringAndDouble = new FunctionType(Parser.vd, argTypes); doubleprintf = Parser.module.GetOrInsertFunction("printf", stringAndDouble); // do it this.compileString(); return(block); }
public void setupFunctions() { functionNames = new Dictionary <NumericSuppliedFunction, string>(); functionTypes = new Dictionary <NumericSuppliedFunction, FunctionType>(); functionNames[NumericSuppliedFunction.ABS] = "abs"; functionNames[NumericSuppliedFunction.ATN] = "atan"; functionNames[NumericSuppliedFunction.COS] = "cos"; functionNames[NumericSuppliedFunction.EXP] = "exp"; functionNames[NumericSuppliedFunction.INT] = "floor"; functionNames[NumericSuppliedFunction.LOG] = "log"; functionNames[NumericSuppliedFunction.RND] = "rand"; functionNames[NumericSuppliedFunction.SGN] = "copysign"; functionNames[NumericSuppliedFunction.SIN] = "sin"; functionNames[NumericSuppliedFunction.SQR] = "sqrt"; functionNames[NumericSuppliedFunction.TAN] = "tan"; LLVM.Type[] argDouble = new LLVM.Type[] { Parser.dbl }; LLVM.Type[] argVoid = new LLVM.Type[] { }; LLVM.Type[] argDoublePair = new LLVM.Type[] { Parser.dbl, Parser.dbl }; FunctionType doubleToDouble = new FunctionType(Parser.dbl, argDouble); FunctionType doublePairToDouble = new FunctionType(Parser.dbl, argDoublePair); FunctionType voidToDouble = new FunctionType(Parser.dbl, argVoid); functionTypes[NumericSuppliedFunction.ABS] = doubleToDouble; functionTypes[NumericSuppliedFunction.ATN] = doubleToDouble; functionTypes[NumericSuppliedFunction.COS] = doubleToDouble; functionTypes[NumericSuppliedFunction.EXP] = doubleToDouble; functionTypes[NumericSuppliedFunction.INT] = doubleToDouble; functionTypes[NumericSuppliedFunction.LOG] = doubleToDouble; functionTypes[NumericSuppliedFunction.RND] = voidToDouble; functionTypes[NumericSuppliedFunction.SGN] = doublePairToDouble; functionTypes[NumericSuppliedFunction.SIN] = doubleToDouble; functionTypes[NumericSuppliedFunction.SQR] = doubleToDouble; functionTypes[NumericSuppliedFunction.TAN] = doubleToDouble; }
public override BasicBlock code() { block = bb(); IRBuilder builder = new IRBuilder(block); LLVM.Type[] argTypes = new LLVM.Type[] { Parser.i8p, Parser.dblp, Parser.i8 }; FunctionType stringToInt = new FunctionType(Parser.vd, argTypes); Constant writeArrayToFile = Parser.module.GetOrInsertFunction("writeArrayToFile", stringToInt); Value arrayPointer = Parser.variables.arrayItem(builder, arrayName, Parser.zero); Value fileNamePointer = fileName.code(builder); Value arraySize = Parser.variables.arraySizes[arrayName]; Value arrayPointer2 = builder.CreateGEP(arrayPointer, Parser.zero, "arrayGEP"); Value[] args = { fileNamePointer, arrayPointer2, arraySize }; builder.CreateCall(writeArrayToFile, args); return(block); }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Usage: BASICLLVM <inputfile> <flags>"); Console.WriteLine("-debug enables compiler debugging output"); Console.WriteLine("-block blocks on finished compile"); Console.WriteLine("-o <outputfile> outputs to specified file"); Console.WriteLine("-output LL/S/EXE specifies desired output format"); Console.WriteLine("-output LL/S/EXE specifies desired output format"); return; } // Interpret arguments string inputFile = args[0]; string defaultOutputFile = inputFile.Substring(0, inputFile.LastIndexOf(".")); outputFile = defaultOutputFile; bool outNext = false; bool formatNext = false; foreach (string arg in args) { if (outNext) { outputFile = arg; outNext = false; } if (formatNext) { outputFormat = (arg == "EXE") ? outputFormats.EXE : ((arg == "S") ? outputFormats.S : outputFormats.LL); formatNext = false; } if (arg == "-debug") { debug = true; } if (arg == "-block") { block = true; } if (arg == "-o") { outNext = true; } if (arg == "-output") { formatNext = true; } } if (outputFile.Equals(defaultOutputFile)) { if (outputFormat == outputFormats.LL) { outputFile += ".ll"; } if (outputFormat == outputFormats.S) { outputFile += ".s"; } if (outputFormat == outputFormats.EXE) { outputFile += ".exe"; } } // Setup LLVM LLVMContext context = new LLVMContext(); Parser.context = context; /* * PARSE STAGE */ if (debug) { Console.WriteLine("---"); } if (debug) { Console.WriteLine(); } if (debug) { Console.WriteLine("1 - Parsing"); } List <Statement> lines = Parser.parseFile(inputFile); if (lines == null) { // parsing failed if (block) { Console.ReadLine(); } return; } if (debug) { Console.WriteLine("Done"); } if (debug) { Console.WriteLine(); } if (debug) { Console.WriteLine("---"); } if (debug) { Console.WriteLine(); } /* * COMPILE STAGE */ if (debug) { Console.WriteLine("2 - Compiling"); } // Setup LLVM module Module module = new Module(context, "SourceFile"); Parser.module = module; // Setup LLVM function LLVM.Type[] mainArgs = new LLVM.Type[] { Parser.i32, Parser.i8pp }; FunctionType mainType = new FunctionType(Parser.i32, mainArgs); Function mainFunction = new Function(module, "main", mainType); Parser.function = mainFunction; try { for (int i = 0; i < lines.Count; i++) { Parser.currentLine = i; // Compile Line lines[i].code(); if (lines[i].hasLineNumber) { // add code line number to dictionary if (!Parser.variables.lines.ContainsKey(lines[i].lineNumber)) { Parser.variables.lines.Add(lines[i].lineNumber, lines[i]); } else { CompileException ex = new CompileException("Duplicate line number"); ex.message = "Line numbers must be unique"; throw ex; } } } // add jumps between adjacent lines for (int i = 0; i < lines.Count - 1; i++) { lines[i].jumpToNext(lines[i + 1]); } // process control flow statements for (int i = 0; i < lines.Count; i++) { lines[i].processGoto(); } } catch (CompileException ex) { ex.print("COMPILE ERROR"); if (block) { Console.ReadLine(); } return; } if (debug) { Console.WriteLine("Done"); } if (debug) { Console.WriteLine(); Console.WriteLine("---"); Console.WriteLine(); // Compile is complete ConsoleColor prevColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Magenta; module.Dump(); // Dump LLVM IR for debug purposes Console.ForegroundColor = prevColor; Console.WriteLine(); Console.WriteLine("---"); Console.WriteLine(); Console.WriteLine("3 - Output"); } // Write out LLVM module to file try { module.WriteToFile("ll.tmp"); } catch (Exception e) { CompileException.printColour("Failed to write to output file", ConsoleColor.Red); Console.WriteLine(e.Message); } // Call llc and gcc as well if we were asked to do that switch (outputFormat) { case outputFormats.LL: File.Delete(outputFile); File.Move("ll.tmp", outputFile); break; case outputFormats.S: do_llc(); File.Delete(outputFile); File.Move("ll.tmp.s", outputFile); break; case outputFormats.EXE: do_llc(); do_gcc(); break; } if (debug) { Console.WriteLine("Compile complete"); } if (block) { Console.ReadLine(); } }
private static void ConvertNum(EmitFuncObj _, Type target, bool integerSignedness) { //var value = _.Stack.Pop(); //var valueType = value.Type; //if (valueType is IntegerType && target is FloatType) //{ // value = _.Builder. //} }
public static Value FloatExtend(this InstructionBuilder builder, Value value, LLVM.Type type, string name = "") { return((Value)ValueConstructor.Invoke(new object[] { LLVMBuildFPExt(builder, value, type, name) })); }
public static Value SignedIntToFloat(this InstructionBuilder builder, Value value, LLVM.Type type, string name = "") { return((Value)ValueConstructor.Invoke(new object[] { LLVMBuildSIToFP(builder, value, type, name) })); }
public static List <Statement> parseFile(string inputFile) { try { // setup global static variables i8 = LLVM.Type.GetInteger8Type(context); i8p = LLVM.Type.GetInteger8PointerType(context); i8pp = LLVM.PointerType.GetUnqualified(i8p); i32 = LLVM.Type.GetInteger32Type(context); dbl = LLVM.Type.GetDoubleType(context); dblp = LLVM.Type.GetDoublePointerType(context); vd = LLVM.Type.GetVoidType(context); zero = new Constant(context, 8, 0); zero32 = new Constant(context, 32, 0); zeroFP = ConstantFP.Get(context, new APFloat((double)0)); variables = new VariableStore(); currentLine = 0; string line; List <Statement> parsedLines = new List <Statement>(); // Read the file and parse it line by line StreamReader file = new System.IO.StreamReader(inputFile); while ((line = file.ReadLine()) != null) { // Do ANTLR stuff AntlrInputStream stream = new AntlrInputStream(line); ITokenSource lexer = new BASICLexer(stream); ITokenStream tokens = new CommonTokenStream(lexer); BASICParser parser = new BASICParser(tokens); parser.RemoveErrorListeners(); parser.AddErrorListener(new AntlrErrorListener()); Listener lis = new Listener(); parser.BuildParseTree = true; parser.AddParseListener(lis); try { RuleContext tree = parser.line(); } catch (CompileException ex) { ex.print("INNER PARSE ERROR"); file.Close(); return(null); } parsedLines.Add(lis.finishedLine); currentLine++; } file.Close(); currentLine = -1; if (!Statement_End.existsEnd) { CompileException ex = new CompileException("No END line"); ex.message = "An END line is required"; throw ex; } return(parsedLines); } catch (CompileException ex) { ex.print("OUTER PARSE ERROR"); return(null); } catch (Exception ex) { CompileException.printColour("UNHANDLED PARSE ERROR", ConsoleColor.Red); Console.WriteLine(ex.Message); return(null); } }
private static void ConvertNum(EmitFuncObj _, Type target, bool integerSignedness) { var value = _.Stack.Pop(); var valueType = value.Type; if (valueType is IntegerType && target is FloatType) { if (integerSignedness) value = _.Builder.SignedIntToFloat(value, target); else value = _.Builder.UnsignedIntToFloat(value, target); } else if (valueType is FloatType && target is IntegerType) { if (integerSignedness) value = _.Builder.FloatToSignedInt(value, target); else value = _.Builder.FloatToUnsignedInt(value, target); } else if (valueType is IntegerType && target is IntegerType) { var valueInt = (IntegerType) valueType; var targetInt = (IntegerType) target; if (valueInt.Width > targetInt.Width) value = _.Builder.Trunc(value, target); else if (integerSignedness) value = _.Builder.SignExtend(value, target); else value = _.Builder.ZeroExtend(value, target); } else { throw new CudaSharpException(string.Format("Cannot convert {0} to {1}", valueType, target)); } _.Stack.Push(value); }