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