1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 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 coordinates the per-function state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "CGDebugInfo.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/Decl.h" 20 #include "llvm/Analysis/Verifier.h" 21 #include "llvm/Support/CFG.h" 22 using namespace clang; 23 using namespace CodeGen; 24 25 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 26 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL), 27 CaseRangeBlock(NULL) { 28 LLVMIntTy = ConvertType(getContext().IntTy); 29 LLVMPointerWidth = Target.getPointerWidth(0); 30 } 31 32 ASTContext &CodeGenFunction::getContext() const { 33 return CGM.getContext(); 34 } 35 36 37 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 38 llvm::BasicBlock *&BB = LabelMap[S]; 39 if (BB) return BB; 40 41 // Create, but don't insert, the new block. 42 return BB = llvm::BasicBlock::Create(S->getName()); 43 } 44 45 llvm::Constant * 46 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 47 return cast<llvm::Constant>(LocalDeclMap[BVD]); 48 } 49 50 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 51 return CGM.getTypes().ConvertType(T); 52 } 53 54 bool CodeGenFunction::isObjCPointerType(QualType T) { 55 // All Objective-C types are pointers. 56 return T->isObjCInterfaceType() || 57 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType(); 58 } 59 60 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 61 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() && 62 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType(); 63 } 64 65 void CodeGenFunction::GenerateFunction(const Stmt *Body) { 66 // Emit the function body. 67 EmitStmt(Body); 68 69 // Finish emission of indirect switches. 70 EmitIndirectSwitches(); 71 72 // Emit debug descriptor for function end. 73 CGDebugInfo *DI = CGM.getDebugInfo(); 74 if (DI) { 75 const CompoundStmt* s = dyn_cast<CompoundStmt>(Body); 76 if (s && s->getRBracLoc().isValid()) { 77 DI->setLocation(s->getRBracLoc()); 78 } 79 DI->EmitRegionEnd(CurFn, Builder); 80 } 81 82 // Emit a return for code that falls off the end. If insert point 83 // is a dummy block with no predecessors then remove the block itself. 84 llvm::BasicBlock *BB = Builder.GetInsertBlock(); 85 if (isDummyBlock(BB)) 86 BB->eraseFromParent(); 87 else { 88 // FIXME: if this is C++ main, this should return 0. 89 if (CurFn->getReturnType() == llvm::Type::VoidTy) 90 Builder.CreateRetVoid(); 91 else 92 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType())); 93 } 94 assert(BreakContinueStack.empty() && 95 "mismatched push/pop in break/continue stack!"); 96 97 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 98 AllocaInsertPt->eraseFromParent(); 99 AllocaInsertPt = 0; 100 101 // Verify that the function is well formed. 102 assert(!verifyFunction(*CurFn) && "Generated function is not well formed."); 103 } 104 105 void CodeGenFunction::GenerateCode(const FunctionDecl *FD, 106 llvm::Function *Fn) { 107 CurFuncDecl = FD; 108 FnRetTy = FD->getResultType(); 109 CurFn = Fn; 110 assert(CurFn->isDeclaration() && "Function already has body?"); 111 112 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn); 113 114 // Create a marker to make it easy to insert allocas into the entryblock 115 // later. Don't create this with the builder, because we don't want it 116 // folded. 117 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty); 118 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt", 119 EntryBB); 120 121 Builder.SetInsertPoint(EntryBB); 122 123 // Emit subprogram debug descriptor. 124 CGDebugInfo *DI = CGM.getDebugInfo(); 125 if (DI) { 126 CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody()); 127 if (body && body->getLBracLoc().isValid()) { 128 DI->setLocation(body->getLBracLoc()); 129 } 130 DI->EmitFunctionStart(FD, CurFn, Builder); 131 } 132 133 // Emit allocs for param decls. Give the LLVM Argument nodes names. 134 llvm::Function::arg_iterator AI = CurFn->arg_begin(); 135 136 // Name the struct return argument. 137 if (hasAggregateLLVMType(FD->getResultType())) { 138 AI->setName("agg.result"); 139 ++AI; 140 } 141 142 if (FD->getNumParams()) { 143 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto(); 144 assert(FProto && "Function def must have prototype!"); 145 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) { 146 assert(AI != CurFn->arg_end() && "Argument mismatch!"); 147 const ParmVarDecl* CurParam = FD->getParamDecl(i); 148 llvm::Value* V = AI; 149 if (!getContext().typesAreCompatible(FProto->getArgType(i), 150 CurParam->getType())) { 151 // This must be a promotion, for something like 152 // "void a(x) short x; {..." 153 V = EmitScalarConversion(V, FProto->getArgType(i), 154 CurParam->getType()); 155 } 156 EmitParmDecl(*CurParam, V); 157 } 158 } 159 GenerateFunction(FD->getBody()); 160 } 161 162 /// isDummyBlock - Return true if BB is an empty basic block 163 /// with no predecessors. 164 bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) { 165 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName()) 166 return true; 167 return false; 168 } 169 170 /// StartBlock - Start new block named N. If insert block is a dummy block 171 /// then reuse it. 172 void CodeGenFunction::StartBlock(const char *N) { 173 llvm::BasicBlock *BB = Builder.GetInsertBlock(); 174 if (!isDummyBlock(BB)) 175 EmitBlock(llvm::BasicBlock::Create(N)); 176 else 177 BB->setName(N); 178 } 179 180 /// getCGRecordLayout - Return record layout info. 181 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT, 182 QualType Ty) { 183 const RecordType *RTy = Ty->getAsRecordType(); 184 assert (RTy && "Unexpected type. RecordType expected here."); 185 186 return CGT.getCGRecordLayout(RTy->getDecl()); 187 } 188 189 /// ErrorUnsupported - Print out an error that codegen doesn't support the 190 /// specified stmt yet. 191 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 192 CGM.ErrorUnsupported(S, Type); 193 } 194 195 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 196 // Use LabelIDs.size() as the new ID if one hasn't been assigned. 197 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; 198 } 199 200 void CodeGenFunction::EmitIndirectSwitches() { 201 llvm::BasicBlock *Default; 202 203 if (IndirectSwitches.empty()) 204 return; 205 206 if (!LabelIDs.empty()) { 207 Default = getBasicBlockForLabel(LabelIDs.begin()->first); 208 } else { 209 // No possible targets for indirect goto, just emit an infinite 210 // loop. 211 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn); 212 llvm::BranchInst::Create(Default, Default); 213 } 214 215 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), 216 e = IndirectSwitches.end(); i != e; ++i) { 217 llvm::SwitchInst *I = *i; 218 219 I->setSuccessor(0, Default); 220 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), 221 LE = LabelIDs.end(); LI != LE; ++LI) { 222 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty, 223 LI->second), 224 getBasicBlockForLabel(LI->first)); 225 } 226 } 227 } 228