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