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