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