1 //===-- BrainFDriver.cpp - BrainF compiler driver -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===--------------------------------------------------------------------===//
9 //
10 // This program converts the BrainF language into LLVM assembly,
11 // which it can then run using the JIT or output as BitCode.
12 //
13 // This implementation has a tape of 65536 bytes,
14 // with the head starting in the middle.
15 // Range checking is off by default, so be careful.
16 // It can be enabled with -abc.
17 //
18 // Use:
19 // ./BrainF -jit      prog.bf          #Run program now
20 // ./BrainF -jit -abc prog.bf          #Run program now safely
21 // ./BrainF           prog.bf          #Write as BitCode
22 //
23 // lli prog.bf.bc                      #Run generated BitCode
24 //
25 //===--------------------------------------------------------------------===//
26 
27 #include "BrainF.h"
28 #include "llvm/Bitcode/ReaderWriter.h"
29 #include "llvm/ExecutionEngine/ExecutionEngine.h"
30 #include "llvm/ExecutionEngine/GenericValue.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <fstream>
39 #include <iostream>
40 using namespace llvm;
41 
42 //Command line options
43 
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input brainf>"));
46 
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
49 
50 static cl::opt<bool>
51 ArrayBoundsChecking("abc", cl::desc("Enable array bounds checking"));
52 
53 static cl::opt<bool>
54 JIT("jit", cl::desc("Run program Just-In-Time"));
55 
56 
57 //Add main function so can be fully compiled
addMainFunction(Module * mod)58 void addMainFunction(Module *mod) {
59   //define i32 @main(i32 %argc, i8 **%argv)
60   Function *main_func = cast<Function>(mod->
61     getOrInsertFunction("main", IntegerType::getInt32Ty(mod->getContext()),
62                         IntegerType::getInt32Ty(mod->getContext()),
63                         PointerType::getUnqual(PointerType::getUnqual(
64                           IntegerType::getInt8Ty(mod->getContext()))), NULL));
65   {
66     Function::arg_iterator args = main_func->arg_begin();
67     Value *arg_0 = &*args++;
68     arg_0->setName("argc");
69     Value *arg_1 = &*args++;
70     arg_1->setName("argv");
71   }
72 
73   //main.0:
74   BasicBlock *bb = BasicBlock::Create(mod->getContext(), "main.0", main_func);
75 
76   //call void @brainf()
77   {
78     CallInst *brainf_call = CallInst::Create(mod->getFunction("brainf"),
79                                              "", bb);
80     brainf_call->setTailCall(false);
81   }
82 
83   //ret i32 0
84   ReturnInst::Create(mod->getContext(),
85                      ConstantInt::get(mod->getContext(), APInt(32, 0)), bb);
86 }
87 
main(int argc,char ** argv)88 int main(int argc, char **argv) {
89   cl::ParseCommandLineOptions(argc, argv, " BrainF compiler\n");
90 
91   LLVMContext &Context = getGlobalContext();
92 
93   if (InputFilename == "") {
94     errs() << "Error: You must specify the filename of the program to "
95     "be compiled.  Use --help to see the options.\n";
96     abort();
97   }
98 
99   //Get the output stream
100   raw_ostream *out = &outs();
101   if (!JIT) {
102     if (OutputFilename == "") {
103       std::string base = InputFilename;
104       if (InputFilename == "-") { base = "a"; }
105 
106       // Use default filename.
107       OutputFilename = base+".bc";
108     }
109     if (OutputFilename != "-") {
110       std::error_code EC;
111       out = new raw_fd_ostream(OutputFilename, EC, sys::fs::F_None);
112     }
113   }
114 
115   //Get the input stream
116   std::istream *in = &std::cin;
117   if (InputFilename != "-")
118     in = new std::ifstream(InputFilename.c_str());
119 
120   //Gather the compile flags
121   BrainF::CompileFlags cf = BrainF::flag_off;
122   if (ArrayBoundsChecking)
123     cf = BrainF::CompileFlags(cf | BrainF::flag_arraybounds);
124 
125   //Read the BrainF program
126   BrainF bf;
127   std::unique_ptr<Module> Mod(bf.parse(in, 65536, cf, Context)); // 64 KiB
128   if (in != &std::cin)
129     delete in;
130   addMainFunction(Mod.get());
131 
132   //Verify generated code
133   if (verifyModule(*Mod)) {
134     errs() << "Error: module failed verification.  This shouldn't happen.\n";
135     abort();
136   }
137 
138   //Write it out
139   if (JIT) {
140     InitializeNativeTarget();
141 
142     outs() << "------- Running JIT -------\n";
143     Module &M = *Mod;
144     ExecutionEngine *ee = EngineBuilder(std::move(Mod)).create();
145     std::vector<GenericValue> args;
146     Function *brainf_func = M.getFunction("brainf");
147     GenericValue gv = ee->runFunction(brainf_func, args);
148   } else {
149     WriteBitcodeToFile(Mod.get(), *out);
150   }
151 
152   //Clean up
153   if (out != &outs())
154     delete out;
155 
156   llvm_shutdown();
157 
158   return 0;
159 }
160