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