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