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