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 "CGException.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "clang/AST/APValue.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/Decl.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/StmtCXX.h" 24 #include "clang/Frontend/CodeGenOptions.h" 25 #include "llvm/Target/TargetData.h" 26 #include "llvm/Intrinsics.h" 27 using namespace clang; 28 using namespace CodeGen; 29 30 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 31 : BlockFunction(cgm, *this, Builder), CGM(cgm), 32 Target(CGM.getContext().Target), 33 Builder(cgm.getModule().getContext()), 34 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1), 35 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0), 36 SwitchInsn(0), CaseRangeBlock(0), 37 DidCallStackSave(false), UnreachableBlock(0), 38 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0), 39 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0), 40 TrapBB(0) { 41 42 // Get some frequently used types. 43 LLVMPointerWidth = Target.getPointerWidth(0); 44 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext(); 45 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth); 46 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 47 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 48 49 Exceptions = getContext().getLangOptions().Exceptions; 50 CatchUndefined = getContext().getLangOptions().CatchUndefined; 51 CGM.getMangleContext().startNewFunction(); 52 } 53 54 ASTContext &CodeGenFunction::getContext() const { 55 return CGM.getContext(); 56 } 57 58 59 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { 60 llvm::Value *Res = LocalDeclMap[VD]; 61 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 62 return Res; 63 } 64 65 llvm::Constant * 66 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 67 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 68 } 69 70 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 71 return CGM.getTypes().ConvertTypeForMem(T); 72 } 73 74 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 75 return CGM.getTypes().ConvertType(T); 76 } 77 78 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 79 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 80 T->isObjCObjectType(); 81 } 82 83 void CodeGenFunction::EmitReturnBlock() { 84 // For cleanliness, we try to avoid emitting the return block for 85 // simple cases. 86 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 87 88 if (CurBB) { 89 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 90 91 // We have a valid insert point, reuse it if it is empty or there are no 92 // explicit jumps to the return block. 93 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 94 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 95 delete ReturnBlock.getBlock(); 96 } else 97 EmitBlock(ReturnBlock.getBlock()); 98 return; 99 } 100 101 // Otherwise, if the return block is the target of a single direct 102 // branch then we can just put the code in that block instead. This 103 // cleans up functions which started with a unified return block. 104 if (ReturnBlock.getBlock()->hasOneUse()) { 105 llvm::BranchInst *BI = 106 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin()); 107 if (BI && BI->isUnconditional() && 108 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 109 // Reset insertion point and delete the branch. 110 Builder.SetInsertPoint(BI->getParent()); 111 BI->eraseFromParent(); 112 delete ReturnBlock.getBlock(); 113 return; 114 } 115 } 116 117 // FIXME: We are at an unreachable point, there is no reason to emit the block 118 // unless it has uses. However, we still need a place to put the debug 119 // region.end for now. 120 121 EmitBlock(ReturnBlock.getBlock()); 122 } 123 124 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 125 if (!BB) return; 126 if (!BB->use_empty()) 127 return CGF.CurFn->getBasicBlockList().push_back(BB); 128 delete BB; 129 } 130 131 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 132 assert(BreakContinueStack.empty() && 133 "mismatched push/pop in break/continue stack!"); 134 135 // Emit function epilog (to return). 136 EmitReturnBlock(); 137 138 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 139 140 // Emit debug descriptor for function end. 141 if (CGDebugInfo *DI = getDebugInfo()) { 142 DI->setLocation(EndLoc); 143 DI->EmitFunctionEnd(Builder); 144 } 145 146 EmitFunctionEpilog(*CurFnInfo); 147 EmitEndEHSpec(CurCodeDecl); 148 149 assert(EHStack.empty() && 150 "did not remove all scopes from cleanup stack!"); 151 152 // If someone did an indirect goto, emit the indirect goto block at the end of 153 // the function. 154 if (IndirectBranch) { 155 EmitBlock(IndirectBranch->getParent()); 156 Builder.ClearInsertionPoint(); 157 } 158 159 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 160 llvm::Instruction *Ptr = AllocaInsertPt; 161 AllocaInsertPt = 0; 162 Ptr->eraseFromParent(); 163 164 // If someone took the address of a label but never did an indirect goto, we 165 // made a zero entry PHI node, which is illegal, zap it now. 166 if (IndirectBranch) { 167 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 168 if (PN->getNumIncomingValues() == 0) { 169 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 170 PN->eraseFromParent(); 171 } 172 } 173 174 EmitIfUsed(*this, RethrowBlock.getBlock()); 175 EmitIfUsed(*this, TerminateLandingPad); 176 EmitIfUsed(*this, TerminateHandler); 177 EmitIfUsed(*this, UnreachableBlock); 178 179 if (CGM.getCodeGenOpts().EmitDeclMetadata) 180 EmitDeclMetadata(); 181 } 182 183 /// ShouldInstrumentFunction - Return true if the current function should be 184 /// instrumented with __cyg_profile_func_* calls 185 bool CodeGenFunction::ShouldInstrumentFunction() { 186 if (!CGM.getCodeGenOpts().InstrumentFunctions) 187 return false; 188 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 189 return false; 190 return true; 191 } 192 193 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 194 /// instrumentation function with the current function and the call site, if 195 /// function instrumentation is enabled. 196 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 197 if (!ShouldInstrumentFunction()) 198 return; 199 200 const llvm::PointerType *PointerTy; 201 const llvm::FunctionType *FunctionTy; 202 std::vector<const llvm::Type*> ProfileFuncArgs; 203 204 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 205 PointerTy = llvm::Type::getInt8PtrTy(VMContext); 206 ProfileFuncArgs.push_back(PointerTy); 207 ProfileFuncArgs.push_back(PointerTy); 208 FunctionTy = llvm::FunctionType::get( 209 llvm::Type::getVoidTy(VMContext), 210 ProfileFuncArgs, false); 211 212 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 213 llvm::CallInst *CallSite = Builder.CreateCall( 214 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0), 215 llvm::ConstantInt::get(Int32Ty, 0), 216 "callsite"); 217 218 Builder.CreateCall2(F, 219 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 220 CallSite); 221 } 222 223 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 224 llvm::Function *Fn, 225 const FunctionArgList &Args, 226 SourceLocation StartLoc) { 227 const Decl *D = GD.getDecl(); 228 229 DidCallStackSave = false; 230 CurCodeDecl = CurFuncDecl = D; 231 FnRetTy = RetTy; 232 CurFn = Fn; 233 assert(CurFn->isDeclaration() && "Function already has body?"); 234 235 // Pass inline keyword to optimizer if it appears explicitly on any 236 // declaration. 237 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 238 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(), 239 RE = FD->redecls_end(); RI != RE; ++RI) 240 if (RI->isInlineSpecified()) { 241 Fn->addFnAttr(llvm::Attribute::InlineHint); 242 break; 243 } 244 245 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 246 247 // Create a marker to make it easy to insert allocas into the entryblock 248 // later. Don't create this with the builder, because we don't want it 249 // folded. 250 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 251 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 252 if (Builder.isNamePreserving()) 253 AllocaInsertPt->setName("allocapt"); 254 255 ReturnBlock = getJumpDestInCurrentScope("return"); 256 257 Builder.SetInsertPoint(EntryBB); 258 259 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0, 260 false, false, 0, 0, 261 /*FIXME?*/ 262 FunctionType::ExtInfo()); 263 264 // Emit subprogram debug descriptor. 265 if (CGDebugInfo *DI = getDebugInfo()) { 266 DI->setLocation(StartLoc); 267 DI->EmitFunctionStart(GD, FnType, CurFn, Builder); 268 } 269 270 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 271 272 // FIXME: Leaked. 273 // CC info is ignored, hopefully? 274 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args, 275 FunctionType::ExtInfo()); 276 277 if (RetTy->isVoidType()) { 278 // Void type; nothing to return. 279 ReturnValue = 0; 280 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 281 hasAggregateLLVMType(CurFnInfo->getReturnType())) { 282 // Indirect aggregate return; emit returned value directly into sret slot. 283 // This reduces code size, and affects correctness in C++. 284 ReturnValue = CurFn->arg_begin(); 285 } else { 286 ReturnValue = CreateIRTemp(RetTy, "retval"); 287 } 288 289 EmitStartEHSpec(CurCodeDecl); 290 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 291 292 if (CXXThisDecl) 293 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); 294 if (CXXVTTDecl) 295 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt"); 296 297 // If any of the arguments have a variably modified type, make sure to 298 // emit the type size. 299 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 300 i != e; ++i) { 301 QualType Ty = i->second; 302 303 if (Ty->isVariablyModifiedType()) 304 EmitVLASize(Ty); 305 } 306 } 307 308 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) { 309 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl()); 310 assert(FD->getBody()); 311 EmitStmt(FD->getBody()); 312 } 313 314 /// Tries to mark the given function nounwind based on the 315 /// non-existence of any throwing calls within it. We believe this is 316 /// lightweight enough to do at -O0. 317 static void TryMarkNoThrow(llvm::Function *F) { 318 // LLVM treats 'nounwind' on a function as part of the type, so we 319 // can't do this on functions that can be overwritten. 320 if (F->mayBeOverridden()) return; 321 322 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) 323 for (llvm::BasicBlock::iterator 324 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) 325 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) 326 if (!Call->doesNotThrow()) 327 return; 328 F->setDoesNotThrow(true); 329 } 330 331 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) { 332 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 333 334 // Check if we should generate debug info for this function. 335 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 336 DebugInfo = CGM.getDebugInfo(); 337 338 FunctionArgList Args; 339 340 CurGD = GD; 341 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 342 if (MD->isInstance()) { 343 // Create the implicit 'this' decl. 344 // FIXME: I'm not entirely sure I like using a fake decl just for code 345 // generation. Maybe we can come up with a better way? 346 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, 347 FD->getLocation(), 348 &getContext().Idents.get("this"), 349 MD->getThisType(getContext())); 350 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 351 352 // Check if we need a VTT parameter as well. 353 if (CodeGenVTables::needsVTTParameter(GD)) { 354 // FIXME: The comment about using a fake decl above applies here too. 355 QualType T = getContext().getPointerType(getContext().VoidPtrTy); 356 CXXVTTDecl = 357 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(), 358 &getContext().Idents.get("vtt"), T); 359 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType())); 360 } 361 } 362 } 363 364 if (FD->getNumParams()) { 365 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 366 assert(FProto && "Function def must have prototype!"); 367 368 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 369 Args.push_back(std::make_pair(FD->getParamDecl(i), 370 FProto->getArgType(i))); 371 } 372 373 SourceRange BodyRange; 374 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 375 376 // Emit the standard function prologue. 377 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin()); 378 379 // Generate the body of the function. 380 if (isa<CXXDestructorDecl>(FD)) 381 EmitDestructorBody(Args); 382 else if (isa<CXXConstructorDecl>(FD)) 383 EmitConstructorBody(Args); 384 else 385 EmitFunctionBody(Args); 386 387 // Emit the standard function epilogue. 388 FinishFunction(BodyRange.getEnd()); 389 390 // If we haven't marked the function nothrow through other means, do 391 // a quick pass now to see if we can. 392 if (!CurFn->doesNotThrow()) 393 TryMarkNoThrow(CurFn); 394 } 395 396 /// ContainsLabel - Return true if the statement contains a label in it. If 397 /// this statement is not executed normally, it not containing a label means 398 /// that we can just remove the code. 399 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 400 // Null statement, not a label! 401 if (S == 0) return false; 402 403 // If this is a label, we have to emit the code, consider something like: 404 // if (0) { ... foo: bar(); } goto foo; 405 if (isa<LabelStmt>(S)) 406 return true; 407 408 // If this is a case/default statement, and we haven't seen a switch, we have 409 // to emit the code. 410 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 411 return true; 412 413 // If this is a switch statement, we want to ignore cases below it. 414 if (isa<SwitchStmt>(S)) 415 IgnoreCaseStmts = true; 416 417 // Scan subexpressions for verboten labels. 418 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 419 I != E; ++I) 420 if (ContainsLabel(*I, IgnoreCaseStmts)) 421 return true; 422 423 return false; 424 } 425 426 427 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 428 /// a constant, or if it does but contains a label, return 0. If it constant 429 /// folds to 'true' and does not contain a label, return 1, if it constant folds 430 /// to 'false' and does not contain a label, return -1. 431 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 432 // FIXME: Rename and handle conversion of other evaluatable things 433 // to bool. 434 Expr::EvalResult Result; 435 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 436 Result.HasSideEffects) 437 return 0; // Not foldable, not integer or not fully evaluatable. 438 439 if (CodeGenFunction::ContainsLabel(Cond)) 440 return 0; // Contains a label. 441 442 return Result.Val.getInt().getBoolValue() ? 1 : -1; 443 } 444 445 446 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 447 /// statement) to the specified blocks. Based on the condition, this might try 448 /// to simplify the codegen of the conditional based on the branch. 449 /// 450 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 451 llvm::BasicBlock *TrueBlock, 452 llvm::BasicBlock *FalseBlock) { 453 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 454 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 455 456 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 457 // Handle X && Y in a condition. 458 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 459 // If we have "1 && X", simplify the code. "0 && X" would have constant 460 // folded if the case was simple enough. 461 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 462 // br(1 && X) -> br(X). 463 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 464 } 465 466 // If we have "X && 1", simplify the code to use an uncond branch. 467 // "X && 0" would have been constant folded to 0. 468 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 469 // br(X && 1) -> br(X). 470 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 471 } 472 473 // Emit the LHS as a conditional. If the LHS conditional is false, we 474 // want to jump to the FalseBlock. 475 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 476 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 477 EmitBlock(LHSTrue); 478 479 // Any temporaries created here are conditional. 480 BeginConditionalBranch(); 481 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 482 EndConditionalBranch(); 483 484 return; 485 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 486 // If we have "0 || X", simplify the code. "1 || X" would have constant 487 // folded if the case was simple enough. 488 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 489 // br(0 || X) -> br(X). 490 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 491 } 492 493 // If we have "X || 0", simplify the code to use an uncond branch. 494 // "X || 1" would have been constant folded to 1. 495 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 496 // br(X || 0) -> br(X). 497 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 498 } 499 500 // Emit the LHS as a conditional. If the LHS conditional is true, we 501 // want to jump to the TrueBlock. 502 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 503 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 504 EmitBlock(LHSFalse); 505 506 // Any temporaries created here are conditional. 507 BeginConditionalBranch(); 508 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 509 EndConditionalBranch(); 510 511 return; 512 } 513 } 514 515 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 516 // br(!x, t, f) -> br(x, f, t) 517 if (CondUOp->getOpcode() == UnaryOperator::LNot) 518 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 519 } 520 521 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 522 // Handle ?: operator. 523 524 // Just ignore GNU ?: extension. 525 if (CondOp->getLHS()) { 526 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 527 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 528 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 529 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 530 EmitBlock(LHSBlock); 531 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 532 EmitBlock(RHSBlock); 533 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 534 return; 535 } 536 } 537 538 // Emit the code with the fully general case. 539 llvm::Value *CondV = EvaluateExprAsBool(Cond); 540 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 541 } 542 543 /// ErrorUnsupported - Print out an error that codegen doesn't support the 544 /// specified stmt yet. 545 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 546 bool OmitOnError) { 547 CGM.ErrorUnsupported(S, Type, OmitOnError); 548 } 549 550 void 551 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 552 // Ignore empty classes in C++. 553 if (getContext().getLangOptions().CPlusPlus) { 554 if (const RecordType *RT = Ty->getAs<RecordType>()) { 555 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 556 return; 557 } 558 } 559 560 // Cast the dest ptr to the appropriate i8 pointer type. 561 unsigned DestAS = 562 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 563 const llvm::Type *BP = 564 llvm::Type::getInt8PtrTy(VMContext, DestAS); 565 if (DestPtr->getType() != BP) 566 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 567 568 // Get size and alignment info for this aggregate. 569 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 570 uint64_t Size = TypeInfo.first; 571 unsigned Align = TypeInfo.second; 572 573 // Don't bother emitting a zero-byte memset. 574 if (Size == 0) 575 return; 576 577 llvm::ConstantInt *SizeVal = llvm::ConstantInt::get(IntPtrTy, Size / 8); 578 llvm::ConstantInt *AlignVal = Builder.getInt32(Align / 8); 579 580 // If the type contains a pointer to data member we can't memset it to zero. 581 // Instead, create a null constant and copy it to the destination. 582 if (CGM.getLangOptions().CPlusPlus && 583 CGM.getCXXABI().RequiresNonZeroInitializer(Ty)) { 584 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 585 586 llvm::GlobalVariable *NullVariable = 587 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 588 /*isConstant=*/true, 589 llvm::GlobalVariable::PrivateLinkage, 590 NullConstant, llvm::Twine()); 591 llvm::Value *SrcPtr = 592 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 593 594 // FIXME: variable-size types? 595 596 // Get and call the appropriate llvm.memcpy overload. 597 llvm::Constant *Memcpy = 598 CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), IntPtrTy); 599 Builder.CreateCall5(Memcpy, DestPtr, SrcPtr, SizeVal, AlignVal, 600 /*volatile*/ Builder.getFalse()); 601 return; 602 } 603 604 // Otherwise, just memset the whole thing to zero. This is legal 605 // because in LLVM, all default initializers (other than the ones we just 606 // handled above) are guaranteed to have a bit pattern of all zeros. 607 608 // FIXME: Handle variable sized types. 609 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr, 610 Builder.getInt8(0), 611 SizeVal, AlignVal, /*volatile*/ Builder.getFalse()); 612 } 613 614 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) { 615 // Make sure that there is a block for the indirect goto. 616 if (IndirectBranch == 0) 617 GetIndirectGotoBlock(); 618 619 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 620 621 // Make sure the indirect branch includes all of the address-taken blocks. 622 IndirectBranch->addDestination(BB); 623 return llvm::BlockAddress::get(CurFn, BB); 624 } 625 626 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 627 // If we already made the indirect branch for indirect goto, return its block. 628 if (IndirectBranch) return IndirectBranch->getParent(); 629 630 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 631 632 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 633 634 // Create the PHI node that indirect gotos will add entries to. 635 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest"); 636 637 // Create the indirect branch instruction. 638 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 639 return IndirectBranch->getParent(); 640 } 641 642 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 643 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 644 645 assert(SizeEntry && "Did not emit size for type"); 646 return SizeEntry; 647 } 648 649 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 650 assert(Ty->isVariablyModifiedType() && 651 "Must pass variably modified type to EmitVLASizes!"); 652 653 EnsureInsertPoint(); 654 655 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 656 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 657 658 if (!SizeEntry) { 659 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 660 661 // Get the element size; 662 QualType ElemTy = VAT->getElementType(); 663 llvm::Value *ElemSize; 664 if (ElemTy->isVariableArrayType()) 665 ElemSize = EmitVLASize(ElemTy); 666 else 667 ElemSize = llvm::ConstantInt::get(SizeTy, 668 getContext().getTypeSizeInChars(ElemTy).getQuantity()); 669 670 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 671 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 672 673 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 674 } 675 676 return SizeEntry; 677 } 678 679 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 680 EmitVLASize(AT->getElementType()); 681 return 0; 682 } 683 684 const PointerType *PT = Ty->getAs<PointerType>(); 685 assert(PT && "unknown VM type!"); 686 EmitVLASize(PT->getPointeeType()); 687 return 0; 688 } 689 690 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 691 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) 692 return EmitScalarExpr(E); 693 return EmitLValue(E).getAddress(); 694 } 695 696 /// Pops cleanup blocks until the given savepoint is reached. 697 void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) { 698 assert(Old.isValid()); 699 700 while (EHStack.stable_begin() != Old) { 701 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin()); 702 703 // As long as Old strictly encloses the scope's enclosing normal 704 // cleanup, we're going to emit another normal cleanup which 705 // fallthrough can propagate through. 706 bool FallThroughIsBranchThrough = 707 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup()); 708 709 PopCleanupBlock(FallThroughIsBranchThrough); 710 } 711 } 712 713 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF, 714 EHCleanupScope &Scope) { 715 assert(Scope.isNormalCleanup()); 716 llvm::BasicBlock *Entry = Scope.getNormalBlock(); 717 if (!Entry) { 718 Entry = CGF.createBasicBlock("cleanup"); 719 Scope.setNormalBlock(Entry); 720 } 721 return Entry; 722 } 723 724 static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF, 725 EHCleanupScope &Scope) { 726 assert(Scope.isEHCleanup()); 727 llvm::BasicBlock *Entry = Scope.getEHBlock(); 728 if (!Entry) { 729 Entry = CGF.createBasicBlock("eh.cleanup"); 730 Scope.setEHBlock(Entry); 731 } 732 return Entry; 733 } 734 735 /// Transitions the terminator of the given exit-block of a cleanup to 736 /// be a cleanup switch. 737 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF, 738 llvm::BasicBlock *Block) { 739 // If it's a branch, turn it into a switch whose default 740 // destination is its original target. 741 llvm::TerminatorInst *Term = Block->getTerminator(); 742 assert(Term && "can't transition block without terminator"); 743 744 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) { 745 assert(Br->isUnconditional()); 746 llvm::LoadInst *Load = 747 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term); 748 llvm::SwitchInst *Switch = 749 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block); 750 Br->eraseFromParent(); 751 return Switch; 752 } else { 753 return cast<llvm::SwitchInst>(Term); 754 } 755 } 756 757 /// Attempts to reduce a cleanup's entry block to a fallthrough. This 758 /// is basically llvm::MergeBlockIntoPredecessor, except 759 /// simplified/optimized for the tighter constraints on cleanup blocks. 760 /// 761 /// Returns the new block, whatever it is. 762 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF, 763 llvm::BasicBlock *Entry) { 764 llvm::BasicBlock *Pred = Entry->getSinglePredecessor(); 765 if (!Pred) return Entry; 766 767 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator()); 768 if (!Br || Br->isConditional()) return Entry; 769 assert(Br->getSuccessor(0) == Entry); 770 771 // If we were previously inserting at the end of the cleanup entry 772 // block, we'll need to continue inserting at the end of the 773 // predecessor. 774 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry; 775 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end()); 776 777 // Kill the branch. 778 Br->eraseFromParent(); 779 780 // Merge the blocks. 781 Pred->getInstList().splice(Pred->end(), Entry->getInstList()); 782 783 // Kill the entry block. 784 Entry->eraseFromParent(); 785 786 if (WasInsertBlock) 787 CGF.Builder.SetInsertPoint(Pred); 788 789 return Pred; 790 } 791 792 static void EmitCleanup(CodeGenFunction &CGF, 793 EHScopeStack::Cleanup *Fn, 794 bool ForEH) { 795 if (ForEH) CGF.EHStack.pushTerminate(); 796 Fn->Emit(CGF, ForEH); 797 if (ForEH) CGF.EHStack.popTerminate(); 798 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?"); 799 } 800 801 /// Pops a cleanup block. If the block includes a normal cleanup, the 802 /// current insertion point is threaded through the cleanup, as are 803 /// any branch fixups on the cleanup. 804 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { 805 assert(!EHStack.empty() && "cleanup stack is empty!"); 806 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!"); 807 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin()); 808 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups()); 809 assert(Scope.isActive() && "cleanup was still inactive when popped!"); 810 811 // Check whether we need an EH cleanup. This is only true if we've 812 // generated a lazy EH cleanup block. 813 bool RequiresEHCleanup = Scope.hasEHBranches(); 814 815 // Check the three conditions which might require a normal cleanup: 816 817 // - whether there are branch fix-ups through this cleanup 818 unsigned FixupDepth = Scope.getFixupDepth(); 819 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth; 820 821 // - whether there are branch-throughs or branch-afters 822 bool HasExistingBranches = Scope.hasBranches(); 823 824 // - whether there's a fallthrough 825 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock(); 826 bool HasFallthrough = (FallthroughSource != 0); 827 828 bool RequiresNormalCleanup = false; 829 if (Scope.isNormalCleanup() && 830 (HasFixups || HasExistingBranches || HasFallthrough)) { 831 RequiresNormalCleanup = true; 832 } 833 834 // If we don't need the cleanup at all, we're done. 835 if (!RequiresNormalCleanup && !RequiresEHCleanup) { 836 EHStack.popCleanup(); // safe because there are no fixups 837 assert(EHStack.getNumBranchFixups() == 0 || 838 EHStack.hasNormalCleanups()); 839 return; 840 } 841 842 // Copy the cleanup emission data out. Note that SmallVector 843 // guarantees maximal alignment for its buffer regardless of its 844 // type parameter. 845 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer; 846 CleanupBuffer.reserve(Scope.getCleanupSize()); 847 memcpy(CleanupBuffer.data(), 848 Scope.getCleanupBuffer(), Scope.getCleanupSize()); 849 CleanupBuffer.set_size(Scope.getCleanupSize()); 850 EHScopeStack::Cleanup *Fn = 851 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data()); 852 853 // We want to emit the EH cleanup after the normal cleanup, but go 854 // ahead and do the setup for the EH cleanup while the scope is still 855 // alive. 856 llvm::BasicBlock *EHEntry = 0; 857 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend; 858 if (RequiresEHCleanup) { 859 EHEntry = CreateEHEntry(*this, Scope); 860 861 // Figure out the branch-through dest if necessary. 862 llvm::BasicBlock *EHBranchThroughDest = 0; 863 if (Scope.hasEHBranchThroughs()) { 864 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end()); 865 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup()); 866 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S)); 867 } 868 869 // If we have exactly one branch-after and no branch-throughs, we 870 // can dispatch it without a switch. 871 if (!Scope.hasEHBranchThroughs() && 872 Scope.getNumEHBranchAfters() == 1) { 873 assert(!EHBranchThroughDest); 874 875 // TODO: remove the spurious eh.cleanup.dest stores if this edge 876 // never went through any switches. 877 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0); 878 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest)); 879 880 // Otherwise, if we have any branch-afters, we need a switch. 881 } else if (Scope.getNumEHBranchAfters()) { 882 // The default of the switch belongs to the branch-throughs if 883 // they exist. 884 llvm::BasicBlock *Default = 885 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock()); 886 887 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters(); 888 889 llvm::LoadInst *Load = 890 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest"); 891 llvm::SwitchInst *Switch = 892 llvm::SwitchInst::Create(Load, Default, SwitchCapacity); 893 894 EHInstsToAppend.push_back(Load); 895 EHInstsToAppend.push_back(Switch); 896 897 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I) 898 Switch->addCase(Scope.getEHBranchAfterIndex(I), 899 Scope.getEHBranchAfterBlock(I)); 900 901 // Otherwise, we have only branch-throughs; jump to the next EH 902 // cleanup. 903 } else { 904 assert(EHBranchThroughDest); 905 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest)); 906 } 907 } 908 909 if (!RequiresNormalCleanup) { 910 EHStack.popCleanup(); 911 } else { 912 // As a kindof crazy internal case, branch-through fall-throughs 913 // leave the insertion point set to the end of the last cleanup. 914 bool HasPrebranchedFallthrough = 915 (HasFallthrough && FallthroughSource->getTerminator()); 916 assert(!HasPrebranchedFallthrough || 917 FallthroughSource->getTerminator()->getSuccessor(0) 918 == Scope.getNormalBlock()); 919 920 // If we have a fallthrough and no other need for the cleanup, 921 // emit it directly. 922 if (HasFallthrough && !HasPrebranchedFallthrough && 923 !HasFixups && !HasExistingBranches) { 924 925 // Fixups can cause us to optimistically create a normal block, 926 // only to later have no real uses for it. Just delete it in 927 // this case. 928 // TODO: we can potentially simplify all the uses after this. 929 if (Scope.getNormalBlock()) { 930 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock()); 931 delete Scope.getNormalBlock(); 932 } 933 934 EHStack.popCleanup(); 935 936 EmitCleanup(*this, Fn, /*ForEH*/ false); 937 938 // Otherwise, the best approach is to thread everything through 939 // the cleanup block and then try to clean up after ourselves. 940 } else { 941 // Force the entry block to exist. 942 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope); 943 944 // If there's a fallthrough, we need to store the cleanup 945 // destination index. For fall-throughs this is always zero. 946 if (HasFallthrough && !HasPrebranchedFallthrough) 947 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot()); 948 949 // Emit the entry block. This implicitly branches to it if we 950 // have fallthrough. All the fixups and existing branches should 951 // already be branched to it. 952 EmitBlock(NormalEntry); 953 954 bool HasEnclosingCleanups = 955 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end()); 956 957 // Compute the branch-through dest if we need it: 958 // - if there are branch-throughs threaded through the scope 959 // - if fall-through is a branch-through 960 // - if there are fixups that will be optimistically forwarded 961 // to the enclosing cleanup 962 llvm::BasicBlock *BranchThroughDest = 0; 963 if (Scope.hasBranchThroughs() || 964 (HasFallthrough && FallthroughIsBranchThrough) || 965 (HasFixups && HasEnclosingCleanups)) { 966 assert(HasEnclosingCleanups); 967 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup()); 968 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S)); 969 } 970 971 llvm::BasicBlock *FallthroughDest = 0; 972 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend; 973 974 // If there's exactly one branch-after and no other threads, 975 // we can route it without a switch. 976 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough && 977 Scope.getNumBranchAfters() == 1) { 978 assert(!BranchThroughDest); 979 980 // TODO: clean up the possibly dead stores to the cleanup dest slot. 981 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0); 982 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter)); 983 984 // Build a switch-out if we need it: 985 // - if there are branch-afters threaded through the scope 986 // - if fall-through is a branch-after 987 // - if there are fixups that have nowhere left to go and 988 // so must be immediately resolved 989 } else if (Scope.getNumBranchAfters() || 990 (HasFallthrough && !FallthroughIsBranchThrough) || 991 (HasFixups && !HasEnclosingCleanups)) { 992 993 llvm::BasicBlock *Default = 994 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock()); 995 996 // TODO: base this on the number of branch-afters and fixups 997 const unsigned SwitchCapacity = 10; 998 999 llvm::LoadInst *Load = 1000 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest"); 1001 llvm::SwitchInst *Switch = 1002 llvm::SwitchInst::Create(Load, Default, SwitchCapacity); 1003 1004 InstsToAppend.push_back(Load); 1005 InstsToAppend.push_back(Switch); 1006 1007 // Branch-after fallthrough. 1008 if (HasFallthrough && !FallthroughIsBranchThrough) { 1009 FallthroughDest = createBasicBlock("cleanup.cont"); 1010 Switch->addCase(Builder.getInt32(0), FallthroughDest); 1011 } 1012 1013 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) { 1014 Switch->addCase(Scope.getBranchAfterIndex(I), 1015 Scope.getBranchAfterBlock(I)); 1016 } 1017 1018 if (HasFixups && !HasEnclosingCleanups) 1019 ResolveAllBranchFixups(Switch); 1020 } else { 1021 // We should always have a branch-through destination in this case. 1022 assert(BranchThroughDest); 1023 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest)); 1024 } 1025 1026 // We're finally ready to pop the cleanup. 1027 EHStack.popCleanup(); 1028 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups); 1029 1030 EmitCleanup(*this, Fn, /*ForEH*/ false); 1031 1032 // Append the prepared cleanup prologue from above. 1033 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock(); 1034 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I) 1035 NormalExit->getInstList().push_back(InstsToAppend[I]); 1036 1037 // Optimistically hope that any fixups will continue falling through. 1038 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups(); 1039 I < E; ++I) { 1040 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I); 1041 if (!Fixup.Destination) continue; 1042 if (!Fixup.OptimisticBranchBlock) { 1043 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex), 1044 getNormalCleanupDestSlot(), 1045 Fixup.InitialBranch); 1046 Fixup.InitialBranch->setSuccessor(0, NormalEntry); 1047 } 1048 Fixup.OptimisticBranchBlock = NormalExit; 1049 } 1050 1051 if (FallthroughDest) 1052 EmitBlock(FallthroughDest); 1053 else if (!HasFallthrough) 1054 Builder.ClearInsertionPoint(); 1055 1056 // Check whether we can merge NormalEntry into a single predecessor. 1057 // This might invalidate (non-IR) pointers to NormalEntry. 1058 llvm::BasicBlock *NewNormalEntry = 1059 SimplifyCleanupEntry(*this, NormalEntry); 1060 1061 // If it did invalidate those pointers, and NormalEntry was the same 1062 // as NormalExit, go back and patch up the fixups. 1063 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit) 1064 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups(); 1065 I < E; ++I) 1066 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry; 1067 } 1068 } 1069 1070 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0); 1071 1072 // Emit the EH cleanup if required. 1073 if (RequiresEHCleanup) { 1074 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1075 1076 EmitBlock(EHEntry); 1077 EmitCleanup(*this, Fn, /*ForEH*/ true); 1078 1079 // Append the prepared cleanup prologue from above. 1080 llvm::BasicBlock *EHExit = Builder.GetInsertBlock(); 1081 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I) 1082 EHExit->getInstList().push_back(EHInstsToAppend[I]); 1083 1084 Builder.restoreIP(SavedIP); 1085 1086 SimplifyCleanupEntry(*this, EHEntry); 1087 } 1088 } 1089 1090 /// Terminate the current block by emitting a branch which might leave 1091 /// the current cleanup-protected scope. The target scope may not yet 1092 /// be known, in which case this will require a fixup. 1093 /// 1094 /// As a side-effect, this method clears the insertion point. 1095 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) { 1096 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup()) 1097 && "stale jump destination"); 1098 1099 if (!HaveInsertPoint()) 1100 return; 1101 1102 // Create the branch. 1103 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock()); 1104 1105 // Calculate the innermost active normal cleanup. 1106 EHScopeStack::stable_iterator 1107 TopCleanup = EHStack.getInnermostActiveNormalCleanup(); 1108 1109 // If we're not in an active normal cleanup scope, or if the 1110 // destination scope is within the innermost active normal cleanup 1111 // scope, we don't need to worry about fixups. 1112 if (TopCleanup == EHStack.stable_end() || 1113 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid 1114 Builder.ClearInsertionPoint(); 1115 return; 1116 } 1117 1118 // If we can't resolve the destination cleanup scope, just add this 1119 // to the current cleanup scope as a branch fixup. 1120 if (!Dest.getScopeDepth().isValid()) { 1121 BranchFixup &Fixup = EHStack.addBranchFixup(); 1122 Fixup.Destination = Dest.getBlock(); 1123 Fixup.DestinationIndex = Dest.getDestIndex(); 1124 Fixup.InitialBranch = BI; 1125 Fixup.OptimisticBranchBlock = 0; 1126 1127 Builder.ClearInsertionPoint(); 1128 return; 1129 } 1130 1131 // Otherwise, thread through all the normal cleanups in scope. 1132 1133 // Store the index at the start. 1134 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex()); 1135 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI); 1136 1137 // Adjust BI to point to the first cleanup block. 1138 { 1139 EHCleanupScope &Scope = 1140 cast<EHCleanupScope>(*EHStack.find(TopCleanup)); 1141 BI->setSuccessor(0, CreateNormalEntry(*this, Scope)); 1142 } 1143 1144 // Add this destination to all the scopes involved. 1145 EHScopeStack::stable_iterator I = TopCleanup; 1146 EHScopeStack::stable_iterator E = Dest.getScopeDepth(); 1147 if (E.strictlyEncloses(I)) { 1148 while (true) { 1149 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I)); 1150 assert(Scope.isNormalCleanup()); 1151 I = Scope.getEnclosingNormalCleanup(); 1152 1153 // If this is the last cleanup we're propagating through, tell it 1154 // that there's a resolved jump moving through it. 1155 if (!E.strictlyEncloses(I)) { 1156 Scope.addBranchAfter(Index, Dest.getBlock()); 1157 break; 1158 } 1159 1160 // Otherwise, tell the scope that there's a jump propoagating 1161 // through it. If this isn't new information, all the rest of 1162 // the work has been done before. 1163 if (!Scope.addBranchThrough(Dest.getBlock())) 1164 break; 1165 } 1166 } 1167 1168 Builder.ClearInsertionPoint(); 1169 } 1170 1171 void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) { 1172 // We should never get invalid scope depths for an UnwindDest; that 1173 // implies that the destination wasn't set up correctly. 1174 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?"); 1175 1176 if (!HaveInsertPoint()) 1177 return; 1178 1179 // Create the branch. 1180 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock()); 1181 1182 // Calculate the innermost active cleanup. 1183 EHScopeStack::stable_iterator 1184 InnermostCleanup = EHStack.getInnermostActiveEHCleanup(); 1185 1186 // If the destination is in the same EH cleanup scope as us, we 1187 // don't need to thread through anything. 1188 if (InnermostCleanup.encloses(Dest.getScopeDepth())) { 1189 Builder.ClearInsertionPoint(); 1190 return; 1191 } 1192 assert(InnermostCleanup != EHStack.stable_end()); 1193 1194 // Store the index at the start. 1195 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex()); 1196 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI); 1197 1198 // Adjust BI to point to the first cleanup block. 1199 { 1200 EHCleanupScope &Scope = 1201 cast<EHCleanupScope>(*EHStack.find(InnermostCleanup)); 1202 BI->setSuccessor(0, CreateEHEntry(*this, Scope)); 1203 } 1204 1205 // Add this destination to all the scopes involved. 1206 for (EHScopeStack::stable_iterator 1207 I = InnermostCleanup, E = Dest.getScopeDepth(); ; ) { 1208 assert(E.strictlyEncloses(I)); 1209 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I)); 1210 assert(Scope.isEHCleanup()); 1211 I = Scope.getEnclosingEHCleanup(); 1212 1213 // If this is the last cleanup we're propagating through, add this 1214 // as a branch-after. 1215 if (I == E) { 1216 Scope.addEHBranchAfter(Index, Dest.getBlock()); 1217 break; 1218 } 1219 1220 // Otherwise, add it as a branch-through. If this isn't new 1221 // information, all the rest of the work has been done before. 1222 if (!Scope.addEHBranchThrough(Dest.getBlock())) 1223 break; 1224 } 1225 1226 Builder.ClearInsertionPoint(); 1227 } 1228 1229 /// All the branch fixups on the EH stack have propagated out past the 1230 /// outermost normal cleanup; resolve them all by adding cases to the 1231 /// given switch instruction. 1232 void CodeGenFunction::ResolveAllBranchFixups(llvm::SwitchInst *Switch) { 1233 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded; 1234 1235 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) { 1236 // Skip this fixup if its destination isn't set or if we've 1237 // already treated it. 1238 BranchFixup &Fixup = EHStack.getBranchFixup(I); 1239 if (Fixup.Destination == 0) continue; 1240 if (!CasesAdded.insert(Fixup.Destination)) continue; 1241 1242 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), 1243 Fixup.Destination); 1244 } 1245 1246 EHStack.clearFixups(); 1247 } 1248 1249 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) { 1250 assert(Block && "resolving a null target block"); 1251 if (!EHStack.getNumBranchFixups()) return; 1252 1253 assert(EHStack.hasNormalCleanups() && 1254 "branch fixups exist with no normal cleanups on stack"); 1255 1256 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks; 1257 bool ResolvedAny = false; 1258 1259 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) { 1260 // Skip this fixup if its destination doesn't match. 1261 BranchFixup &Fixup = EHStack.getBranchFixup(I); 1262 if (Fixup.Destination != Block) continue; 1263 1264 Fixup.Destination = 0; 1265 ResolvedAny = true; 1266 1267 // If it doesn't have an optimistic branch block, LatestBranch is 1268 // already pointing to the right place. 1269 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock; 1270 if (!BranchBB) 1271 continue; 1272 1273 // Don't process the same optimistic branch block twice. 1274 if (!ModifiedOptimisticBlocks.insert(BranchBB)) 1275 continue; 1276 1277 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB); 1278 1279 // Add a case to the switch. 1280 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block); 1281 } 1282 1283 if (ResolvedAny) 1284 EHStack.popNullFixups(); 1285 } 1286 1287 /// Activate a cleanup that was created in an inactivated state. 1288 void CodeGenFunction::ActivateCleanup(EHScopeStack::stable_iterator C) { 1289 assert(C != EHStack.stable_end() && "activating bottom of stack?"); 1290 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C)); 1291 assert(!Scope.isActive() && "double activation"); 1292 1293 // Calculate whether the cleanup was used: 1294 bool Used = false; 1295 1296 // - as a normal cleanup 1297 if (Scope.isNormalCleanup()) { 1298 bool NormalUsed = false; 1299 if (Scope.getNormalBlock()) { 1300 NormalUsed = true; 1301 } else { 1302 // Check whether any enclosed cleanups were needed. 1303 for (EHScopeStack::stable_iterator 1304 I = EHStack.getInnermostNormalCleanup(); I != C; ) { 1305 assert(C.strictlyEncloses(I)); 1306 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I)); 1307 if (S.getNormalBlock()) { 1308 NormalUsed = true; 1309 break; 1310 } 1311 I = S.getEnclosingNormalCleanup(); 1312 } 1313 } 1314 1315 if (NormalUsed) 1316 Used = true; 1317 else 1318 Scope.setActivatedBeforeNormalUse(true); 1319 } 1320 1321 // - as an EH cleanup 1322 if (Scope.isEHCleanup()) { 1323 bool EHUsed = false; 1324 if (Scope.getEHBlock()) { 1325 EHUsed = true; 1326 } else { 1327 // Check whether any enclosed cleanups were needed. 1328 for (EHScopeStack::stable_iterator 1329 I = EHStack.getInnermostEHCleanup(); I != C; ) { 1330 assert(C.strictlyEncloses(I)); 1331 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I)); 1332 if (S.getEHBlock()) { 1333 EHUsed = true; 1334 break; 1335 } 1336 I = S.getEnclosingEHCleanup(); 1337 } 1338 } 1339 1340 if (EHUsed) 1341 Used = true; 1342 else 1343 Scope.setActivatedBeforeEHUse(true); 1344 } 1345 1346 llvm::AllocaInst *Var = EHCleanupScope::activeSentinel(); 1347 if (Used) { 1348 Var = CreateTempAlloca(Builder.getInt1Ty()); 1349 InitTempAlloca(Var, Builder.getFalse()); 1350 } 1351 Scope.setActiveVar(Var); 1352 } 1353 1354 llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() { 1355 if (!NormalCleanupDest) 1356 NormalCleanupDest = 1357 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot"); 1358 return NormalCleanupDest; 1359 } 1360 1361 llvm::Value *CodeGenFunction::getEHCleanupDestSlot() { 1362 if (!EHCleanupDest) 1363 EHCleanupDest = 1364 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot"); 1365 return EHCleanupDest; 1366 } 1367 1368 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1369 llvm::ConstantInt *Init) { 1370 assert (Init && "Invalid DeclRefExpr initializer!"); 1371 if (CGDebugInfo *Dbg = getDebugInfo()) 1372 Dbg->EmitGlobalVariable(E->getDecl(), Init, Builder); 1373 } 1374