[Orc] Move Orc code into a namespace (llvm::orc), update Kaleidoscope code.
[oota-llvm.git] / examples / Kaleidoscope / Orc / lazy_irgen / toy.cpp
index 7c99478a5d2b3ae7636a16b7535a1025d6ec7ba8..162b0e589996ec78135b55ed16d0388f4631e831 100644 (file)
@@ -7,9 +7,9 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
-#include "llvm/PassManager.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Transforms/Scalar.h"
 #include <cctype>
@@ -19,7 +19,9 @@
 #include <sstream>
 #include <string>
 #include <vector>
+
 using namespace llvm;
+using namespace llvm::orc;
 
 //===----------------------------------------------------------------------===//
 // Lexer
@@ -115,13 +117,13 @@ class IRGenContext;
 /// ExprAST - Base class for all expression nodes.
 struct ExprAST {
   virtual ~ExprAST() {}
-  virtual Value* IRGen(IRGenContext &C) = 0;
+  virtual Value *IRGen(IRGenContext &C) const = 0;
 };
 
 /// NumberExprAST - Expression class for numeric literals like "1.0".
 struct NumberExprAST : public ExprAST {
   NumberExprAST(double Val) : Val(Val) {}
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   double Val;
 };
@@ -129,7 +131,7 @@ struct NumberExprAST : public ExprAST {
 /// VariableExprAST - Expression class for referencing a variable, like "a".
 struct VariableExprAST : public ExprAST {
   VariableExprAST(std::string Name) : Name(std::move(Name)) {}
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   std::string Name;
 };
@@ -139,7 +141,7 @@ struct UnaryExprAST : public ExprAST {
   UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand) 
     : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
 
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   char Opcode;
   std::unique_ptr<ExprAST> Operand;
@@ -151,7 +153,7 @@ struct BinaryExprAST : public ExprAST {
                 std::unique_ptr<ExprAST> RHS) 
     : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
 
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   char Op;
   std::unique_ptr<ExprAST> LHS, RHS;
@@ -163,7 +165,7 @@ struct CallExprAST : public ExprAST {
               std::vector<std::unique_ptr<ExprAST>> Args)
     : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
 
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   std::string CalleeName;
   std::vector<std::unique_ptr<ExprAST>> Args;
@@ -174,7 +176,7 @@ struct IfExprAST : public ExprAST {
   IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
             std::unique_ptr<ExprAST> Else)
     : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   std::unique_ptr<ExprAST> Cond, Then, Else;
 };
