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 "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGDebugInfo.h" 19 #include "CGException.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "clang/AST/APValue.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/Decl.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/AST/StmtCXX.h" 26 #include "clang/Frontend/CodeGenOptions.h" 27 #include "llvm/Target/TargetData.h" 28 #include "llvm/Intrinsics.h" 29 using namespace clang; 30 using namespace CodeGen; 31 32 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 33 : CodeGenTypeCache(cgm), CGM(cgm), 34 Target(CGM.getContext().getTargetInfo()), Builder(cgm.getModule().getContext()), 35 AutoreleaseResult(false), BlockInfo(0), BlockPointer(0), 36 NormalCleanupDest(0), NextCleanupDestIndex(1), 37 EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0), 38 DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false), 39 IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0), 40 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0), 41 OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0), 42 TrapBB(0) { 43 44 CatchUndefined = getContext().getLangOptions().CatchUndefined; 45 CGM.getCXXABI().getMangleContext().startNewFunction(); 46 } 47 48 49 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 50 return CGM.getTypes().ConvertTypeForMem(T); 51 } 52 53 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 54 return CGM.getTypes().ConvertType(T); 55 } 56 57 bool CodeGenFunction::hasAggregateLLVMType(QualType type) { 58 switch (type.getCanonicalType()->getTypeClass()) { 59 #define TYPE(name, parent) 60 #define ABSTRACT_TYPE(name, parent) 61 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 62 #define DEPENDENT_TYPE(name, parent) case Type::name: 63 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 64 #include "clang/AST/TypeNodes.def" 65 llvm_unreachable("non-canonical or dependent type in IR-generation"); 66 67 case Type::Builtin: 68 case Type::Pointer: 69 case Type::BlockPointer: 70 case Type::LValueReference: 71 case Type::RValueReference: 72 case Type::MemberPointer: 73 case Type::Vector: 74 case Type::ExtVector: 75 case Type::FunctionProto: 76 case Type::FunctionNoProto: 77 case Type::Enum: 78 case Type::ObjCObjectPointer: 79 return false; 80 81 // Complexes, arrays, records, and Objective-C objects. 82 case Type::Complex: 83 case Type::ConstantArray: 84 case Type::IncompleteArray: 85 case Type::VariableArray: 86 case Type::Record: 87 case Type::ObjCObject: 88 case Type::ObjCInterface: 89 return true; 90 } 91 llvm_unreachable("unknown type kind!"); 92 } 93 94 void CodeGenFunction::EmitReturnBlock() { 95 // For cleanliness, we try to avoid emitting the return block for 96 // simple cases. 97 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 98 99 if (CurBB) { 100 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 101 102 // We have a valid insert point, reuse it if it is empty or there are no 103 // explicit jumps to the return block. 104 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 105 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 106 delete ReturnBlock.getBlock(); 107 } else 108 EmitBlock(ReturnBlock.getBlock()); 109 return; 110 } 111 112 // Otherwise, if the return block is the target of a single direct 113 // branch then we can just put the code in that block instead. This 114 // cleans up functions which started with a unified return block. 115 if (ReturnBlock.getBlock()->hasOneUse()) { 116 llvm::BranchInst *BI = 117 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin()); 118 if (BI && BI->isUnconditional() && 119 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 120 // Reset insertion point, including debug location, and delete the branch. 121 Builder.SetCurrentDebugLocation(BI->getDebugLoc()); 122 Builder.SetInsertPoint(BI->getParent()); 123 BI->eraseFromParent(); 124 delete ReturnBlock.getBlock(); 125 return; 126 } 127 } 128 129 // FIXME: We are at an unreachable point, there is no reason to emit the block 130 // unless it has uses. However, we still need a place to put the debug 131 // region.end for now. 132 133 EmitBlock(ReturnBlock.getBlock()); 134 } 135 136 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 137 if (!BB) return; 138 if (!BB->use_empty()) 139 return CGF.CurFn->getBasicBlockList().push_back(BB); 140 delete BB; 141 } 142 143 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 144 assert(BreakContinueStack.empty() && 145 "mismatched push/pop in break/continue stack!"); 146 147 // Pop any cleanups that might have been associated with the 148 // parameters. Do this in whatever block we're currently in; it's 149 // important to do this before we enter the return block or return 150 // edges will be *really* confused. 151 if (EHStack.stable_begin() != PrologueCleanupDepth) 152 PopCleanupBlocks(PrologueCleanupDepth); 153 154 // Emit function epilog (to return). 155 EmitReturnBlock(); 156 157 if (ShouldInstrumentFunction()) 158 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 159 160 // Emit debug descriptor for function end. 161 if (CGDebugInfo *DI = getDebugInfo()) { 162 DI->setLocation(EndLoc); 163 DI->EmitFunctionEnd(Builder); 164 } 165 166 EmitFunctionEpilog(*CurFnInfo); 167 EmitEndEHSpec(CurCodeDecl); 168 169 assert(EHStack.empty() && 170 "did not remove all scopes from cleanup stack!"); 171 172 // If someone did an indirect goto, emit the indirect goto block at the end of 173 // the function. 174 if (IndirectBranch) { 175 EmitBlock(IndirectBranch->getParent()); 176 Builder.ClearInsertionPoint(); 177 } 178 179 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 180 llvm::Instruction *Ptr = AllocaInsertPt; 181 AllocaInsertPt = 0; 182 Ptr->eraseFromParent(); 183 184 // If someone took the address of a label but never did an indirect goto, we 185 // made a zero entry PHI node, which is illegal, zap it now. 186 if (IndirectBranch) { 187 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 188 if (PN->getNumIncomingValues() == 0) { 189 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 190 PN->eraseFromParent(); 191 } 192 } 193 194 EmitIfUsed(*this, EHResumeBlock); 195 EmitIfUsed(*this, TerminateLandingPad); 196 EmitIfUsed(*this, TerminateHandler); 197 EmitIfUsed(*this, UnreachableBlock); 198 199 if (CGM.getCodeGenOpts().EmitDeclMetadata) 200 EmitDeclMetadata(); 201 } 202 203 /// ShouldInstrumentFunction - Return true if the current function should be 204 /// instrumented with __cyg_profile_func_* calls 205 bool CodeGenFunction::ShouldInstrumentFunction() { 206 if (!CGM.getCodeGenOpts().InstrumentFunctions) 207 return false; 208 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 209 return false; 210 return true; 211 } 212 213 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 214 /// instrumentation function with the current function and the call site, if 215 /// function instrumentation is enabled. 216 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 217 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 218 llvm::PointerType *PointerTy = Int8PtrTy; 219 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 220 llvm::FunctionType *FunctionTy = 221 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), 222 ProfileFuncArgs, false); 223 224 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 225 llvm::CallInst *CallSite = Builder.CreateCall( 226 CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 227 llvm::ConstantInt::get(Int32Ty, 0), 228 "callsite"); 229 230 Builder.CreateCall2(F, 231 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 232 CallSite); 233 } 234 235 void CodeGenFunction::EmitMCountInstrumentation() { 236 llvm::FunctionType *FTy = 237 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false); 238 239 llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy, 240 Target.getMCountName()); 241 Builder.CreateCall(MCountFn); 242 } 243 244 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 245 llvm::Function *Fn, 246 const CGFunctionInfo &FnInfo, 247 const FunctionArgList &Args, 248 SourceLocation StartLoc) { 249 const Decl *D = GD.getDecl(); 250 251 DidCallStackSave = false; 252 CurCodeDecl = CurFuncDecl = D; 253 FnRetTy = RetTy; 254 CurFn = Fn; 255 CurFnInfo = &FnInfo; 256 assert(CurFn->isDeclaration() && "Function already has body?"); 257 258 // Pass inline keyword to optimizer if it appears explicitly on any 259 // declaration. 260 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 261 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(), 262 RE = FD->redecls_end(); RI != RE; ++RI) 263 if (RI->isInlineSpecified()) { 264 Fn->addFnAttr(llvm::Attribute::InlineHint); 265 break; 266 } 267 268 if (getContext().getLangOptions().OpenCL) { 269 // Add metadata for a kernel function. 270 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 271 if (FD->hasAttr<OpenCLKernelAttr>()) { 272 llvm::LLVMContext &Context = getLLVMContext(); 273 llvm::NamedMDNode *OpenCLMetadata = 274 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels"); 275 276 llvm::Value *Op = Fn; 277 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op)); 278 } 279 } 280 281 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 282 283 // Create a marker to make it easy to insert allocas into the entryblock 284 // later. Don't create this with the builder, because we don't want it 285 // folded. 286 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 287 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 288 if (Builder.isNamePreserving()) 289 AllocaInsertPt->setName("allocapt"); 290 291 ReturnBlock = getJumpDestInCurrentScope("return"); 292 293 Builder.SetInsertPoint(EntryBB); 294 295 // Emit subprogram debug descriptor. 296 if (CGDebugInfo *DI = getDebugInfo()) { 297 // FIXME: what is going on here and why does it ignore all these 298 // interesting type properties? 299 QualType FnType = 300 getContext().getFunctionType(RetTy, 0, 0, 301 FunctionProtoType::ExtProtoInfo()); 302 303 DI->setLocation(StartLoc); 304 DI->EmitFunctionStart(GD, FnType, CurFn, Builder); 305 } 306 307 if (ShouldInstrumentFunction()) 308 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 309 310 if (CGM.getCodeGenOpts().InstrumentForProfiling) 311 EmitMCountInstrumentation(); 312 313 if (RetTy->isVoidType()) { 314 // Void type; nothing to return. 315 ReturnValue = 0; 316 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 317 hasAggregateLLVMType(CurFnInfo->getReturnType())) { 318 // Indirect aggregate return; emit returned value directly into sret slot. 319 // This reduces code size, and affects correctness in C++. 320 ReturnValue = CurFn->arg_begin(); 321 } else { 322 ReturnValue = CreateIRTemp(RetTy, "retval"); 323 324 // Tell the epilog emitter to autorelease the result. We do this 325 // now so that various specialized functions can suppress it 326 // during their IR-generation. 327 if (getLangOptions().ObjCAutoRefCount && 328 !CurFnInfo->isReturnsRetained() && 329 RetTy->isObjCRetainableType()) 330 AutoreleaseResult = true; 331 } 332 333 EmitStartEHSpec(CurCodeDecl); 334 335 PrologueCleanupDepth = EHStack.stable_begin(); 336 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 337 338 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) 339 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 340 341 // If any of the arguments have a variably modified type, make sure to 342 // emit the type size. 343 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 344 i != e; ++i) { 345 QualType Ty = (*i)->getType(); 346 347 if (Ty->isVariablyModifiedType()) 348 EmitVariablyModifiedType(Ty); 349 } 350 } 351 352 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) { 353 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl()); 354 assert(FD->getBody()); 355 EmitStmt(FD->getBody()); 356 } 357 358 /// Tries to mark the given function nounwind based on the 359 /// non-existence of any throwing calls within it. We believe this is 360 /// lightweight enough to do at -O0. 361 static void TryMarkNoThrow(llvm::Function *F) { 362 // LLVM treats 'nounwind' on a function as part of the type, so we 363 // can't do this on functions that can be overwritten. 364 if (F->mayBeOverridden()) return; 365 366 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) 367 for (llvm::BasicBlock::iterator 368 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) 369 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) { 370 if (!Call->doesNotThrow()) 371 return; 372 } else if (isa<llvm::ResumeInst>(&*BI)) { 373 return; 374 } 375 F->setDoesNotThrow(true); 376 } 377 378 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 379 const CGFunctionInfo &FnInfo) { 380 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 381 382 // Check if we should generate debug info for this function. 383 if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 384 DebugInfo = CGM.getModuleDebugInfo(); 385 386 FunctionArgList Args; 387 QualType ResTy = FD->getResultType(); 388 389 CurGD = GD; 390 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance()) 391 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args); 392 393 if (FD->getNumParams()) 394 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 395 Args.push_back(FD->getParamDecl(i)); 396 397 SourceRange BodyRange; 398 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 399 400 // Emit the standard function prologue. 401 StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin()); 402 403 // Generate the body of the function. 404 if (isa<CXXDestructorDecl>(FD)) 405 EmitDestructorBody(Args); 406 else if (isa<CXXConstructorDecl>(FD)) 407 EmitConstructorBody(Args); 408 else if (getContext().getLangOptions().CUDA && 409 !CGM.getCodeGenOpts().CUDAIsDevice && 410 FD->hasAttr<CUDAGlobalAttr>()) 411 CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args); 412 else 413 EmitFunctionBody(Args); 414 415 // Emit the standard function epilogue. 416 FinishFunction(BodyRange.getEnd()); 417 418 // If we haven't marked the function nothrow through other means, do 419 // a quick pass now to see if we can. 420 if (!CurFn->doesNotThrow()) 421 TryMarkNoThrow(CurFn); 422 } 423 424 /// ContainsLabel - Return true if the statement contains a label in it. If 425 /// this statement is not executed normally, it not containing a label means 426 /// that we can just remove the code. 427 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 428 // Null statement, not a label! 429 if (S == 0) return false; 430 431 // If this is a label, we have to emit the code, consider something like: 432 // if (0) { ... foo: bar(); } goto foo; 433 // 434 // TODO: If anyone cared, we could track __label__'s, since we know that you 435 // can't jump to one from outside their declared region. 436 if (isa<LabelStmt>(S)) 437 return true; 438 439 // If this is a case/default statement, and we haven't seen a switch, we have 440 // to emit the code. 441 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 442 return true; 443 444 // If this is a switch statement, we want to ignore cases below it. 445 if (isa<SwitchStmt>(S)) 446 IgnoreCaseStmts = true; 447 448 // Scan subexpressions for verboten labels. 449 for (Stmt::const_child_range I = S->children(); I; ++I) 450 if (ContainsLabel(*I, IgnoreCaseStmts)) 451 return true; 452 453 return false; 454 } 455 456 /// containsBreak - Return true if the statement contains a break out of it. 457 /// If the statement (recursively) contains a switch or loop with a break 458 /// inside of it, this is fine. 459 bool CodeGenFunction::containsBreak(const Stmt *S) { 460 // Null statement, not a label! 461 if (S == 0) return false; 462 463 // If this is a switch or loop that defines its own break scope, then we can 464 // include it and anything inside of it. 465 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 466 isa<ForStmt>(S)) 467 return false; 468 469 if (isa<BreakStmt>(S)) 470 return true; 471 472 // Scan subexpressions for verboten breaks. 473 for (Stmt::const_child_range I = S->children(); I; ++I) 474 if (containsBreak(*I)) 475 return true; 476 477 return false; 478 } 479 480 481 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 482 /// to a constant, or if it does but contains a label, return false. If it 483 /// constant folds return true and set the boolean result in Result. 484 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 485 bool &ResultBool) { 486 llvm::APInt ResultInt; 487 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt)) 488 return false; 489 490 ResultBool = ResultInt.getBoolValue(); 491 return true; 492 } 493 494 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 495 /// to a constant, or if it does but contains a label, return false. If it 496 /// constant folds return true and set the folded value. 497 bool CodeGenFunction:: 498 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) { 499 // FIXME: Rename and handle conversion of other evaluatable things 500 // to bool. 501 Expr::EvalResult Result; 502 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 503 Result.HasSideEffects) 504 return false; // Not foldable, not integer or not fully evaluatable. 505 506 if (CodeGenFunction::ContainsLabel(Cond)) 507 return false; // Contains a label. 508 509 ResultInt = Result.Val.getInt(); 510 return true; 511 } 512 513 514 515 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 516 /// statement) to the specified blocks. Based on the condition, this might try 517 /// to simplify the codegen of the conditional based on the branch. 518 /// 519 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 520 llvm::BasicBlock *TrueBlock, 521 llvm::BasicBlock *FalseBlock) { 522 Cond = Cond->IgnoreParens(); 523 524 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 525 // Handle X && Y in a condition. 526 if (CondBOp->getOpcode() == BO_LAnd) { 527 // If we have "1 && X", simplify the code. "0 && X" would have constant 528 // folded if the case was simple enough. 529 bool ConstantBool = false; 530 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 531 ConstantBool) { 532 // br(1 && X) -> br(X). 533 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 534 } 535 536 // If we have "X && 1", simplify the code to use an uncond branch. 537 // "X && 0" would have been constant folded to 0. 538 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 539 ConstantBool) { 540 // br(X && 1) -> br(X). 541 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 542 } 543 544 // Emit the LHS as a conditional. If the LHS conditional is false, we 545 // want to jump to the FalseBlock. 546 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 547 548 ConditionalEvaluation eval(*this); 549 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 550 EmitBlock(LHSTrue); 551 552 // Any temporaries created here are conditional. 553 eval.begin(*this); 554 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 555 eval.end(*this); 556 557 return; 558 } 559 560 if (CondBOp->getOpcode() == BO_LOr) { 561 // If we have "0 || X", simplify the code. "1 || X" would have constant 562 // folded if the case was simple enough. 563 bool ConstantBool = false; 564 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 565 !ConstantBool) { 566 // br(0 || X) -> br(X). 567 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 568 } 569 570 // If we have "X || 0", simplify the code to use an uncond branch. 571 // "X || 1" would have been constant folded to 1. 572 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 573 !ConstantBool) { 574 // br(X || 0) -> br(X). 575 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 576 } 577 578 // Emit the LHS as a conditional. If the LHS conditional is true, we 579 // want to jump to the TrueBlock. 580 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 581 582 ConditionalEvaluation eval(*this); 583 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 584 EmitBlock(LHSFalse); 585 586 // Any temporaries created here are conditional. 587 eval.begin(*this); 588 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 589 eval.end(*this); 590 591 return; 592 } 593 } 594 595 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 596 // br(!x, t, f) -> br(x, f, t) 597 if (CondUOp->getOpcode() == UO_LNot) 598 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 599 } 600 601 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 602 // Handle ?: operator. 603 604 // Just ignore GNU ?: extension. 605 if (CondOp->getLHS()) { 606 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 607 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 608 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 609 610 ConditionalEvaluation cond(*this); 611 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 612 613 cond.begin(*this); 614 EmitBlock(LHSBlock); 615 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 616 cond.end(*this); 617 618 cond.begin(*this); 619 EmitBlock(RHSBlock); 620 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 621 cond.end(*this); 622 623 return; 624 } 625 } 626 627 // Emit the code with the fully general case. 628 llvm::Value *CondV = EvaluateExprAsBool(Cond); 629 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 630 } 631 632 /// ErrorUnsupported - Print out an error that codegen doesn't support the 633 /// specified stmt yet. 634 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 635 bool OmitOnError) { 636 CGM.ErrorUnsupported(S, Type, OmitOnError); 637 } 638 639 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 640 /// variable-length array whose elements have a non-zero bit-pattern. 641 /// 642 /// \param src - a char* pointing to the bit-pattern for a single 643 /// base element of the array 644 /// \param sizeInChars - the total size of the VLA, in chars 645 /// \param align - the total alignment of the VLA 646 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 647 llvm::Value *dest, llvm::Value *src, 648 llvm::Value *sizeInChars) { 649 std::pair<CharUnits,CharUnits> baseSizeAndAlign 650 = CGF.getContext().getTypeInfoInChars(baseType); 651 652 CGBuilderTy &Builder = CGF.Builder; 653 654 llvm::Value *baseSizeInChars 655 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity()); 656 657 llvm::Type *i8p = Builder.getInt8PtrTy(); 658 659 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin"); 660 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end"); 661 662 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 663 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 664 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 665 666 // Make a loop over the VLA. C99 guarantees that the VLA element 667 // count must be nonzero. 668 CGF.EmitBlock(loopBB); 669 670 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur"); 671 cur->addIncoming(begin, originBB); 672 673 // memcpy the individual element bit-pattern. 674 Builder.CreateMemCpy(cur, src, baseSizeInChars, 675 baseSizeAndAlign.second.getQuantity(), 676 /*volatile*/ false); 677 678 // Go to the next element. 679 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next"); 680 681 // Leave if that's the end of the VLA. 682 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 683 Builder.CreateCondBr(done, contBB, loopBB); 684 cur->addIncoming(next, loopBB); 685 686 CGF.EmitBlock(contBB); 687 } 688 689 void 690 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 691 // Ignore empty classes in C++. 692 if (getContext().getLangOptions().CPlusPlus) { 693 if (const RecordType *RT = Ty->getAs<RecordType>()) { 694 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 695 return; 696 } 697 } 698 699 // Cast the dest ptr to the appropriate i8 pointer type. 700 unsigned DestAS = 701 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 702 llvm::Type *BP = Builder.getInt8PtrTy(DestAS); 703 if (DestPtr->getType() != BP) 704 DestPtr = Builder.CreateBitCast(DestPtr, BP); 705 706 // Get size and alignment info for this aggregate. 707 std::pair<CharUnits, CharUnits> TypeInfo = 708 getContext().getTypeInfoInChars(Ty); 709 CharUnits Size = TypeInfo.first; 710 CharUnits Align = TypeInfo.second; 711 712 llvm::Value *SizeVal; 713 const VariableArrayType *vla; 714 715 // Don't bother emitting a zero-byte memset. 716 if (Size.isZero()) { 717 // But note that getTypeInfo returns 0 for a VLA. 718 if (const VariableArrayType *vlaType = 719 dyn_cast_or_null<VariableArrayType>( 720 getContext().getAsArrayType(Ty))) { 721 QualType eltType; 722 llvm::Value *numElts; 723 llvm::tie(numElts, eltType) = getVLASize(vlaType); 724 725 SizeVal = numElts; 726 CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 727 if (!eltSize.isOne()) 728 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 729 vla = vlaType; 730 } else { 731 return; 732 } 733 } else { 734 SizeVal = CGM.getSize(Size); 735 vla = 0; 736 } 737 738 // If the type contains a pointer to data member we can't memset it to zero. 739 // Instead, create a null constant and copy it to the destination. 740 // TODO: there are other patterns besides zero that we can usefully memset, 741 // like -1, which happens to be the pattern used by member-pointers. 742 if (!CGM.getTypes().isZeroInitializable(Ty)) { 743 // For a VLA, emit a single element, then splat that over the VLA. 744 if (vla) Ty = getContext().getBaseElementType(vla); 745 746 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 747 748 llvm::GlobalVariable *NullVariable = 749 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 750 /*isConstant=*/true, 751 llvm::GlobalVariable::PrivateLinkage, 752 NullConstant, Twine()); 753 llvm::Value *SrcPtr = 754 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 755 756 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 757 758 // Get and call the appropriate llvm.memcpy overload. 759 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false); 760 return; 761 } 762 763 // Otherwise, just memset the whole thing to zero. This is legal 764 // because in LLVM, all default initializers (other than the ones we just 765 // handled above) are guaranteed to have a bit pattern of all zeros. 766 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, 767 Align.getQuantity(), false); 768 } 769 770 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 771 // Make sure that there is a block for the indirect goto. 772 if (IndirectBranch == 0) 773 GetIndirectGotoBlock(); 774 775 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 776 777 // Make sure the indirect branch includes all of the address-taken blocks. 778 IndirectBranch->addDestination(BB); 779 return llvm::BlockAddress::get(CurFn, BB); 780 } 781 782 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 783 // If we already made the indirect branch for indirect goto, return its block. 784 if (IndirectBranch) return IndirectBranch->getParent(); 785 786 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 787 788 // Create the PHI node that indirect gotos will add entries to. 789 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 790 "indirect.goto.dest"); 791 792 // Create the indirect branch instruction. 793 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 794 return IndirectBranch->getParent(); 795 } 796 797 /// Computes the length of an array in elements, as well as the base 798 /// element type and a properly-typed first element pointer. 799 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 800 QualType &baseType, 801 llvm::Value *&addr) { 802 const ArrayType *arrayType = origArrayType; 803 804 // If it's a VLA, we have to load the stored size. Note that 805 // this is the size of the VLA in bytes, not its size in elements. 806 llvm::Value *numVLAElements = 0; 807 if (isa<VariableArrayType>(arrayType)) { 808 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 809 810 // Walk into all VLAs. This doesn't require changes to addr, 811 // which has type T* where T is the first non-VLA element type. 812 do { 813 QualType elementType = arrayType->getElementType(); 814 arrayType = getContext().getAsArrayType(elementType); 815 816 // If we only have VLA components, 'addr' requires no adjustment. 817 if (!arrayType) { 818 baseType = elementType; 819 return numVLAElements; 820 } 821 } while (isa<VariableArrayType>(arrayType)); 822 823 // We get out here only if we find a constant array type 824 // inside the VLA. 825 } 826 827 // We have some number of constant-length arrays, so addr should 828 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 829 // down to the first element of addr. 830 SmallVector<llvm::Value*, 8> gepIndices; 831 832 // GEP down to the array type. 833 llvm::ConstantInt *zero = Builder.getInt32(0); 834 gepIndices.push_back(zero); 835 836 // It's more efficient to calculate the count from the LLVM 837 // constant-length arrays than to re-evaluate the array bounds. 838 uint64_t countFromCLAs = 1; 839 840 llvm::ArrayType *llvmArrayType = 841 cast<llvm::ArrayType>( 842 cast<llvm::PointerType>(addr->getType())->getElementType()); 843 while (true) { 844 assert(isa<ConstantArrayType>(arrayType)); 845 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 846 == llvmArrayType->getNumElements()); 847 848 gepIndices.push_back(zero); 849 countFromCLAs *= llvmArrayType->getNumElements(); 850 851 llvmArrayType = 852 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 853 if (!llvmArrayType) break; 854 855 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 856 assert(arrayType && "LLVM and Clang types are out-of-synch"); 857 } 858 859 baseType = arrayType->getElementType(); 860 861 // Create the actual GEP. 862 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin"); 863 864 llvm::Value *numElements 865 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 866 867 // If we had any VLA dimensions, factor them in. 868 if (numVLAElements) 869 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 870 871 return numElements; 872 } 873 874 std::pair<llvm::Value*, QualType> 875 CodeGenFunction::getVLASize(QualType type) { 876 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 877 assert(vla && "type was not a variable array type!"); 878 return getVLASize(vla); 879 } 880 881 std::pair<llvm::Value*, QualType> 882 CodeGenFunction::getVLASize(const VariableArrayType *type) { 883 // The number of elements so far; always size_t. 884 llvm::Value *numElements = 0; 885 886 QualType elementType; 887 do { 888 elementType = type->getElementType(); 889 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 890 assert(vlaSize && "no size for VLA!"); 891 assert(vlaSize->getType() == SizeTy); 892 893 if (!numElements) { 894 numElements = vlaSize; 895 } else { 896 // It's undefined behavior if this wraps around, so mark it that way. 897 numElements = Builder.CreateNUWMul(numElements, vlaSize); 898 } 899 } while ((type = getContext().getAsVariableArrayType(elementType))); 900 901 return std::pair<llvm::Value*,QualType>(numElements, elementType); 902 } 903 904 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 905 assert(type->isVariablyModifiedType() && 906 "Must pass variably modified type to EmitVLASizes!"); 907 908 EnsureInsertPoint(); 909 910 // We're going to walk down into the type and look for VLA 911 // expressions. 912 type = type.getCanonicalType(); 913 do { 914 assert(type->isVariablyModifiedType()); 915 916 const Type *ty = type.getTypePtr(); 917 switch (ty->getTypeClass()) { 918 #define TYPE(Class, Base) 919 #define ABSTRACT_TYPE(Class, Base) 920 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 921 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 922 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 923 #include "clang/AST/TypeNodes.def" 924 llvm_unreachable("unexpected dependent or non-canonical type!"); 925 926 // These types are never variably-modified. 927 case Type::Builtin: 928 case Type::Complex: 929 case Type::Vector: 930 case Type::ExtVector: 931 case Type::Record: 932 case Type::Enum: 933 case Type::ObjCObject: 934 case Type::ObjCInterface: 935 case Type::ObjCObjectPointer: 936 llvm_unreachable("type class is never variably-modified!"); 937 938 case Type::Pointer: 939 type = cast<PointerType>(ty)->getPointeeType(); 940 break; 941 942 case Type::BlockPointer: 943 type = cast<BlockPointerType>(ty)->getPointeeType(); 944 break; 945 946 case Type::LValueReference: 947 case Type::RValueReference: 948 type = cast<ReferenceType>(ty)->getPointeeType(); 949 break; 950 951 case Type::MemberPointer: 952 type = cast<MemberPointerType>(ty)->getPointeeType(); 953 break; 954 955 case Type::ConstantArray: 956 case Type::IncompleteArray: 957 // Losing element qualification here is fine. 958 type = cast<ArrayType>(ty)->getElementType(); 959 break; 960 961 case Type::VariableArray: { 962 // Losing element qualification here is fine. 963 const VariableArrayType *vat = cast<VariableArrayType>(ty); 964 965 // Unknown size indication requires no size computation. 966 // Otherwise, evaluate and record it. 967 if (const Expr *size = vat->getSizeExpr()) { 968 // It's possible that we might have emitted this already, 969 // e.g. with a typedef and a pointer to it. 970 llvm::Value *&entry = VLASizeMap[size]; 971 if (!entry) { 972 // Always zexting here would be wrong if it weren't 973 // undefined behavior to have a negative bound. 974 entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy, 975 /*signed*/ false); 976 } 977 } 978 type = vat->getElementType(); 979 break; 980 } 981 982 case Type::FunctionProto: 983 case Type::FunctionNoProto: 984 type = cast<FunctionType>(ty)->getResultType(); 985 break; 986 } 987 } while (type->isVariablyModifiedType()); 988 } 989 990 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 991 if (getContext().getBuiltinVaListType()->isArrayType()) 992 return EmitScalarExpr(E); 993 return EmitLValue(E).getAddress(); 994 } 995 996 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 997 llvm::Constant *Init) { 998 assert (Init && "Invalid DeclRefExpr initializer!"); 999 if (CGDebugInfo *Dbg = getDebugInfo()) 1000 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1001 } 1002 1003 CodeGenFunction::PeepholeProtection 1004 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 1005 // At the moment, the only aggressive peephole we do in IR gen 1006 // is trunc(zext) folding, but if we add more, we can easily 1007 // extend this protection. 1008 1009 if (!rvalue.isScalar()) return PeepholeProtection(); 1010 llvm::Value *value = rvalue.getScalarVal(); 1011 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 1012 1013 // Just make an extra bitcast. 1014 assert(HaveInsertPoint()); 1015 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 1016 Builder.GetInsertBlock()); 1017 1018 PeepholeProtection protection; 1019 protection.Inst = inst; 1020 return protection; 1021 } 1022 1023 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 1024 if (!protection.Inst) return; 1025 1026 // In theory, we could try to duplicate the peepholes now, but whatever. 1027 protection.Inst->eraseFromParent(); 1028 } 1029 1030 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 1031 llvm::Value *AnnotatedVal, 1032 llvm::StringRef AnnotationStr, 1033 SourceLocation Location) { 1034 llvm::Value *Args[4] = { 1035 AnnotatedVal, 1036 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 1037 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 1038 CGM.EmitAnnotationLineNo(Location) 1039 }; 1040 return Builder.CreateCall(AnnotationFn, Args); 1041 } 1042 1043 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 1044 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1045 // FIXME We create a new bitcast for every annotation because that's what 1046 // llvm-gcc was doing. 1047 for (specific_attr_iterator<AnnotateAttr> 1048 ai = D->specific_attr_begin<AnnotateAttr>(), 1049 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 1050 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 1051 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 1052 (*ai)->getAnnotation(), D->getLocation()); 1053 } 1054 1055 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 1056 llvm::Value *V) { 1057 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1058 llvm::Type *VTy = V->getType(); 1059 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 1060 CGM.Int8PtrTy); 1061 1062 for (specific_attr_iterator<AnnotateAttr> 1063 ai = D->specific_attr_begin<AnnotateAttr>(), 1064 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) { 1065 // FIXME Always emit the cast inst so we can differentiate between 1066 // annotation on the first field of a struct and annotation on the struct 1067 // itself. 1068 if (VTy != CGM.Int8PtrTy) 1069 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 1070 V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation()); 1071 V = Builder.CreateBitCast(V, VTy); 1072 } 1073 1074 return V; 1075 } 1076