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 "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGException.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/AST/APValue.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/Frontend/CodeGenOptions.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Intrinsics.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 32 : CGM(cgm), Target(CGM.getContext().Target), 33 Builder(cgm.getModule().getContext()), 34 BlockInfo(0), BlockPointer(0), 35 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1), 36 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0), 37 SwitchInsn(0), CaseRangeBlock(0), 38 DidCallStackSave(false), UnreachableBlock(0), 39 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0), 40 OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0), 41 TrapBB(0) { 42 43 // Get some frequently used types. 44 LLVMPointerWidth = Target.getPointerWidth(0); 45 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext(); 46 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth); 47 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 48 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 49 Int8PtrTy = cgm.Int8PtrTy; 50 51 Exceptions = getContext().getLangOptions().Exceptions; 52 CatchUndefined = getContext().getLangOptions().CatchUndefined; 53 CGM.getCXXABI().getMangleContext().startNewFunction(); 54 } 55 56 ASTContext &CodeGenFunction::getContext() const { 57 return CGM.getContext(); 58 } 59 60 61 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 62 return CGM.getTypes().ConvertTypeForMem(T); 63 } 64 65 const llvm::Type *CodeGenFunction::ConvertType(QualType T) { 66 return CGM.getTypes().ConvertType(T); 67 } 68 69 bool CodeGenFunction::hasAggregateLLVMType(QualType T) { 70 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 71 T->isObjCObjectType(); 72 } 73 74 void CodeGenFunction::EmitReturnBlock() { 75 // For cleanliness, we try to avoid emitting the return block for 76 // simple cases. 77 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 78 79 if (CurBB) { 80 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 81 82 // We have a valid insert point, reuse it if it is empty or there are no 83 // explicit jumps to the return block. 84 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 85 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 86 delete ReturnBlock.getBlock(); 87 } else 88 EmitBlock(ReturnBlock.getBlock()); 89 return; 90 } 91 92 // Otherwise, if the return block is the target of a single direct 93 // branch then we can just put the code in that block instead. This 94 // cleans up functions which started with a unified return block. 95 if (ReturnBlock.getBlock()->hasOneUse()) { 96 llvm::BranchInst *BI = 97 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin()); 98 if (BI && BI->isUnconditional() && 99 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 100 // Reset insertion point and delete the branch. 101 Builder.SetInsertPoint(BI->getParent()); 102 BI->eraseFromParent(); 103 delete ReturnBlock.getBlock(); 104 return; 105 } 106 } 107 108 // FIXME: We are at an unreachable point, there is no reason to emit the block 109 // unless it has uses. However, we still need a place to put the debug 110 // region.end for now. 111 112 EmitBlock(ReturnBlock.getBlock()); 113 } 114 115 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 116 if (!BB) return; 117 if (!BB->use_empty()) 118 return CGF.CurFn->getBasicBlockList().push_back(BB); 119 delete BB; 120 } 121 122 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 123 assert(BreakContinueStack.empty() && 124 "mismatched push/pop in break/continue stack!"); 125 126 // Emit function epilog (to return). 127 EmitReturnBlock(); 128 129 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 130 131 // Emit debug descriptor for function end. 132 if (CGDebugInfo *DI = getDebugInfo()) { 133 DI->setLocation(EndLoc); 134 DI->EmitFunctionEnd(Builder); 135 } 136 137 EmitFunctionEpilog(*CurFnInfo); 138 EmitEndEHSpec(CurCodeDecl); 139 140 assert(EHStack.empty() && 141 "did not remove all scopes from cleanup stack!"); 142 143 // If someone did an indirect goto, emit the indirect goto block at the end of 144 // the function. 145 if (IndirectBranch) { 146 EmitBlock(IndirectBranch->getParent()); 147 Builder.ClearInsertionPoint(); 148 } 149 150 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 151 llvm::Instruction *Ptr = AllocaInsertPt; 152 AllocaInsertPt = 0; 153 Ptr->eraseFromParent(); 154 155 // If someone took the address of a label but never did an indirect goto, we 156 // made a zero entry PHI node, which is illegal, zap it now. 157 if (IndirectBranch) { 158 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 159 if (PN->getNumIncomingValues() == 0) { 160 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 161 PN->eraseFromParent(); 162 } 163 } 164 165 EmitIfUsed(*this, RethrowBlock.getBlock()); 166 EmitIfUsed(*this, TerminateLandingPad); 167 EmitIfUsed(*this, TerminateHandler); 168 EmitIfUsed(*this, UnreachableBlock); 169 170 if (CGM.getCodeGenOpts().EmitDeclMetadata) 171 EmitDeclMetadata(); 172 } 173 174 /// ShouldInstrumentFunction - Return true if the current function should be 175 /// instrumented with __cyg_profile_func_* calls 176 bool CodeGenFunction::ShouldInstrumentFunction() { 177 if (!CGM.getCodeGenOpts().InstrumentFunctions) 178 return false; 179 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 180 return false; 181 return true; 182 } 183 184 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 185 /// instrumentation function with the current function and the call site, if 186 /// function instrumentation is enabled. 187 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 188 if (!ShouldInstrumentFunction()) 189 return; 190 191 const llvm::PointerType *PointerTy; 192 const llvm::FunctionType *FunctionTy; 193 std::vector<const llvm::Type*> ProfileFuncArgs; 194 195 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 196 PointerTy = Int8PtrTy; 197 ProfileFuncArgs.push_back(PointerTy); 198 ProfileFuncArgs.push_back(PointerTy); 199 FunctionTy = llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), 200 ProfileFuncArgs, false); 201 202 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 203 llvm::CallInst *CallSite = Builder.CreateCall( 204 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0), 205 llvm::ConstantInt::get(Int32Ty, 0), 206 "callsite"); 207 208 Builder.CreateCall2(F, 209 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 210 CallSite); 211 } 212 213 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 214 llvm::Function *Fn, 215 const FunctionArgList &Args, 216 SourceLocation StartLoc) { 217 const Decl *D = GD.getDecl(); 218 219 DidCallStackSave = false; 220 CurCodeDecl = CurFuncDecl = D; 221 FnRetTy = RetTy; 222 CurFn = Fn; 223 assert(CurFn->isDeclaration() && "Function already has body?"); 224 225 // Pass inline keyword to optimizer if it appears explicitly on any 226 // declaration. 227 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 228 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(), 229 RE = FD->redecls_end(); RI != RE; ++RI) 230 if (RI->isInlineSpecified()) { 231 Fn->addFnAttr(llvm::Attribute::InlineHint); 232 break; 233 } 234 235 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 236 237 // Create a marker to make it easy to insert allocas into the entryblock 238 // later. Don't create this with the builder, because we don't want it 239 // folded. 240 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 241 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 242 if (Builder.isNamePreserving()) 243 AllocaInsertPt->setName("allocapt"); 244 245 ReturnBlock = getJumpDestInCurrentScope("return"); 246 247 Builder.SetInsertPoint(EntryBB); 248 249 // Emit subprogram debug descriptor. 250 if (CGDebugInfo *DI = getDebugInfo()) { 251 // FIXME: what is going on here and why does it ignore all these 252 // interesting type properties? 253 QualType FnType = 254 getContext().getFunctionType(RetTy, 0, 0, 255 FunctionProtoType::ExtProtoInfo()); 256 257 DI->setLocation(StartLoc); 258 DI->EmitFunctionStart(GD, FnType, CurFn, Builder); 259 } 260 261 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 262 263 // FIXME: Leaked. 264 // CC info is ignored, hopefully? 265 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args, 266 FunctionType::ExtInfo()); 267 268 if (RetTy->isVoidType()) { 269 // Void type; nothing to return. 270 ReturnValue = 0; 271 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 272 hasAggregateLLVMType(CurFnInfo->getReturnType())) { 273 // Indirect aggregate return; emit returned value directly into sret slot. 274 // This reduces code size, and affects correctness in C++. 275 ReturnValue = CurFn->arg_begin(); 276 } else { 277 ReturnValue = CreateIRTemp(RetTy, "retval"); 278 } 279 280 EmitStartEHSpec(CurCodeDecl); 281 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 282 283 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) 284 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 285 286 // If any of the arguments have a variably modified type, make sure to 287 // emit the type size. 288 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 289 i != e; ++i) { 290 QualType Ty = i->second; 291 292 if (Ty->isVariablyModifiedType()) 293 EmitVLASize(Ty); 294 } 295 } 296 297 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) { 298 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl()); 299 assert(FD->getBody()); 300 EmitStmt(FD->getBody()); 301 } 302 303 /// Tries to mark the given function nounwind based on the 304 /// non-existence of any throwing calls within it. We believe this is 305 /// lightweight enough to do at -O0. 306 static void TryMarkNoThrow(llvm::Function *F) { 307 // LLVM treats 'nounwind' on a function as part of the type, so we 308 // can't do this on functions that can be overwritten. 309 if (F->mayBeOverridden()) return; 310 311 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) 312 for (llvm::BasicBlock::iterator 313 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) 314 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) 315 if (!Call->doesNotThrow()) 316 return; 317 F->setDoesNotThrow(true); 318 } 319 320 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) { 321 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 322 323 // Check if we should generate debug info for this function. 324 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 325 DebugInfo = CGM.getDebugInfo(); 326 327 FunctionArgList Args; 328 QualType ResTy = FD->getResultType(); 329 330 CurGD = GD; 331 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance()) 332 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args); 333 334 if (FD->getNumParams()) { 335 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 336 assert(FProto && "Function def must have prototype!"); 337 338 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 339 Args.push_back(std::make_pair(FD->getParamDecl(i), 340 FProto->getArgType(i))); 341 } 342 343 SourceRange BodyRange; 344 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 345 346 // Emit the standard function prologue. 347 StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin()); 348 349 // Generate the body of the function. 350 if (isa<CXXDestructorDecl>(FD)) 351 EmitDestructorBody(Args); 352 else if (isa<CXXConstructorDecl>(FD)) 353 EmitConstructorBody(Args); 354 else 355 EmitFunctionBody(Args); 356 357 // Emit the standard function epilogue. 358 FinishFunction(BodyRange.getEnd()); 359 360 // If we haven't marked the function nothrow through other means, do 361 // a quick pass now to see if we can. 362 if (!CurFn->doesNotThrow()) 363 TryMarkNoThrow(CurFn); 364 } 365 366 /// ContainsLabel - Return true if the statement contains a label in it. If 367 /// this statement is not executed normally, it not containing a label means 368 /// that we can just remove the code. 369 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 370 // Null statement, not a label! 371 if (S == 0) return false; 372 373 // If this is a label, we have to emit the code, consider something like: 374 // if (0) { ... foo: bar(); } goto foo; 375 if (isa<LabelStmt>(S)) 376 return true; 377 378 // If this is a case/default statement, and we haven't seen a switch, we have 379 // to emit the code. 380 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 381 return true; 382 383 // If this is a switch statement, we want to ignore cases below it. 384 if (isa<SwitchStmt>(S)) 385 IgnoreCaseStmts = true; 386 387 // Scan subexpressions for verboten labels. 388 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 389 I != E; ++I) 390 if (ContainsLabel(*I, IgnoreCaseStmts)) 391 return true; 392 393 return false; 394 } 395 396 397 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 398 /// a constant, or if it does but contains a label, return 0. If it constant 399 /// folds to 'true' and does not contain a label, return 1, if it constant folds 400 /// to 'false' and does not contain a label, return -1. 401 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 402 // FIXME: Rename and handle conversion of other evaluatable things 403 // to bool. 404 Expr::EvalResult Result; 405 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 406 Result.HasSideEffects) 407 return 0; // Not foldable, not integer or not fully evaluatable. 408 409 if (CodeGenFunction::ContainsLabel(Cond)) 410 return 0; // Contains a label. 411 412 return Result.Val.getInt().getBoolValue() ? 1 : -1; 413 } 414 415 416 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 417 /// statement) to the specified blocks. Based on the condition, this might try 418 /// to simplify the codegen of the conditional based on the branch. 419 /// 420 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 421 llvm::BasicBlock *TrueBlock, 422 llvm::BasicBlock *FalseBlock) { 423 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 424 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 425 426 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 427 // Handle X && Y in a condition. 428 if (CondBOp->getOpcode() == BO_LAnd) { 429 // If we have "1 && X", simplify the code. "0 && X" would have constant 430 // folded if the case was simple enough. 431 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 432 // br(1 && X) -> br(X). 433 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 434 } 435 436 // If we have "X && 1", simplify the code to use an uncond branch. 437 // "X && 0" would have been constant folded to 0. 438 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 439 // br(X && 1) -> br(X). 440 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 441 } 442 443 // Emit the LHS as a conditional. If the LHS conditional is false, we 444 // want to jump to the FalseBlock. 445 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 446 447 ConditionalEvaluation eval(*this); 448 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 449 EmitBlock(LHSTrue); 450 451 // Any temporaries created here are conditional. 452 eval.begin(*this); 453 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 454 eval.end(*this); 455 456 return; 457 } else if (CondBOp->getOpcode() == BO_LOr) { 458 // If we have "0 || X", simplify the code. "1 || X" would have constant 459 // folded if the case was simple enough. 460 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 461 // br(0 || X) -> br(X). 462 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 463 } 464 465 // If we have "X || 0", simplify the code to use an uncond branch. 466 // "X || 1" would have been constant folded to 1. 467 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 468 // br(X || 0) -> br(X). 469 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 470 } 471 472 // Emit the LHS as a conditional. If the LHS conditional is true, we 473 // want to jump to the TrueBlock. 474 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 475 476 ConditionalEvaluation eval(*this); 477 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 478 EmitBlock(LHSFalse); 479 480 // Any temporaries created here are conditional. 481 eval.begin(*this); 482 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 483 eval.end(*this); 484 485 return; 486 } 487 } 488 489 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 490 // br(!x, t, f) -> br(x, f, t) 491 if (CondUOp->getOpcode() == UO_LNot) 492 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 493 } 494 495 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 496 // Handle ?: operator. 497 498 // Just ignore GNU ?: extension. 499 if (CondOp->getLHS()) { 500 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 501 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 502 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 503 504 ConditionalEvaluation cond(*this); 505 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 506 507 cond.begin(*this); 508 EmitBlock(LHSBlock); 509 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 510 cond.end(*this); 511 512 cond.begin(*this); 513 EmitBlock(RHSBlock); 514 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 515 cond.end(*this); 516 517 return; 518 } 519 } 520 521 // Emit the code with the fully general case. 522 llvm::Value *CondV = EvaluateExprAsBool(Cond); 523 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 524 } 525 526 /// ErrorUnsupported - Print out an error that codegen doesn't support the 527 /// specified stmt yet. 528 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 529 bool OmitOnError) { 530 CGM.ErrorUnsupported(S, Type, OmitOnError); 531 } 532 533 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 534 /// variable-length array whose elements have a non-zero bit-pattern. 535 /// 536 /// \param src - a char* pointing to the bit-pattern for a single 537 /// base element of the array 538 /// \param sizeInChars - the total size of the VLA, in chars 539 /// \param align - the total alignment of the VLA 540 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 541 llvm::Value *dest, llvm::Value *src, 542 llvm::Value *sizeInChars) { 543 std::pair<CharUnits,CharUnits> baseSizeAndAlign 544 = CGF.getContext().getTypeInfoInChars(baseType); 545 546 CGBuilderTy &Builder = CGF.Builder; 547 548 llvm::Value *baseSizeInChars 549 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity()); 550 551 const llvm::Type *i8p = Builder.getInt8PtrTy(); 552 553 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin"); 554 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end"); 555 556 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 557 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 558 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 559 560 // Make a loop over the VLA. C99 guarantees that the VLA element 561 // count must be nonzero. 562 CGF.EmitBlock(loopBB); 563 564 llvm::PHINode *cur = Builder.CreatePHI(i8p, "vla.cur"); 565 cur->reserveOperandSpace(2); 566 cur->addIncoming(begin, originBB); 567 568 // memcpy the individual element bit-pattern. 569 Builder.CreateMemCpy(cur, src, baseSizeInChars, 570 baseSizeAndAlign.second.getQuantity(), 571 /*volatile*/ false); 572 573 // Go to the next element. 574 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next"); 575 576 // Leave if that's the end of the VLA. 577 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 578 Builder.CreateCondBr(done, contBB, loopBB); 579 cur->addIncoming(next, loopBB); 580 581 CGF.EmitBlock(contBB); 582 } 583 584 void 585 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 586 // Ignore empty classes in C++. 587 if (getContext().getLangOptions().CPlusPlus) { 588 if (const RecordType *RT = Ty->getAs<RecordType>()) { 589 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 590 return; 591 } 592 } 593 594 // Cast the dest ptr to the appropriate i8 pointer type. 595 unsigned DestAS = 596 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 597 const llvm::Type *BP = Builder.getInt8PtrTy(DestAS); 598 if (DestPtr->getType() != BP) 599 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 600 601 // Get size and alignment info for this aggregate. 602 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 603 uint64_t Size = TypeInfo.first / 8; 604 unsigned Align = TypeInfo.second / 8; 605 606 llvm::Value *SizeVal; 607 const VariableArrayType *vla; 608 609 // Don't bother emitting a zero-byte memset. 610 if (Size == 0) { 611 // But note that getTypeInfo returns 0 for a VLA. 612 if (const VariableArrayType *vlaType = 613 dyn_cast_or_null<VariableArrayType>( 614 getContext().getAsArrayType(Ty))) { 615 SizeVal = GetVLASize(vlaType); 616 vla = vlaType; 617 } else { 618 return; 619 } 620 } else { 621 SizeVal = llvm::ConstantInt::get(IntPtrTy, Size); 622 vla = 0; 623 } 624 625 // If the type contains a pointer to data member we can't memset it to zero. 626 // Instead, create a null constant and copy it to the destination. 627 // TODO: there are other patterns besides zero that we can usefully memset, 628 // like -1, which happens to be the pattern used by member-pointers. 629 if (!CGM.getTypes().isZeroInitializable(Ty)) { 630 // For a VLA, emit a single element, then splat that over the VLA. 631 if (vla) Ty = getContext().getBaseElementType(vla); 632 633 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 634 635 llvm::GlobalVariable *NullVariable = 636 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 637 /*isConstant=*/true, 638 llvm::GlobalVariable::PrivateLinkage, 639 NullConstant, llvm::Twine()); 640 llvm::Value *SrcPtr = 641 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 642 643 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 644 645 // Get and call the appropriate llvm.memcpy overload. 646 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align, false); 647 return; 648 } 649 650 // Otherwise, just memset the whole thing to zero. This is legal 651 // because in LLVM, all default initializers (other than the ones we just 652 // handled above) are guaranteed to have a bit pattern of all zeros. 653 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, Align, false); 654 } 655 656 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) { 657 // Make sure that there is a block for the indirect goto. 658 if (IndirectBranch == 0) 659 GetIndirectGotoBlock(); 660 661 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 662 663 // Make sure the indirect branch includes all of the address-taken blocks. 664 IndirectBranch->addDestination(BB); 665 return llvm::BlockAddress::get(CurFn, BB); 666 } 667 668 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 669 // If we already made the indirect branch for indirect goto, return its block. 670 if (IndirectBranch) return IndirectBranch->getParent(); 671 672 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 673 674 // Create the PHI node that indirect gotos will add entries to. 675 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest"); 676 677 // Create the indirect branch instruction. 678 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 679 return IndirectBranch->getParent(); 680 } 681 682 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 683 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 684 685 assert(SizeEntry && "Did not emit size for type"); 686 return SizeEntry; 687 } 688 689 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 690 assert(Ty->isVariablyModifiedType() && 691 "Must pass variably modified type to EmitVLASizes!"); 692 693 EnsureInsertPoint(); 694 695 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 696 // unknown size indication requires no size computation. 697 if (!VAT->getSizeExpr()) 698 return 0; 699 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 700 701 if (!SizeEntry) { 702 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 703 704 // Get the element size; 705 QualType ElemTy = VAT->getElementType(); 706 llvm::Value *ElemSize; 707 if (ElemTy->isVariableArrayType()) 708 ElemSize = EmitVLASize(ElemTy); 709 else 710 ElemSize = llvm::ConstantInt::get(SizeTy, 711 getContext().getTypeSizeInChars(ElemTy).getQuantity()); 712 713 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 714 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 715 716 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 717 } 718 719 return SizeEntry; 720 } 721 722 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 723 EmitVLASize(AT->getElementType()); 724 return 0; 725 } 726 727 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) { 728 EmitVLASize(PT->getInnerType()); 729 return 0; 730 } 731 732 const PointerType *PT = Ty->getAs<PointerType>(); 733 assert(PT && "unknown VM type!"); 734 EmitVLASize(PT->getPointeeType()); 735 return 0; 736 } 737 738 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 739 if (getContext().getBuiltinVaListType()->isArrayType()) 740 return EmitScalarExpr(E); 741 return EmitLValue(E).getAddress(); 742 } 743 744 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 745 llvm::Constant *Init) { 746 assert (Init && "Invalid DeclRefExpr initializer!"); 747 if (CGDebugInfo *Dbg = getDebugInfo()) 748 Dbg->EmitGlobalVariable(E->getDecl(), Init); 749 } 750