@@ -187,7 +189,7 @@ struct ForExprAST : public ExprAST {
     : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
       Step(std::move(Step)), Body(std::move(Body)) {}
 
-  Value* IRGen(IRGenContext &C) override;
+  Value *IRGen(IRGenContext &C) const override;
 
   std::string VarName;
   std::unique_ptr<ExprAST> Start, End, Step, Body;
@@ -200,8 +202,8 @@ struct VarExprAST : public ExprAST {
 
   VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
     : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
-  
-  Value* IRGen(IRGenContext &C) override;
+
+  Value *IRGen(IRGenContext &C) const override;
 
   BindingList VarBindings;
   std::unique_ptr<ExprAST> Body;
@@ -215,7 +217,7 @@ struct PrototypeAST {
     : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
       Precedence(Precedence) {}
 
-  Function* IRGen(IRGenContext &C);
+  Function *IRGen(IRGenContext &C) const;
   void CreateArgumentAllocas(Function *F, IRGenContext &C);
 
   bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
@@ -238,7 +240,7 @@ struct FunctionAST {
               std::unique_ptr<ExprAST> Body)
     : Proto(std::move(Proto)), Body(std::move(Body)) {}
 
-  Function* IRGen(IRGenContext &C);
+  Function *IRGen(IRGenContext &C) const;
 
   std::unique_ptr<PrototypeAST> Proto;
   std::unique_ptr<ExprAST> Body;
@@ -742,11 +744,11 @@ static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
                            VarName.c_str());
 }
 
-Value *NumberExprAST::IRGen(IRGenContext &C) {
+Value *NumberExprAST::IRGen(IRGenContext &C) const {
   return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
 }
 
-Value *VariableExprAST::IRGen(IRGenContext &C) {
+Value *VariableExprAST::IRGen(IRGenContext &C) const {
   // Look this variable up in the function.
   Value *V = C.NamedValues[Name];
 
@@ -757,7 +759,7 @@ Value *VariableExprAST::IRGen(IRGenContext &C) {
   return C.getBuilder().CreateLoad(V, Name.c_str());
 }
 
-Value *UnaryExprAST::IRGen(IRGenContext &C) {
+Value *UnaryExprAST::IRGen(IRGenContext &C) const {
   if (Value *OperandV = Operand->IRGen(C)) {
     std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
     if (Function *F = C.getPrototype(FnName))
@@ -769,7 +771,7 @@ Value *UnaryExprAST::IRGen(IRGenContext &C) {
   return nullptr;
 }
 
-Value *BinaryExprAST::IRGen(IRGenContext &C) {
+Value *BinaryExprAST::IRGen(IRGenContext &C) const {
   // Special case '=' because we don't want to emit the LHS as an expression.
   if (Op == '=') {
     // Assignment requires the LHS to be an identifier.
@@ -814,7 +816,7 @@ Value *BinaryExprAST::IRGen(IRGenContext &C) {
   return ErrorP<Value>("Unknown binary operator");
 }
 
-Value *CallExprAST::IRGen(IRGenContext &C) {
+Value *CallExprAST::IRGen(IRGenContext &C) const {
   // Look up the name in the global module table.
   if (auto CalleeF = C.getPrototype(CalleeName)) {
     // If argument mismatch error.
@@ -833,7 +835,7 @@ Value *CallExprAST::IRGen(IRGenContext &C) {
   return ErrorP<Value>("Unknown function referenced");
 }
 
-Value *IfExprAST::IRGen(IRGenContext &C) {
+Value *IfExprAST::IRGen(IRGenContext &C) const {
   Value *CondV = Cond->IRGen(C);
   if (!CondV) return nullptr;
   
@@ -884,7 +886,7 @@ Value *IfExprAST::IRGen(IRGenContext &C) {
   return PN;
 }
 
-Value *ForExprAST::IRGen(IRGenContext &C) {
+Value *ForExprAST::IRGen(IRGenContext &C) const {
   // Output this as:
   //   var = alloca double
   //   ...
@@ -983,7 +985,7 @@ Value *ForExprAST::IRGen(IRGenContext &C) {
   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
 }
 
-Value *VarExprAST::IRGen(IRGenContext &C) {
+Value *VarExprAST::IRGen(IRGenContext &C) const {
   std::vector<AllocaInst *> OldBindings;
   
   Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
@@ -1028,7 +1030,7 @@ Value *VarExprAST::IRGen(IRGenContext &C) {
   return BodyVal;
 }
 
-Function *PrototypeAST::IRGen(IRGenContext &C) {
+Function *PrototypeAST::IRGen(IRGenContext &C) const {
   std::string FnName = MakeLegalFunctionName(Name);
 
   // Make the function type:  double(double,double) etc.
@@ -1084,7 +1086,7 @@ void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
   }
 }
 
-Function *FunctionAST::IRGen(IRGenContext &C) {
+Function *FunctionAST::IRGen(IRGenContext &C) const {
   C.NamedValues.clear();
   
   Function *TheFunction = Proto->IRGen(C);
@@ -1124,6 +1126,19 @@ Function *FunctionAST::IRGen(IRGenContext &C) {
 // Top-Level parsing and JIT Driver
 //===----------------------------------------------------------------------===//
 
+static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
+                                           const FunctionAST &F) {
+  IRGenContext C(S);
+  auto LF = F.IRGen(C);
+  if (!LF)
+    return nullptr;
+#ifndef MINIMAL_STDERR_OUTPUT
+  fprintf(stderr, "Read function definition:");
+  LF->dump();
+#endif
+  return C.takeM();
+}
+
 class KaleidoscopeJIT {
 public:
   typedef ObjectLinkingLayer<> ObjLayerT;
@@ -1161,27 +1176,26 @@ public:
     auto MM = createLookasideRTDyldMM<SectionMemoryManager>(
                 [&](const std::string &Name) -> uint64_t {
                   // First try to find 'Name' within the JIT.
-                  if (uint64_t Addr = getMangledSymbolAddress(Name))
-                    return Addr;
+                  if (auto Symbol = findMangledSymbol(Name))
+                    return Symbol.getAddress();
 
                   // If we don't find 'Name' in the JIT, see if we have some AST
                   // for it.
-                  if (!Session.FunctionDefs.count(Name))
+                  auto DefI = Session.FunctionDefs.find(Name);
+                  if (DefI == Session.FunctionDefs.end())
                     return 0;
 
                   // We have AST for 'Name'. IRGen it, add it to the JIT, and
                   // return the address for it.
-                  IRGenContext C(Session);
-                  {
-                    // Take ownership of the AST: We can release the memory as
-                    // soon as we've IRGen'd it.
-                    auto FuncAST = std::move(Session.FunctionDefs[Name]);
-                    FuncAST->IRGen(C);
-                  }
-
-                  addModule(C.takeM());
-                  return getMangledSymbolAddress(Name);
-                }, 
+                  // FIXME: What happens if IRGen fails?
+                  addModule(IRGen(Session, *DefI->second));
+
+                  // Remove the function definition's AST now that we've
+                  // finished with it.
+                  Session.FunctionDefs.erase(DefI);
+
+                  return findMangledSymbol(Name).getAddress();
+                },
                 [](const std::string &S) { return 0; } );
 
     return LazyEmitLayer.addModuleSet(std::move(S), std::move(MM));
@@ -1189,12 +1203,12 @@ public:
 
   void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
 
-  uint64_t getMangledSymbolAddress(const std::string &Name) {
-    return LazyEmitLayer.getSymbolAddress(Name, false);
+  JITSymbol findMangledSymbol(const std::string &Name) {
+    return LazyEmitLayer.findSymbol(Name, false);
   }
 
-  uint64_t getSymbolAddress(const std::string &Name) {
-    return getMangledSymbolAddress(Mangle(Name));
+  JITSymbol findSymbol(const std::string &Name) {
+    return findMangledSymbol(Mangle(Name));
   }
 
 private:
@@ -1241,11 +1255,11 @@ static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
       auto H = J.addModule(C.takeM());
 
       // Get the address of the JIT'd function in memory.
-      uint64_t ExprFuncAddr = J.getSymbolAddress("__anon_expr");
+      auto ExprSymbol = J.findSymbol("__anon_expr");
       
       // Cast it to the right type (takes no arguments, returns a double) so we
       // can call it as a native function.
-      double (*FP)() = (double (*)())(intptr_t)ExprFuncAddr;
+      double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
 #ifdef MINIMAL_STDERR_OUTPUT
       FP();
 #else
@@ -1267,16 +1281,16 @@ static void MainLoop() {
   KaleidoscopeJIT J(S);
 
   while (1) {
-#ifndef MINIMAL_STDERR_OUTPUT
-    std::cerr << "ready> ";
-#endif
     switch (CurTok) {
     case tok_eof:    return;
-    case ';':        getNextToken(); break;  // ignore top-level semicolons.
+    case ';':        getNextToken(); continue;  // ignore top-level semicolons.
     case tok_def:    HandleDefinition(S, J); break;
     case tok_extern: HandleExtern(S); break;
     default:         HandleTopLevelExpression(S, J); break;
     }
+#ifndef MINIMAL_STDERR_OUTPUT
+    std::cerr << "ready> ";
+#endif
   }
 }