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