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