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