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/APValue.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "llvm/Target/TargetData.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 28 : BlockFunction(cgm, *this, Builder), CGM(cgm), 29 Target(CGM.getContext().Target), 30 Builder(cgm.getModule().getContext()), 31 DebugInfo(0), IndirectBranch(0), 32 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), 33 CXXThisDecl(0), CXXVTTDecl(0), 34 ConditionalBranchLevel(0) { 35 LLVMIntTy = ConvertType(getContext().IntTy); 36 LLVMPointerWidth = Target.getPointerWidth(0); 37 } 38 39 ASTContext &CodeGenFunction::getContext() const { 40 return CGM.getContext(); 41 } 42 43 44 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 45 llvm::BasicBlock *&BB = LabelMap[S]; 46 if (BB) return BB; 47 48 // Create, but don't insert, the new block. 49 return BB = createBasicBlock(S->getName()); 50 } 51 52 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { 53 llvm::Value *Res = LocalDeclMap[VD]; 54 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 55 return Res; 56 } 57 58 llvm::Constant * 59 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 60 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 61 } 62 63 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 64 return CGM.getTypes().ConvertTypeForMem(T); 65 } 66 67 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 68 return CGM.getTypes().ConvertType(T); 69 } 70 71 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 72 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 73 T->isMemberFunctionPointerType(); 74 } 75 76 void CodeGenFunction::EmitReturnBlock() { 77 // For cleanliness, we try to avoid emitting the return block for 78 // simple cases. 79 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 80 81 if (CurBB) { 82 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 83 84 // We have a valid insert point, reuse it if it is empty or there are no 85 // explicit jumps to the return block. 86 if (CurBB->empty() || ReturnBlock->use_empty()) { 87 ReturnBlock->replaceAllUsesWith(CurBB); 88 delete ReturnBlock; 89 } else 90 EmitBlock(ReturnBlock); 91 return; 92 } 93 94 // Otherwise, if the return block is the target of a single direct 95 // branch then we can just put the code in that block instead. This 96 // cleans up functions which started with a unified return block. 97 if (ReturnBlock->hasOneUse()) { 98 llvm::BranchInst *BI = 99 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin()); 100 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { 101 // Reset insertion point and delete the branch. 102 Builder.SetInsertPoint(BI->getParent()); 103 BI->eraseFromParent(); 104 delete ReturnBlock; 105 return; 106 } 107 } 108 109 // FIXME: We are at an unreachable point, there is no reason to emit the block 110 // unless it has uses. However, we still need a place to put the debug 111 // region.end for now. 112 113 EmitBlock(ReturnBlock); 114 } 115 116 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 117 assert(BreakContinueStack.empty() && 118 "mismatched push/pop in break/continue stack!"); 119 assert(BlockScopes.empty() && 120 "did not remove all blocks from block scope map!"); 121 assert(CleanupEntries.empty() && 122 "mismatched push/pop in cleanup stack!"); 123 124 // Emit function epilog (to return). 125 EmitReturnBlock(); 126 127 // Emit debug descriptor for function end. 128 if (CGDebugInfo *DI = getDebugInfo()) { 129 DI->setLocation(EndLoc); 130 DI->EmitRegionEnd(CurFn, Builder); 131 } 132 133 EmitFunctionEpilog(*CurFnInfo, ReturnValue); 134 135 // If someone did an indirect goto, emit the indirect goto block at the end of 136 // the function. 137 if (IndirectBranch) { 138 EmitBlock(IndirectBranch->getParent()); 139 Builder.ClearInsertionPoint(); 140 } 141 142 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 143 llvm::Instruction *Ptr = AllocaInsertPt; 144 AllocaInsertPt = 0; 145 Ptr->eraseFromParent(); 146 147 // If someone took the address of a label but never did an indirect goto, we 148 // made a zero entry PHI node, which is illegal, zap it now. 149 if (IndirectBranch) { 150 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 151 if (PN->getNumIncomingValues() == 0) { 152 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 153 PN->eraseFromParent(); 154 } 155 } 156 } 157 158 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 159 llvm::Function *Fn, 160 const FunctionArgList &Args, 161 SourceLocation StartLoc) { 162 const Decl *D = GD.getDecl(); 163 164 DidCallStackSave = false; 165 CurCodeDecl = CurFuncDecl = D; 166 FnRetTy = RetTy; 167 CurFn = Fn; 168 assert(CurFn->isDeclaration() && "Function already has body?"); 169 170 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 171 172 // Create a marker to make it easy to insert allocas into the entryblock 173 // later. Don't create this with the builder, because we don't want it 174 // folded. 175 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)); 176 AllocaInsertPt = new llvm::BitCastInst(Undef, 177 llvm::Type::getInt32Ty(VMContext), "", 178 EntryBB); 179 if (Builder.isNamePreserving()) 180 AllocaInsertPt->setName("allocapt"); 181 182 ReturnBlock = createBasicBlock("return"); 183 184 Builder.SetInsertPoint(EntryBB); 185 186 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0); 187 188 // Emit subprogram debug descriptor. 189 // FIXME: The cast here is a huge hack. 190 if (CGDebugInfo *DI = getDebugInfo()) { 191 DI->setLocation(StartLoc); 192 if (isa<FunctionDecl>(D)) { 193 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder); 194 } else { 195 // Just use LLVM function name. 196 197 // FIXME: Remove unnecessary conversion to std::string when API settles. 198 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(), 199 FnType, CurFn, Builder); 200 } 201 } 202 203 // FIXME: Leaked. 204 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); 205 206 if (RetTy->isVoidType()) { 207 // Void type; nothing to return. 208 ReturnValue = 0; 209 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 210 hasAggregateLLVMType(CurFnInfo->getReturnType())) { 211 // Indirect aggregate return; emit returned value directly into sret slot. 212 // This reduces code size, and is also affects correctness in C++. 213 ReturnValue = CurFn->arg_begin(); 214 } else { 215 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 216 } 217 218 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 219 220 // If any of the arguments have a variably modified type, make sure to 221 // emit the type size. 222 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 223 i != e; ++i) { 224 QualType Ty = i->second; 225 226 if (Ty->isVariablyModifiedType()) 227 EmitVLASize(Ty); 228 } 229 } 230 231 static bool NeedsVTTParameter(GlobalDecl GD) { 232 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 233 234 // We don't have any virtual bases, just return early. 235 if (!MD->getParent()->getNumVBases()) 236 return false; 237 238 // Check if we have a base constructor. 239 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 240 return true; 241 242 // Check if we have a base destructor. 243 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 244 return true; 245 246 return false; 247 } 248 249 void CodeGenFunction::GenerateCode(GlobalDecl GD, 250 llvm::Function *Fn) { 251 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 252 253 // Check if we should generate debug info for this function. 254 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 255 DebugInfo = CGM.getDebugInfo(); 256 257 FunctionArgList Args; 258 259 CurGD = GD; 260 OuterTryBlock = 0; 261 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 262 if (MD->isInstance()) { 263 // Create the implicit 'this' decl. 264 // FIXME: I'm not entirely sure I like using a fake decl just for code 265 // generation. Maybe we can come up with a better way? 266 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 267 &getContext().Idents.get("this"), 268 MD->getThisType(getContext())); 269 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 270 271 // Check if we need a VTT parameter as well. 272 if (NeedsVTTParameter(GD)) { 273 // FIXME: The comment about using a fake decl above applies here too. 274 QualType T = getContext().getPointerType(getContext().VoidPtrTy); 275 CXXVTTDecl = 276 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 277 &getContext().Idents.get("vtt"), T); 278 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType())); 279 } 280 } 281 } 282 283 if (FD->getNumParams()) { 284 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 285 assert(FProto && "Function def must have prototype!"); 286 287 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 288 Args.push_back(std::make_pair(FD->getParamDecl(i), 289 FProto->getArgType(i))); 290 } 291 292 if (const CompoundStmt *S = FD->getCompoundBody()) { 293 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc()); 294 295 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 296 EmitCtorPrologue(CD, GD.getCtorType()); 297 EmitStmt(S); 298 299 // If any of the member initializers are temporaries bound to references 300 // make sure to emit their destructors. 301 EmitCleanupBlocks(0); 302 303 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 304 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue"); 305 PushCleanupBlock(DtorEpilogue); 306 307 EmitStmt(S); 308 309 CleanupBlockInfo Info = PopCleanupBlock(); 310 311 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!"); 312 EmitBlock(DtorEpilogue); 313 EmitDtorEpilogue(DD, GD.getDtorType()); 314 315 if (Info.SwitchBlock) 316 EmitBlock(Info.SwitchBlock); 317 if (Info.EndBlock) 318 EmitBlock(Info.EndBlock); 319 } else { 320 // Just a regular function, emit its body. 321 EmitStmt(S); 322 } 323 324 FinishFunction(S->getRBracLoc()); 325 } else if (FD->isImplicit()) { 326 const CXXRecordDecl *ClassDecl = 327 cast<CXXRecordDecl>(FD->getDeclContext()); 328 (void) ClassDecl; 329 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 330 // FIXME: For C++0x, we want to look for implicit *definitions* of 331 // these special member functions, rather than implicit *declarations*. 332 if (CD->isCopyConstructor(getContext())) { 333 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 334 "Cannot synthesize a non-implicit copy constructor"); 335 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args); 336 } else if (CD->isDefaultConstructor()) { 337 assert(!ClassDecl->hasUserDeclaredConstructor() && 338 "Cannot synthesize a non-implicit default constructor."); 339 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args); 340 } else { 341 assert(false && "Implicit constructor cannot be synthesized"); 342 } 343 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) { 344 assert(!ClassDecl->hasUserDeclaredDestructor() && 345 "Cannot synthesize a non-implicit destructor"); 346 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args); 347 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 348 assert(MD->isCopyAssignment() && 349 !ClassDecl->hasUserDeclaredCopyAssignment() && 350 "Cannot synthesize a method that is not an implicit-defined " 351 "copy constructor"); 352 SynthesizeCXXCopyAssignment(MD, Fn, Args); 353 } else { 354 assert(false && "Cannot synthesize unknown implicit function"); 355 } 356 } else if (const Stmt *S = FD->getBody()) { 357 if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) { 358 OuterTryBlock = TS; 359 StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc()); 360 EmitStmt(TS); 361 FinishFunction(TS->getEndLoc()); 362 } 363 } 364 365 // Destroy the 'this' declaration. 366 if (CXXThisDecl) 367 CXXThisDecl->Destroy(getContext()); 368 369 // Destroy the VTT declaration. 370 if (CXXVTTDecl) 371 CXXVTTDecl->Destroy(getContext()); 372 } 373 374 /// ContainsLabel - Return true if the statement contains a label in it. If 375 /// this statement is not executed normally, it not containing a label means 376 /// that we can just remove the code. 377 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 378 // Null statement, not a label! 379 if (S == 0) return false; 380 381 // If this is a label, we have to emit the code, consider something like: 382 // if (0) { ... foo: bar(); } goto foo; 383 if (isa<LabelStmt>(S)) 384 return true; 385 386 // If this is a case/default statement, and we haven't seen a switch, we have 387 // to emit the code. 388 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 389 return true; 390 391 // If this is a switch statement, we want to ignore cases below it. 392 if (isa<SwitchStmt>(S)) 393 IgnoreCaseStmts = true; 394 395 // Scan subexpressions for verboten labels. 396 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 397 I != E; ++I) 398 if (ContainsLabel(*I, IgnoreCaseStmts)) 399 return true; 400 401 return false; 402 } 403 404 405 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 406 /// a constant, or if it does but contains a label, return 0. If it constant 407 /// folds to 'true' and does not contain a label, return 1, if it constant folds 408 /// to 'false' and does not contain a label, return -1. 409 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 410 // FIXME: Rename and handle conversion of other evaluatable things 411 // to bool. 412 Expr::EvalResult Result; 413 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 414 Result.HasSideEffects) 415 return 0; // Not foldable, not integer or not fully evaluatable. 416 417 if (CodeGenFunction::ContainsLabel(Cond)) 418 return 0; // Contains a label. 419 420 return Result.Val.getInt().getBoolValue() ? 1 : -1; 421 } 422 423 424 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 425 /// statement) to the specified blocks. Based on the condition, this might try 426 /// to simplify the codegen of the conditional based on the branch. 427 /// 428 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 429 llvm::BasicBlock *TrueBlock, 430 llvm::BasicBlock *FalseBlock) { 431 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 432 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 433 434 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 435 // Handle X && Y in a condition. 436 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 437 // If we have "1 && X", simplify the code. "0 && X" would have constant 438 // folded if the case was simple enough. 439 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 440 // br(1 && X) -> br(X). 441 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 442 } 443 444 // If we have "X && 1", simplify the code to use an uncond branch. 445 // "X && 0" would have been constant folded to 0. 446 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 447 // br(X && 1) -> br(X). 448 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 449 } 450 451 // Emit the LHS as a conditional. If the LHS conditional is false, we 452 // want to jump to the FalseBlock. 453 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 454 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 455 EmitBlock(LHSTrue); 456 457 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 458 return; 459 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 460 // If we have "0 || X", simplify the code. "1 || X" would have constant 461 // folded if the case was simple enough. 462 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 463 // br(0 || X) -> br(X). 464 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 465 } 466 467 // If we have "X || 0", simplify the code to use an uncond branch. 468 // "X || 1" would have been constant folded to 1. 469 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 470 // br(X || 0) -> br(X). 471 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 472 } 473 474 // Emit the LHS as a conditional. If the LHS conditional is true, we 475 // want to jump to the TrueBlock. 476 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 477 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 478 EmitBlock(LHSFalse); 479 480 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 481 return; 482 } 483 } 484 485 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 486 // br(!x, t, f) -> br(x, f, t) 487 if (CondUOp->getOpcode() == UnaryOperator::LNot) 488 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 489 } 490 491 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 492 // Handle ?: operator. 493 494 // Just ignore GNU ?: extension. 495 if (CondOp->getLHS()) { 496 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 497 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 498 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 499 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 500 EmitBlock(LHSBlock); 501 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 502 EmitBlock(RHSBlock); 503 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 504 return; 505 } 506 } 507 508 // Emit the code with the fully general case. 509 llvm::Value *CondV = EvaluateExprAsBool(Cond); 510 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 511 } 512 513 /// ErrorUnsupported - Print out an error that codegen doesn't support the 514 /// specified stmt yet. 515 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 516 bool OmitOnError) { 517 CGM.ErrorUnsupported(S, Type, OmitOnError); 518 } 519 520 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { 521 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 522 if (DestPtr->getType() != BP) 523 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 524 525 // Get size and alignment info for this aggregate. 526 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 527 528 // Don't bother emitting a zero-byte memset. 529 if (TypeInfo.first == 0) 530 return; 531 532 // FIXME: Handle variable sized types. 533 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, 534 LLVMPointerWidth); 535 536 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 537 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)), 538 // TypeInfo.first describes size in bits. 539 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 540 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 541 TypeInfo.second/8)); 542 } 543 544 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) { 545 // Make sure that there is a block for the indirect goto. 546 if (IndirectBranch == 0) 547 GetIndirectGotoBlock(); 548 549 llvm::BasicBlock *BB = getBasicBlockForLabel(L); 550 551 // Make sure the indirect branch includes all of the address-taken blocks. 552 IndirectBranch->addDestination(BB); 553 return llvm::BlockAddress::get(CurFn, BB); 554 } 555 556 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 557 // If we already made the indirect branch for indirect goto, return its block. 558 if (IndirectBranch) return IndirectBranch->getParent(); 559 560 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 561 562 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 563 564 // Create the PHI node that indirect gotos will add entries to. 565 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest"); 566 567 // Create the indirect branch instruction. 568 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 569 return IndirectBranch->getParent(); 570 } 571 572 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 573 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 574 575 assert(SizeEntry && "Did not emit size for type"); 576 return SizeEntry; 577 } 578 579 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 580 assert(Ty->isVariablyModifiedType() && 581 "Must pass variably modified type to EmitVLASizes!"); 582 583 EnsureInsertPoint(); 584 585 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 586 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 587 588 if (!SizeEntry) { 589 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 590 591 // Get the element size; 592 QualType ElemTy = VAT->getElementType(); 593 llvm::Value *ElemSize; 594 if (ElemTy->isVariableArrayType()) 595 ElemSize = EmitVLASize(ElemTy); 596 else 597 ElemSize = llvm::ConstantInt::get(SizeTy, 598 getContext().getTypeSize(ElemTy) / 8); 599 600 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 601 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 602 603 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 604 } 605 606 return SizeEntry; 607 } 608 609 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 610 EmitVLASize(AT->getElementType()); 611 return 0; 612 } 613 614 const PointerType *PT = Ty->getAs<PointerType>(); 615 assert(PT && "unknown VM type!"); 616 EmitVLASize(PT->getPointeeType()); 617 return 0; 618 } 619 620 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 621 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 622 return EmitScalarExpr(E); 623 } 624 return EmitLValue(E).getAddress(); 625 } 626 627 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock, 628 llvm::BasicBlock *CleanupExitBlock, 629 bool EHOnly) { 630 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock, 631 EHOnly)); 632 } 633 634 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { 635 assert(CleanupEntries.size() >= OldCleanupStackSize && 636 "Cleanup stack mismatch!"); 637 638 while (CleanupEntries.size() > OldCleanupStackSize) 639 EmitCleanupBlock(); 640 } 641 642 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { 643 CleanupEntry &CE = CleanupEntries.back(); 644 645 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock; 646 647 std::vector<llvm::BasicBlock *> Blocks; 648 std::swap(Blocks, CE.Blocks); 649 650 std::vector<llvm::BranchInst *> BranchFixups; 651 std::swap(BranchFixups, CE.BranchFixups); 652 653 bool EHOnly = CE.EHOnly; 654 655 CleanupEntries.pop_back(); 656 657 // Check if any branch fixups pointed to the scope we just popped. If so, 658 // we can remove them. 659 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 660 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); 661 BlockScopeMap::iterator I = BlockScopes.find(Dest); 662 663 if (I == BlockScopes.end()) 664 continue; 665 666 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); 667 668 if (I->second == CleanupEntries.size()) { 669 // We don't need to do this branch fixup. 670 BranchFixups[i] = BranchFixups.back(); 671 BranchFixups.pop_back(); 672 i--; 673 e--; 674 continue; 675 } 676 } 677 678 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock; 679 llvm::BasicBlock *EndBlock = 0; 680 if (!BranchFixups.empty()) { 681 if (!SwitchBlock) 682 SwitchBlock = createBasicBlock("cleanup.switch"); 683 EndBlock = createBasicBlock("cleanup.end"); 684 685 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 686 687 Builder.SetInsertPoint(SwitchBlock); 688 689 llvm::Value *DestCodePtr 690 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), 691 "cleanup.dst"); 692 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); 693 694 // Create a switch instruction to determine where to jump next. 695 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, 696 BranchFixups.size()); 697 698 // Restore the current basic block (if any) 699 if (CurBB) { 700 Builder.SetInsertPoint(CurBB); 701 702 // If we had a current basic block, we also need to emit an instruction 703 // to initialize the cleanup destination. 704 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)), 705 DestCodePtr); 706 } else 707 Builder.ClearInsertionPoint(); 708 709 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 710 llvm::BranchInst *BI = BranchFixups[i]; 711 llvm::BasicBlock *Dest = BI->getSuccessor(0); 712 713 // Fixup the branch instruction to point to the cleanup block. 714 BI->setSuccessor(0, CleanupEntryBlock); 715 716 if (CleanupEntries.empty()) { 717 llvm::ConstantInt *ID; 718 719 // Check if we already have a destination for this block. 720 if (Dest == SI->getDefaultDest()) 721 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 722 else { 723 ID = SI->findCaseDest(Dest); 724 if (!ID) { 725 // No code found, get a new unique one by using the number of 726 // switch successors. 727 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 728 SI->getNumSuccessors()); 729 SI->addCase(ID, Dest); 730 } 731 } 732 733 // Store the jump destination before the branch instruction. 734 new llvm::StoreInst(ID, DestCodePtr, BI); 735 } else { 736 // We need to jump through another cleanup block. Create a pad block 737 // with a branch instruction that jumps to the final destination and add 738 // it as a branch fixup to the current cleanup scope. 739 740 // Create the pad block. 741 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); 742 743 // Create a unique case ID. 744 llvm::ConstantInt *ID 745 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 746 SI->getNumSuccessors()); 747 748 // Store the jump destination before the branch instruction. 749 new llvm::StoreInst(ID, DestCodePtr, BI); 750 751 // Add it as the destination. 752 SI->addCase(ID, CleanupPad); 753 754 // Create the branch to the final destination. 755 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); 756 CleanupPad->getInstList().push_back(BI); 757 758 // And add it as a branch fixup. 759 CleanupEntries.back().BranchFixups.push_back(BI); 760 } 761 } 762 } 763 764 // Remove all blocks from the block scope map. 765 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 766 assert(BlockScopes.count(Blocks[i]) && 767 "Did not find block in scope map!"); 768 769 BlockScopes.erase(Blocks[i]); 770 } 771 772 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly); 773 } 774 775 void CodeGenFunction::EmitCleanupBlock() { 776 CleanupBlockInfo Info = PopCleanupBlock(); 777 778 if (Info.EHOnly) { 779 // FIXME: Add this to the exceptional edge 780 if (Info.CleanupBlock->getNumUses() == 0) 781 delete Info.CleanupBlock; 782 return; 783 } 784 785 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 786 if (CurBB && !CurBB->getTerminator() && 787 Info.CleanupBlock->getNumUses() == 0) { 788 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); 789 delete Info.CleanupBlock; 790 } else 791 EmitBlock(Info.CleanupBlock); 792 793 if (Info.SwitchBlock) 794 EmitBlock(Info.SwitchBlock); 795 if (Info.EndBlock) 796 EmitBlock(Info.EndBlock); 797 } 798 799 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { 800 assert(!CleanupEntries.empty() && 801 "Trying to add branch fixup without cleanup block!"); 802 803 // FIXME: We could be more clever here and check if there's already a branch 804 // fixup for this destination and recycle it. 805 CleanupEntries.back().BranchFixups.push_back(BI); 806 } 807 808 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { 809 if (!HaveInsertPoint()) 810 return; 811 812 llvm::BranchInst* BI = Builder.CreateBr(Dest); 813 814 Builder.ClearInsertionPoint(); 815 816 // The stack is empty, no need to do any cleanup. 817 if (CleanupEntries.empty()) 818 return; 819 820 if (!Dest->getParent()) { 821 // We are trying to branch to a block that hasn't been inserted yet. 822 AddBranchFixup(BI); 823 return; 824 } 825 826 BlockScopeMap::iterator I = BlockScopes.find(Dest); 827 if (I == BlockScopes.end()) { 828 // We are trying to jump to a block that is outside of any cleanup scope. 829 AddBranchFixup(BI); 830 return; 831 } 832 833 assert(I->second < CleanupEntries.size() && 834 "Trying to branch into cleanup region"); 835 836 if (I->second == CleanupEntries.size() - 1) { 837 // We have a branch to a block in the same scope. 838 return; 839 } 840 841 AddBranchFixup(BI); 842 } 843