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