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