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