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