1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This coordinates the per-function state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenFunction.h" 14 #include "CGBlocks.h" 15 #include "CGCleanup.h" 16 #include "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGDebugInfo.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "TargetInfo.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/ASTLambda.h" 25 #include "clang/AST/Decl.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/AST/StmtObjC.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/CodeGenOptions.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/CodeGen/CGFunctionInfo.h" 33 #include "clang/Frontend/FrontendDiagnostic.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/FPEnv.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/MDBuilder.h" 40 #include "llvm/IR/Operator.h" 41 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 42 using namespace clang; 43 using namespace CodeGen; 44 45 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 46 /// markers. 47 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 48 const LangOptions &LangOpts) { 49 if (CGOpts.DisableLifetimeMarkers) 50 return false; 51 52 // Sanitizers may use markers. 53 if (CGOpts.SanitizeAddressUseAfterScope || 54 LangOpts.Sanitize.has(SanitizerKind::HWAddress) || 55 LangOpts.Sanitize.has(SanitizerKind::Memory)) 56 return true; 57 58 // For now, only in optimized builds. 59 return CGOpts.OptimizationLevel != 0; 60 } 61 62 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 63 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 64 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 65 CGBuilderInserterTy(this)), 66 SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()), 67 PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers( 68 CGM.getCodeGenOpts(), CGM.getLangOpts())) { 69 if (!suppressNewContext) 70 CGM.getCXXABI().getMangleContext().startNewFunction(); 71 72 llvm::FastMathFlags FMF; 73 if (CGM.getLangOpts().FastMath) 74 FMF.setFast(); 75 if (CGM.getLangOpts().FiniteMathOnly) { 76 FMF.setNoNaNs(); 77 FMF.setNoInfs(); 78 } 79 if (CGM.getCodeGenOpts().NoNaNsFPMath) { 80 FMF.setNoNaNs(); 81 } 82 if (CGM.getCodeGenOpts().NoSignedZeros) { 83 FMF.setNoSignedZeros(); 84 } 85 if (CGM.getCodeGenOpts().ReciprocalMath) { 86 FMF.setAllowReciprocal(); 87 } 88 if (CGM.getCodeGenOpts().Reassociate) { 89 FMF.setAllowReassoc(); 90 } 91 Builder.setFastMathFlags(FMF); 92 SetFPModel(); 93 } 94 95 CodeGenFunction::~CodeGenFunction() { 96 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 97 98 // If there are any unclaimed block infos, go ahead and destroy them 99 // now. This can happen if IR-gen gets clever and skips evaluating 100 // something. 101 if (FirstBlockInfo) 102 destroyBlockInfos(FirstBlockInfo); 103 104 if (getLangOpts().OpenMP && CurFn) 105 CGM.getOpenMPRuntime().functionFinished(*this); 106 } 107 108 // Map the LangOption for rounding mode into 109 // the corresponding enum in the IR. 110 static llvm::fp::RoundingMode ToConstrainedRoundingMD( 111 LangOptions::FPRoundingModeKind Kind) { 112 113 switch (Kind) { 114 case LangOptions::FPR_ToNearest: return llvm::fp::rmToNearest; 115 case LangOptions::FPR_Downward: return llvm::fp::rmDownward; 116 case LangOptions::FPR_Upward: return llvm::fp::rmUpward; 117 case LangOptions::FPR_TowardZero: return llvm::fp::rmTowardZero; 118 case LangOptions::FPR_Dynamic: return llvm::fp::rmDynamic; 119 } 120 llvm_unreachable("Unsupported FP RoundingMode"); 121 } 122 123 // Map the LangOption for exception behavior into 124 // the corresponding enum in the IR. 125 static llvm::fp::ExceptionBehavior ToConstrainedExceptMD( 126 LangOptions::FPExceptionModeKind Kind) { 127 128 switch (Kind) { 129 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore; 130 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap; 131 case LangOptions::FPE_Strict: return llvm::fp::ebStrict; 132 } 133 llvm_unreachable("Unsupported FP Exception Behavior"); 134 } 135 136 void CodeGenFunction::SetFPModel() { 137 auto fpRoundingMode = ToConstrainedRoundingMD( 138 getLangOpts().getFPRoundingMode()); 139 auto fpExceptionBehavior = ToConstrainedExceptMD( 140 getLangOpts().getFPExceptionMode()); 141 142 if (fpExceptionBehavior == llvm::fp::ebIgnore && 143 fpRoundingMode == llvm::fp::rmToNearest) 144 // Constrained intrinsics are not used. 145 ; 146 else { 147 Builder.setIsFPConstrained(true); 148 Builder.setDefaultConstrainedRounding(fpRoundingMode); 149 Builder.setDefaultConstrainedExcept(fpExceptionBehavior); 150 } 151 } 152 153 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 154 LValueBaseInfo *BaseInfo, 155 TBAAAccessInfo *TBAAInfo) { 156 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 157 /* forPointeeType= */ true); 158 } 159 160 CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 161 LValueBaseInfo *BaseInfo, 162 TBAAAccessInfo *TBAAInfo, 163 bool forPointeeType) { 164 if (TBAAInfo) 165 *TBAAInfo = CGM.getTBAAAccessInfo(T); 166 167 // Honor alignment typedef attributes even on incomplete types. 168 // We also honor them straight for C++ class types, even as pointees; 169 // there's an expressivity gap here. 170 if (auto TT = T->getAs<TypedefType>()) { 171 if (auto Align = TT->getDecl()->getMaxAlignment()) { 172 if (BaseInfo) 173 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 174 return getContext().toCharUnitsFromBits(Align); 175 } 176 } 177 178 if (BaseInfo) 179 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 180 181 CharUnits Alignment; 182 if (T->isIncompleteType()) { 183 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 184 } else { 185 // For C++ class pointees, we don't know whether we're pointing at a 186 // base or a complete object, so we generally need to use the 187 // non-virtual alignment. 188 const CXXRecordDecl *RD; 189 if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 190 Alignment = CGM.getClassPointerAlignment(RD); 191 } else { 192 Alignment = getContext().getTypeAlignInChars(T); 193 if (T.getQualifiers().hasUnaligned()) 194 Alignment = CharUnits::One(); 195 } 196 197 // Cap to the global maximum type alignment unless the alignment 198 // was somehow explicit on the type. 199 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 200 if (Alignment.getQuantity() > MaxAlign && 201 !getContext().isAlignmentRequired(T)) 202 Alignment = CharUnits::fromQuantity(MaxAlign); 203 } 204 } 205 return Alignment; 206 } 207 208 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 209 LValueBaseInfo BaseInfo; 210 TBAAAccessInfo TBAAInfo; 211 CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo); 212 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo, 213 TBAAInfo); 214 } 215 216 /// Given a value of type T* that may not be to a complete object, 217 /// construct an l-value with the natural pointee alignment of T. 218 LValue 219 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 220 LValueBaseInfo BaseInfo; 221 TBAAAccessInfo TBAAInfo; 222 CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, 223 /* forPointeeType= */ true); 224 return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo); 225 } 226 227 228 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 229 return CGM.getTypes().ConvertTypeForMem(T); 230 } 231 232 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 233 return CGM.getTypes().ConvertType(T); 234 } 235 236 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 237 type = type.getCanonicalType(); 238 while (true) { 239 switch (type->getTypeClass()) { 240 #define TYPE(name, parent) 241 #define ABSTRACT_TYPE(name, parent) 242 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 243 #define DEPENDENT_TYPE(name, parent) case Type::name: 244 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 245 #include "clang/AST/TypeNodes.inc" 246 llvm_unreachable("non-canonical or dependent type in IR-generation"); 247 248 case Type::Auto: 249 case Type::DeducedTemplateSpecialization: 250 llvm_unreachable("undeduced type in IR-generation"); 251 252 // Various scalar types. 253 case Type::Builtin: 254 case Type::Pointer: 255 case Type::BlockPointer: 256 case Type::LValueReference: 257 case Type::RValueReference: 258 case Type::MemberPointer: 259 case Type::Vector: 260 case Type::ExtVector: 261 case Type::FunctionProto: 262 case Type::FunctionNoProto: 263 case Type::Enum: 264 case Type::ObjCObjectPointer: 265 case Type::Pipe: 266 return TEK_Scalar; 267 268 // Complexes. 269 case Type::Complex: 270 return TEK_Complex; 271 272 // Arrays, records, and Objective-C objects. 273 case Type::ConstantArray: 274 case Type::IncompleteArray: 275 case Type::VariableArray: 276 case Type::Record: 277 case Type::ObjCObject: 278 case Type::ObjCInterface: 279 return TEK_Aggregate; 280 281 // We operate on atomic values according to their underlying type. 282 case Type::Atomic: 283 type = cast<AtomicType>(type)->getValueType(); 284 continue; 285 } 286 llvm_unreachable("unknown type kind!"); 287 } 288 } 289 290 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 291 // For cleanliness, we try to avoid emitting the return block for 292 // simple cases. 293 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 294 295 if (CurBB) { 296 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 297 298 // We have a valid insert point, reuse it if it is empty or there are no 299 // explicit jumps to the return block. 300 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 301 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 302 delete ReturnBlock.getBlock(); 303 ReturnBlock = JumpDest(); 304 } else 305 EmitBlock(ReturnBlock.getBlock()); 306 return llvm::DebugLoc(); 307 } 308 309 // Otherwise, if the return block is the target of a single direct 310 // branch then we can just put the code in that block instead. This 311 // cleans up functions which started with a unified return block. 312 if (ReturnBlock.getBlock()->hasOneUse()) { 313 llvm::BranchInst *BI = 314 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 315 if (BI && BI->isUnconditional() && 316 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 317 // Record/return the DebugLoc of the simple 'return' expression to be used 318 // later by the actual 'ret' instruction. 319 llvm::DebugLoc Loc = BI->getDebugLoc(); 320 Builder.SetInsertPoint(BI->getParent()); 321 BI->eraseFromParent(); 322 delete ReturnBlock.getBlock(); 323 ReturnBlock = JumpDest(); 324 return Loc; 325 } 326 } 327 328 // FIXME: We are at an unreachable point, there is no reason to emit the block 329 // unless it has uses. However, we still need a place to put the debug 330 // region.end for now. 331 332 EmitBlock(ReturnBlock.getBlock()); 333 return llvm::DebugLoc(); 334 } 335 336 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 337 if (!BB) return; 338 if (!BB->use_empty()) 339 return CGF.CurFn->getBasicBlockList().push_back(BB); 340 delete BB; 341 } 342 343 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 344 assert(BreakContinueStack.empty() && 345 "mismatched push/pop in break/continue stack!"); 346 347 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 348 && NumSimpleReturnExprs == NumReturnExprs 349 && ReturnBlock.getBlock()->use_empty(); 350 // Usually the return expression is evaluated before the cleanup 351 // code. If the function contains only a simple return statement, 352 // such as a constant, the location before the cleanup code becomes 353 // the last useful breakpoint in the function, because the simple 354 // return expression will be evaluated after the cleanup code. To be 355 // safe, set the debug location for cleanup code to the location of 356 // the return statement. Otherwise the cleanup code should be at the 357 // end of the function's lexical scope. 358 // 359 // If there are multiple branches to the return block, the branch 360 // instructions will get the location of the return statements and 361 // all will be fine. 362 if (CGDebugInfo *DI = getDebugInfo()) { 363 if (OnlySimpleReturnStmts) 364 DI->EmitLocation(Builder, LastStopPoint); 365 else 366 DI->EmitLocation(Builder, EndLoc); 367 } 368 369 // Pop any cleanups that might have been associated with the 370 // parameters. Do this in whatever block we're currently in; it's 371 // important to do this before we enter the return block or return 372 // edges will be *really* confused. 373 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 374 bool HasOnlyLifetimeMarkers = 375 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 376 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 377 if (HasCleanups) { 378 // Make sure the line table doesn't jump back into the body for 379 // the ret after it's been at EndLoc. 380 if (CGDebugInfo *DI = getDebugInfo()) 381 if (OnlySimpleReturnStmts) 382 DI->EmitLocation(Builder, EndLoc); 383 384 PopCleanupBlocks(PrologueCleanupDepth); 385 } 386 387 // Emit function epilog (to return). 388 llvm::DebugLoc Loc = EmitReturnBlock(); 389 390 if (ShouldInstrumentFunction()) { 391 if (CGM.getCodeGenOpts().InstrumentFunctions) 392 CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit"); 393 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 394 CurFn->addFnAttr("instrument-function-exit-inlined", 395 "__cyg_profile_func_exit"); 396 } 397 398 // Emit debug descriptor for function end. 399 if (CGDebugInfo *DI = getDebugInfo()) 400 DI->EmitFunctionEnd(Builder, CurFn); 401 402 // Reset the debug location to that of the simple 'return' expression, if any 403 // rather than that of the end of the function's scope '}'. 404 ApplyDebugLocation AL(*this, Loc); 405 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 406 EmitEndEHSpec(CurCodeDecl); 407 408 assert(EHStack.empty() && 409 "did not remove all scopes from cleanup stack!"); 410 411 // If someone did an indirect goto, emit the indirect goto block at the end of 412 // the function. 413 if (IndirectBranch) { 414 EmitBlock(IndirectBranch->getParent()); 415 Builder.ClearInsertionPoint(); 416 } 417 418 // If some of our locals escaped, insert a call to llvm.localescape in the 419 // entry block. 420 if (!EscapedLocals.empty()) { 421 // Invert the map from local to index into a simple vector. There should be 422 // no holes. 423 SmallVector<llvm::Value *, 4> EscapeArgs; 424 EscapeArgs.resize(EscapedLocals.size()); 425 for (auto &Pair : EscapedLocals) 426 EscapeArgs[Pair.second] = Pair.first; 427 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 428 &CGM.getModule(), llvm::Intrinsic::localescape); 429 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 430 } 431 432 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 433 llvm::Instruction *Ptr = AllocaInsertPt; 434 AllocaInsertPt = nullptr; 435 Ptr->eraseFromParent(); 436 437 // If someone took the address of a label but never did an indirect goto, we 438 // made a zero entry PHI node, which is illegal, zap it now. 439 if (IndirectBranch) { 440 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 441 if (PN->getNumIncomingValues() == 0) { 442 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 443 PN->eraseFromParent(); 444 } 445 } 446 447 EmitIfUsed(*this, EHResumeBlock); 448 EmitIfUsed(*this, TerminateLandingPad); 449 EmitIfUsed(*this, TerminateHandler); 450 EmitIfUsed(*this, UnreachableBlock); 451 452 for (const auto &FuncletAndParent : TerminateFunclets) 453 EmitIfUsed(*this, FuncletAndParent.second); 454 455 if (CGM.getCodeGenOpts().EmitDeclMetadata) 456 EmitDeclMetadata(); 457 458 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 459 I = DeferredReplacements.begin(), 460 E = DeferredReplacements.end(); 461 I != E; ++I) { 462 I->first->replaceAllUsesWith(I->second); 463 I->first->eraseFromParent(); 464 } 465 466 // Eliminate CleanupDestSlot alloca by replacing it with SSA values and 467 // PHIs if the current function is a coroutine. We don't do it for all 468 // functions as it may result in slight increase in numbers of instructions 469 // if compiled with no optimizations. We do it for coroutine as the lifetime 470 // of CleanupDestSlot alloca make correct coroutine frame building very 471 // difficult. 472 if (NormalCleanupDest.isValid() && isCoroutine()) { 473 llvm::DominatorTree DT(*CurFn); 474 llvm::PromoteMemToReg( 475 cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT); 476 NormalCleanupDest = Address::invalid(); 477 } 478 479 // Scan function arguments for vector width. 480 for (llvm::Argument &A : CurFn->args()) 481 if (auto *VT = dyn_cast<llvm::VectorType>(A.getType())) 482 LargestVectorWidth = std::max((uint64_t)LargestVectorWidth, 483 VT->getPrimitiveSizeInBits().getFixedSize()); 484 485 // Update vector width based on return type. 486 if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType())) 487 LargestVectorWidth = std::max((uint64_t)LargestVectorWidth, 488 VT->getPrimitiveSizeInBits().getFixedSize()); 489 490 // Add the required-vector-width attribute. This contains the max width from: 491 // 1. min-vector-width attribute used in the source program. 492 // 2. Any builtins used that have a vector width specified. 493 // 3. Values passed in and out of inline assembly. 494 // 4. Width of vector arguments and return types for this function. 495 // 5. Width of vector aguments and return types for functions called by this 496 // function. 497 CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth)); 498 499 // If we generated an unreachable return block, delete it now. 500 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) { 501 Builder.ClearInsertionPoint(); 502 ReturnBlock.getBlock()->eraseFromParent(); 503 } 504 if (ReturnValue.isValid()) { 505 auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer()); 506 if (RetAlloca && RetAlloca->use_empty()) { 507 RetAlloca->eraseFromParent(); 508 ReturnValue = Address::invalid(); 509 } 510 } 511 } 512 513 /// ShouldInstrumentFunction - Return true if the current function should be 514 /// instrumented with __cyg_profile_func_* calls 515 bool CodeGenFunction::ShouldInstrumentFunction() { 516 if (!CGM.getCodeGenOpts().InstrumentFunctions && 517 !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining && 518 !CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 519 return false; 520 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 521 return false; 522 return true; 523 } 524 525 /// ShouldXRayInstrument - Return true if the current function should be 526 /// instrumented with XRay nop sleds. 527 bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 528 return CGM.getCodeGenOpts().XRayInstrumentFunctions; 529 } 530 531 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to 532 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation. 533 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const { 534 return CGM.getCodeGenOpts().XRayInstrumentFunctions && 535 (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents || 536 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 537 XRayInstrKind::Custom); 538 } 539 540 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const { 541 return CGM.getCodeGenOpts().XRayInstrumentFunctions && 542 (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents || 543 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 544 XRayInstrKind::Typed); 545 } 546 547 llvm::Constant * 548 CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F, 549 llvm::Constant *Addr) { 550 // Addresses stored in prologue data can't require run-time fixups and must 551 // be PC-relative. Run-time fixups are undesirable because they necessitate 552 // writable text segments, which are unsafe. And absolute addresses are 553 // undesirable because they break PIE mode. 554 555 // Add a layer of indirection through a private global. Taking its address 556 // won't result in a run-time fixup, even if Addr has linkonce_odr linkage. 557 auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(), 558 /*isConstant=*/true, 559 llvm::GlobalValue::PrivateLinkage, Addr); 560 561 // Create a PC-relative address. 562 auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy); 563 auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy); 564 auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt); 565 return (IntPtrTy == Int32Ty) 566 ? PCRelAsInt 567 : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty); 568 } 569 570 llvm::Value * 571 CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F, 572 llvm::Value *EncodedAddr) { 573 // Reconstruct the address of the global. 574 auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy); 575 auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int"); 576 auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int"); 577 auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr"); 578 579 // Load the original pointer through the global. 580 return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()), 581 "decoded_addr"); 582 } 583 584 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 585 llvm::Function *Fn) 586 { 587 if (!FD->hasAttr<OpenCLKernelAttr>()) 588 return; 589 590 llvm::LLVMContext &Context = getLLVMContext(); 591 592 CGM.GenOpenCLArgMetadata(Fn, FD, this); 593 594 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 595 QualType HintQTy = A->getTypeHint(); 596 const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>(); 597 bool IsSignedInteger = 598 HintQTy->isSignedIntegerType() || 599 (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType()); 600 llvm::Metadata *AttrMDArgs[] = { 601 llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 602 CGM.getTypes().ConvertType(A->getTypeHint()))), 603 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 604 llvm::IntegerType::get(Context, 32), 605 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))}; 606 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs)); 607 } 608 609 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 610 llvm::Metadata *AttrMDArgs[] = { 611 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 612 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 613 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 614 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs)); 615 } 616 617 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 618 llvm::Metadata *AttrMDArgs[] = { 619 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 620 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 621 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 622 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs)); 623 } 624 625 if (const OpenCLIntelReqdSubGroupSizeAttr *A = 626 FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 627 llvm::Metadata *AttrMDArgs[] = { 628 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))}; 629 Fn->setMetadata("intel_reqd_sub_group_size", 630 llvm::MDNode::get(Context, AttrMDArgs)); 631 } 632 } 633 634 /// Determine whether the function F ends with a return stmt. 635 static bool endsWithReturn(const Decl* F) { 636 const Stmt *Body = nullptr; 637 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 638 Body = FD->getBody(); 639 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 640 Body = OMD->getBody(); 641 642 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 643 auto LastStmt = CS->body_rbegin(); 644 if (LastStmt != CS->body_rend()) 645 return isa<ReturnStmt>(*LastStmt); 646 } 647 return false; 648 } 649 650 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) { 651 if (SanOpts.has(SanitizerKind::Thread)) { 652 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 653 Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 654 } 655 } 656 657 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) { 658 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 659 if (!MD || !MD->getDeclName().getAsIdentifierInfo() || 660 !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") || 661 (MD->getNumParams() != 1 && MD->getNumParams() != 2)) 662 return false; 663 664 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType()) 665 return false; 666 667 if (MD->getNumParams() == 2) { 668 auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>(); 669 if (!PT || !PT->isVoidPointerType() || 670 !PT->getPointeeType().isConstQualified()) 671 return false; 672 } 673 674 return true; 675 } 676 677 /// Return the UBSan prologue signature for \p FD if one is available. 678 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM, 679 const FunctionDecl *FD) { 680 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 681 if (!MD->isStatic()) 682 return nullptr; 683 return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM); 684 } 685 686 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 687 llvm::Function *Fn, 688 const CGFunctionInfo &FnInfo, 689 const FunctionArgList &Args, 690 SourceLocation Loc, 691 SourceLocation StartLoc) { 692 assert(!CurFn && 693 "Do not use a CodeGenFunction object for more than one function"); 694 695 const Decl *D = GD.getDecl(); 696 697 DidCallStackSave = false; 698 CurCodeDecl = D; 699 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 700 if (FD->usesSEHTry()) 701 CurSEHParent = FD; 702 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 703 FnRetTy = RetTy; 704 CurFn = Fn; 705 CurFnInfo = &FnInfo; 706 assert(CurFn->isDeclaration() && "Function already has body?"); 707 708 // If this function has been blacklisted for any of the enabled sanitizers, 709 // disable the sanitizer for the function. 710 do { 711 #define SANITIZER(NAME, ID) \ 712 if (SanOpts.empty()) \ 713 break; \ 714 if (SanOpts.has(SanitizerKind::ID)) \ 715 if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \ 716 SanOpts.set(SanitizerKind::ID, false); 717 718 #include "clang/Basic/Sanitizers.def" 719 #undef SANITIZER 720 } while (0); 721 722 if (D) { 723 // Apply the no_sanitize* attributes to SanOpts. 724 for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) { 725 SanitizerMask mask = Attr->getMask(); 726 SanOpts.Mask &= ~mask; 727 if (mask & SanitizerKind::Address) 728 SanOpts.set(SanitizerKind::KernelAddress, false); 729 if (mask & SanitizerKind::KernelAddress) 730 SanOpts.set(SanitizerKind::Address, false); 731 if (mask & SanitizerKind::HWAddress) 732 SanOpts.set(SanitizerKind::KernelHWAddress, false); 733 if (mask & SanitizerKind::KernelHWAddress) 734 SanOpts.set(SanitizerKind::HWAddress, false); 735 } 736 } 737 738 // Apply sanitizer attributes to the function. 739 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 740 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 741 if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress)) 742 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); 743 if (SanOpts.has(SanitizerKind::MemTag)) 744 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag); 745 if (SanOpts.has(SanitizerKind::Thread)) 746 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 747 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory)) 748 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 749 if (SanOpts.has(SanitizerKind::SafeStack)) 750 Fn->addFnAttr(llvm::Attribute::SafeStack); 751 if (SanOpts.has(SanitizerKind::ShadowCallStack)) 752 Fn->addFnAttr(llvm::Attribute::ShadowCallStack); 753 754 // Apply fuzzing attribute to the function. 755 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink)) 756 Fn->addFnAttr(llvm::Attribute::OptForFuzzing); 757 758 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 759 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time. 760 if (SanOpts.has(SanitizerKind::Thread)) { 761 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 762 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 763 if (OMD->getMethodFamily() == OMF_dealloc || 764 OMD->getMethodFamily() == OMF_initialize || 765 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 766 markAsIgnoreThreadCheckingAtRuntime(Fn); 767 } 768 } 769 } 770 771 // Ignore unrelated casts in STL allocate() since the allocator must cast 772 // from void* to T* before object initialization completes. Don't match on the 773 // namespace because not all allocators are in std:: 774 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 775 if (matchesStlAllocatorFn(D, getContext())) 776 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast; 777 } 778 779 // Ignore null checks in coroutine functions since the coroutines passes 780 // are not aware of how to move the extra UBSan instructions across the split 781 // coroutine boundaries. 782 if (D && SanOpts.has(SanitizerKind::Null)) 783 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 784 if (FD->getBody() && 785 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass) 786 SanOpts.Mask &= ~SanitizerKind::Null; 787 788 // Apply xray attributes to the function (as a string, for now) 789 if (D) { 790 if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) { 791 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 792 XRayInstrKind::Function)) { 793 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) 794 Fn->addFnAttr("function-instrument", "xray-always"); 795 if (XRayAttr->neverXRayInstrument()) 796 Fn->addFnAttr("function-instrument", "xray-never"); 797 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) 798 if (ShouldXRayInstrumentFunction()) 799 Fn->addFnAttr("xray-log-args", 800 llvm::utostr(LogArgs->getArgumentCount())); 801 } 802 } else { 803 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc)) 804 Fn->addFnAttr( 805 "xray-instruction-threshold", 806 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 807 } 808 } 809 810 // Add no-jump-tables value. 811 Fn->addFnAttr("no-jump-tables", 812 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables)); 813 814 // Add no-inline-line-tables value. 815 if (CGM.getCodeGenOpts().NoInlineLineTables) 816 Fn->addFnAttr("no-inline-line-tables"); 817 818 // Add profile-sample-accurate value. 819 if (CGM.getCodeGenOpts().ProfileSampleAccurate) 820 Fn->addFnAttr("profile-sample-accurate"); 821 822 if (D && D->hasAttr<CFICanonicalJumpTableAttr>()) 823 Fn->addFnAttr("cfi-canonical-jump-table"); 824 825 if (getLangOpts().OpenCL) { 826 // Add metadata for a kernel function. 827 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 828 EmitOpenCLKernelMetadata(FD, Fn); 829 } 830 831 // If we are checking function types, emit a function type signature as 832 // prologue data. 833 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 834 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 835 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) { 836 // Remove any (C++17) exception specifications, to allow calling e.g. a 837 // noexcept function through a non-noexcept pointer. 838 auto ProtoTy = 839 getContext().getFunctionTypeWithExceptionSpec(FD->getType(), 840 EST_None); 841 llvm::Constant *FTRTTIConst = 842 CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true); 843 llvm::Constant *FTRTTIConstEncoded = 844 EncodeAddrForUseInPrologue(Fn, FTRTTIConst); 845 llvm::Constant *PrologueStructElems[] = {PrologueSig, 846 FTRTTIConstEncoded}; 847 llvm::Constant *PrologueStructConst = 848 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 849 Fn->setPrologueData(PrologueStructConst); 850 } 851 } 852 } 853 854 // If we're checking nullability, we need to know whether we can check the 855 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl. 856 if (SanOpts.has(SanitizerKind::NullabilityReturn)) { 857 auto Nullability = FnRetTy->getNullability(getContext()); 858 if (Nullability && *Nullability == NullabilityKind::NonNull) { 859 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && 860 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>())) 861 RetValNullabilityPrecondition = 862 llvm::ConstantInt::getTrue(getLLVMContext()); 863 } 864 } 865 866 // If we're in C++ mode and the function name is "main", it is guaranteed 867 // to be norecurse by the standard (3.6.1.3 "The function main shall not be 868 // used within a program"). 869 if (getLangOpts().CPlusPlus) 870 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 871 if (FD->isMain()) 872 Fn->addFnAttr(llvm::Attribute::NoRecurse); 873 874 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 875 if (FD->usesFPIntrin()) 876 Fn->addFnAttr(llvm::Attribute::StrictFP); 877 878 // If a custom alignment is used, force realigning to this alignment on 879 // any main function which certainly will need it. 880 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 881 if ((FD->isMain() || FD->isMSVCRTEntryPoint()) && 882 CGM.getCodeGenOpts().StackAlignment) 883 Fn->addFnAttr("stackrealign"); 884 885 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 886 887 // Create a marker to make it easy to insert allocas into the entryblock 888 // later. Don't create this with the builder, because we don't want it 889 // folded. 890 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 891 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 892 893 ReturnBlock = getJumpDestInCurrentScope("return"); 894 895 Builder.SetInsertPoint(EntryBB); 896 897 // If we're checking the return value, allocate space for a pointer to a 898 // precise source location of the checked return statement. 899 if (requiresReturnValueCheck()) { 900 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr"); 901 InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy)); 902 } 903 904 // Emit subprogram debug descriptor. 905 if (CGDebugInfo *DI = getDebugInfo()) { 906 // Reconstruct the type from the argument list so that implicit parameters, 907 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 908 // convention. 909 CallingConv CC = CallingConv::CC_C; 910 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 911 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 912 CC = SrcFnTy->getCallConv(); 913 SmallVector<QualType, 16> ArgTypes; 914 for (const VarDecl *VD : Args) 915 ArgTypes.push_back(VD->getType()); 916 QualType FnType = getContext().getFunctionType( 917 RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 918 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk, 919 Builder); 920 } 921 922 if (ShouldInstrumentFunction()) { 923 if (CGM.getCodeGenOpts().InstrumentFunctions) 924 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter"); 925 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 926 CurFn->addFnAttr("instrument-function-entry-inlined", 927 "__cyg_profile_func_enter"); 928 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 929 CurFn->addFnAttr("instrument-function-entry-inlined", 930 "__cyg_profile_func_enter_bare"); 931 } 932 933 // Since emitting the mcount call here impacts optimizations such as function 934 // inlining, we just add an attribute to insert a mcount call in backend. 935 // The attribute "counting-function" is set to mcount function name which is 936 // architecture dependent. 937 if (CGM.getCodeGenOpts().InstrumentForProfiling) { 938 // Calls to fentry/mcount should not be generated if function has 939 // the no_instrument_function attribute. 940 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) { 941 if (CGM.getCodeGenOpts().CallFEntry) 942 Fn->addFnAttr("fentry-call", "true"); 943 else { 944 Fn->addFnAttr("instrument-function-entry-inlined", 945 getTarget().getMCountName()); 946 } 947 if (CGM.getCodeGenOpts().MNopMCount) { 948 if (getContext().getTargetInfo().getTriple().getArch() != 949 llvm::Triple::systemz) 950 CGM.getDiags().Report(diag::err_opt_not_valid_on_target) 951 << "-mnop-mcount"; 952 if (!CGM.getCodeGenOpts().CallFEntry) 953 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 954 << "-mnop-mcount" << "-mfentry"; 955 Fn->addFnAttr("mnop-mcount", "true"); 956 } 957 } 958 } 959 960 if (RetTy->isVoidType()) { 961 // Void type; nothing to return. 962 ReturnValue = Address::invalid(); 963 964 // Count the implicit return. 965 if (!endsWithReturn(D)) 966 ++NumReturnExprs; 967 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) { 968 // Indirect return; emit returned value directly into sret slot. 969 // This reduces code size, and affects correctness in C++. 970 auto AI = CurFn->arg_begin(); 971 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 972 ++AI; 973 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 974 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) { 975 ReturnValuePointer = 976 CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr"); 977 Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast( 978 ReturnValue.getPointer(), Int8PtrTy), 979 ReturnValuePointer); 980 } 981 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 982 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 983 // Load the sret pointer from the argument struct and return into that. 984 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 985 llvm::Function::arg_iterator EI = CurFn->arg_end(); 986 --EI; 987 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx); 988 ReturnValuePointer = Address(Addr, getPointerAlign()); 989 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 990 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 991 } else { 992 ReturnValue = CreateIRTemp(RetTy, "retval"); 993 994 // Tell the epilog emitter to autorelease the result. We do this 995 // now so that various specialized functions can suppress it 996 // during their IR-generation. 997 if (getLangOpts().ObjCAutoRefCount && 998 !CurFnInfo->isReturnsRetained() && 999 RetTy->isObjCRetainableType()) 1000 AutoreleaseResult = true; 1001 } 1002 1003 EmitStartEHSpec(CurCodeDecl); 1004 1005 PrologueCleanupDepth = EHStack.stable_begin(); 1006 1007 // Emit OpenMP specific initialization of the device functions. 1008 if (getLangOpts().OpenMP && CurCodeDecl) 1009 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl); 1010 1011 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 1012 1013 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 1014 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 1015 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 1016 if (MD->getParent()->isLambda() && 1017 MD->getOverloadedOperator() == OO_Call) { 1018 // We're in a lambda; figure out the captures. 1019 MD->getParent()->getCaptureFields(LambdaCaptureFields, 1020 LambdaThisCaptureField); 1021 if (LambdaThisCaptureField) { 1022 // If the lambda captures the object referred to by '*this' - either by 1023 // value or by reference, make sure CXXThisValue points to the correct 1024 // object. 1025 1026 // Get the lvalue for the field (which is a copy of the enclosing object 1027 // or contains the address of the enclosing object). 1028 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 1029 if (!LambdaThisCaptureField->getType()->isPointerType()) { 1030 // If the enclosing object was captured by value, just use its address. 1031 CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer(); 1032 } else { 1033 // Load the lvalue pointed to by the field, since '*this' was captured 1034 // by reference. 1035 CXXThisValue = 1036 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 1037 } 1038 } 1039 for (auto *FD : MD->getParent()->fields()) { 1040 if (FD->hasCapturedVLAType()) { 1041 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 1042 SourceLocation()).getScalarVal(); 1043 auto VAT = FD->getCapturedVLAType(); 1044 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 1045 } 1046 } 1047 } else { 1048 // Not in a lambda; just use 'this' from the method. 1049 // FIXME: Should we generate a new load for each use of 'this'? The 1050 // fast register allocator would be happier... 1051 CXXThisValue = CXXABIThisValue; 1052 } 1053 1054 // Check the 'this' pointer once per function, if it's available. 1055 if (CXXABIThisValue) { 1056 SanitizerSet SkippedChecks; 1057 SkippedChecks.set(SanitizerKind::ObjectSize, true); 1058 QualType ThisTy = MD->getThisType(); 1059 1060 // If this is the call operator of a lambda with no capture-default, it 1061 // may have a static invoker function, which may call this operator with 1062 // a null 'this' pointer. 1063 if (isLambdaCallOperator(MD) && 1064 MD->getParent()->getLambdaCaptureDefault() == LCD_None) 1065 SkippedChecks.set(SanitizerKind::Null, true); 1066 1067 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall 1068 : TCK_MemberCall, 1069 Loc, CXXABIThisValue, ThisTy, 1070 getContext().getTypeAlignInChars(ThisTy->getPointeeType()), 1071 SkippedChecks); 1072 } 1073 } 1074 1075 // If any of the arguments have a variably modified type, make sure to 1076 // emit the type size. 1077 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 1078 i != e; ++i) { 1079 const VarDecl *VD = *i; 1080 1081 // Dig out the type as written from ParmVarDecls; it's unclear whether 1082 // the standard (C99 6.9.1p10) requires this, but we're following the 1083 // precedent set by gcc. 1084 QualType Ty; 1085 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 1086 Ty = PVD->getOriginalType(); 1087 else 1088 Ty = VD->getType(); 1089 1090 if (Ty->isVariablyModifiedType()) 1091 EmitVariablyModifiedType(Ty); 1092 } 1093 // Emit a location at the end of the prologue. 1094 if (CGDebugInfo *DI = getDebugInfo()) 1095 DI->EmitLocation(Builder, StartLoc); 1096 1097 // TODO: Do we need to handle this in two places like we do with 1098 // target-features/target-cpu? 1099 if (CurFuncDecl) 1100 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>()) 1101 LargestVectorWidth = VecWidth->getVectorWidth(); 1102 } 1103 1104 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) { 1105 incrementProfileCounter(Body); 1106 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 1107 EmitCompoundStmtWithoutScope(*S); 1108 else 1109 EmitStmt(Body); 1110 } 1111 1112 /// When instrumenting to collect profile data, the counts for some blocks 1113 /// such as switch cases need to not include the fall-through counts, so 1114 /// emit a branch around the instrumentation code. When not instrumenting, 1115 /// this just calls EmitBlock(). 1116 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 1117 const Stmt *S) { 1118 llvm::BasicBlock *SkipCountBB = nullptr; 1119 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 1120 // When instrumenting for profiling, the fallthrough to certain 1121 // statements needs to skip over the instrumentation code so that we 1122 // get an accurate count. 1123 SkipCountBB = createBasicBlock("skipcount"); 1124 EmitBranch(SkipCountBB); 1125 } 1126 EmitBlock(BB); 1127 uint64_t CurrentCount = getCurrentProfileCount(); 1128 incrementProfileCounter(S); 1129 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 1130 if (SkipCountBB) 1131 EmitBlock(SkipCountBB); 1132 } 1133 1134 /// Tries to mark the given function nounwind based on the 1135 /// non-existence of any throwing calls within it. We believe this is 1136 /// lightweight enough to do at -O0. 1137 static void TryMarkNoThrow(llvm::Function *F) { 1138 // LLVM treats 'nounwind' on a function as part of the type, so we 1139 // can't do this on functions that can be overwritten. 1140 if (F->isInterposable()) return; 1141 1142 for (llvm::BasicBlock &BB : *F) 1143 for (llvm::Instruction &I : BB) 1144 if (I.mayThrow()) 1145 return; 1146 1147 F->setDoesNotThrow(); 1148 } 1149 1150 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 1151 FunctionArgList &Args) { 1152 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1153 QualType ResTy = FD->getReturnType(); 1154 1155 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1156 if (MD && MD->isInstance()) { 1157 if (CGM.getCXXABI().HasThisReturn(GD)) 1158 ResTy = MD->getThisType(); 1159 else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 1160 ResTy = CGM.getContext().VoidPtrTy; 1161 CGM.getCXXABI().buildThisParam(*this, Args); 1162 } 1163 1164 // The base version of an inheriting constructor whose constructed base is a 1165 // virtual base is not passed any arguments (because it doesn't actually call 1166 // the inherited constructor). 1167 bool PassedParams = true; 1168 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 1169 if (auto Inherited = CD->getInheritedConstructor()) 1170 PassedParams = 1171 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1172 1173 if (PassedParams) { 1174 for (auto *Param : FD->parameters()) { 1175 Args.push_back(Param); 1176 if (!Param->hasAttr<PassObjectSizeAttr>()) 1177 continue; 1178 1179 auto *Implicit = ImplicitParamDecl::Create( 1180 getContext(), Param->getDeclContext(), Param->getLocation(), 1181 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other); 1182 SizeArguments[Param] = Implicit; 1183 Args.push_back(Implicit); 1184 } 1185 } 1186 1187 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 1188 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 1189 1190 return ResTy; 1191 } 1192 1193 static bool 1194 shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD, 1195 const ASTContext &Context) { 1196 QualType T = FD->getReturnType(); 1197 // Avoid the optimization for functions that return a record type with a 1198 // trivial destructor or another trivially copyable type. 1199 if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) { 1200 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1201 return !ClassDecl->hasTrivialDestructor(); 1202 } 1203 return !T.isTriviallyCopyableType(Context); 1204 } 1205 1206 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1207 const CGFunctionInfo &FnInfo) { 1208 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1209 CurGD = GD; 1210 1211 FunctionArgList Args; 1212 QualType ResTy = BuildFunctionArgList(GD, Args); 1213 1214 // Check if we should generate debug info for this function. 1215 if (FD->hasAttr<NoDebugAttr>()) 1216 DebugInfo = nullptr; // disable debug info indefinitely for this function 1217 1218 // The function might not have a body if we're generating thunks for a 1219 // function declaration. 1220 SourceRange BodyRange; 1221 if (Stmt *Body = FD->getBody()) 1222 BodyRange = Body->getSourceRange(); 1223 else 1224 BodyRange = FD->getLocation(); 1225 CurEHLocation = BodyRange.getEnd(); 1226 1227 // Use the location of the start of the function to determine where 1228 // the function definition is located. By default use the location 1229 // of the declaration as the location for the subprogram. A function 1230 // may lack a declaration in the source code if it is created by code 1231 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 1232 SourceLocation Loc = FD->getLocation(); 1233 1234 // If this is a function specialization then use the pattern body 1235 // as the location for the function. 1236 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 1237 if (SpecDecl->hasBody(SpecDecl)) 1238 Loc = SpecDecl->getLocation(); 1239 1240 Stmt *Body = FD->getBody(); 1241 1242 // Initialize helper which will detect jumps which can cause invalid lifetime 1243 // markers. 1244 if (Body && ShouldEmitLifetimeMarkers) 1245 Bypasses.Init(Body); 1246 1247 // Emit the standard function prologue. 1248 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1249 1250 // Generate the body of the function. 1251 PGO.assignRegionCounters(GD, CurFn); 1252 if (isa<CXXDestructorDecl>(FD)) 1253 EmitDestructorBody(Args); 1254 else if (isa<CXXConstructorDecl>(FD)) 1255 EmitConstructorBody(Args); 1256 else if (getLangOpts().CUDA && 1257 !getLangOpts().CUDAIsDevice && 1258 FD->hasAttr<CUDAGlobalAttr>()) 1259 CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1260 else if (isa<CXXMethodDecl>(FD) && 1261 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1262 // The lambda static invoker function is special, because it forwards or 1263 // clones the body of the function call operator (but is actually static). 1264 EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD)); 1265 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1266 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1267 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1268 // Implicit copy-assignment gets the same special treatment as implicit 1269 // copy-constructors. 1270 emitImplicitAssignmentOperatorBody(Args); 1271 } else if (Body) { 1272 EmitFunctionBody(Body); 1273 } else 1274 llvm_unreachable("no definition for emitted function"); 1275 1276 // C++11 [stmt.return]p2: 1277 // Flowing off the end of a function [...] results in undefined behavior in 1278 // a value-returning function. 1279 // C11 6.9.1p12: 1280 // If the '}' that terminates a function is reached, and the value of the 1281 // function call is used by the caller, the behavior is undefined. 1282 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 1283 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 1284 bool ShouldEmitUnreachable = 1285 CGM.getCodeGenOpts().StrictReturn || 1286 shouldUseUndefinedBehaviorReturnOptimization(FD, getContext()); 1287 if (SanOpts.has(SanitizerKind::Return)) { 1288 SanitizerScope SanScope(this); 1289 llvm::Value *IsFalse = Builder.getFalse(); 1290 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 1291 SanitizerHandler::MissingReturn, 1292 EmitCheckSourceLocation(FD->getLocation()), None); 1293 } else if (ShouldEmitUnreachable) { 1294 if (CGM.getCodeGenOpts().OptimizationLevel == 0) 1295 EmitTrapCall(llvm::Intrinsic::trap); 1296 } 1297 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 1298 Builder.CreateUnreachable(); 1299 Builder.ClearInsertionPoint(); 1300 } 1301 } 1302 1303 // Emit the standard function epilogue. 1304 FinishFunction(BodyRange.getEnd()); 1305 1306 // If we haven't marked the function nothrow through other means, do 1307 // a quick pass now to see if we can. 1308 if (!CurFn->doesNotThrow()) 1309 TryMarkNoThrow(CurFn); 1310 } 1311 1312 /// ContainsLabel - Return true if the statement contains a label in it. If 1313 /// this statement is not executed normally, it not containing a label means 1314 /// that we can just remove the code. 1315 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1316 // Null statement, not a label! 1317 if (!S) return false; 1318 1319 // If this is a label, we have to emit the code, consider something like: 1320 // if (0) { ... foo: bar(); } goto foo; 1321 // 1322 // TODO: If anyone cared, we could track __label__'s, since we know that you 1323 // can't jump to one from outside their declared region. 1324 if (isa<LabelStmt>(S)) 1325 return true; 1326 1327 // If this is a case/default statement, and we haven't seen a switch, we have 1328 // to emit the code. 1329 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1330 return true; 1331 1332 // If this is a switch statement, we want to ignore cases below it. 1333 if (isa<SwitchStmt>(S)) 1334 IgnoreCaseStmts = true; 1335 1336 // Scan subexpressions for verboten labels. 1337 for (const Stmt *SubStmt : S->children()) 1338 if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1339 return true; 1340 1341 return false; 1342 } 1343 1344 /// containsBreak - Return true if the statement contains a break out of it. 1345 /// If the statement (recursively) contains a switch or loop with a break 1346 /// inside of it, this is fine. 1347 bool CodeGenFunction::containsBreak(const Stmt *S) { 1348 // Null statement, not a label! 1349 if (!S) return false; 1350 1351 // If this is a switch or loop that defines its own break scope, then we can 1352 // include it and anything inside of it. 1353 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 1354 isa<ForStmt>(S)) 1355 return false; 1356 1357 if (isa<BreakStmt>(S)) 1358 return true; 1359 1360 // Scan subexpressions for verboten breaks. 1361 for (const Stmt *SubStmt : S->children()) 1362 if (containsBreak(SubStmt)) 1363 return true; 1364 1365 return false; 1366 } 1367 1368 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 1369 if (!S) return false; 1370 1371 // Some statement kinds add a scope and thus never add a decl to the current 1372 // scope. Note, this list is longer than the list of statements that might 1373 // have an unscoped decl nested within them, but this way is conservatively 1374 // correct even if more statement kinds are added. 1375 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 1376 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 1377 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 1378 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 1379 return false; 1380 1381 if (isa<DeclStmt>(S)) 1382 return true; 1383 1384 for (const Stmt *SubStmt : S->children()) 1385 if (mightAddDeclToScope(SubStmt)) 1386 return true; 1387 1388 return false; 1389 } 1390 1391 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1392 /// to a constant, or if it does but contains a label, return false. If it 1393 /// constant folds return true and set the boolean result in Result. 1394 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1395 bool &ResultBool, 1396 bool AllowLabels) { 1397 llvm::APSInt ResultInt; 1398 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 1399 return false; 1400 1401 ResultBool = ResultInt.getBoolValue(); 1402 return true; 1403 } 1404 1405 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1406 /// to a constant, or if it does but contains a label, return false. If it 1407 /// constant folds return true and set the folded value. 1408 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1409 llvm::APSInt &ResultInt, 1410 bool AllowLabels) { 1411 // FIXME: Rename and handle conversion of other evaluatable things 1412 // to bool. 1413 Expr::EvalResult Result; 1414 if (!Cond->EvaluateAsInt(Result, getContext())) 1415 return false; // Not foldable, not integer or not fully evaluatable. 1416 1417 llvm::APSInt Int = Result.Val.getInt(); 1418 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 1419 return false; // Contains a label. 1420 1421 ResultInt = Int; 1422 return true; 1423 } 1424 1425 1426 1427 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1428 /// statement) to the specified blocks. Based on the condition, this might try 1429 /// to simplify the codegen of the conditional based on the branch. 1430 /// 1431 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1432 llvm::BasicBlock *TrueBlock, 1433 llvm::BasicBlock *FalseBlock, 1434 uint64_t TrueCount) { 1435 Cond = Cond->IgnoreParens(); 1436 1437 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1438 1439 // Handle X && Y in a condition. 1440 if (CondBOp->getOpcode() == BO_LAnd) { 1441 // If we have "1 && X", simplify the code. "0 && X" would have constant 1442 // folded if the case was simple enough. 1443 bool ConstantBool = false; 1444 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1445 ConstantBool) { 1446 // br(1 && X) -> br(X). 1447 incrementProfileCounter(CondBOp); 1448 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1449 TrueCount); 1450 } 1451 1452 // If we have "X && 1", simplify the code to use an uncond branch. 1453 // "X && 0" would have been constant folded to 0. 1454 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1455 ConstantBool) { 1456 // br(X && 1) -> br(X). 1457 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1458 TrueCount); 1459 } 1460 1461 // Emit the LHS as a conditional. If the LHS conditional is false, we 1462 // want to jump to the FalseBlock. 1463 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1464 // The counter tells us how often we evaluate RHS, and all of TrueCount 1465 // can be propagated to that branch. 1466 uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1467 1468 ConditionalEvaluation eval(*this); 1469 { 1470 ApplyDebugLocation DL(*this, Cond); 1471 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1472 EmitBlock(LHSTrue); 1473 } 1474 1475 incrementProfileCounter(CondBOp); 1476 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1477 1478 // Any temporaries created here are conditional. 1479 eval.begin(*this); 1480 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1481 eval.end(*this); 1482 1483 return; 1484 } 1485 1486 if (CondBOp->getOpcode() == BO_LOr) { 1487 // If we have "0 || X", simplify the code. "1 || X" would have constant 1488 // folded if the case was simple enough. 1489 bool ConstantBool = false; 1490 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1491 !ConstantBool) { 1492 // br(0 || X) -> br(X). 1493 incrementProfileCounter(CondBOp); 1494 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1495 TrueCount); 1496 } 1497 1498 // If we have "X || 0", simplify the code to use an uncond branch. 1499 // "X || 1" would have been constant folded to 1. 1500 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1501 !ConstantBool) { 1502 // br(X || 0) -> br(X). 1503 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1504 TrueCount); 1505 } 1506 1507 // Emit the LHS as a conditional. If the LHS conditional is true, we 1508 // want to jump to the TrueBlock. 1509 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1510 // We have the count for entry to the RHS and for the whole expression 1511 // being true, so we can divy up True count between the short circuit and 1512 // the RHS. 1513 uint64_t LHSCount = 1514 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1515 uint64_t RHSCount = TrueCount - LHSCount; 1516 1517 ConditionalEvaluation eval(*this); 1518 { 1519 ApplyDebugLocation DL(*this, Cond); 1520 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1521 EmitBlock(LHSFalse); 1522 } 1523 1524 incrementProfileCounter(CondBOp); 1525 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1526 1527 // Any temporaries created here are conditional. 1528 eval.begin(*this); 1529 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1530 1531 eval.end(*this); 1532 1533 return; 1534 } 1535 } 1536 1537 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1538 // br(!x, t, f) -> br(x, f, t) 1539 if (CondUOp->getOpcode() == UO_LNot) { 1540 // Negate the count. 1541 uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1542 // Negate the condition and swap the destination blocks. 1543 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1544 FalseCount); 1545 } 1546 } 1547 1548 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1549 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1550 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1551 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1552 1553 ConditionalEvaluation cond(*this); 1554 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1555 getProfileCount(CondOp)); 1556 1557 // When computing PGO branch weights, we only know the overall count for 1558 // the true block. This code is essentially doing tail duplication of the 1559 // naive code-gen, introducing new edges for which counts are not 1560 // available. Divide the counts proportionally between the LHS and RHS of 1561 // the conditional operator. 1562 uint64_t LHSScaledTrueCount = 0; 1563 if (TrueCount) { 1564 double LHSRatio = 1565 getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1566 LHSScaledTrueCount = TrueCount * LHSRatio; 1567 } 1568 1569 cond.begin(*this); 1570 EmitBlock(LHSBlock); 1571 incrementProfileCounter(CondOp); 1572 { 1573 ApplyDebugLocation DL(*this, Cond); 1574 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1575 LHSScaledTrueCount); 1576 } 1577 cond.end(*this); 1578 1579 cond.begin(*this); 1580 EmitBlock(RHSBlock); 1581 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1582 TrueCount - LHSScaledTrueCount); 1583 cond.end(*this); 1584 1585 return; 1586 } 1587 1588 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1589 // Conditional operator handling can give us a throw expression as a 1590 // condition for a case like: 1591 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1592 // Fold this to: 1593 // br(c, throw x, br(y, t, f)) 1594 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1595 return; 1596 } 1597 1598 // If the branch has a condition wrapped by __builtin_unpredictable, 1599 // create metadata that specifies that the branch is unpredictable. 1600 // Don't bother if not optimizing because that metadata would not be used. 1601 llvm::MDNode *Unpredictable = nullptr; 1602 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts()); 1603 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1604 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1605 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1606 llvm::MDBuilder MDHelper(getLLVMContext()); 1607 Unpredictable = MDHelper.createUnpredictable(); 1608 } 1609 } 1610 1611 // Create branch weights based on the number of times we get here and the 1612 // number of times the condition should be true. 1613 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1614 llvm::MDNode *Weights = 1615 createProfileWeights(TrueCount, CurrentCount - TrueCount); 1616 1617 // Emit the code with the fully general case. 1618 llvm::Value *CondV; 1619 { 1620 ApplyDebugLocation DL(*this, Cond); 1621 CondV = EvaluateExprAsBool(Cond); 1622 } 1623 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1624 } 1625 1626 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1627 /// specified stmt yet. 1628 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1629 CGM.ErrorUnsupported(S, Type); 1630 } 1631 1632 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 1633 /// variable-length array whose elements have a non-zero bit-pattern. 1634 /// 1635 /// \param baseType the inner-most element type of the array 1636 /// \param src - a char* pointing to the bit-pattern for a single 1637 /// base element of the array 1638 /// \param sizeInChars - the total size of the VLA, in chars 1639 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1640 Address dest, Address src, 1641 llvm::Value *sizeInChars) { 1642 CGBuilderTy &Builder = CGF.Builder; 1643 1644 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 1645 llvm::Value *baseSizeInChars 1646 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 1647 1648 Address begin = 1649 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 1650 llvm::Value *end = 1651 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 1652 1653 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1654 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1655 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1656 1657 // Make a loop over the VLA. C99 guarantees that the VLA element 1658 // count must be nonzero. 1659 CGF.EmitBlock(loopBB); 1660 1661 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 1662 cur->addIncoming(begin.getPointer(), originBB); 1663 1664 CharUnits curAlign = 1665 dest.getAlignment().alignmentOfArrayElement(baseSize); 1666 1667 // memcpy the individual element bit-pattern. 1668 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 1669 /*volatile*/ false); 1670 1671 // Go to the next element. 1672 llvm::Value *next = 1673 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 1674 1675 // Leave if that's the end of the VLA. 1676 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1677 Builder.CreateCondBr(done, contBB, loopBB); 1678 cur->addIncoming(next, loopBB); 1679 1680 CGF.EmitBlock(contBB); 1681 } 1682 1683 void 1684 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1685 // Ignore empty classes in C++. 1686 if (getLangOpts().CPlusPlus) { 1687 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1688 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1689 return; 1690 } 1691 } 1692 1693 // Cast the dest ptr to the appropriate i8 pointer type. 1694 if (DestPtr.getElementType() != Int8Ty) 1695 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1696 1697 // Get size and alignment info for this aggregate. 1698 CharUnits size = getContext().getTypeSizeInChars(Ty); 1699 1700 llvm::Value *SizeVal; 1701 const VariableArrayType *vla; 1702 1703 // Don't bother emitting a zero-byte memset. 1704 if (size.isZero()) { 1705 // But note that getTypeInfo returns 0 for a VLA. 1706 if (const VariableArrayType *vlaType = 1707 dyn_cast_or_null<VariableArrayType>( 1708 getContext().getAsArrayType(Ty))) { 1709 auto VlaSize = getVLASize(vlaType); 1710 SizeVal = VlaSize.NumElts; 1711 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type); 1712 if (!eltSize.isOne()) 1713 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1714 vla = vlaType; 1715 } else { 1716 return; 1717 } 1718 } else { 1719 SizeVal = CGM.getSize(size); 1720 vla = nullptr; 1721 } 1722 1723 // If the type contains a pointer to data member we can't memset it to zero. 1724 // Instead, create a null constant and copy it to the destination. 1725 // TODO: there are other patterns besides zero that we can usefully memset, 1726 // like -1, which happens to be the pattern used by member-pointers. 1727 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1728 // For a VLA, emit a single element, then splat that over the VLA. 1729 if (vla) Ty = getContext().getBaseElementType(vla); 1730 1731 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1732 1733 llvm::GlobalVariable *NullVariable = 1734 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1735 /*isConstant=*/true, 1736 llvm::GlobalVariable::PrivateLinkage, 1737 NullConstant, Twine()); 1738 CharUnits NullAlign = DestPtr.getAlignment(); 1739 NullVariable->setAlignment(NullAlign.getAsAlign()); 1740 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 1741 NullAlign); 1742 1743 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1744 1745 // Get and call the appropriate llvm.memcpy overload. 1746 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1747 return; 1748 } 1749 1750 // Otherwise, just memset the whole thing to zero. This is legal 1751 // because in LLVM, all default initializers (other than the ones we just 1752 // handled above) are guaranteed to have a bit pattern of all zeros. 1753 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1754 } 1755 1756 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1757 // Make sure that there is a block for the indirect goto. 1758 if (!IndirectBranch) 1759 GetIndirectGotoBlock(); 1760 1761 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1762 1763 // Make sure the indirect branch includes all of the address-taken blocks. 1764 IndirectBranch->addDestination(BB); 1765 return llvm::BlockAddress::get(CurFn, BB); 1766 } 1767 1768 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1769 // If we already made the indirect branch for indirect goto, return its block. 1770 if (IndirectBranch) return IndirectBranch->getParent(); 1771 1772 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1773 1774 // Create the PHI node that indirect gotos will add entries to. 1775 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1776 "indirect.goto.dest"); 1777 1778 // Create the indirect branch instruction. 1779 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1780 return IndirectBranch->getParent(); 1781 } 1782 1783 /// Computes the length of an array in elements, as well as the base 1784 /// element type and a properly-typed first element pointer. 1785 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1786 QualType &baseType, 1787 Address &addr) { 1788 const ArrayType *arrayType = origArrayType; 1789 1790 // If it's a VLA, we have to load the stored size. Note that 1791 // this is the size of the VLA in bytes, not its size in elements. 1792 llvm::Value *numVLAElements = nullptr; 1793 if (isa<VariableArrayType>(arrayType)) { 1794 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts; 1795 1796 // Walk into all VLAs. This doesn't require changes to addr, 1797 // which has type T* where T is the first non-VLA element type. 1798 do { 1799 QualType elementType = arrayType->getElementType(); 1800 arrayType = getContext().getAsArrayType(elementType); 1801 1802 // If we only have VLA components, 'addr' requires no adjustment. 1803 if (!arrayType) { 1804 baseType = elementType; 1805 return numVLAElements; 1806 } 1807 } while (isa<VariableArrayType>(arrayType)); 1808 1809 // We get out here only if we find a constant array type 1810 // inside the VLA. 1811 } 1812 1813 // We have some number of constant-length arrays, so addr should 1814 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1815 // down to the first element of addr. 1816 SmallVector<llvm::Value*, 8> gepIndices; 1817 1818 // GEP down to the array type. 1819 llvm::ConstantInt *zero = Builder.getInt32(0); 1820 gepIndices.push_back(zero); 1821 1822 uint64_t countFromCLAs = 1; 1823 QualType eltType; 1824 1825 llvm::ArrayType *llvmArrayType = 1826 dyn_cast<llvm::ArrayType>(addr.getElementType()); 1827 while (llvmArrayType) { 1828 assert(isa<ConstantArrayType>(arrayType)); 1829 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1830 == llvmArrayType->getNumElements()); 1831 1832 gepIndices.push_back(zero); 1833 countFromCLAs *= llvmArrayType->getNumElements(); 1834 eltType = arrayType->getElementType(); 1835 1836 llvmArrayType = 1837 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1838 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1839 assert((!llvmArrayType || arrayType) && 1840 "LLVM and Clang types are out-of-synch"); 1841 } 1842 1843 if (arrayType) { 1844 // From this point onwards, the Clang array type has been emitted 1845 // as some other type (probably a packed struct). Compute the array 1846 // size, and just emit the 'begin' expression as a bitcast. 1847 while (arrayType) { 1848 countFromCLAs *= 1849 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1850 eltType = arrayType->getElementType(); 1851 arrayType = getContext().getAsArrayType(eltType); 1852 } 1853 1854 llvm::Type *baseType = ConvertType(eltType); 1855 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 1856 } else { 1857 // Create the actual GEP. 1858 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 1859 gepIndices, "array.begin"), 1860 addr.getAlignment()); 1861 } 1862 1863 baseType = eltType; 1864 1865 llvm::Value *numElements 1866 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1867 1868 // If we had any VLA dimensions, factor them in. 1869 if (numVLAElements) 1870 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1871 1872 return numElements; 1873 } 1874 1875 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) { 1876 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1877 assert(vla && "type was not a variable array type!"); 1878 return getVLASize(vla); 1879 } 1880 1881 CodeGenFunction::VlaSizePair 1882 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1883 // The number of elements so far; always size_t. 1884 llvm::Value *numElements = nullptr; 1885 1886 QualType elementType; 1887 do { 1888 elementType = type->getElementType(); 1889 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1890 assert(vlaSize && "no size for VLA!"); 1891 assert(vlaSize->getType() == SizeTy); 1892 1893 if (!numElements) { 1894 numElements = vlaSize; 1895 } else { 1896 // It's undefined behavior if this wraps around, so mark it that way. 1897 // FIXME: Teach -fsanitize=undefined to trap this. 1898 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1899 } 1900 } while ((type = getContext().getAsVariableArrayType(elementType))); 1901 1902 return { numElements, elementType }; 1903 } 1904 1905 CodeGenFunction::VlaSizePair 1906 CodeGenFunction::getVLAElements1D(QualType type) { 1907 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1908 assert(vla && "type was not a variable array type!"); 1909 return getVLAElements1D(vla); 1910 } 1911 1912 CodeGenFunction::VlaSizePair 1913 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) { 1914 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()]; 1915 assert(VlaSize && "no size for VLA!"); 1916 assert(VlaSize->getType() == SizeTy); 1917 return { VlaSize, Vla->getElementType() }; 1918 } 1919 1920 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1921 assert(type->isVariablyModifiedType() && 1922 "Must pass variably modified type to EmitVLASizes!"); 1923 1924 EnsureInsertPoint(); 1925 1926 // We're going to walk down into the type and look for VLA 1927 // expressions. 1928 do { 1929 assert(type->isVariablyModifiedType()); 1930 1931 const Type *ty = type.getTypePtr(); 1932 switch (ty->getTypeClass()) { 1933 1934 #define TYPE(Class, Base) 1935 #define ABSTRACT_TYPE(Class, Base) 1936 #define NON_CANONICAL_TYPE(Class, Base) 1937 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1938 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1939 #include "clang/AST/TypeNodes.inc" 1940 llvm_unreachable("unexpected dependent type!"); 1941 1942 // These types are never variably-modified. 1943 case Type::Builtin: 1944 case Type::Complex: 1945 case Type::Vector: 1946 case Type::ExtVector: 1947 case Type::Record: 1948 case Type::Enum: 1949 case Type::Elaborated: 1950 case Type::TemplateSpecialization: 1951 case Type::ObjCTypeParam: 1952 case Type::ObjCObject: 1953 case Type::ObjCInterface: 1954 case Type::ObjCObjectPointer: 1955 llvm_unreachable("type class is never variably-modified!"); 1956 1957 case Type::Adjusted: 1958 type = cast<AdjustedType>(ty)->getAdjustedType(); 1959 break; 1960 1961 case Type::Decayed: 1962 type = cast<DecayedType>(ty)->getPointeeType(); 1963 break; 1964 1965 case Type::Pointer: 1966 type = cast<PointerType>(ty)->getPointeeType(); 1967 break; 1968 1969 case Type::BlockPointer: 1970 type = cast<BlockPointerType>(ty)->getPointeeType(); 1971 break; 1972 1973 case Type::LValueReference: 1974 case Type::RValueReference: 1975 type = cast<ReferenceType>(ty)->getPointeeType(); 1976 break; 1977 1978 case Type::MemberPointer: 1979 type = cast<MemberPointerType>(ty)->getPointeeType(); 1980 break; 1981 1982 case Type::ConstantArray: 1983 case Type::IncompleteArray: 1984 // Losing element qualification here is fine. 1985 type = cast<ArrayType>(ty)->getElementType(); 1986 break; 1987 1988 case Type::VariableArray: { 1989 // Losing element qualification here is fine. 1990 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1991 1992 // Unknown size indication requires no size computation. 1993 // Otherwise, evaluate and record it. 1994 if (const Expr *size = vat->getSizeExpr()) { 1995 // It's possible that we might have emitted this already, 1996 // e.g. with a typedef and a pointer to it. 1997 llvm::Value *&entry = VLASizeMap[size]; 1998 if (!entry) { 1999 llvm::Value *Size = EmitScalarExpr(size); 2000 2001 // C11 6.7.6.2p5: 2002 // If the size is an expression that is not an integer constant 2003 // expression [...] each time it is evaluated it shall have a value 2004 // greater than zero. 2005 if (SanOpts.has(SanitizerKind::VLABound) && 2006 size->getType()->isSignedIntegerType()) { 2007 SanitizerScope SanScope(this); 2008 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 2009 llvm::Constant *StaticArgs[] = { 2010 EmitCheckSourceLocation(size->getBeginLoc()), 2011 EmitCheckTypeDescriptor(size->getType())}; 2012 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 2013 SanitizerKind::VLABound), 2014 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size); 2015 } 2016 2017 // Always zexting here would be wrong if it weren't 2018 // undefined behavior to have a negative bound. 2019 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 2020 } 2021 } 2022 type = vat->getElementType(); 2023 break; 2024 } 2025 2026 case Type::FunctionProto: 2027 case Type::FunctionNoProto: 2028 type = cast<FunctionType>(ty)->getReturnType(); 2029 break; 2030 2031 case Type::Paren: 2032 case Type::TypeOf: 2033 case Type::UnaryTransform: 2034 case Type::Attributed: 2035 case Type::SubstTemplateTypeParm: 2036 case Type::PackExpansion: 2037 case Type::MacroQualified: 2038 // Keep walking after single level desugaring. 2039 type = type.getSingleStepDesugaredType(getContext()); 2040 break; 2041 2042 case Type::Typedef: 2043 case Type::Decltype: 2044 case Type::Auto: 2045 case Type::DeducedTemplateSpecialization: 2046 // Stop walking: nothing to do. 2047 return; 2048 2049 case Type::TypeOfExpr: 2050 // Stop walking: emit typeof expression. 2051 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 2052 return; 2053 2054 case Type::Atomic: 2055 type = cast<AtomicType>(ty)->getValueType(); 2056 break; 2057 2058 case Type::Pipe: 2059 type = cast<PipeType>(ty)->getElementType(); 2060 break; 2061 } 2062 } while (type->isVariablyModifiedType()); 2063 } 2064 2065 Address CodeGenFunction::EmitVAListRef(const Expr* E) { 2066 if (getContext().getBuiltinVaListType()->isArrayType()) 2067 return EmitPointerWithAlignment(E); 2068 return EmitLValue(E).getAddress(*this); 2069 } 2070 2071 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 2072 return EmitLValue(E).getAddress(*this); 2073 } 2074 2075 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 2076 const APValue &Init) { 2077 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!"); 2078 if (CGDebugInfo *Dbg = getDebugInfo()) 2079 if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2080 Dbg->EmitGlobalVariable(E->getDecl(), Init); 2081 } 2082 2083 CodeGenFunction::PeepholeProtection 2084 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 2085 // At the moment, the only aggressive peephole we do in IR gen 2086 // is trunc(zext) folding, but if we add more, we can easily 2087 // extend this protection. 2088 2089 if (!rvalue.isScalar()) return PeepholeProtection(); 2090 llvm::Value *value = rvalue.getScalarVal(); 2091 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 2092 2093 // Just make an extra bitcast. 2094 assert(HaveInsertPoint()); 2095 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 2096 Builder.GetInsertBlock()); 2097 2098 PeepholeProtection protection; 2099 protection.Inst = inst; 2100 return protection; 2101 } 2102 2103 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 2104 if (!protection.Inst) return; 2105 2106 // In theory, we could try to duplicate the peepholes now, but whatever. 2107 protection.Inst->eraseFromParent(); 2108 } 2109 2110 void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue, 2111 QualType Ty, SourceLocation Loc, 2112 SourceLocation AssumptionLoc, 2113 llvm::Value *Alignment, 2114 llvm::Value *OffsetValue) { 2115 llvm::Value *TheCheck; 2116 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption( 2117 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck); 2118 if (SanOpts.has(SanitizerKind::Alignment)) { 2119 EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2120 OffsetValue, TheCheck, Assumption); 2121 } 2122 } 2123 2124 void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue, 2125 const Expr *E, 2126 SourceLocation AssumptionLoc, 2127 llvm::Value *Alignment, 2128 llvm::Value *OffsetValue) { 2129 if (auto *CE = dyn_cast<CastExpr>(E)) 2130 E = CE->getSubExprAsWritten(); 2131 QualType Ty = E->getType(); 2132 SourceLocation Loc = E->getExprLoc(); 2133 2134 EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2135 OffsetValue); 2136 } 2137 2138 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn, 2139 llvm::Value *AnnotatedVal, 2140 StringRef AnnotationStr, 2141 SourceLocation Location) { 2142 llvm::Value *Args[4] = { 2143 AnnotatedVal, 2144 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 2145 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 2146 CGM.EmitAnnotationLineNo(Location) 2147 }; 2148 return Builder.CreateCall(AnnotationFn, Args); 2149 } 2150 2151 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 2152 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2153 // FIXME We create a new bitcast for every annotation because that's what 2154 // llvm-gcc was doing. 2155 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2156 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 2157 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 2158 I->getAnnotation(), D->getLocation()); 2159 } 2160 2161 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 2162 Address Addr) { 2163 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2164 llvm::Value *V = Addr.getPointer(); 2165 llvm::Type *VTy = V->getType(); 2166 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 2167 CGM.Int8PtrTy); 2168 2169 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 2170 // FIXME Always emit the cast inst so we can differentiate between 2171 // annotation on the first field of a struct and annotation on the struct 2172 // itself. 2173 if (VTy != CGM.Int8PtrTy) 2174 V = Builder.CreateBitCast(V, CGM.Int8PtrTy); 2175 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 2176 V = Builder.CreateBitCast(V, VTy); 2177 } 2178 2179 return Address(V, Addr.getAlignment()); 2180 } 2181 2182 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 2183 2184 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 2185 : CGF(CGF) { 2186 assert(!CGF->IsSanitizerScope); 2187 CGF->IsSanitizerScope = true; 2188 } 2189 2190 CodeGenFunction::SanitizerScope::~SanitizerScope() { 2191 CGF->IsSanitizerScope = false; 2192 } 2193 2194 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 2195 const llvm::Twine &Name, 2196 llvm::BasicBlock *BB, 2197 llvm::BasicBlock::iterator InsertPt) const { 2198 LoopStack.InsertHelper(I); 2199 if (IsSanitizerScope) 2200 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 2201 } 2202 2203 void CGBuilderInserter::InsertHelper( 2204 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 2205 llvm::BasicBlock::iterator InsertPt) const { 2206 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 2207 if (CGF) 2208 CGF->InsertHelper(I, Name, BB, InsertPt); 2209 } 2210 2211 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures, 2212 CodeGenModule &CGM, const FunctionDecl *FD, 2213 std::string &FirstMissing) { 2214 // If there aren't any required features listed then go ahead and return. 2215 if (ReqFeatures.empty()) 2216 return false; 2217 2218 // Now build up the set of caller features and verify that all the required 2219 // features are there. 2220 llvm::StringMap<bool> CallerFeatureMap; 2221 CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD)); 2222 2223 // If we have at least one of the features in the feature list return 2224 // true, otherwise return false. 2225 return std::all_of( 2226 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) { 2227 SmallVector<StringRef, 1> OrFeatures; 2228 Feature.split(OrFeatures, '|'); 2229 return llvm::any_of(OrFeatures, [&](StringRef Feature) { 2230 if (!CallerFeatureMap.lookup(Feature)) { 2231 FirstMissing = Feature.str(); 2232 return false; 2233 } 2234 return true; 2235 }); 2236 }); 2237 } 2238 2239 // Emits an error if we don't have a valid set of target features for the 2240 // called function. 2241 void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 2242 const FunctionDecl *TargetDecl) { 2243 return checkTargetFeatures(E->getBeginLoc(), TargetDecl); 2244 } 2245 2246 // Emits an error if we don't have a valid set of target features for the 2247 // called function. 2248 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc, 2249 const FunctionDecl *TargetDecl) { 2250 // Early exit if this is an indirect call. 2251 if (!TargetDecl) 2252 return; 2253 2254 // Get the current enclosing function if it exists. If it doesn't 2255 // we can't check the target features anyhow. 2256 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl); 2257 if (!FD) 2258 return; 2259 2260 // Grab the required features for the call. For a builtin this is listed in 2261 // the td file with the default cpu, for an always_inline function this is any 2262 // listed cpu and any listed features. 2263 unsigned BuiltinID = TargetDecl->getBuiltinID(); 2264 std::string MissingFeature; 2265 if (BuiltinID) { 2266 SmallVector<StringRef, 1> ReqFeatures; 2267 const char *FeatureList = 2268 CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2269 // Return if the builtin doesn't have any required features. 2270 if (!FeatureList || StringRef(FeatureList) == "") 2271 return; 2272 StringRef(FeatureList).split(ReqFeatures, ','); 2273 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2274 CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature) 2275 << TargetDecl->getDeclName() 2276 << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2277 2278 } else if (!TargetDecl->isMultiVersion() && 2279 TargetDecl->hasAttr<TargetAttr>()) { 2280 // Get the required features for the callee. 2281 2282 const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>(); 2283 TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD); 2284 2285 SmallVector<StringRef, 1> ReqFeatures; 2286 llvm::StringMap<bool> CalleeFeatureMap; 2287 CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2288 2289 for (const auto &F : ParsedAttr.Features) { 2290 if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1))) 2291 ReqFeatures.push_back(StringRef(F).substr(1)); 2292 } 2293 2294 for (const auto &F : CalleeFeatureMap) { 2295 // Only positive features are "required". 2296 if (F.getValue()) 2297 ReqFeatures.push_back(F.getKey()); 2298 } 2299 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2300 CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 2301 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 2302 } 2303 } 2304 2305 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2306 if (!CGM.getCodeGenOpts().SanitizeStats) 2307 return; 2308 2309 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2310 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2311 CGM.getSanStats().create(IRB, SSK); 2312 } 2313 2314 llvm::Value * 2315 CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) { 2316 llvm::Value *Condition = nullptr; 2317 2318 if (!RO.Conditions.Architecture.empty()) 2319 Condition = EmitX86CpuIs(RO.Conditions.Architecture); 2320 2321 if (!RO.Conditions.Features.empty()) { 2322 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features); 2323 Condition = 2324 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond; 2325 } 2326 return Condition; 2327 } 2328 2329 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, 2330 llvm::Function *Resolver, 2331 CGBuilderTy &Builder, 2332 llvm::Function *FuncToReturn, 2333 bool SupportsIFunc) { 2334 if (SupportsIFunc) { 2335 Builder.CreateRet(FuncToReturn); 2336 return; 2337 } 2338 2339 llvm::SmallVector<llvm::Value *, 10> Args; 2340 llvm::for_each(Resolver->args(), 2341 [&](llvm::Argument &Arg) { Args.push_back(&Arg); }); 2342 2343 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args); 2344 Result->setTailCallKind(llvm::CallInst::TCK_MustTail); 2345 2346 if (Resolver->getReturnType()->isVoidTy()) 2347 Builder.CreateRetVoid(); 2348 else 2349 Builder.CreateRet(Result); 2350 } 2351 2352 void CodeGenFunction::EmitMultiVersionResolver( 2353 llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2354 assert((getContext().getTargetInfo().getTriple().getArch() == 2355 llvm::Triple::x86 || 2356 getContext().getTargetInfo().getTriple().getArch() == 2357 llvm::Triple::x86_64) && 2358 "Only implemented for x86 targets"); 2359 2360 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 2361 2362 // Main function's basic block. 2363 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 2364 Builder.SetInsertPoint(CurBlock); 2365 EmitX86CpuInit(); 2366 2367 for (const MultiVersionResolverOption &RO : Options) { 2368 Builder.SetInsertPoint(CurBlock); 2369 llvm::Value *Condition = FormResolverCondition(RO); 2370 2371 // The 'default' or 'generic' case. 2372 if (!Condition) { 2373 assert(&RO == Options.end() - 1 && 2374 "Default or Generic case must be last"); 2375 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 2376 SupportsIFunc); 2377 return; 2378 } 2379 2380 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 2381 CGBuilderTy RetBuilder(*this, RetBlock); 2382 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 2383 SupportsIFunc); 2384 CurBlock = createBasicBlock("resolver_else", Resolver); 2385 Builder.CreateCondBr(Condition, RetBlock, CurBlock); 2386 } 2387 2388 // If no generic/default, emit an unreachable. 2389 Builder.SetInsertPoint(CurBlock); 2390 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2391 TrapCall->setDoesNotReturn(); 2392 TrapCall->setDoesNotThrow(); 2393 Builder.CreateUnreachable(); 2394 Builder.ClearInsertionPoint(); 2395 } 2396 2397 // Loc - where the diagnostic will point, where in the source code this 2398 // alignment has failed. 2399 // SecondaryLoc - if present (will be present if sufficiently different from 2400 // Loc), the diagnostic will additionally point a "Note:" to this location. 2401 // It should be the location where the __attribute__((assume_aligned)) 2402 // was written e.g. 2403 void CodeGenFunction::EmitAlignmentAssumptionCheck( 2404 llvm::Value *Ptr, QualType Ty, SourceLocation Loc, 2405 SourceLocation SecondaryLoc, llvm::Value *Alignment, 2406 llvm::Value *OffsetValue, llvm::Value *TheCheck, 2407 llvm::Instruction *Assumption) { 2408 assert(Assumption && isa<llvm::CallInst>(Assumption) && 2409 cast<llvm::CallInst>(Assumption)->getCalledValue() == 2410 llvm::Intrinsic::getDeclaration( 2411 Builder.GetInsertBlock()->getParent()->getParent(), 2412 llvm::Intrinsic::assume) && 2413 "Assumption should be a call to llvm.assume()."); 2414 assert(&(Builder.GetInsertBlock()->back()) == Assumption && 2415 "Assumption should be the last instruction of the basic block, " 2416 "since the basic block is still being generated."); 2417 2418 if (!SanOpts.has(SanitizerKind::Alignment)) 2419 return; 2420 2421 // Don't check pointers to volatile data. The behavior here is implementation- 2422 // defined. 2423 if (Ty->getPointeeType().isVolatileQualified()) 2424 return; 2425 2426 // We need to temorairly remove the assumption so we can insert the 2427 // sanitizer check before it, else the check will be dropped by optimizations. 2428 Assumption->removeFromParent(); 2429 2430 { 2431 SanitizerScope SanScope(this); 2432 2433 if (!OffsetValue) 2434 OffsetValue = Builder.getInt1(0); // no offset. 2435 2436 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc), 2437 EmitCheckSourceLocation(SecondaryLoc), 2438 EmitCheckTypeDescriptor(Ty)}; 2439 llvm::Value *DynamicData[] = {EmitCheckValue(Ptr), 2440 EmitCheckValue(Alignment), 2441 EmitCheckValue(OffsetValue)}; 2442 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)}, 2443 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData); 2444 } 2445 2446 // We are now in the (new, empty) "cont" basic block. 2447 // Reintroduce the assumption. 2448 Builder.Insert(Assumption); 2449 // FIXME: Assumption still has it's original basic block as it's Parent. 2450 } 2451 2452 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 2453 if (CGDebugInfo *DI = getDebugInfo()) 2454 return DI->SourceLocToDebugLoc(Location); 2455 2456 return llvm::DebugLoc(); 2457 } 2458