1 //===-- BrainF.cpp - BrainF compiler example ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===--------------------------------------------------------------------===//
10 // This class compiles the BrainF language into LLVM assembly.
12 // The BrainF language has 8 commands:
13 // Command Equivalent C Action
14 // ------- ------------ ------
15 // , *h=getchar(); Read a character from stdin, 255 on EOF
16 // . putchar(*h); Write a character to stdout
17 // - --*h; Decrement tape
18 // + ++*h; Increment tape
19 // < --h; Move head left
20 // > ++h; Move head right
21 // [ while(*h) { Start loop
24 //===--------------------------------------------------------------------===//
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
35 //Set the constants for naming
36 const char *BrainF::tapereg = "tape";
37 const char *BrainF::headreg = "head";
38 const char *BrainF::label = "brainf";
39 const char *BrainF::testreg = "test";
41 Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
42 LLVMContext& Context) {
48 readloop(nullptr, nullptr, nullptr, Context);
53 void BrainF::header(LLVMContext& C) {
54 module = new Module("BrainF", C);
58 //declare void @llvm.memset.p0i8.i32(i8 *, i8, i32, i32, i1)
59 Type *Tys[] = { Type::getInt8PtrTy(C), Type::getInt32Ty(C) };
60 Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset,
63 //declare i32 @getchar()
64 getchar_func = cast<Function>(module->
65 getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL));
67 //declare i32 @putchar(i32)
68 putchar_func = cast<Function>(module->
69 getOrInsertFunction("putchar", IntegerType::getInt32Ty(C),
70 IntegerType::getInt32Ty(C), NULL));
74 //define void @brainf()
75 brainf_func = cast<Function>(module->
76 getOrInsertFunction("brainf", Type::getVoidTy(C), NULL));
78 builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func));
80 //%arr = malloc i8, i32 %d
81 ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal));
82 BasicBlock* BB = builder->GetInsertBlock();
83 Type* IntPtrTy = IntegerType::getInt32Ty(C);
84 Type* Int8Ty = IntegerType::getInt8Ty(C);
85 Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty);
86 allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy);
87 ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem,
89 BB->getInstList().push_back(cast<Instruction>(ptr_arr));
91 //call void @llvm.memset.p0i8.i32(i8 *%arr, i8 0, i32 %d, i32 1, i1 0)
93 Value *memset_params[] = {
95 ConstantInt::get(C, APInt(8, 0)),
97 ConstantInt::get(C, APInt(32, 1)),
98 ConstantInt::get(C, APInt(1, 0))
101 CallInst *memset_call = builder->
102 CreateCall(memset_func, memset_params);
103 memset_call->setTailCall(false);
106 //%arrmax = getelementptr i8 *%arr, i32 %d
107 if (comflag & flag_arraybounds) {
108 ptr_arrmax = builder->
109 CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax");
112 //%head.%d = getelementptr i8 *%arr, i32 %d
113 curhead = builder->CreateGEP(ptr_arr,
114 ConstantInt::get(C, APInt(32, memtotal/2)),
120 endbb = BasicBlock::Create(C, label, brainf_func);
122 //call free(i8 *%arr)
123 endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb));
126 ReturnInst::Create(C, endbb);
128 //Error block for array out of bounds
129 if (comflag & flag_arraybounds)
131 //@aberrormsg = internal constant [%d x i8] c"\00"
133 ConstantDataArray::getString(C, "Error: The head has left the tape.",
136 GlobalVariable *aberrormsg = new GlobalVariable(
140 GlobalValue::InternalLinkage,
144 //declare i32 @puts(i8 *)
145 Function *puts_func = cast<Function>(module->
146 getOrInsertFunction("puts", IntegerType::getInt32Ty(C),
147 PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL));
150 aberrorbb = BasicBlock::Create(C, label, brainf_func);
152 //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
154 Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C));
156 Constant *gep_params[] = {
161 Constant *msgptr = ConstantExpr::
162 getGetElementPtr(aberrormsg->getValueType(), aberrormsg, gep_params);
164 Value *puts_params[] = {
168 CallInst *puts_call =
169 CallInst::Create(puts_func,
172 puts_call->setTailCall(false);
175 //br label %brainf.end
176 BranchInst::Create(endbb, aberrorbb);
180 void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb,
182 Symbol cursym = SYM_NONE;
184 Symbol nextsym = SYM_NONE;
190 while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
191 // Write out commands
199 //%tape.%d = call i32 @getchar()
200 CallInst *getchar_call =
201 builder->CreateCall(getchar_func, {}, tapereg);
202 getchar_call->setTailCall(false);
203 Value *tape_0 = getchar_call;
205 //%tape.%d = trunc i32 %tape.%d to i8
206 Value *tape_1 = builder->
207 CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg);
209 //store i8 %tape.%d, i8 *%head.%d
210 builder->CreateStore(tape_1, curhead);
216 //%tape.%d = load i8 *%head.%d
217 LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
219 //%tape.%d = sext i8 %tape.%d to i32
220 Value *tape_1 = builder->
221 CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg);
223 //call i32 @putchar(i32 %tape.%d)
224 Value *putchar_params[] = {
227 CallInst *putchar_call = builder->
228 CreateCall(putchar_func,
230 putchar_call->setTailCall(false);
236 //%head.%d = getelementptr i8 *%head.%d, i32 %d
238 CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)),
241 //Error block for array out of bounds
242 if (comflag & flag_arraybounds)
244 //%test.%d = icmp uge i8 *%head.%d, %arrmax
245 Value *test_0 = builder->
246 CreateICmpUGE(curhead, ptr_arrmax, testreg);
248 //%test.%d = icmp ult i8 *%head.%d, %arr
249 Value *test_1 = builder->
250 CreateICmpULT(curhead, ptr_arr, testreg);
252 //%test.%d = or i1 %test.%d, %test.%d
253 Value *test_2 = builder->
254 CreateOr(test_0, test_1, testreg);
256 //br i1 %test.%d, label %main.%d, label %main.%d
257 BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func);
258 builder->CreateCondBr(test_2, aberrorbb, nextbb);
261 builder->SetInsertPoint(nextbb);
268 //%tape.%d = load i8 *%head.%d
269 LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
271 //%tape.%d = add i8 %tape.%d, %d
272 Value *tape_1 = builder->
273 CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg);
275 //store i8 %tape.%d, i8 *%head.%d\n"
276 builder->CreateStore(tape_1, curhead);
283 BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func);
284 builder->CreateBr(testbb);
287 BasicBlock *bb_0 = builder->GetInsertBlock();
288 BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func);
289 builder->SetInsertPoint(bb_1);
291 // Make part of PHI instruction now, wait until end of loop to finish
293 PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)),
295 phi_0->addIncoming(curhead, bb_0);
298 readloop(phi_0, bb_1, testbb, C);
303 std::cerr << "Error: Unknown symbol.\n";
309 curvalue = nextvalue;
312 // Reading stdin loop
313 loop = (cursym == SYM_NONE)
314 || (cursym == SYM_MOVE)
315 || (cursym == SYM_CHANGE);
319 if (cursym == SYM_NONE) {
333 if (cursym == SYM_CHANGE) {
334 curvalue += direction;
337 if (cursym == SYM_NONE) {
339 curvalue = direction;
342 nextsym = SYM_CHANGE;
343 nextvalue = direction;
354 if (cursym == SYM_MOVE) {
355 curvalue += direction;
358 if (cursym == SYM_NONE) {
360 curvalue = direction;
364 nextvalue = direction;
371 if (cursym == SYM_NONE) {
380 if (cursym == SYM_NONE) {
389 if (cursym == SYM_NONE) {
398 if (cursym == SYM_NONE) {
399 cursym = SYM_ENDLOOP;
401 nextsym = SYM_ENDLOOP;
406 // Ignore other characters
414 if (cursym == SYM_ENDLOOP) {
416 std::cerr << "Error: Extra ']'\n";
423 builder->CreateBr(testbb);
427 //%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
428 //Finish phi made at beginning of loop
429 phi->addIncoming(curhead, builder->GetInsertBlock());
432 //%tape.%d = load i8 *%head.%d
433 LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
435 //%test.%d = icmp eq i8 %tape.%d, 0
436 ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0,
437 ConstantInt::get(C, APInt(8, 0)), testreg);
439 //br i1 %test.%d, label %main.%d, label %main.%d
440 BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func);
441 BranchInst::Create(bb_0, oldbb, test_0, testbb);
444 builder->SetInsertPoint(bb_0);
446 //%head.%d = phi i8 *[%head.%d, %main.%d]
447 PHINode *phi_1 = builder->
448 CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 1,
450 phi_1->addIncoming(head_0, testbb);
457 //End of the program, so go to return block
458 builder->CreateBr(endbb);
461 std::cerr << "Error: Missing ']'\n";