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