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::FinishFunction(SourceLocation EndLoc) { 66 // Finish emission of indirect switches. 67 EmitIndirectSwitches(); 68 69 // Emit debug descriptor for function end. 70 if (CGDebugInfo *DI = CGM.getDebugInfo()) { 71 if (EndLoc.isValid()) { 72 DI->setLocation(EndLoc); 73 } 74 DI->EmitRegionEnd(CurFn, Builder); 75 } 76 77 // Emit a return for code that falls off the end. If insert point 78 // is a dummy block with no predecessors then remove the block itself. 79 llvm::BasicBlock *BB = Builder.GetInsertBlock(); 80 if (isDummyBlock(BB)) { 81 BB->eraseFromParent(); 82 } else { 83 // Just transfer to return 84 Builder.CreateBr(ReturnBlock); 85 } 86 assert(BreakContinueStack.empty() && 87 "mismatched push/pop in break/continue stack!"); 88 89 // Emit function epilog (to return). 90 Builder.SetInsertPoint(ReturnBlock); 91 EmitFunctionEpilog(FnRetTy, ReturnValue); 92 93 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 94 AllocaInsertPt->eraseFromParent(); 95 AllocaInsertPt = 0; 96 97 // Verify that the function is well formed. 98 assert(!verifyFunction(*CurFn) && "Generated function is not well formed."); 99 } 100 101 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, 102 llvm::Function *Fn, 103 const FunctionArgList &Args) { 104 CurFuncDecl = D; 105 FnRetTy = RetTy; 106 CurFn = Fn; 107 assert(CurFn->isDeclaration() && "Function already has body?"); 108 109 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn); 110 111 // Create a marker to make it easy to insert allocas into the entryblock 112 // later. Don't create this with the builder, because we don't want it 113 // folded. 114 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty); 115 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt", 116 EntryBB); 117 118 ReturnBlock = llvm::BasicBlock::Create("return", CurFn); 119 ReturnValue = 0; 120 if (!RetTy->isVoidType()) 121 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 122 123 Builder.SetInsertPoint(EntryBB); 124 125 // Emit subprogram debug descriptor. 126 // FIXME: The cast here is a huge hack. 127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 128 if (CGDebugInfo *DI = CGM.getDebugInfo()) { 129 CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody()); 130 if (body && body->getLBracLoc().isValid()) { 131 DI->setLocation(body->getLBracLoc()); 132 } 133 DI->EmitFunctionStart(FD, CurFn, Builder); 134 } 135 } 136 137 EmitFunctionProlog(CurFn, FnRetTy, Args); 138 } 139 140 void CodeGenFunction::GenerateCode(const FunctionDecl *FD, 141 llvm::Function *Fn) { 142 FunctionArgList Args; 143 if (FD->getNumParams()) { 144 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto(); 145 assert(FProto && "Function def must have prototype!"); 146 147 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 148 Args.push_back(std::make_pair(FD->getParamDecl(i), 149 FProto->getArgType(i))); 150 } 151 152 StartFunction(FD, FD->getResultType(), Fn, Args); 153 154 EmitStmt(FD->getBody()); 155 156 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody()); 157 if (S) { 158 FinishFunction(S->getRBracLoc()); 159 } else { 160 FinishFunction(); 161 } 162 } 163 164 /// isDummyBlock - Return true if BB is an empty basic block 165 /// with no predecessors. 166 bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) { 167 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName()) 168 return true; 169 return false; 170 } 171 172 /// StartBlock - Start new block named N. If insert block is a dummy block 173 /// then reuse it. 174 void CodeGenFunction::StartBlock(const char *N) { 175 llvm::BasicBlock *BB = Builder.GetInsertBlock(); 176 if (!isDummyBlock(BB)) 177 EmitBlock(llvm::BasicBlock::Create(N)); 178 else 179 BB->setName(N); 180 } 181 182 /// getCGRecordLayout - Return record layout info. 183 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT, 184 QualType Ty) { 185 const RecordType *RTy = Ty->getAsRecordType(); 186 assert (RTy && "Unexpected type. RecordType expected here."); 187 188 return CGT.getCGRecordLayout(RTy->getDecl()); 189 } 190 191 /// ErrorUnsupported - Print out an error that codegen doesn't support the 192 /// specified stmt yet. 193 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 194 bool OmitOnError) { 195 CGM.ErrorUnsupported(S, Type, OmitOnError); 196 } 197 198 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 199 // Use LabelIDs.size() as the new ID if one hasn't been assigned. 200 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; 201 } 202 203 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) 204 { 205 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 206 if (DestPtr->getType() != BP) 207 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 208 209 // Get size and alignment info for this aggregate. 210 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 211 212 // FIXME: Handle variable sized types. 213 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); 214 215 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 216 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 217 // TypeInfo.first describes size in bits. 218 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 219 llvm::ConstantInt::get(llvm::Type::Int32Ty, 220 TypeInfo.second/8)); 221 } 222 223 void CodeGenFunction::EmitIndirectSwitches() { 224 llvm::BasicBlock *Default; 225 226 if (IndirectSwitches.empty()) 227 return; 228 229 if (!LabelIDs.empty()) { 230 Default = getBasicBlockForLabel(LabelIDs.begin()->first); 231 } else { 232 // No possible targets for indirect goto, just emit an infinite 233 // loop. 234 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn); 235 llvm::BranchInst::Create(Default, Default); 236 } 237 238 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), 239 e = IndirectSwitches.end(); i != e; ++i) { 240 llvm::SwitchInst *I = *i; 241 242 I->setSuccessor(0, Default); 243 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), 244 LE = LabelIDs.end(); LI != LE; ++LI) { 245 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty, 246 LI->second), 247 getBasicBlockForLabel(LI->first)); 248 } 249 } 250 } 251