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 "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGOpenMPRuntime.h" 19 #include "CodeGenModule.h" 20 #include "CodeGenPGO.h" 21 #include "TargetInfo.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/Basic/TargetInfo.h" 27 #include "clang/CodeGen/CGFunctionInfo.h" 28 #include "clang/Frontend/CodeGenOptions.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Intrinsics.h" 31 #include "llvm/IR/MDBuilder.h" 32 #include "llvm/IR/Operator.h" 33 using namespace clang; 34 using namespace CodeGen; 35 36 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 37 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 38 Builder(cgm.getModule().getContext(), llvm::ConstantFolder(), 39 CGBuilderInserterTy(this)), CapturedStmtInfo(nullptr), 40 SanitizePerformTypeCheck(CGM.getSanOpts().Null | 41 CGM.getSanOpts().Alignment | 42 CGM.getSanOpts().ObjectSize | 43 CGM.getSanOpts().Vptr), 44 SanOpts(&CGM.getSanOpts()), AutoreleaseResult(false), BlockInfo(nullptr), 45 BlockPointer(nullptr), LambdaThisCaptureField(nullptr), 46 NormalCleanupDest(nullptr), NextCleanupDestIndex(1), 47 FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr), 48 EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()), 49 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr), 50 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr), 51 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0), 52 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr), 53 CXXABIThisValue(nullptr), CXXThisValue(nullptr), 54 CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr), 55 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr), 56 CurLexicalScope(nullptr), TerminateLandingPad(nullptr), 57 TerminateHandler(nullptr), TrapBB(nullptr) { 58 if (!suppressNewContext) 59 CGM.getCXXABI().getMangleContext().startNewFunction(); 60 61 llvm::FastMathFlags FMF; 62 if (CGM.getLangOpts().FastMath) 63 FMF.setUnsafeAlgebra(); 64 if (CGM.getLangOpts().FiniteMathOnly) { 65 FMF.setNoNaNs(); 66 FMF.setNoInfs(); 67 } 68 Builder.SetFastMathFlags(FMF); 69 } 70 71 CodeGenFunction::~CodeGenFunction() { 72 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 73 74 // If there are any unclaimed block infos, go ahead and destroy them 75 // now. This can happen if IR-gen gets clever and skips evaluating 76 // something. 77 if (FirstBlockInfo) 78 destroyBlockInfos(FirstBlockInfo); 79 80 if (getLangOpts().OpenMP) { 81 CGM.getOpenMPRuntime().FunctionFinished(*this); 82 } 83 } 84 85 86 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 87 return CGM.getTypes().ConvertTypeForMem(T); 88 } 89 90 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 91 return CGM.getTypes().ConvertType(T); 92 } 93 94 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 95 type = type.getCanonicalType(); 96 while (true) { 97 switch (type->getTypeClass()) { 98 #define TYPE(name, parent) 99 #define ABSTRACT_TYPE(name, parent) 100 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 101 #define DEPENDENT_TYPE(name, parent) case Type::name: 102 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 103 #include "clang/AST/TypeNodes.def" 104 llvm_unreachable("non-canonical or dependent type in IR-generation"); 105 106 case Type::Auto: 107 llvm_unreachable("undeduced auto type in IR-generation"); 108 109 // Various scalar types. 110 case Type::Builtin: 111 case Type::Pointer: 112 case Type::BlockPointer: 113 case Type::LValueReference: 114 case Type::RValueReference: 115 case Type::MemberPointer: 116 case Type::Vector: 117 case Type::ExtVector: 118 case Type::FunctionProto: 119 case Type::FunctionNoProto: 120 case Type::Enum: 121 case Type::ObjCObjectPointer: 122 return TEK_Scalar; 123 124 // Complexes. 125 case Type::Complex: 126 return TEK_Complex; 127 128 // Arrays, records, and Objective-C objects. 129 case Type::ConstantArray: 130 case Type::IncompleteArray: 131 case Type::VariableArray: 132 case Type::Record: 133 case Type::ObjCObject: 134 case Type::ObjCInterface: 135 return TEK_Aggregate; 136 137 // We operate on atomic values according to their underlying type. 138 case Type::Atomic: 139 type = cast<AtomicType>(type)->getValueType(); 140 continue; 141 } 142 llvm_unreachable("unknown type kind!"); 143 } 144 } 145 146 void CodeGenFunction::EmitReturnBlock() { 147 // For cleanliness, we try to avoid emitting the return block for 148 // simple cases. 149 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 150 151 if (CurBB) { 152 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 153 154 // We have a valid insert point, reuse it if it is empty or there are no 155 // explicit jumps to the return block. 156 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 157 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 158 delete ReturnBlock.getBlock(); 159 } else 160 EmitBlock(ReturnBlock.getBlock()); 161 return; 162 } 163 164 // Otherwise, if the return block is the target of a single direct 165 // branch then we can just put the code in that block instead. This 166 // cleans up functions which started with a unified return block. 167 if (ReturnBlock.getBlock()->hasOneUse()) { 168 llvm::BranchInst *BI = 169 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 170 if (BI && BI->isUnconditional() && 171 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 172 // Reset insertion point, including debug location, and delete the 173 // branch. This is really subtle and only works because the next change 174 // in location will hit the caching in CGDebugInfo::EmitLocation and not 175 // override this. 176 Builder.SetCurrentDebugLocation(BI->getDebugLoc()); 177 Builder.SetInsertPoint(BI->getParent()); 178 BI->eraseFromParent(); 179 delete ReturnBlock.getBlock(); 180 return; 181 } 182 } 183 184 // FIXME: We are at an unreachable point, there is no reason to emit the block 185 // unless it has uses. However, we still need a place to put the debug 186 // region.end for now. 187 188 EmitBlock(ReturnBlock.getBlock()); 189 } 190 191 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 192 if (!BB) return; 193 if (!BB->use_empty()) 194 return CGF.CurFn->getBasicBlockList().push_back(BB); 195 delete BB; 196 } 197 198 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 199 assert(BreakContinueStack.empty() && 200 "mismatched push/pop in break/continue stack!"); 201 202 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 203 && NumSimpleReturnExprs == NumReturnExprs 204 && ReturnBlock.getBlock()->use_empty(); 205 // Usually the return expression is evaluated before the cleanup 206 // code. If the function contains only a simple return statement, 207 // such as a constant, the location before the cleanup code becomes 208 // the last useful breakpoint in the function, because the simple 209 // return expression will be evaluated after the cleanup code. To be 210 // safe, set the debug location for cleanup code to the location of 211 // the return statement. Otherwise the cleanup code should be at the 212 // end of the function's lexical scope. 213 // 214 // If there are multiple branches to the return block, the branch 215 // instructions will get the location of the return statements and 216 // all will be fine. 217 if (CGDebugInfo *DI = getDebugInfo()) { 218 if (OnlySimpleReturnStmts) 219 DI->EmitLocation(Builder, LastStopPoint); 220 else 221 DI->EmitLocation(Builder, EndLoc); 222 } 223 224 // Pop any cleanups that might have been associated with the 225 // parameters. Do this in whatever block we're currently in; it's 226 // important to do this before we enter the return block or return 227 // edges will be *really* confused. 228 bool EmitRetDbgLoc = true; 229 if (EHStack.stable_begin() != PrologueCleanupDepth) { 230 PopCleanupBlocks(PrologueCleanupDepth); 231 232 // Make sure the line table doesn't jump back into the body for 233 // the ret after it's been at EndLoc. 234 EmitRetDbgLoc = false; 235 236 if (CGDebugInfo *DI = getDebugInfo()) 237 if (OnlySimpleReturnStmts) 238 DI->EmitLocation(Builder, EndLoc); 239 } 240 241 // Emit function epilog (to return). 242 EmitReturnBlock(); 243 244 if (ShouldInstrumentFunction()) 245 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 246 247 // Emit debug descriptor for function end. 248 if (CGDebugInfo *DI = getDebugInfo()) { 249 DI->EmitFunctionEnd(Builder); 250 } 251 252 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 253 EmitEndEHSpec(CurCodeDecl); 254 255 assert(EHStack.empty() && 256 "did not remove all scopes from cleanup stack!"); 257 258 // If someone did an indirect goto, emit the indirect goto block at the end of 259 // the function. 260 if (IndirectBranch) { 261 EmitBlock(IndirectBranch->getParent()); 262 Builder.ClearInsertionPoint(); 263 } 264 265 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 266 llvm::Instruction *Ptr = AllocaInsertPt; 267 AllocaInsertPt = nullptr; 268 Ptr->eraseFromParent(); 269 270 // If someone took the address of a label but never did an indirect goto, we 271 // made a zero entry PHI node, which is illegal, zap it now. 272 if (IndirectBranch) { 273 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 274 if (PN->getNumIncomingValues() == 0) { 275 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 276 PN->eraseFromParent(); 277 } 278 } 279 280 EmitIfUsed(*this, EHResumeBlock); 281 EmitIfUsed(*this, TerminateLandingPad); 282 EmitIfUsed(*this, TerminateHandler); 283 EmitIfUsed(*this, UnreachableBlock); 284 285 if (CGM.getCodeGenOpts().EmitDeclMetadata) 286 EmitDeclMetadata(); 287 288 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 289 I = DeferredReplacements.begin(), 290 E = DeferredReplacements.end(); 291 I != E; ++I) { 292 I->first->replaceAllUsesWith(I->second); 293 I->first->eraseFromParent(); 294 } 295 } 296 297 /// ShouldInstrumentFunction - Return true if the current function should be 298 /// instrumented with __cyg_profile_func_* calls 299 bool CodeGenFunction::ShouldInstrumentFunction() { 300 if (!CGM.getCodeGenOpts().InstrumentFunctions) 301 return false; 302 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 303 return false; 304 return true; 305 } 306 307 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 308 /// instrumentation function with the current function and the call site, if 309 /// function instrumentation is enabled. 310 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 311 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 312 llvm::PointerType *PointerTy = Int8PtrTy; 313 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 314 llvm::FunctionType *FunctionTy = 315 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 316 317 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 318 llvm::CallInst *CallSite = Builder.CreateCall( 319 CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 320 llvm::ConstantInt::get(Int32Ty, 0), 321 "callsite"); 322 323 llvm::Value *args[] = { 324 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 325 CallSite 326 }; 327 328 EmitNounwindRuntimeCall(F, args); 329 } 330 331 void CodeGenFunction::EmitMCountInstrumentation() { 332 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 333 334 llvm::Constant *MCountFn = 335 CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName()); 336 EmitNounwindRuntimeCall(MCountFn); 337 } 338 339 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 340 // information in the program executable. The argument information stored 341 // includes the argument name, its type, the address and access qualifiers used. 342 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 343 CodeGenModule &CGM,llvm::LLVMContext &Context, 344 SmallVector <llvm::Value*, 5> &kernelMDArgs, 345 CGBuilderTy& Builder, ASTContext &ASTCtx) { 346 // Create MDNodes that represent the kernel arg metadata. 347 // Each MDNode is a list in the form of "key", N number of values which is 348 // the same number of values as their are kernel arguments. 349 350 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy(); 351 352 // MDNode for the kernel argument address space qualifiers. 353 SmallVector<llvm::Value*, 8> addressQuals; 354 addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space")); 355 356 // MDNode for the kernel argument access qualifiers (images only). 357 SmallVector<llvm::Value*, 8> accessQuals; 358 accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual")); 359 360 // MDNode for the kernel argument type names. 361 SmallVector<llvm::Value*, 8> argTypeNames; 362 argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type")); 363 364 // MDNode for the kernel argument type qualifiers. 365 SmallVector<llvm::Value*, 8> argTypeQuals; 366 argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual")); 367 368 // MDNode for the kernel argument names. 369 SmallVector<llvm::Value*, 8> argNames; 370 argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name")); 371 372 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 373 const ParmVarDecl *parm = FD->getParamDecl(i); 374 QualType ty = parm->getType(); 375 std::string typeQuals; 376 377 if (ty->isPointerType()) { 378 QualType pointeeTy = ty->getPointeeType(); 379 380 // Get address qualifier. 381 addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace( 382 pointeeTy.getAddressSpace()))); 383 384 // Get argument type name. 385 std::string typeName = 386 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 387 388 // Turn "unsigned type" to "utype" 389 std::string::size_type pos = typeName.find("unsigned"); 390 if (pos != std::string::npos) 391 typeName.erase(pos+1, 8); 392 393 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 394 395 // Get argument type qualifiers: 396 if (ty.isRestrictQualified()) 397 typeQuals = "restrict"; 398 if (pointeeTy.isConstQualified() || 399 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 400 typeQuals += typeQuals.empty() ? "const" : " const"; 401 if (pointeeTy.isVolatileQualified()) 402 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 403 } else { 404 uint32_t AddrSpc = 0; 405 if (ty->isImageType()) 406 AddrSpc = 407 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global); 408 409 addressQuals.push_back(Builder.getInt32(AddrSpc)); 410 411 // Get argument type name. 412 std::string typeName = ty.getUnqualifiedType().getAsString(Policy); 413 414 // Turn "unsigned type" to "utype" 415 std::string::size_type pos = typeName.find("unsigned"); 416 if (pos != std::string::npos) 417 typeName.erase(pos+1, 8); 418 419 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 420 421 // Get argument type qualifiers: 422 if (ty.isConstQualified()) 423 typeQuals = "const"; 424 if (ty.isVolatileQualified()) 425 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 426 } 427 428 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals)); 429 430 // Get image access qualifier: 431 if (ty->isImageType()) { 432 const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>(); 433 if (A && A->isWriteOnly()) 434 accessQuals.push_back(llvm::MDString::get(Context, "write_only")); 435 else 436 accessQuals.push_back(llvm::MDString::get(Context, "read_only")); 437 // FIXME: what about read_write? 438 } else 439 accessQuals.push_back(llvm::MDString::get(Context, "none")); 440 441 // Get argument name. 442 argNames.push_back(llvm::MDString::get(Context, parm->getName())); 443 } 444 445 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals)); 446 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals)); 447 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames)); 448 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals)); 449 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames)); 450 } 451 452 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 453 llvm::Function *Fn) 454 { 455 if (!FD->hasAttr<OpenCLKernelAttr>()) 456 return; 457 458 llvm::LLVMContext &Context = getLLVMContext(); 459 460 SmallVector <llvm::Value*, 5> kernelMDArgs; 461 kernelMDArgs.push_back(Fn); 462 463 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 464 GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, 465 Builder, getContext()); 466 467 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 468 QualType hintQTy = A->getTypeHint(); 469 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>(); 470 bool isSignedInteger = 471 hintQTy->isSignedIntegerType() || 472 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType()); 473 llvm::Value *attrMDArgs[] = { 474 llvm::MDString::get(Context, "vec_type_hint"), 475 llvm::UndefValue::get(CGM.getTypes().ConvertType(A->getTypeHint())), 476 llvm::ConstantInt::get( 477 llvm::IntegerType::get(Context, 32), 478 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))) 479 }; 480 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 481 } 482 483 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 484 llvm::Value *attrMDArgs[] = { 485 llvm::MDString::get(Context, "work_group_size_hint"), 486 Builder.getInt32(A->getXDim()), 487 Builder.getInt32(A->getYDim()), 488 Builder.getInt32(A->getZDim()) 489 }; 490 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 491 } 492 493 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 494 llvm::Value *attrMDArgs[] = { 495 llvm::MDString::get(Context, "reqd_work_group_size"), 496 Builder.getInt32(A->getXDim()), 497 Builder.getInt32(A->getYDim()), 498 Builder.getInt32(A->getZDim()) 499 }; 500 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 501 } 502 503 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs); 504 llvm::NamedMDNode *OpenCLKernelMetadata = 505 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels"); 506 OpenCLKernelMetadata->addOperand(kernelMDNode); 507 } 508 509 /// Determine whether the function F ends with a return stmt. 510 static bool endsWithReturn(const Decl* F) { 511 const Stmt *Body = nullptr; 512 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 513 Body = FD->getBody(); 514 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 515 Body = OMD->getBody(); 516 517 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 518 auto LastStmt = CS->body_rbegin(); 519 if (LastStmt != CS->body_rend()) 520 return isa<ReturnStmt>(*LastStmt); 521 } 522 return false; 523 } 524 525 void CodeGenFunction::StartFunction(GlobalDecl GD, 526 QualType RetTy, 527 llvm::Function *Fn, 528 const CGFunctionInfo &FnInfo, 529 const FunctionArgList &Args, 530 SourceLocation Loc, 531 SourceLocation StartLoc) { 532 const Decl *D = GD.getDecl(); 533 534 DidCallStackSave = false; 535 CurCodeDecl = D; 536 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 537 FnRetTy = RetTy; 538 CurFn = Fn; 539 CurFnInfo = &FnInfo; 540 assert(CurFn->isDeclaration() && "Function already has body?"); 541 542 if (CGM.getSanitizerBlacklist().isIn(*Fn)) { 543 SanOpts = &SanitizerOptions::Disabled; 544 SanitizePerformTypeCheck = false; 545 } 546 547 // Pass inline keyword to optimizer if it appears explicitly on any 548 // declaration. Also, in the case of -fno-inline attach NoInline 549 // attribute to all function that are not marked AlwaysInline. 550 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 551 if (!CGM.getCodeGenOpts().NoInline) { 552 for (auto RI : FD->redecls()) 553 if (RI->isInlineSpecified()) { 554 Fn->addFnAttr(llvm::Attribute::InlineHint); 555 break; 556 } 557 } else if (!FD->hasAttr<AlwaysInlineAttr>()) 558 Fn->addFnAttr(llvm::Attribute::NoInline); 559 } 560 561 if (getLangOpts().OpenCL) { 562 // Add metadata for a kernel function. 563 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 564 EmitOpenCLKernelMetadata(FD, Fn); 565 } 566 567 // If we are checking function types, emit a function type signature as 568 // prefix data. 569 if (getLangOpts().CPlusPlus && SanOpts->Function) { 570 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 571 if (llvm::Constant *PrefixSig = 572 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 573 llvm::Constant *FTRTTIConst = 574 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true); 575 llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst }; 576 llvm::Constant *PrefixStructConst = 577 llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true); 578 Fn->setPrefixData(PrefixStructConst); 579 } 580 } 581 } 582 583 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 584 585 // Create a marker to make it easy to insert allocas into the entryblock 586 // later. Don't create this with the builder, because we don't want it 587 // folded. 588 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 589 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 590 if (Builder.isNamePreserving()) 591 AllocaInsertPt->setName("allocapt"); 592 593 ReturnBlock = getJumpDestInCurrentScope("return"); 594 595 Builder.SetInsertPoint(EntryBB); 596 597 // Emit subprogram debug descriptor. 598 if (CGDebugInfo *DI = getDebugInfo()) { 599 SmallVector<QualType, 16> ArgTypes; 600 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 601 i != e; ++i) { 602 ArgTypes.push_back((*i)->getType()); 603 } 604 605 QualType FnType = 606 getContext().getFunctionType(RetTy, ArgTypes, 607 FunctionProtoType::ExtProtoInfo()); 608 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder); 609 } 610 611 if (ShouldInstrumentFunction()) 612 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 613 614 if (CGM.getCodeGenOpts().InstrumentForProfiling) 615 EmitMCountInstrumentation(); 616 617 if (RetTy->isVoidType()) { 618 // Void type; nothing to return. 619 ReturnValue = nullptr; 620 621 // Count the implicit return. 622 if (!endsWithReturn(D)) 623 ++NumReturnExprs; 624 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 625 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 626 // Indirect aggregate return; emit returned value directly into sret slot. 627 // This reduces code size, and affects correctness in C++. 628 auto AI = CurFn->arg_begin(); 629 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 630 ++AI; 631 ReturnValue = AI; 632 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 633 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 634 // Load the sret pointer from the argument struct and return into that. 635 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 636 llvm::Function::arg_iterator EI = CurFn->arg_end(); 637 --EI; 638 llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx); 639 ReturnValue = Builder.CreateLoad(Addr, "agg.result"); 640 } else { 641 ReturnValue = CreateIRTemp(RetTy, "retval"); 642 643 // Tell the epilog emitter to autorelease the result. We do this 644 // now so that various specialized functions can suppress it 645 // during their IR-generation. 646 if (getLangOpts().ObjCAutoRefCount && 647 !CurFnInfo->isReturnsRetained() && 648 RetTy->isObjCRetainableType()) 649 AutoreleaseResult = true; 650 } 651 652 EmitStartEHSpec(CurCodeDecl); 653 654 PrologueCleanupDepth = EHStack.stable_begin(); 655 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 656 657 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 658 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 659 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 660 if (MD->getParent()->isLambda() && 661 MD->getOverloadedOperator() == OO_Call) { 662 // We're in a lambda; figure out the captures. 663 MD->getParent()->getCaptureFields(LambdaCaptureFields, 664 LambdaThisCaptureField); 665 if (LambdaThisCaptureField) { 666 // If this lambda captures this, load it. 667 LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 668 CXXThisValue = EmitLoadOfLValue(ThisLValue, 669 SourceLocation()).getScalarVal(); 670 } 671 } else { 672 // Not in a lambda; just use 'this' from the method. 673 // FIXME: Should we generate a new load for each use of 'this'? The 674 // fast register allocator would be happier... 675 CXXThisValue = CXXABIThisValue; 676 } 677 } 678 679 // If any of the arguments have a variably modified type, make sure to 680 // emit the type size. 681 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 682 i != e; ++i) { 683 const VarDecl *VD = *i; 684 685 // Dig out the type as written from ParmVarDecls; it's unclear whether 686 // the standard (C99 6.9.1p10) requires this, but we're following the 687 // precedent set by gcc. 688 QualType Ty; 689 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 690 Ty = PVD->getOriginalType(); 691 else 692 Ty = VD->getType(); 693 694 if (Ty->isVariablyModifiedType()) 695 EmitVariablyModifiedType(Ty); 696 } 697 // Emit a location at the end of the prologue. 698 if (CGDebugInfo *DI = getDebugInfo()) 699 DI->EmitLocation(Builder, StartLoc); 700 } 701 702 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args, 703 const Stmt *Body) { 704 RegionCounter Cnt = getPGORegionCounter(Body); 705 Cnt.beginRegion(Builder); 706 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 707 EmitCompoundStmtWithoutScope(*S); 708 else 709 EmitStmt(Body); 710 } 711 712 /// When instrumenting to collect profile data, the counts for some blocks 713 /// such as switch cases need to not include the fall-through counts, so 714 /// emit a branch around the instrumentation code. When not instrumenting, 715 /// this just calls EmitBlock(). 716 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 717 RegionCounter &Cnt) { 718 llvm::BasicBlock *SkipCountBB = nullptr; 719 if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) { 720 // When instrumenting for profiling, the fallthrough to certain 721 // statements needs to skip over the instrumentation code so that we 722 // get an accurate count. 723 SkipCountBB = createBasicBlock("skipcount"); 724 EmitBranch(SkipCountBB); 725 } 726 EmitBlock(BB); 727 Cnt.beginRegion(Builder, /*AddIncomingFallThrough=*/true); 728 if (SkipCountBB) 729 EmitBlock(SkipCountBB); 730 } 731 732 /// Tries to mark the given function nounwind based on the 733 /// non-existence of any throwing calls within it. We believe this is 734 /// lightweight enough to do at -O0. 735 static void TryMarkNoThrow(llvm::Function *F) { 736 // LLVM treats 'nounwind' on a function as part of the type, so we 737 // can't do this on functions that can be overwritten. 738 if (F->mayBeOverridden()) return; 739 740 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) 741 for (llvm::BasicBlock::iterator 742 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) 743 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) { 744 if (!Call->doesNotThrow()) 745 return; 746 } else if (isa<llvm::ResumeInst>(&*BI)) { 747 return; 748 } 749 F->setDoesNotThrow(); 750 } 751 752 static void EmitSizedDeallocationFunction(CodeGenFunction &CGF, 753 const FunctionDecl *UnsizedDealloc) { 754 // This is a weak discardable definition of the sized deallocation function. 755 CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage); 756 757 // Call the unsized deallocation function and forward the first argument 758 // unchanged. 759 llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc); 760 CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin()); 761 } 762 763 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 764 const CGFunctionInfo &FnInfo) { 765 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 766 767 // Check if we should generate debug info for this function. 768 if (FD->hasAttr<NoDebugAttr>()) 769 DebugInfo = nullptr; // disable debug info indefinitely for this function 770 771 FunctionArgList Args; 772 QualType ResTy = FD->getReturnType(); 773 774 CurGD = GD; 775 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 776 if (MD && MD->isInstance()) { 777 if (CGM.getCXXABI().HasThisReturn(GD)) 778 ResTy = MD->getThisType(getContext()); 779 CGM.getCXXABI().buildThisParam(*this, Args); 780 } 781 782 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 783 Args.push_back(FD->getParamDecl(i)); 784 785 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 786 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 787 788 SourceRange BodyRange; 789 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 790 CurEHLocation = BodyRange.getEnd(); 791 792 // Use the location of the start of the function to determine where 793 // the function definition is located. By default use the location 794 // of the declaration as the location for the subprogram. A function 795 // may lack a declaration in the source code if it is created by code 796 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 797 SourceLocation Loc; 798 if (FD) { 799 Loc = FD->getLocation(); 800 801 // If this is a function specialization then use the pattern body 802 // as the location for the function. 803 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 804 if (SpecDecl->hasBody(SpecDecl)) 805 Loc = SpecDecl->getLocation(); 806 } 807 808 // Emit the standard function prologue. 809 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 810 811 // Generate the body of the function. 812 PGO.assignRegionCounters(GD.getDecl(), CurFn); 813 if (isa<CXXDestructorDecl>(FD)) 814 EmitDestructorBody(Args); 815 else if (isa<CXXConstructorDecl>(FD)) 816 EmitConstructorBody(Args); 817 else if (getLangOpts().CUDA && 818 !CGM.getCodeGenOpts().CUDAIsDevice && 819 FD->hasAttr<CUDAGlobalAttr>()) 820 CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args); 821 else if (isa<CXXConversionDecl>(FD) && 822 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 823 // The lambda conversion to block pointer is special; the semantics can't be 824 // expressed in the AST, so IRGen needs to special-case it. 825 EmitLambdaToBlockPointerBody(Args); 826 } else if (isa<CXXMethodDecl>(FD) && 827 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 828 // The lambda static invoker function is special, because it forwards or 829 // clones the body of the function call operator (but is actually static). 830 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 831 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 832 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 833 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 834 // Implicit copy-assignment gets the same special treatment as implicit 835 // copy-constructors. 836 emitImplicitAssignmentOperatorBody(Args); 837 } else if (Stmt *Body = FD->getBody()) { 838 EmitFunctionBody(Args, Body); 839 } else if (FunctionDecl *UnsizedDealloc = 840 FD->getCorrespondingUnsizedGlobalDeallocationFunction()) { 841 // Global sized deallocation functions get an implicit weak definition if 842 // they don't have an explicit definition. 843 EmitSizedDeallocationFunction(*this, UnsizedDealloc); 844 } else 845 llvm_unreachable("no definition for emitted function"); 846 847 // C++11 [stmt.return]p2: 848 // Flowing off the end of a function [...] results in undefined behavior in 849 // a value-returning function. 850 // C11 6.9.1p12: 851 // If the '}' that terminates a function is reached, and the value of the 852 // function call is used by the caller, the behavior is undefined. 853 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && 854 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 855 if (SanOpts->Return) 856 EmitCheck(Builder.getFalse(), "missing_return", 857 EmitCheckSourceLocation(FD->getLocation()), 858 ArrayRef<llvm::Value *>(), CRK_Unrecoverable); 859 else if (CGM.getCodeGenOpts().OptimizationLevel == 0) 860 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap)); 861 Builder.CreateUnreachable(); 862 Builder.ClearInsertionPoint(); 863 } 864 865 // Emit the standard function epilogue. 866 FinishFunction(BodyRange.getEnd()); 867 868 // If we haven't marked the function nothrow through other means, do 869 // a quick pass now to see if we can. 870 if (!CurFn->doesNotThrow()) 871 TryMarkNoThrow(CurFn); 872 873 PGO.emitInstrumentationData(); 874 PGO.destroyRegionCounters(); 875 } 876 877 /// ContainsLabel - Return true if the statement contains a label in it. If 878 /// this statement is not executed normally, it not containing a label means 879 /// that we can just remove the code. 880 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 881 // Null statement, not a label! 882 if (!S) return false; 883 884 // If this is a label, we have to emit the code, consider something like: 885 // if (0) { ... foo: bar(); } goto foo; 886 // 887 // TODO: If anyone cared, we could track __label__'s, since we know that you 888 // can't jump to one from outside their declared region. 889 if (isa<LabelStmt>(S)) 890 return true; 891 892 // If this is a case/default statement, and we haven't seen a switch, we have 893 // to emit the code. 894 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 895 return true; 896 897 // If this is a switch statement, we want to ignore cases below it. 898 if (isa<SwitchStmt>(S)) 899 IgnoreCaseStmts = true; 900 901 // Scan subexpressions for verboten labels. 902 for (Stmt::const_child_range I = S->children(); I; ++I) 903 if (ContainsLabel(*I, IgnoreCaseStmts)) 904 return true; 905 906 return false; 907 } 908 909 /// containsBreak - Return true if the statement contains a break out of it. 910 /// If the statement (recursively) contains a switch or loop with a break 911 /// inside of it, this is fine. 912 bool CodeGenFunction::containsBreak(const Stmt *S) { 913 // Null statement, not a label! 914 if (!S) return false; 915 916 // If this is a switch or loop that defines its own break scope, then we can 917 // include it and anything inside of it. 918 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 919 isa<ForStmt>(S)) 920 return false; 921 922 if (isa<BreakStmt>(S)) 923 return true; 924 925 // Scan subexpressions for verboten breaks. 926 for (Stmt::const_child_range I = S->children(); I; ++I) 927 if (containsBreak(*I)) 928 return true; 929 930 return false; 931 } 932 933 934 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 935 /// to a constant, or if it does but contains a label, return false. If it 936 /// constant folds return true and set the boolean result in Result. 937 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 938 bool &ResultBool) { 939 llvm::APSInt ResultInt; 940 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt)) 941 return false; 942 943 ResultBool = ResultInt.getBoolValue(); 944 return true; 945 } 946 947 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 948 /// to a constant, or if it does but contains a label, return false. If it 949 /// constant folds return true and set the folded value. 950 bool CodeGenFunction:: 951 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) { 952 // FIXME: Rename and handle conversion of other evaluatable things 953 // to bool. 954 llvm::APSInt Int; 955 if (!Cond->EvaluateAsInt(Int, getContext())) 956 return false; // Not foldable, not integer or not fully evaluatable. 957 958 if (CodeGenFunction::ContainsLabel(Cond)) 959 return false; // Contains a label. 960 961 ResultInt = Int; 962 return true; 963 } 964 965 966 967 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 968 /// statement) to the specified blocks. Based on the condition, this might try 969 /// to simplify the codegen of the conditional based on the branch. 970 /// 971 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 972 llvm::BasicBlock *TrueBlock, 973 llvm::BasicBlock *FalseBlock, 974 uint64_t TrueCount) { 975 Cond = Cond->IgnoreParens(); 976 977 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 978 979 // Handle X && Y in a condition. 980 if (CondBOp->getOpcode() == BO_LAnd) { 981 RegionCounter Cnt = getPGORegionCounter(CondBOp); 982 983 // If we have "1 && X", simplify the code. "0 && X" would have constant 984 // folded if the case was simple enough. 985 bool ConstantBool = false; 986 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 987 ConstantBool) { 988 // br(1 && X) -> br(X). 989 Cnt.beginRegion(Builder); 990 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 991 TrueCount); 992 } 993 994 // If we have "X && 1", simplify the code to use an uncond branch. 995 // "X && 0" would have been constant folded to 0. 996 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 997 ConstantBool) { 998 // br(X && 1) -> br(X). 999 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1000 TrueCount); 1001 } 1002 1003 // Emit the LHS as a conditional. If the LHS conditional is false, we 1004 // want to jump to the FalseBlock. 1005 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1006 // The counter tells us how often we evaluate RHS, and all of TrueCount 1007 // can be propagated to that branch. 1008 uint64_t RHSCount = Cnt.getCount(); 1009 1010 ConditionalEvaluation eval(*this); 1011 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1012 EmitBlock(LHSTrue); 1013 1014 // Any temporaries created here are conditional. 1015 Cnt.beginRegion(Builder); 1016 eval.begin(*this); 1017 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1018 eval.end(*this); 1019 1020 return; 1021 } 1022 1023 if (CondBOp->getOpcode() == BO_LOr) { 1024 RegionCounter Cnt = getPGORegionCounter(CondBOp); 1025 1026 // If we have "0 || X", simplify the code. "1 || X" would have constant 1027 // folded if the case was simple enough. 1028 bool ConstantBool = false; 1029 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1030 !ConstantBool) { 1031 // br(0 || X) -> br(X). 1032 Cnt.beginRegion(Builder); 1033 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1034 TrueCount); 1035 } 1036 1037 // If we have "X || 0", simplify the code to use an uncond branch. 1038 // "X || 1" would have been constant folded to 1. 1039 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1040 !ConstantBool) { 1041 // br(X || 0) -> br(X). 1042 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1043 TrueCount); 1044 } 1045 1046 // Emit the LHS as a conditional. If the LHS conditional is true, we 1047 // want to jump to the TrueBlock. 1048 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1049 // We have the count for entry to the RHS and for the whole expression 1050 // being true, so we can divy up True count between the short circuit and 1051 // the RHS. 1052 uint64_t LHSCount = Cnt.getParentCount() - Cnt.getCount(); 1053 uint64_t RHSCount = TrueCount - LHSCount; 1054 1055 ConditionalEvaluation eval(*this); 1056 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1057 EmitBlock(LHSFalse); 1058 1059 // Any temporaries created here are conditional. 1060 Cnt.beginRegion(Builder); 1061 eval.begin(*this); 1062 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1063 1064 eval.end(*this); 1065 1066 return; 1067 } 1068 } 1069 1070 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1071 // br(!x, t, f) -> br(x, f, t) 1072 if (CondUOp->getOpcode() == UO_LNot) { 1073 // Negate the count. 1074 uint64_t FalseCount = PGO.getCurrentRegionCount() - TrueCount; 1075 // Negate the condition and swap the destination blocks. 1076 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1077 FalseCount); 1078 } 1079 } 1080 1081 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1082 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1083 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1084 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1085 1086 RegionCounter Cnt = getPGORegionCounter(CondOp); 1087 ConditionalEvaluation cond(*this); 1088 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, Cnt.getCount()); 1089 1090 // When computing PGO branch weights, we only know the overall count for 1091 // the true block. This code is essentially doing tail duplication of the 1092 // naive code-gen, introducing new edges for which counts are not 1093 // available. Divide the counts proportionally between the LHS and RHS of 1094 // the conditional operator. 1095 uint64_t LHSScaledTrueCount = 0; 1096 if (TrueCount) { 1097 double LHSRatio = Cnt.getCount() / (double) Cnt.getParentCount(); 1098 LHSScaledTrueCount = TrueCount * LHSRatio; 1099 } 1100 1101 cond.begin(*this); 1102 EmitBlock(LHSBlock); 1103 Cnt.beginRegion(Builder); 1104 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1105 LHSScaledTrueCount); 1106 cond.end(*this); 1107 1108 cond.begin(*this); 1109 EmitBlock(RHSBlock); 1110 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1111 TrueCount - LHSScaledTrueCount); 1112 cond.end(*this); 1113 1114 return; 1115 } 1116 1117 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1118 // Conditional operator handling can give us a throw expression as a 1119 // condition for a case like: 1120 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1121 // Fold this to: 1122 // br(c, throw x, br(y, t, f)) 1123 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1124 return; 1125 } 1126 1127 // Create branch weights based on the number of times we get here and the 1128 // number of times the condition should be true. 1129 uint64_t CurrentCount = std::max(PGO.getCurrentRegionCount(), TrueCount); 1130 llvm::MDNode *Weights = PGO.createBranchWeights(TrueCount, 1131 CurrentCount - TrueCount); 1132 1133 // Emit the code with the fully general case. 1134 llvm::Value *CondV = EvaluateExprAsBool(Cond); 1135 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights); 1136 } 1137 1138 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1139 /// specified stmt yet. 1140 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1141 CGM.ErrorUnsupported(S, Type); 1142 } 1143 1144 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 1145 /// variable-length array whose elements have a non-zero bit-pattern. 1146 /// 1147 /// \param baseType the inner-most element type of the array 1148 /// \param src - a char* pointing to the bit-pattern for a single 1149 /// base element of the array 1150 /// \param sizeInChars - the total size of the VLA, in chars 1151 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1152 llvm::Value *dest, llvm::Value *src, 1153 llvm::Value *sizeInChars) { 1154 std::pair<CharUnits,CharUnits> baseSizeAndAlign 1155 = CGF.getContext().getTypeInfoInChars(baseType); 1156 1157 CGBuilderTy &Builder = CGF.Builder; 1158 1159 llvm::Value *baseSizeInChars 1160 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity()); 1161 1162 llvm::Type *i8p = Builder.getInt8PtrTy(); 1163 1164 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin"); 1165 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end"); 1166 1167 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1168 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1169 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1170 1171 // Make a loop over the VLA. C99 guarantees that the VLA element 1172 // count must be nonzero. 1173 CGF.EmitBlock(loopBB); 1174 1175 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur"); 1176 cur->addIncoming(begin, originBB); 1177 1178 // memcpy the individual element bit-pattern. 1179 Builder.CreateMemCpy(cur, src, baseSizeInChars, 1180 baseSizeAndAlign.second.getQuantity(), 1181 /*volatile*/ false); 1182 1183 // Go to the next element. 1184 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next"); 1185 1186 // Leave if that's the end of the VLA. 1187 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1188 Builder.CreateCondBr(done, contBB, loopBB); 1189 cur->addIncoming(next, loopBB); 1190 1191 CGF.EmitBlock(contBB); 1192 } 1193 1194 void 1195 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 1196 // Ignore empty classes in C++. 1197 if (getLangOpts().CPlusPlus) { 1198 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1199 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1200 return; 1201 } 1202 } 1203 1204 // Cast the dest ptr to the appropriate i8 pointer type. 1205 unsigned DestAS = 1206 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 1207 llvm::Type *BP = Builder.getInt8PtrTy(DestAS); 1208 if (DestPtr->getType() != BP) 1209 DestPtr = Builder.CreateBitCast(DestPtr, BP); 1210 1211 // Get size and alignment info for this aggregate. 1212 std::pair<CharUnits, CharUnits> TypeInfo = 1213 getContext().getTypeInfoInChars(Ty); 1214 CharUnits Size = TypeInfo.first; 1215 CharUnits Align = TypeInfo.second; 1216 1217 llvm::Value *SizeVal; 1218 const VariableArrayType *vla; 1219 1220 // Don't bother emitting a zero-byte memset. 1221 if (Size.isZero()) { 1222 // But note that getTypeInfo returns 0 for a VLA. 1223 if (const VariableArrayType *vlaType = 1224 dyn_cast_or_null<VariableArrayType>( 1225 getContext().getAsArrayType(Ty))) { 1226 QualType eltType; 1227 llvm::Value *numElts; 1228 std::tie(numElts, eltType) = getVLASize(vlaType); 1229 1230 SizeVal = numElts; 1231 CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 1232 if (!eltSize.isOne()) 1233 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1234 vla = vlaType; 1235 } else { 1236 return; 1237 } 1238 } else { 1239 SizeVal = CGM.getSize(Size); 1240 vla = nullptr; 1241 } 1242 1243 // If the type contains a pointer to data member we can't memset it to zero. 1244 // Instead, create a null constant and copy it to the destination. 1245 // TODO: there are other patterns besides zero that we can usefully memset, 1246 // like -1, which happens to be the pattern used by member-pointers. 1247 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1248 // For a VLA, emit a single element, then splat that over the VLA. 1249 if (vla) Ty = getContext().getBaseElementType(vla); 1250 1251 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1252 1253 llvm::GlobalVariable *NullVariable = 1254 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1255 /*isConstant=*/true, 1256 llvm::GlobalVariable::PrivateLinkage, 1257 NullConstant, Twine()); 1258 llvm::Value *SrcPtr = 1259 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 1260 1261 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1262 1263 // Get and call the appropriate llvm.memcpy overload. 1264 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false); 1265 return; 1266 } 1267 1268 // Otherwise, just memset the whole thing to zero. This is legal 1269 // because in LLVM, all default initializers (other than the ones we just 1270 // handled above) are guaranteed to have a bit pattern of all zeros. 1271 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, 1272 Align.getQuantity(), false); 1273 } 1274 1275 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1276 // Make sure that there is a block for the indirect goto. 1277 if (!IndirectBranch) 1278 GetIndirectGotoBlock(); 1279 1280 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1281 1282 // Make sure the indirect branch includes all of the address-taken blocks. 1283 IndirectBranch->addDestination(BB); 1284 return llvm::BlockAddress::get(CurFn, BB); 1285 } 1286 1287 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1288 // If we already made the indirect branch for indirect goto, return its block. 1289 if (IndirectBranch) return IndirectBranch->getParent(); 1290 1291 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 1292 1293 // Create the PHI node that indirect gotos will add entries to. 1294 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1295 "indirect.goto.dest"); 1296 1297 // Create the indirect branch instruction. 1298 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1299 return IndirectBranch->getParent(); 1300 } 1301 1302 /// Computes the length of an array in elements, as well as the base 1303 /// element type and a properly-typed first element pointer. 1304 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1305 QualType &baseType, 1306 llvm::Value *&addr) { 1307 const ArrayType *arrayType = origArrayType; 1308 1309 // If it's a VLA, we have to load the stored size. Note that 1310 // this is the size of the VLA in bytes, not its size in elements. 1311 llvm::Value *numVLAElements = nullptr; 1312 if (isa<VariableArrayType>(arrayType)) { 1313 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 1314 1315 // Walk into all VLAs. This doesn't require changes to addr, 1316 // which has type T* where T is the first non-VLA element type. 1317 do { 1318 QualType elementType = arrayType->getElementType(); 1319 arrayType = getContext().getAsArrayType(elementType); 1320 1321 // If we only have VLA components, 'addr' requires no adjustment. 1322 if (!arrayType) { 1323 baseType = elementType; 1324 return numVLAElements; 1325 } 1326 } while (isa<VariableArrayType>(arrayType)); 1327 1328 // We get out here only if we find a constant array type 1329 // inside the VLA. 1330 } 1331 1332 // We have some number of constant-length arrays, so addr should 1333 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1334 // down to the first element of addr. 1335 SmallVector<llvm::Value*, 8> gepIndices; 1336 1337 // GEP down to the array type. 1338 llvm::ConstantInt *zero = Builder.getInt32(0); 1339 gepIndices.push_back(zero); 1340 1341 uint64_t countFromCLAs = 1; 1342 QualType eltType; 1343 1344 llvm::ArrayType *llvmArrayType = 1345 dyn_cast<llvm::ArrayType>( 1346 cast<llvm::PointerType>(addr->getType())->getElementType()); 1347 while (llvmArrayType) { 1348 assert(isa<ConstantArrayType>(arrayType)); 1349 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1350 == llvmArrayType->getNumElements()); 1351 1352 gepIndices.push_back(zero); 1353 countFromCLAs *= llvmArrayType->getNumElements(); 1354 eltType = arrayType->getElementType(); 1355 1356 llvmArrayType = 1357 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1358 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1359 assert((!llvmArrayType || arrayType) && 1360 "LLVM and Clang types are out-of-synch"); 1361 } 1362 1363 if (arrayType) { 1364 // From this point onwards, the Clang array type has been emitted 1365 // as some other type (probably a packed struct). Compute the array 1366 // size, and just emit the 'begin' expression as a bitcast. 1367 while (arrayType) { 1368 countFromCLAs *= 1369 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1370 eltType = arrayType->getElementType(); 1371 arrayType = getContext().getAsArrayType(eltType); 1372 } 1373 1374 unsigned AddressSpace = addr->getType()->getPointerAddressSpace(); 1375 llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace); 1376 addr = Builder.CreateBitCast(addr, BaseType, "array.begin"); 1377 } else { 1378 // Create the actual GEP. 1379 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin"); 1380 } 1381 1382 baseType = eltType; 1383 1384 llvm::Value *numElements 1385 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1386 1387 // If we had any VLA dimensions, factor them in. 1388 if (numVLAElements) 1389 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1390 1391 return numElements; 1392 } 1393 1394 std::pair<llvm::Value*, QualType> 1395 CodeGenFunction::getVLASize(QualType type) { 1396 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1397 assert(vla && "type was not a variable array type!"); 1398 return getVLASize(vla); 1399 } 1400 1401 std::pair<llvm::Value*, QualType> 1402 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1403 // The number of elements so far; always size_t. 1404 llvm::Value *numElements = nullptr; 1405 1406 QualType elementType; 1407 do { 1408 elementType = type->getElementType(); 1409 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1410 assert(vlaSize && "no size for VLA!"); 1411 assert(vlaSize->getType() == SizeTy); 1412 1413 if (!numElements) { 1414 numElements = vlaSize; 1415 } else { 1416 // It's undefined behavior if this wraps around, so mark it that way. 1417 // FIXME: Teach -fsanitize=undefined to trap this. 1418 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1419 } 1420 } while ((type = getContext().getAsVariableArrayType(elementType))); 1421 1422 return std::pair<llvm::Value*,QualType>(numElements, elementType); 1423 } 1424 1425 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1426 assert(type->isVariablyModifiedType() && 1427 "Must pass variably modified type to EmitVLASizes!"); 1428 1429 EnsureInsertPoint(); 1430 1431 // We're going to walk down into the type and look for VLA 1432 // expressions. 1433 do { 1434 assert(type->isVariablyModifiedType()); 1435 1436 const Type *ty = type.getTypePtr(); 1437 switch (ty->getTypeClass()) { 1438 1439 #define TYPE(Class, Base) 1440 #define ABSTRACT_TYPE(Class, Base) 1441 #define NON_CANONICAL_TYPE(Class, Base) 1442 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1443 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1444 #include "clang/AST/TypeNodes.def" 1445 llvm_unreachable("unexpected dependent type!"); 1446 1447 // These types are never variably-modified. 1448 case Type::Builtin: 1449 case Type::Complex: 1450 case Type::Vector: 1451 case Type::ExtVector: 1452 case Type::Record: 1453 case Type::Enum: 1454 case Type::Elaborated: 1455 case Type::TemplateSpecialization: 1456 case Type::ObjCObject: 1457 case Type::ObjCInterface: 1458 case Type::ObjCObjectPointer: 1459 llvm_unreachable("type class is never variably-modified!"); 1460 1461 case Type::Adjusted: 1462 type = cast<AdjustedType>(ty)->getAdjustedType(); 1463 break; 1464 1465 case Type::Decayed: 1466 type = cast<DecayedType>(ty)->getPointeeType(); 1467 break; 1468 1469 case Type::Pointer: 1470 type = cast<PointerType>(ty)->getPointeeType(); 1471 break; 1472 1473 case Type::BlockPointer: 1474 type = cast<BlockPointerType>(ty)->getPointeeType(); 1475 break; 1476 1477 case Type::LValueReference: 1478 case Type::RValueReference: 1479 type = cast<ReferenceType>(ty)->getPointeeType(); 1480 break; 1481 1482 case Type::MemberPointer: 1483 type = cast<MemberPointerType>(ty)->getPointeeType(); 1484 break; 1485 1486 case Type::ConstantArray: 1487 case Type::IncompleteArray: 1488 // Losing element qualification here is fine. 1489 type = cast<ArrayType>(ty)->getElementType(); 1490 break; 1491 1492 case Type::VariableArray: { 1493 // Losing element qualification here is fine. 1494 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1495 1496 // Unknown size indication requires no size computation. 1497 // Otherwise, evaluate and record it. 1498 if (const Expr *size = vat->getSizeExpr()) { 1499 // It's possible that we might have emitted this already, 1500 // e.g. with a typedef and a pointer to it. 1501 llvm::Value *&entry = VLASizeMap[size]; 1502 if (!entry) { 1503 llvm::Value *Size = EmitScalarExpr(size); 1504 1505 // C11 6.7.6.2p5: 1506 // If the size is an expression that is not an integer constant 1507 // expression [...] each time it is evaluated it shall have a value 1508 // greater than zero. 1509 if (SanOpts->VLABound && 1510 size->getType()->isSignedIntegerType()) { 1511 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 1512 llvm::Constant *StaticArgs[] = { 1513 EmitCheckSourceLocation(size->getLocStart()), 1514 EmitCheckTypeDescriptor(size->getType()) 1515 }; 1516 EmitCheck(Builder.CreateICmpSGT(Size, Zero), 1517 "vla_bound_not_positive", StaticArgs, Size, 1518 CRK_Recoverable); 1519 } 1520 1521 // Always zexting here would be wrong if it weren't 1522 // undefined behavior to have a negative bound. 1523 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 1524 } 1525 } 1526 type = vat->getElementType(); 1527 break; 1528 } 1529 1530 case Type::FunctionProto: 1531 case Type::FunctionNoProto: 1532 type = cast<FunctionType>(ty)->getReturnType(); 1533 break; 1534 1535 case Type::Paren: 1536 case Type::TypeOf: 1537 case Type::UnaryTransform: 1538 case Type::Attributed: 1539 case Type::SubstTemplateTypeParm: 1540 case Type::PackExpansion: 1541 // Keep walking after single level desugaring. 1542 type = type.getSingleStepDesugaredType(getContext()); 1543 break; 1544 1545 case Type::Typedef: 1546 case Type::Decltype: 1547 case Type::Auto: 1548 // Stop walking: nothing to do. 1549 return; 1550 1551 case Type::TypeOfExpr: 1552 // Stop walking: emit typeof expression. 1553 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1554 return; 1555 1556 case Type::Atomic: 1557 type = cast<AtomicType>(ty)->getValueType(); 1558 break; 1559 } 1560 } while (type->isVariablyModifiedType()); 1561 } 1562 1563 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 1564 if (getContext().getBuiltinVaListType()->isArrayType()) 1565 return EmitScalarExpr(E); 1566 return EmitLValue(E).getAddress(); 1567 } 1568 1569 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1570 llvm::Constant *Init) { 1571 assert (Init && "Invalid DeclRefExpr initializer!"); 1572 if (CGDebugInfo *Dbg = getDebugInfo()) 1573 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1574 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1575 } 1576 1577 CodeGenFunction::PeepholeProtection 1578 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 1579 // At the moment, the only aggressive peephole we do in IR gen 1580 // is trunc(zext) folding, but if we add more, we can easily 1581 // extend this protection. 1582 1583 if (!rvalue.isScalar()) return PeepholeProtection(); 1584 llvm::Value *value = rvalue.getScalarVal(); 1585 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 1586 1587 // Just make an extra bitcast. 1588 assert(HaveInsertPoint()); 1589 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 1590 Builder.GetInsertBlock()); 1591 1592 PeepholeProtection protection; 1593 protection.Inst = inst; 1594 return protection; 1595 } 1596 1597 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 1598 if (!protection.Inst) return; 1599 1600 // In theory, we could try to duplicate the peepholes now, but whatever. 1601 protection.Inst->eraseFromParent(); 1602 } 1603 1604 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 1605 llvm::Value *AnnotatedVal, 1606 StringRef AnnotationStr, 1607 SourceLocation Location) { 1608 llvm::Value *Args[4] = { 1609 AnnotatedVal, 1610 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 1611 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 1612 CGM.EmitAnnotationLineNo(Location) 1613 }; 1614 return Builder.CreateCall(AnnotationFn, Args); 1615 } 1616 1617 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 1618 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1619 // FIXME We create a new bitcast for every annotation because that's what 1620 // llvm-gcc was doing. 1621 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1622 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 1623 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 1624 I->getAnnotation(), D->getLocation()); 1625 } 1626 1627 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 1628 llvm::Value *V) { 1629 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1630 llvm::Type *VTy = V->getType(); 1631 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 1632 CGM.Int8PtrTy); 1633 1634 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 1635 // FIXME Always emit the cast inst so we can differentiate between 1636 // annotation on the first field of a struct and annotation on the struct 1637 // itself. 1638 if (VTy != CGM.Int8PtrTy) 1639 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 1640 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 1641 V = Builder.CreateBitCast(V, VTy); 1642 } 1643 1644 return V; 1645 } 1646 1647 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 1648 1649 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 1650 const llvm::Twine &Name, 1651 llvm::BasicBlock *BB, 1652 llvm::BasicBlock::iterator InsertPt) const { 1653 LoopStack.InsertHelper(I); 1654 } 1655 1656 template <bool PreserveNames> 1657 void CGBuilderInserter<PreserveNames>::InsertHelper( 1658 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1659 llvm::BasicBlock::iterator InsertPt) const { 1660 llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB, 1661 InsertPt); 1662 if (CGF) 1663 CGF->InsertHelper(I, Name, BB, InsertPt); 1664 } 1665 1666 #ifdef NDEBUG 1667 #define PreserveNames false 1668 #else 1669 #define PreserveNames true 1670 #endif 1671 template void CGBuilderInserter<PreserveNames>::InsertHelper( 1672 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1673 llvm::BasicBlock::iterator InsertPt) const; 1674 #undef PreserveNames 1675