1193326Sed//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2193326Sed// 3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4353358Sdim// See https://llvm.org/LICENSE.txt for license information. 5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6193326Sed// 7193326Sed//===----------------------------------------------------------------------===// 8193326Sed// 9193326Sed// This coordinates the per-function state used while generating code. 10193326Sed// 11193326Sed//===----------------------------------------------------------------------===// 12193326Sed 13193326Sed#include "CodeGenFunction.h" 14296417Sdim#include "CGBlocks.h" 15226633Sdim#include "CGCUDARuntime.h" 16212904Sdim#include "CGCXXABI.h" 17360784Sdim#include "CGCleanup.h" 18193326Sed#include "CGDebugInfo.h" 19276479Sdim#include "CGOpenMPRuntime.h" 20249423Sdim#include "CodeGenModule.h" 21276479Sdim#include "CodeGenPGO.h" 22261991Sdim#include "TargetInfo.h" 23193326Sed#include "clang/AST/ASTContext.h" 24323112Sdim#include "clang/AST/ASTLambda.h" 25360784Sdim#include "clang/AST/Attr.h" 26193326Sed#include "clang/AST/Decl.h" 27193326Sed#include "clang/AST/DeclCXX.h" 28200583Srdivacky#include "clang/AST/StmtCXX.h" 29310194Sdim#include "clang/AST/StmtObjC.h" 30296417Sdim#include "clang/Basic/Builtins.h" 31344779Sdim#include "clang/Basic/CodeGenOptions.h" 32249423Sdim#include "clang/Basic/TargetInfo.h" 33261991Sdim#include "clang/CodeGen/CGFunctionInfo.h" 34344779Sdim#include "clang/Frontend/FrontendDiagnostic.h" 35249423Sdim#include "llvm/IR/DataLayout.h" 36327952Sdim#include "llvm/IR/Dominators.h" 37360784Sdim#include "llvm/IR/FPEnv.h" 38360784Sdim#include "llvm/IR/IntrinsicInst.h" 39249423Sdim#include "llvm/IR/Intrinsics.h" 40249423Sdim#include "llvm/IR/MDBuilder.h" 41249423Sdim#include "llvm/IR/Operator.h" 42327952Sdim#include "llvm/Transforms/Utils/PromoteMemToReg.h" 43193326Sedusing namespace clang; 44193326Sedusing namespace CodeGen; 45193326Sed 46314564Sdim/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 47314564Sdim/// markers. 48314564Sdimstatic bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 49314564Sdim const LangOptions &LangOpts) { 50314564Sdim if (CGOpts.DisableLifetimeMarkers) 51314564Sdim return false; 52314564Sdim 53360784Sdim // Sanitizers may use markers. 54360784Sdim if (CGOpts.SanitizeAddressUseAfterScope || 55360784Sdim LangOpts.Sanitize.has(SanitizerKind::HWAddress) || 56360784Sdim LangOpts.Sanitize.has(SanitizerKind::Memory)) 57321369Sdim return true; 58321369Sdim 59314564Sdim // For now, only in optimized builds. 60314564Sdim return CGOpts.OptimizationLevel != 0; 61314564Sdim} 62314564Sdim 63239462SdimCodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 64261991Sdim : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 65296417Sdim Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 66276479Sdim CGBuilderInserterTy(this)), 67341825Sdim SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()), 68341825Sdim PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers( 69341825Sdim CGM.getCodeGenOpts(), CGM.getLangOpts())) { 70239462Sdim if (!suppressNewContext) 71239462Sdim CGM.getCXXABI().getMangleContext().startNewFunction(); 72249423Sdim 73249423Sdim llvm::FastMathFlags FMF; 74249423Sdim if (CGM.getLangOpts().FastMath) 75327952Sdim FMF.setFast(); 76249423Sdim if (CGM.getLangOpts().FiniteMathOnly) { 77249423Sdim FMF.setNoNaNs(); 78249423Sdim FMF.setNoInfs(); 79249423Sdim } 80280031Sdim if (CGM.getCodeGenOpts().NoNaNsFPMath) { 81280031Sdim FMF.setNoNaNs(); 82280031Sdim } 83280031Sdim if (CGM.getCodeGenOpts().NoSignedZeros) { 84280031Sdim FMF.setNoSignedZeros(); 85280031Sdim } 86288943Sdim if (CGM.getCodeGenOpts().ReciprocalMath) { 87288943Sdim FMF.setAllowReciprocal(); 88288943Sdim } 89327952Sdim if (CGM.getCodeGenOpts().Reassociate) { 90327952Sdim FMF.setAllowReassoc(); 91327952Sdim } 92296417Sdim Builder.setFastMathFlags(FMF); 93360784Sdim SetFPModel(); 94193326Sed} 95193326Sed 96234353SdimCodeGenFunction::~CodeGenFunction() { 97261991Sdim assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 98261991Sdim 99234353Sdim // If there are any unclaimed block infos, go ahead and destroy them 100234353Sdim // now. This can happen if IR-gen gets clever and skips evaluating 101234353Sdim // something. 102234353Sdim if (FirstBlockInfo) 103234353Sdim destroyBlockInfos(FirstBlockInfo); 104276479Sdim 105314564Sdim if (getLangOpts().OpenMP && CurFn) 106288943Sdim CGM.getOpenMPRuntime().functionFinished(*this); 107234353Sdim} 108193326Sed 109360784Sdim// Map the LangOption for rounding mode into 110360784Sdim// the corresponding enum in the IR. 111360784Sdimstatic llvm::fp::RoundingMode ToConstrainedRoundingMD( 112360784Sdim LangOptions::FPRoundingModeKind Kind) { 113360784Sdim 114360784Sdim switch (Kind) { 115360784Sdim case LangOptions::FPR_ToNearest: return llvm::fp::rmToNearest; 116360784Sdim case LangOptions::FPR_Downward: return llvm::fp::rmDownward; 117360784Sdim case LangOptions::FPR_Upward: return llvm::fp::rmUpward; 118360784Sdim case LangOptions::FPR_TowardZero: return llvm::fp::rmTowardZero; 119360784Sdim case LangOptions::FPR_Dynamic: return llvm::fp::rmDynamic; 120360784Sdim } 121360784Sdim llvm_unreachable("Unsupported FP RoundingMode"); 122360784Sdim} 123360784Sdim 124360784Sdim// Map the LangOption for exception behavior into 125360784Sdim// the corresponding enum in the IR. 126360784Sdimstatic llvm::fp::ExceptionBehavior ToConstrainedExceptMD( 127360784Sdim LangOptions::FPExceptionModeKind Kind) { 128360784Sdim 129360784Sdim switch (Kind) { 130360784Sdim case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore; 131360784Sdim case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap; 132360784Sdim case LangOptions::FPE_Strict: return llvm::fp::ebStrict; 133360784Sdim } 134360784Sdim llvm_unreachable("Unsupported FP Exception Behavior"); 135360784Sdim} 136360784Sdim 137360784Sdimvoid CodeGenFunction::SetFPModel() { 138360784Sdim auto fpRoundingMode = ToConstrainedRoundingMD( 139360784Sdim getLangOpts().getFPRoundingMode()); 140360784Sdim auto fpExceptionBehavior = ToConstrainedExceptMD( 141360784Sdim getLangOpts().getFPExceptionMode()); 142360784Sdim 143360784Sdim if (fpExceptionBehavior == llvm::fp::ebIgnore && 144360784Sdim fpRoundingMode == llvm::fp::rmToNearest) 145360784Sdim // Constrained intrinsics are not used. 146360784Sdim ; 147360784Sdim else { 148360784Sdim Builder.setIsFPConstrained(true); 149360784Sdim Builder.setDefaultConstrainedRounding(fpRoundingMode); 150360784Sdim Builder.setDefaultConstrainedExcept(fpExceptionBehavior); 151360784Sdim } 152360784Sdim} 153360784Sdim 154296417SdimCharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 155327952Sdim LValueBaseInfo *BaseInfo, 156327952Sdim TBAAAccessInfo *TBAAInfo) { 157327952Sdim return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 158327952Sdim /* forPointeeType= */ true); 159296417Sdim} 160296417Sdim 161296417SdimCharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 162321369Sdim LValueBaseInfo *BaseInfo, 163327952Sdim TBAAAccessInfo *TBAAInfo, 164296417Sdim bool forPointeeType) { 165327952Sdim if (TBAAInfo) 166327952Sdim *TBAAInfo = CGM.getTBAAAccessInfo(T); 167327952Sdim 168296417Sdim // Honor alignment typedef attributes even on incomplete types. 169296417Sdim // We also honor them straight for C++ class types, even as pointees; 170296417Sdim // there's an expressivity gap here. 171296417Sdim if (auto TT = T->getAs<TypedefType>()) { 172296417Sdim if (auto Align = TT->getDecl()->getMaxAlignment()) { 173321369Sdim if (BaseInfo) 174327952Sdim *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 175296417Sdim return getContext().toCharUnitsFromBits(Align); 176296417Sdim } 177296417Sdim } 178296417Sdim 179321369Sdim if (BaseInfo) 180327952Sdim *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 181296417Sdim 182280031Sdim CharUnits Alignment; 183296417Sdim if (T->isIncompleteType()) { 184296417Sdim Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 185296417Sdim } else { 186296417Sdim // For C++ class pointees, we don't know whether we're pointing at a 187296417Sdim // base or a complete object, so we generally need to use the 188296417Sdim // non-virtual alignment. 189296417Sdim const CXXRecordDecl *RD; 190296417Sdim if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 191296417Sdim Alignment = CGM.getClassPointerAlignment(RD); 192296417Sdim } else { 193296417Sdim Alignment = getContext().getTypeAlignInChars(T); 194321369Sdim if (T.getQualifiers().hasUnaligned()) 195321369Sdim Alignment = CharUnits::One(); 196296417Sdim } 197296417Sdim 198296417Sdim // Cap to the global maximum type alignment unless the alignment 199296417Sdim // was somehow explicit on the type. 200296417Sdim if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 201296417Sdim if (Alignment.getQuantity() > MaxAlign && 202296417Sdim !getContext().isAlignmentRequired(T)) 203296417Sdim Alignment = CharUnits::fromQuantity(MaxAlign); 204296417Sdim } 205280031Sdim } 206296417Sdim return Alignment; 207280031Sdim} 208234353Sdim 209296417SdimLValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 210321369Sdim LValueBaseInfo BaseInfo; 211327952Sdim TBAAAccessInfo TBAAInfo; 212327952Sdim CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo); 213321369Sdim return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo, 214327952Sdim TBAAInfo); 215296417Sdim} 216296417Sdim 217296417Sdim/// Given a value of type T* that may not be to a complete object, 218296417Sdim/// construct an l-value with the natural pointee alignment of T. 219296417SdimLValue 220296417SdimCodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 221321369Sdim LValueBaseInfo BaseInfo; 222327952Sdim TBAAAccessInfo TBAAInfo; 223327952Sdim CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, 224327952Sdim /* forPointeeType= */ true); 225327952Sdim return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo); 226296417Sdim} 227296417Sdim 228296417Sdim 229224145Sdimllvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 230193326Sed return CGM.getTypes().ConvertTypeForMem(T); 231193326Sed} 232193326Sed 233224145Sdimllvm::Type *CodeGenFunction::ConvertType(QualType T) { 234193326Sed return CGM.getTypes().ConvertType(T); 235193326Sed} 236193326Sed 237249423SdimTypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 238249423Sdim type = type.getCanonicalType(); 239249423Sdim while (true) { 240249423Sdim switch (type->getTypeClass()) { 241223017Sdim#define TYPE(name, parent) 242223017Sdim#define ABSTRACT_TYPE(name, parent) 243223017Sdim#define NON_CANONICAL_TYPE(name, parent) case Type::name: 244223017Sdim#define DEPENDENT_TYPE(name, parent) case Type::name: 245223017Sdim#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 246360784Sdim#include "clang/AST/TypeNodes.inc" 247249423Sdim llvm_unreachable("non-canonical or dependent type in IR-generation"); 248223017Sdim 249251662Sdim case Type::Auto: 250321369Sdim case Type::DeducedTemplateSpecialization: 251321369Sdim llvm_unreachable("undeduced type in IR-generation"); 252251662Sdim 253249423Sdim // Various scalar types. 254249423Sdim case Type::Builtin: 255249423Sdim case Type::Pointer: 256249423Sdim case Type::BlockPointer: 257249423Sdim case Type::LValueReference: 258249423Sdim case Type::RValueReference: 259249423Sdim case Type::MemberPointer: 260249423Sdim case Type::Vector: 261249423Sdim case Type::ExtVector: 262249423Sdim case Type::FunctionProto: 263249423Sdim case Type::FunctionNoProto: 264249423Sdim case Type::Enum: 265249423Sdim case Type::ObjCObjectPointer: 266296417Sdim case Type::Pipe: 267249423Sdim return TEK_Scalar; 268223017Sdim 269249423Sdim // Complexes. 270249423Sdim case Type::Complex: 271249423Sdim return TEK_Complex; 272226633Sdim 273249423Sdim // Arrays, records, and Objective-C objects. 274249423Sdim case Type::ConstantArray: 275249423Sdim case Type::IncompleteArray: 276249423Sdim case Type::VariableArray: 277249423Sdim case Type::Record: 278249423Sdim case Type::ObjCObject: 279249423Sdim case Type::ObjCInterface: 280249423Sdim return TEK_Aggregate; 281249423Sdim 282249423Sdim // We operate on atomic values according to their underlying type. 283249423Sdim case Type::Atomic: 284249423Sdim type = cast<AtomicType>(type)->getValueType(); 285249423Sdim continue; 286249423Sdim } 287249423Sdim llvm_unreachable("unknown type kind!"); 288223017Sdim } 289193326Sed} 290193326Sed 291280031Sdimllvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 292193326Sed // For cleanliness, we try to avoid emitting the return block for 293193326Sed // simple cases. 294193326Sed llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 295193326Sed 296193326Sed if (CurBB) { 297193326Sed assert(!CurBB->getTerminator() && "Unexpected terminated block."); 298193326Sed 299198092Srdivacky // We have a valid insert point, reuse it if it is empty or there are no 300198092Srdivacky // explicit jumps to the return block. 301212904Sdim if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 302212904Sdim ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 303212904Sdim delete ReturnBlock.getBlock(); 304353358Sdim ReturnBlock = JumpDest(); 305198092Srdivacky } else 306212904Sdim EmitBlock(ReturnBlock.getBlock()); 307280031Sdim return llvm::DebugLoc(); 308193326Sed } 309193326Sed 310193326Sed // Otherwise, if the return block is the target of a single direct 311193326Sed // branch then we can just put the code in that block instead. This 312193326Sed // cleans up functions which started with a unified return block. 313212904Sdim if (ReturnBlock.getBlock()->hasOneUse()) { 314198092Srdivacky llvm::BranchInst *BI = 315276479Sdim dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 316210299Sed if (BI && BI->isUnconditional() && 317212904Sdim BI->getSuccessor(0) == ReturnBlock.getBlock()) { 318280031Sdim // Record/return the DebugLoc of the simple 'return' expression to be used 319280031Sdim // later by the actual 'ret' instruction. 320280031Sdim llvm::DebugLoc Loc = BI->getDebugLoc(); 321193326Sed Builder.SetInsertPoint(BI->getParent()); 322193326Sed BI->eraseFromParent(); 323212904Sdim delete ReturnBlock.getBlock(); 324353358Sdim ReturnBlock = JumpDest(); 325280031Sdim return Loc; 326193326Sed } 327193326Sed } 328193326Sed 329193326Sed // FIXME: We are at an unreachable point, there is no reason to emit the block 330193326Sed // unless it has uses. However, we still need a place to put the debug 331193326Sed // region.end for now. 332193326Sed 333212904Sdim EmitBlock(ReturnBlock.getBlock()); 334280031Sdim return llvm::DebugLoc(); 335193326Sed} 336193326Sed 337210299Sedstatic void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 338210299Sed if (!BB) return; 339210299Sed if (!BB->use_empty()) 340210299Sed return CGF.CurFn->getBasicBlockList().push_back(BB); 341210299Sed delete BB; 342210299Sed} 343210299Sed 344193326Sedvoid CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 345193326Sed assert(BreakContinueStack.empty() && 346193326Sed "mismatched push/pop in break/continue stack!"); 347198092Srdivacky 348251662Sdim bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 349261991Sdim && NumSimpleReturnExprs == NumReturnExprs 350261991Sdim && ReturnBlock.getBlock()->use_empty(); 351261991Sdim // Usually the return expression is evaluated before the cleanup 352261991Sdim // code. If the function contains only a simple return statement, 353261991Sdim // such as a constant, the location before the cleanup code becomes 354261991Sdim // the last useful breakpoint in the function, because the simple 355261991Sdim // return expression will be evaluated after the cleanup code. To be 356261991Sdim // safe, set the debug location for cleanup code to the location of 357261991Sdim // the return statement. Otherwise the cleanup code should be at the 358261991Sdim // end of the function's lexical scope. 359261991Sdim // 360261991Sdim // If there are multiple branches to the return block, the branch 361261991Sdim // instructions will get the location of the return statements and 362261991Sdim // all will be fine. 363251662Sdim if (CGDebugInfo *DI = getDebugInfo()) { 364251662Sdim if (OnlySimpleReturnStmts) 365261991Sdim DI->EmitLocation(Builder, LastStopPoint); 366251662Sdim else 367251662Sdim DI->EmitLocation(Builder, EndLoc); 368251662Sdim } 369249423Sdim 370224145Sdim // Pop any cleanups that might have been associated with the 371224145Sdim // parameters. Do this in whatever block we're currently in; it's 372224145Sdim // important to do this before we enter the return block or return 373224145Sdim // edges will be *really* confused. 374288943Sdim bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 375288943Sdim bool HasOnlyLifetimeMarkers = 376288943Sdim HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 377288943Sdim bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 378288943Sdim if (HasCleanups) { 379251662Sdim // Make sure the line table doesn't jump back into the body for 380251662Sdim // the ret after it's been at EndLoc. 381360784Sdim Optional<ApplyDebugLocation> AL; 382360784Sdim if (CGDebugInfo *DI = getDebugInfo()) { 383251662Sdim if (OnlySimpleReturnStmts) 384251662Sdim DI->EmitLocation(Builder, EndLoc); 385360784Sdim else 386360784Sdim // We may not have a valid end location. Try to apply it anyway, and 387360784Sdim // fall back to an artificial location if needed. 388360784Sdim AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc); 389360784Sdim } 390288943Sdim 391288943Sdim PopCleanupBlocks(PrologueCleanupDepth); 392251662Sdim } 393251662Sdim 394198092Srdivacky // Emit function epilog (to return). 395280031Sdim llvm::DebugLoc Loc = EmitReturnBlock(); 396193326Sed 397327952Sdim if (ShouldInstrumentFunction()) { 398327952Sdim if (CGM.getCodeGenOpts().InstrumentFunctions) 399327952Sdim CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit"); 400327952Sdim if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 401327952Sdim CurFn->addFnAttr("instrument-function-exit-inlined", 402327952Sdim "__cyg_profile_func_exit"); 403327952Sdim } 404210299Sed 405193326Sed // Emit debug descriptor for function end. 406280031Sdim if (CGDebugInfo *DI = getDebugInfo()) 407321369Sdim DI->EmitFunctionEnd(Builder, CurFn); 408193326Sed 409280031Sdim // Reset the debug location to that of the simple 'return' expression, if any 410280031Sdim // rather than that of the end of the function's scope '}'. 411280031Sdim ApplyDebugLocation AL(*this, Loc); 412261991Sdim EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 413200583Srdivacky EmitEndEHSpec(CurCodeDecl); 414193326Sed 415210299Sed assert(EHStack.empty() && 416210299Sed "did not remove all scopes from cleanup stack!"); 417210299Sed 418198893Srdivacky // If someone did an indirect goto, emit the indirect goto block at the end of 419198893Srdivacky // the function. 420198893Srdivacky if (IndirectBranch) { 421198893Srdivacky EmitBlock(IndirectBranch->getParent()); 422198893Srdivacky Builder.ClearInsertionPoint(); 423198893Srdivacky } 424249423Sdim 425288943Sdim // If some of our locals escaped, insert a call to llvm.localescape in the 426288943Sdim // entry block. 427288943Sdim if (!EscapedLocals.empty()) { 428288943Sdim // Invert the map from local to index into a simple vector. There should be 429288943Sdim // no holes. 430288943Sdim SmallVector<llvm::Value *, 4> EscapeArgs; 431288943Sdim EscapeArgs.resize(EscapedLocals.size()); 432288943Sdim for (auto &Pair : EscapedLocals) 433288943Sdim EscapeArgs[Pair.second] = Pair.first; 434288943Sdim llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 435288943Sdim &CGM.getModule(), llvm::Intrinsic::localescape); 436296417Sdim CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 437288943Sdim } 438288943Sdim 439193326Sed // Remove the AllocaInsertPt instruction, which is just a convenience for us. 440193326Sed llvm::Instruction *Ptr = AllocaInsertPt; 441276479Sdim AllocaInsertPt = nullptr; 442193326Sed Ptr->eraseFromParent(); 443249423Sdim 444198893Srdivacky // If someone took the address of a label but never did an indirect goto, we 445198893Srdivacky // made a zero entry PHI node, which is illegal, zap it now. 446198893Srdivacky if (IndirectBranch) { 447198893Srdivacky llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 448198893Srdivacky if (PN->getNumIncomingValues() == 0) { 449198893Srdivacky PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 450198893Srdivacky PN->eraseFromParent(); 451198893Srdivacky } 452198893Srdivacky } 453210299Sed 454226633Sdim EmitIfUsed(*this, EHResumeBlock); 455210299Sed EmitIfUsed(*this, TerminateLandingPad); 456210299Sed EmitIfUsed(*this, TerminateHandler); 457210299Sed EmitIfUsed(*this, UnreachableBlock); 458210299Sed 459327952Sdim for (const auto &FuncletAndParent : TerminateFunclets) 460327952Sdim EmitIfUsed(*this, FuncletAndParent.second); 461327952Sdim 462210299Sed if (CGM.getCodeGenOpts().EmitDeclMetadata) 463210299Sed EmitDeclMetadata(); 464276479Sdim 465276479Sdim for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 466276479Sdim I = DeferredReplacements.begin(), 467276479Sdim E = DeferredReplacements.end(); 468276479Sdim I != E; ++I) { 469276479Sdim I->first->replaceAllUsesWith(I->second); 470276479Sdim I->first->eraseFromParent(); 471276479Sdim } 472327952Sdim 473327952Sdim // Eliminate CleanupDestSlot alloca by replacing it with SSA values and 474327952Sdim // PHIs if the current function is a coroutine. We don't do it for all 475327952Sdim // functions as it may result in slight increase in numbers of instructions 476327952Sdim // if compiled with no optimizations. We do it for coroutine as the lifetime 477327952Sdim // of CleanupDestSlot alloca make correct coroutine frame building very 478327952Sdim // difficult. 479341825Sdim if (NormalCleanupDest.isValid() && isCoroutine()) { 480327952Sdim llvm::DominatorTree DT(*CurFn); 481341825Sdim llvm::PromoteMemToReg( 482341825Sdim cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT); 483341825Sdim NormalCleanupDest = Address::invalid(); 484327952Sdim } 485341825Sdim 486344779Sdim // Scan function arguments for vector width. 487344779Sdim for (llvm::Argument &A : CurFn->args()) 488344779Sdim if (auto *VT = dyn_cast<llvm::VectorType>(A.getType())) 489360784Sdim LargestVectorWidth = std::max((uint64_t)LargestVectorWidth, 490360784Sdim VT->getPrimitiveSizeInBits().getFixedSize()); 491344779Sdim 492344779Sdim // Update vector width based on return type. 493344779Sdim if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType())) 494360784Sdim LargestVectorWidth = std::max((uint64_t)LargestVectorWidth, 495360784Sdim VT->getPrimitiveSizeInBits().getFixedSize()); 496344779Sdim 497344779Sdim // Add the required-vector-width attribute. This contains the max width from: 498344779Sdim // 1. min-vector-width attribute used in the source program. 499344779Sdim // 2. Any builtins used that have a vector width specified. 500344779Sdim // 3. Values passed in and out of inline assembly. 501344779Sdim // 4. Width of vector arguments and return types for this function. 502344779Sdim // 5. Width of vector aguments and return types for functions called by this 503344779Sdim // function. 504344779Sdim CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth)); 505353358Sdim 506353358Sdim // If we generated an unreachable return block, delete it now. 507353358Sdim if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) { 508353358Sdim Builder.ClearInsertionPoint(); 509353358Sdim ReturnBlock.getBlock()->eraseFromParent(); 510353358Sdim } 511353358Sdim if (ReturnValue.isValid()) { 512353358Sdim auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer()); 513353358Sdim if (RetAlloca && RetAlloca->use_empty()) { 514353358Sdim RetAlloca->eraseFromParent(); 515353358Sdim ReturnValue = Address::invalid(); 516353358Sdim } 517353358Sdim } 518193326Sed} 519193326Sed 520210299Sed/// ShouldInstrumentFunction - Return true if the current function should be 521210299Sed/// instrumented with __cyg_profile_func_* calls 522210299Sedbool CodeGenFunction::ShouldInstrumentFunction() { 523327952Sdim if (!CGM.getCodeGenOpts().InstrumentFunctions && 524327952Sdim !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining && 525327952Sdim !CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 526210299Sed return false; 527223017Sdim if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 528210299Sed return false; 529210299Sed return true; 530210299Sed} 531210299Sed 532309124Sdim/// ShouldXRayInstrument - Return true if the current function should be 533309124Sdim/// instrumented with XRay nop sleds. 534309124Sdimbool CodeGenFunction::ShouldXRayInstrumentFunction() const { 535309124Sdim return CGM.getCodeGenOpts().XRayInstrumentFunctions; 536309124Sdim} 537309124Sdim 538327952Sdim/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to 539341825Sdim/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation. 540327952Sdimbool CodeGenFunction::AlwaysEmitXRayCustomEvents() const { 541341825Sdim return CGM.getCodeGenOpts().XRayInstrumentFunctions && 542341825Sdim (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents || 543341825Sdim CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 544341825Sdim XRayInstrKind::Custom); 545327952Sdim} 546210299Sed 547341825Sdimbool CodeGenFunction::AlwaysEmitXRayTypedEvents() const { 548341825Sdim return CGM.getCodeGenOpts().XRayInstrumentFunctions && 549341825Sdim (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents || 550341825Sdim CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 551341825Sdim XRayInstrKind::Typed); 552341825Sdim} 553341825Sdim 554327952Sdimllvm::Constant * 555327952SdimCodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F, 556327952Sdim llvm::Constant *Addr) { 557327952Sdim // Addresses stored in prologue data can't require run-time fixups and must 558327952Sdim // be PC-relative. Run-time fixups are undesirable because they necessitate 559327952Sdim // writable text segments, which are unsafe. And absolute addresses are 560327952Sdim // undesirable because they break PIE mode. 561210299Sed 562327952Sdim // Add a layer of indirection through a private global. Taking its address 563327952Sdim // won't result in a run-time fixup, even if Addr has linkonce_odr linkage. 564327952Sdim auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(), 565327952Sdim /*isConstant=*/true, 566327952Sdim llvm::GlobalValue::PrivateLinkage, Addr); 567249423Sdim 568327952Sdim // Create a PC-relative address. 569327952Sdim auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy); 570327952Sdim auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy); 571327952Sdim auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt); 572327952Sdim return (IntPtrTy == Int32Ty) 573327952Sdim ? PCRelAsInt 574327952Sdim : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty); 575210299Sed} 576210299Sed 577327952Sdimllvm::Value * 578327952SdimCodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F, 579327952Sdim llvm::Value *EncodedAddr) { 580327952Sdim // Reconstruct the address of the global. 581327952Sdim auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy); 582327952Sdim auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int"); 583327952Sdim auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int"); 584327952Sdim auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr"); 585327952Sdim 586327952Sdim // Load the original pointer through the global. 587327952Sdim return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()), 588327952Sdim "decoded_addr"); 589327952Sdim} 590327952Sdim 591249423Sdimvoid CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 592239462Sdim llvm::Function *Fn) 593239462Sdim{ 594239462Sdim if (!FD->hasAttr<OpenCLKernelAttr>()) 595239462Sdim return; 596239462Sdim 597239462Sdim llvm::LLVMContext &Context = getLLVMContext(); 598239462Sdim 599353358Sdim CGM.GenOpenCLArgMetadata(Fn, FD, this); 600239462Sdim 601276479Sdim if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 602321369Sdim QualType HintQTy = A->getTypeHint(); 603321369Sdim const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>(); 604321369Sdim bool IsSignedInteger = 605321369Sdim HintQTy->isSignedIntegerType() || 606321369Sdim (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType()); 607321369Sdim llvm::Metadata *AttrMDArgs[] = { 608280031Sdim llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 609280031Sdim CGM.getTypes().ConvertType(A->getTypeHint()))), 610280031Sdim llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 611280031Sdim llvm::IntegerType::get(Context, 32), 612321369Sdim llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))}; 613321369Sdim Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs)); 614249423Sdim } 615249423Sdim 616276479Sdim if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 617321369Sdim llvm::Metadata *AttrMDArgs[] = { 618280031Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 619280031Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 620280031Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 621321369Sdim Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs)); 622239462Sdim } 623239462Sdim 624276479Sdim if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 625321369Sdim llvm::Metadata *AttrMDArgs[] = { 626280031Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 627280031Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 628280031Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 629321369Sdim Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs)); 630239462Sdim } 631321369Sdim 632321369Sdim if (const OpenCLIntelReqdSubGroupSizeAttr *A = 633321369Sdim FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 634321369Sdim llvm::Metadata *AttrMDArgs[] = { 635321369Sdim llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))}; 636321369Sdim Fn->setMetadata("intel_reqd_sub_group_size", 637321369Sdim llvm::MDNode::get(Context, AttrMDArgs)); 638321369Sdim } 639239462Sdim} 640239462Sdim 641276479Sdim/// Determine whether the function F ends with a return stmt. 642276479Sdimstatic bool endsWithReturn(const Decl* F) { 643276479Sdim const Stmt *Body = nullptr; 644276479Sdim if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 645276479Sdim Body = FD->getBody(); 646276479Sdim else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 647276479Sdim Body = OMD->getBody(); 648276479Sdim 649276479Sdim if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 650276479Sdim auto LastStmt = CS->body_rbegin(); 651276479Sdim if (LastStmt != CS->body_rend()) 652276479Sdim return isa<ReturnStmt>(*LastStmt); 653276479Sdim } 654276479Sdim return false; 655276479Sdim} 656276479Sdim 657344779Sdimvoid CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) { 658344779Sdim if (SanOpts.has(SanitizerKind::Thread)) { 659344779Sdim Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 660344779Sdim Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 661344779Sdim } 662321369Sdim} 663321369Sdim 664360784Sdim/// Check if the return value of this function requires sanitization. 665360784Sdimbool CodeGenFunction::requiresReturnValueCheck() const { 666360784Sdim return requiresReturnValueNullabilityCheck() || 667360784Sdim (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl && 668360784Sdim CurCodeDecl->getAttr<ReturnsNonNullAttr>()); 669360784Sdim} 670360784Sdim 671327952Sdimstatic bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) { 672327952Sdim auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 673327952Sdim if (!MD || !MD->getDeclName().getAsIdentifierInfo() || 674327952Sdim !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") || 675327952Sdim (MD->getNumParams() != 1 && MD->getNumParams() != 2)) 676327952Sdim return false; 677327952Sdim 678327952Sdim if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType()) 679327952Sdim return false; 680327952Sdim 681327952Sdim if (MD->getNumParams() == 2) { 682327952Sdim auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>(); 683327952Sdim if (!PT || !PT->isVoidPointerType() || 684327952Sdim !PT->getPointeeType().isConstQualified()) 685327952Sdim return false; 686327952Sdim } 687327952Sdim 688327952Sdim return true; 689327952Sdim} 690327952Sdim 691327952Sdim/// Return the UBSan prologue signature for \p FD if one is available. 692327952Sdimstatic llvm::Constant *getPrologueSignature(CodeGenModule &CGM, 693327952Sdim const FunctionDecl *FD) { 694327952Sdim if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 695327952Sdim if (!MD->isStatic()) 696327952Sdim return nullptr; 697327952Sdim return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM); 698327952Sdim} 699327952Sdim 700360784Sdimvoid CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 701193326Sed llvm::Function *Fn, 702221345Sdim const CGFunctionInfo &FnInfo, 703193326Sed const FunctionArgList &Args, 704276479Sdim SourceLocation Loc, 705193326Sed SourceLocation StartLoc) { 706280031Sdim assert(!CurFn && 707280031Sdim "Do not use a CodeGenFunction object for more than one function"); 708280031Sdim 709198092Srdivacky const Decl *D = GD.getDecl(); 710249423Sdim 711193326Sed DidCallStackSave = false; 712251662Sdim CurCodeDecl = D; 713309124Sdim if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 714309124Sdim if (FD->usesSEHTry()) 715309124Sdim CurSEHParent = FD; 716276479Sdim CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 717193326Sed FnRetTy = RetTy; 718193326Sed CurFn = Fn; 719221345Sdim CurFnInfo = &FnInfo; 720193326Sed assert(CurFn->isDeclaration() && "Function already has body?"); 721193326Sed 722327952Sdim // If this function has been blacklisted for any of the enabled sanitizers, 723327952Sdim // disable the sanitizer for the function. 724327952Sdim do { 725327952Sdim#define SANITIZER(NAME, ID) \ 726327952Sdim if (SanOpts.empty()) \ 727327952Sdim break; \ 728327952Sdim if (SanOpts.has(SanitizerKind::ID)) \ 729327952Sdim if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \ 730327952Sdim SanOpts.set(SanitizerKind::ID, false); 731249423Sdim 732327952Sdim#include "clang/Basic/Sanitizers.def" 733327952Sdim#undef SANITIZER 734327952Sdim } while (0); 735327952Sdim 736288943Sdim if (D) { 737288943Sdim // Apply the no_sanitize* attributes to SanOpts. 738341825Sdim for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) { 739341825Sdim SanitizerMask mask = Attr->getMask(); 740341825Sdim SanOpts.Mask &= ~mask; 741341825Sdim if (mask & SanitizerKind::Address) 742341825Sdim SanOpts.set(SanitizerKind::KernelAddress, false); 743341825Sdim if (mask & SanitizerKind::KernelAddress) 744341825Sdim SanOpts.set(SanitizerKind::Address, false); 745341825Sdim if (mask & SanitizerKind::HWAddress) 746341825Sdim SanOpts.set(SanitizerKind::KernelHWAddress, false); 747341825Sdim if (mask & SanitizerKind::KernelHWAddress) 748341825Sdim SanOpts.set(SanitizerKind::HWAddress, false); 749341825Sdim } 750288943Sdim } 751288943Sdim 752288943Sdim // Apply sanitizer attributes to the function. 753288943Sdim if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 754288943Sdim Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 755341825Sdim if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress)) 756327952Sdim Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); 757353358Sdim if (SanOpts.has(SanitizerKind::MemTag)) 758353358Sdim Fn->addFnAttr(llvm::Attribute::SanitizeMemTag); 759288943Sdim if (SanOpts.has(SanitizerKind::Thread)) 760288943Sdim Fn->addFnAttr(llvm::Attribute::SanitizeThread); 761344779Sdim if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory)) 762288943Sdim Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 763288943Sdim if (SanOpts.has(SanitizerKind::SafeStack)) 764288943Sdim Fn->addFnAttr(llvm::Attribute::SafeStack); 765341825Sdim if (SanOpts.has(SanitizerKind::ShadowCallStack)) 766341825Sdim Fn->addFnAttr(llvm::Attribute::ShadowCallStack); 767288943Sdim 768341825Sdim // Apply fuzzing attribute to the function. 769341825Sdim if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink)) 770341825Sdim Fn->addFnAttr(llvm::Attribute::OptForFuzzing); 771341825Sdim 772314564Sdim // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 773321369Sdim // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time. 774314564Sdim if (SanOpts.has(SanitizerKind::Thread)) { 775314564Sdim if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 776314564Sdim IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 777314564Sdim if (OMD->getMethodFamily() == OMF_dealloc || 778314564Sdim OMD->getMethodFamily() == OMF_initialize || 779314564Sdim (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 780321369Sdim markAsIgnoreThreadCheckingAtRuntime(Fn); 781314564Sdim } 782314564Sdim } 783314564Sdim } 784314564Sdim 785327952Sdim // Ignore unrelated casts in STL allocate() since the allocator must cast 786327952Sdim // from void* to T* before object initialization completes. Don't match on the 787327952Sdim // namespace because not all allocators are in std:: 788327952Sdim if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 789327952Sdim if (matchesStlAllocatorFn(D, getContext())) 790327952Sdim SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast; 791327952Sdim } 792327952Sdim 793360784Sdim // Ignore null checks in coroutine functions since the coroutines passes 794360784Sdim // are not aware of how to move the extra UBSan instructions across the split 795360784Sdim // coroutine boundaries. 796360784Sdim if (D && SanOpts.has(SanitizerKind::Null)) 797360784Sdim if (const auto *FD = dyn_cast<FunctionDecl>(D)) 798360784Sdim if (FD->getBody() && 799360784Sdim FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass) 800360784Sdim SanOpts.Mask &= ~SanitizerKind::Null; 801360784Sdim 802344779Sdim if (D) { 803360784Sdim // Apply xray attributes to the function (as a string, for now) 804309124Sdim if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) { 805344779Sdim if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 806344779Sdim XRayInstrKind::Function)) { 807344779Sdim if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) 808344779Sdim Fn->addFnAttr("function-instrument", "xray-always"); 809344779Sdim if (XRayAttr->neverXRayInstrument()) 810344779Sdim Fn->addFnAttr("function-instrument", "xray-never"); 811344779Sdim if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) 812344779Sdim if (ShouldXRayInstrumentFunction()) 813344779Sdim Fn->addFnAttr("xray-log-args", 814344779Sdim llvm::utostr(LogArgs->getArgumentCount())); 815321369Sdim } 816309124Sdim } else { 817344779Sdim if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc)) 818321369Sdim Fn->addFnAttr( 819321369Sdim "xray-instruction-threshold", 820321369Sdim llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 821309124Sdim } 822360784Sdim 823360784Sdim unsigned Count, Offset; 824360784Sdim if (const auto *Attr = D->getAttr<PatchableFunctionEntryAttr>()) { 825360784Sdim Count = Attr->getCount(); 826360784Sdim Offset = Attr->getOffset(); 827360784Sdim } else { 828360784Sdim Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount; 829360784Sdim Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset; 830360784Sdim } 831360784Sdim if (Count && Offset <= Count) { 832360784Sdim Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset)); 833360784Sdim if (Offset) 834360784Sdim Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset)); 835360784Sdim } 836309124Sdim } 837309124Sdim 838309124Sdim // Add no-jump-tables value. 839309124Sdim Fn->addFnAttr("no-jump-tables", 840309124Sdim llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables)); 841309124Sdim 842360784Sdim // Add no-inline-line-tables value. 843360784Sdim if (CGM.getCodeGenOpts().NoInlineLineTables) 844360784Sdim Fn->addFnAttr("no-inline-line-tables"); 845360784Sdim 846327952Sdim // Add profile-sample-accurate value. 847327952Sdim if (CGM.getCodeGenOpts().ProfileSampleAccurate) 848327952Sdim Fn->addFnAttr("profile-sample-accurate"); 849327952Sdim 850360784Sdim if (D && D->hasAttr<CFICanonicalJumpTableAttr>()) 851360784Sdim Fn->addFnAttr("cfi-canonical-jump-table"); 852360784Sdim 853243830Sdim if (getLangOpts().OpenCL) { 854218893Sdim // Add metadata for a kernel function. 855218893Sdim if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 856239462Sdim EmitOpenCLKernelMetadata(FD, Fn); 857218893Sdim } 858218893Sdim 859261991Sdim // If we are checking function types, emit a function type signature as 860280031Sdim // prologue data. 861280031Sdim if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 862261991Sdim if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 863327952Sdim if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) { 864341825Sdim // Remove any (C++17) exception specifications, to allow calling e.g. a 865341825Sdim // noexcept function through a non-noexcept pointer. 866341825Sdim auto ProtoTy = 867341825Sdim getContext().getFunctionTypeWithExceptionSpec(FD->getType(), 868341825Sdim EST_None); 869261991Sdim llvm::Constant *FTRTTIConst = 870341825Sdim CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true); 871327952Sdim llvm::Constant *FTRTTIConstEncoded = 872327952Sdim EncodeAddrForUseInPrologue(Fn, FTRTTIConst); 873327952Sdim llvm::Constant *PrologueStructElems[] = {PrologueSig, 874327952Sdim FTRTTIConstEncoded}; 875280031Sdim llvm::Constant *PrologueStructConst = 876280031Sdim llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 877280031Sdim Fn->setPrologueData(PrologueStructConst); 878261991Sdim } 879261991Sdim } 880261991Sdim } 881261991Sdim 882321369Sdim // If we're checking nullability, we need to know whether we can check the 883321369Sdim // return value. Initialize the flag to 'true' and refine it in EmitParmDecl. 884321369Sdim if (SanOpts.has(SanitizerKind::NullabilityReturn)) { 885321369Sdim auto Nullability = FnRetTy->getNullability(getContext()); 886321369Sdim if (Nullability && *Nullability == NullabilityKind::NonNull) { 887321369Sdim if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && 888321369Sdim CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>())) 889321369Sdim RetValNullabilityPrecondition = 890321369Sdim llvm::ConstantInt::getTrue(getLLVMContext()); 891321369Sdim } 892321369Sdim } 893321369Sdim 894296417Sdim // If we're in C++ mode and the function name is "main", it is guaranteed 895296417Sdim // to be norecurse by the standard (3.6.1.3 "The function main shall not be 896296417Sdim // used within a program"). 897296417Sdim if (getLangOpts().CPlusPlus) 898296417Sdim if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 899296417Sdim if (FD->isMain()) 900296417Sdim Fn->addFnAttr(llvm::Attribute::NoRecurse); 901314564Sdim 902360784Sdim if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 903360784Sdim if (FD->usesFPIntrin()) 904360784Sdim Fn->addFnAttr(llvm::Attribute::StrictFP); 905360784Sdim 906344779Sdim // If a custom alignment is used, force realigning to this alignment on 907344779Sdim // any main function which certainly will need it. 908344779Sdim if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 909344779Sdim if ((FD->isMain() || FD->isMSVCRTEntryPoint()) && 910344779Sdim CGM.getCodeGenOpts().StackAlignment) 911344779Sdim Fn->addFnAttr("stackrealign"); 912344779Sdim 913193326Sed llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 914193326Sed 915193326Sed // Create a marker to make it easy to insert allocas into the entryblock 916193326Sed // later. Don't create this with the builder, because we don't want it 917193326Sed // folded. 918210299Sed llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 919309124Sdim AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 920198092Srdivacky 921210299Sed ReturnBlock = getJumpDestInCurrentScope("return"); 922198092Srdivacky 923193326Sed Builder.SetInsertPoint(EntryBB); 924198092Srdivacky 925321369Sdim // If we're checking the return value, allocate space for a pointer to a 926321369Sdim // precise source location of the checked return statement. 927321369Sdim if (requiresReturnValueCheck()) { 928321369Sdim ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr"); 929321369Sdim InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy)); 930321369Sdim } 931321369Sdim 932193326Sed // Emit subprogram debug descriptor. 933193326Sed if (CGDebugInfo *DI = getDebugInfo()) { 934309124Sdim // Reconstruct the type from the argument list so that implicit parameters, 935309124Sdim // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 936309124Sdim // convention. 937309124Sdim CallingConv CC = CallingConv::CC_C; 938309124Sdim if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 939309124Sdim if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 940309124Sdim CC = SrcFnTy->getCallConv(); 941249423Sdim SmallVector<QualType, 16> ArgTypes; 942309124Sdim for (const VarDecl *VD : Args) 943309124Sdim ArgTypes.push_back(VD->getType()); 944309124Sdim QualType FnType = getContext().getFunctionType( 945309124Sdim RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 946341825Sdim DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk, 947341825Sdim Builder); 948193326Sed } 949193326Sed 950327952Sdim if (ShouldInstrumentFunction()) { 951327952Sdim if (CGM.getCodeGenOpts().InstrumentFunctions) 952327952Sdim CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter"); 953327952Sdim if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 954327952Sdim CurFn->addFnAttr("instrument-function-entry-inlined", 955327952Sdim "__cyg_profile_func_enter"); 956327952Sdim if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 957327952Sdim CurFn->addFnAttr("instrument-function-entry-inlined", 958327952Sdim "__cyg_profile_func_enter_bare"); 959327952Sdim } 960210299Sed 961314564Sdim // Since emitting the mcount call here impacts optimizations such as function 962314564Sdim // inlining, we just add an attribute to insert a mcount call in backend. 963314564Sdim // The attribute "counting-function" is set to mcount function name which is 964314564Sdim // architecture dependent. 965321369Sdim if (CGM.getCodeGenOpts().InstrumentForProfiling) { 966341825Sdim // Calls to fentry/mcount should not be generated if function has 967341825Sdim // the no_instrument_function attribute. 968341825Sdim if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) { 969341825Sdim if (CGM.getCodeGenOpts().CallFEntry) 970341825Sdim Fn->addFnAttr("fentry-call", "true"); 971341825Sdim else { 972327952Sdim Fn->addFnAttr("instrument-function-entry-inlined", 973327952Sdim getTarget().getMCountName()); 974327952Sdim } 975360784Sdim if (CGM.getCodeGenOpts().MNopMCount) { 976360784Sdim if (!CGM.getCodeGenOpts().CallFEntry) 977360784Sdim CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 978360784Sdim << "-mnop-mcount" << "-mfentry"; 979360784Sdim Fn->addFnAttr("mnop-mcount"); 980360784Sdim } 981360784Sdim 982360784Sdim if (CGM.getCodeGenOpts().RecordMCount) { 983360784Sdim if (!CGM.getCodeGenOpts().CallFEntry) 984360784Sdim CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 985360784Sdim << "-mrecord-mcount" << "-mfentry"; 986360784Sdim Fn->addFnAttr("mrecord-mcount"); 987360784Sdim } 988321369Sdim } 989321369Sdim } 990218893Sdim 991360784Sdim if (CGM.getCodeGenOpts().PackedStack) { 992360784Sdim if (getContext().getTargetInfo().getTriple().getArch() != 993360784Sdim llvm::Triple::systemz) 994360784Sdim CGM.getDiags().Report(diag::err_opt_not_valid_on_target) 995360784Sdim << "-mpacked-stack"; 996360784Sdim Fn->addFnAttr("packed-stack"); 997360784Sdim } 998360784Sdim 999200583Srdivacky if (RetTy->isVoidType()) { 1000200583Srdivacky // Void type; nothing to return. 1001296417Sdim ReturnValue = Address::invalid(); 1002276479Sdim 1003276479Sdim // Count the implicit return. 1004276479Sdim if (!endsWithReturn(D)) 1005276479Sdim ++NumReturnExprs; 1006344779Sdim } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) { 1007344779Sdim // Indirect return; emit returned value directly into sret slot. 1008204643Srdivacky // This reduces code size, and affects correctness in C++. 1009276479Sdim auto AI = CurFn->arg_begin(); 1010276479Sdim if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 1011276479Sdim ++AI; 1012296417Sdim ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 1013353358Sdim if (!CurFnInfo->getReturnInfo().getIndirectByVal()) { 1014353358Sdim ReturnValuePointer = 1015353358Sdim CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr"); 1016353358Sdim Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast( 1017353358Sdim ReturnValue.getPointer(), Int8PtrTy), 1018353358Sdim ReturnValuePointer); 1019353358Sdim } 1020276479Sdim } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 1021276479Sdim !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 1022276479Sdim // Load the sret pointer from the argument struct and return into that. 1023276479Sdim unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 1024276479Sdim llvm::Function::arg_iterator EI = CurFn->arg_end(); 1025276479Sdim --EI; 1026296417Sdim llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx); 1027353358Sdim ReturnValuePointer = Address(Addr, getPointerAlign()); 1028296417Sdim Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 1029296417Sdim ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 1030200583Srdivacky } else { 1031204643Srdivacky ReturnValue = CreateIRTemp(RetTy, "retval"); 1032224145Sdim 1033224145Sdim // Tell the epilog emitter to autorelease the result. We do this 1034224145Sdim // now so that various specialized functions can suppress it 1035224145Sdim // during their IR-generation. 1036234353Sdim if (getLangOpts().ObjCAutoRefCount && 1037224145Sdim !CurFnInfo->isReturnsRetained() && 1038224145Sdim RetTy->isObjCRetainableType()) 1039224145Sdim AutoreleaseResult = true; 1040200583Srdivacky } 1041200583Srdivacky 1042200583Srdivacky EmitStartEHSpec(CurCodeDecl); 1043224145Sdim 1044224145Sdim PrologueCleanupDepth = EHStack.stable_begin(); 1045341825Sdim 1046341825Sdim // Emit OpenMP specific initialization of the device functions. 1047341825Sdim if (getLangOpts().OpenMP && CurCodeDecl) 1048341825Sdim CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl); 1049341825Sdim 1050193326Sed EmitFunctionProlog(*CurFnInfo, CurFn, Args); 1051198092Srdivacky 1052234353Sdim if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 1053212904Sdim CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 1054234353Sdim const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 1055234353Sdim if (MD->getParent()->isLambda() && 1056234353Sdim MD->getOverloadedOperator() == OO_Call) { 1057234353Sdim // We're in a lambda; figure out the captures. 1058234353Sdim MD->getParent()->getCaptureFields(LambdaCaptureFields, 1059234353Sdim LambdaThisCaptureField); 1060234353Sdim if (LambdaThisCaptureField) { 1061309124Sdim // If the lambda captures the object referred to by '*this' - either by 1062309124Sdim // value or by reference, make sure CXXThisValue points to the correct 1063309124Sdim // object. 1064309124Sdim 1065309124Sdim // Get the lvalue for the field (which is a copy of the enclosing object 1066309124Sdim // or contains the address of the enclosing object). 1067309124Sdim LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 1068309124Sdim if (!LambdaThisCaptureField->getType()->isPointerType()) { 1069309124Sdim // If the enclosing object was captured by value, just use its address. 1070360784Sdim CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer(); 1071309124Sdim } else { 1072309124Sdim // Load the lvalue pointed to by the field, since '*this' was captured 1073309124Sdim // by reference. 1074309124Sdim CXXThisValue = 1075309124Sdim EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 1076309124Sdim } 1077234353Sdim } 1078280031Sdim for (auto *FD : MD->getParent()->fields()) { 1079280031Sdim if (FD->hasCapturedVLAType()) { 1080280031Sdim auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 1081280031Sdim SourceLocation()).getScalarVal(); 1082280031Sdim auto VAT = FD->getCapturedVLAType(); 1083280031Sdim VLASizeMap[VAT->getSizeExpr()] = ExprArg; 1084280031Sdim } 1085280031Sdim } 1086234353Sdim } else { 1087234353Sdim // Not in a lambda; just use 'this' from the method. 1088234353Sdim // FIXME: Should we generate a new load for each use of 'this'? The 1089234353Sdim // fast register allocator would be happier... 1090234353Sdim CXXThisValue = CXXABIThisValue; 1091234353Sdim } 1092321369Sdim 1093321369Sdim // Check the 'this' pointer once per function, if it's available. 1094323112Sdim if (CXXABIThisValue) { 1095321369Sdim SanitizerSet SkippedChecks; 1096321369Sdim SkippedChecks.set(SanitizerKind::ObjectSize, true); 1097344779Sdim QualType ThisTy = MD->getThisType(); 1098323112Sdim 1099323112Sdim // If this is the call operator of a lambda with no capture-default, it 1100323112Sdim // may have a static invoker function, which may call this operator with 1101323112Sdim // a null 'this' pointer. 1102323112Sdim if (isLambdaCallOperator(MD) && 1103341825Sdim MD->getParent()->getLambdaCaptureDefault() == LCD_None) 1104323112Sdim SkippedChecks.set(SanitizerKind::Null, true); 1105323112Sdim 1106323112Sdim EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall 1107323112Sdim : TCK_MemberCall, 1108323112Sdim Loc, CXXABIThisValue, ThisTy, 1109321369Sdim getContext().getTypeAlignInChars(ThisTy->getPointeeType()), 1110321369Sdim SkippedChecks); 1111321369Sdim } 1112234353Sdim } 1113204643Srdivacky 1114193326Sed // If any of the arguments have a variably modified type, make sure to 1115193326Sed // emit the type size. 1116193326Sed for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 1117193326Sed i != e; ++i) { 1118249423Sdim const VarDecl *VD = *i; 1119193326Sed 1120249423Sdim // Dig out the type as written from ParmVarDecls; it's unclear whether 1121249423Sdim // the standard (C99 6.9.1p10) requires this, but we're following the 1122249423Sdim // precedent set by gcc. 1123249423Sdim QualType Ty; 1124249423Sdim if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 1125249423Sdim Ty = PVD->getOriginalType(); 1126249423Sdim else 1127249423Sdim Ty = VD->getType(); 1128249423Sdim 1129193326Sed if (Ty->isVariablyModifiedType()) 1130224145Sdim EmitVariablyModifiedType(Ty); 1131193326Sed } 1132226633Sdim // Emit a location at the end of the prologue. 1133226633Sdim if (CGDebugInfo *DI = getDebugInfo()) 1134226633Sdim DI->EmitLocation(Builder, StartLoc); 1135341825Sdim 1136341825Sdim // TODO: Do we need to handle this in two places like we do with 1137341825Sdim // target-features/target-cpu? 1138341825Sdim if (CurFuncDecl) 1139341825Sdim if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>()) 1140341825Sdim LargestVectorWidth = VecWidth->getVectorWidth(); 1141193326Sed} 1142193326Sed 1143344779Sdimvoid CodeGenFunction::EmitFunctionBody(const Stmt *Body) { 1144288943Sdim incrementProfileCounter(Body); 1145261991Sdim if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 1146249423Sdim EmitCompoundStmtWithoutScope(*S); 1147249423Sdim else 1148261991Sdim EmitStmt(Body); 1149204643Srdivacky} 1150204643Srdivacky 1151276479Sdim/// When instrumenting to collect profile data, the counts for some blocks 1152276479Sdim/// such as switch cases need to not include the fall-through counts, so 1153276479Sdim/// emit a branch around the instrumentation code. When not instrumenting, 1154276479Sdim/// this just calls EmitBlock(). 1155276479Sdimvoid CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 1156288943Sdim const Stmt *S) { 1157276479Sdim llvm::BasicBlock *SkipCountBB = nullptr; 1158309124Sdim if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 1159276479Sdim // When instrumenting for profiling, the fallthrough to certain 1160276479Sdim // statements needs to skip over the instrumentation code so that we 1161276479Sdim // get an accurate count. 1162276479Sdim SkipCountBB = createBasicBlock("skipcount"); 1163276479Sdim EmitBranch(SkipCountBB); 1164276479Sdim } 1165276479Sdim EmitBlock(BB); 1166288943Sdim uint64_t CurrentCount = getCurrentProfileCount(); 1167288943Sdim incrementProfileCounter(S); 1168288943Sdim setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 1169276479Sdim if (SkipCountBB) 1170276479Sdim EmitBlock(SkipCountBB); 1171276479Sdim} 1172276479Sdim 1173212904Sdim/// Tries to mark the given function nounwind based on the 1174212904Sdim/// non-existence of any throwing calls within it. We believe this is 1175212904Sdim/// lightweight enough to do at -O0. 1176212904Sdimstatic void TryMarkNoThrow(llvm::Function *F) { 1177212904Sdim // LLVM treats 'nounwind' on a function as part of the type, so we 1178212904Sdim // can't do this on functions that can be overwritten. 1179309124Sdim if (F->isInterposable()) return; 1180212904Sdim 1181296417Sdim for (llvm::BasicBlock &BB : *F) 1182296417Sdim for (llvm::Instruction &I : BB) 1183296417Sdim if (I.mayThrow()) 1184226633Sdim return; 1185296417Sdim 1186243830Sdim F->setDoesNotThrow(); 1187212904Sdim} 1188212904Sdim 1189309124SdimQualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 1190309124Sdim FunctionArgList &Args) { 1191198092Srdivacky const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1192276479Sdim QualType ResTy = FD->getReturnType(); 1193198092Srdivacky 1194276479Sdim const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1195276479Sdim if (MD && MD->isInstance()) { 1196261991Sdim if (CGM.getCXXABI().HasThisReturn(GD)) 1197344779Sdim ResTy = MD->getThisType(); 1198280031Sdim else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 1199280031Sdim ResTy = CGM.getContext().VoidPtrTy; 1200276479Sdim CGM.getCXXABI().buildThisParam(*this, Args); 1201261991Sdim } 1202288943Sdim 1203309124Sdim // The base version of an inheriting constructor whose constructed base is a 1204309124Sdim // virtual base is not passed any arguments (because it doesn't actually call 1205309124Sdim // the inherited constructor). 1206309124Sdim bool PassedParams = true; 1207309124Sdim if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 1208309124Sdim if (auto Inherited = CD->getInheritedConstructor()) 1209309124Sdim PassedParams = 1210309124Sdim getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1211198092Srdivacky 1212309124Sdim if (PassedParams) { 1213309124Sdim for (auto *Param : FD->parameters()) { 1214309124Sdim Args.push_back(Param); 1215309124Sdim if (!Param->hasAttr<PassObjectSizeAttr>()) 1216309124Sdim continue; 1217309124Sdim 1218309124Sdim auto *Implicit = ImplicitParamDecl::Create( 1219321369Sdim getContext(), Param->getDeclContext(), Param->getLocation(), 1220321369Sdim /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other); 1221309124Sdim SizeArguments[Param] = Implicit; 1222309124Sdim Args.push_back(Implicit); 1223309124Sdim } 1224296417Sdim } 1225296417Sdim 1226276479Sdim if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 1227276479Sdim CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 1228276479Sdim 1229309124Sdim return ResTy; 1230309124Sdim} 1231309124Sdim 1232314564Sdimstatic bool 1233314564SdimshouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD, 1234314564Sdim const ASTContext &Context) { 1235314564Sdim QualType T = FD->getReturnType(); 1236314564Sdim // Avoid the optimization for functions that return a record type with a 1237314564Sdim // trivial destructor or another trivially copyable type. 1238314564Sdim if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) { 1239314564Sdim if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1240314564Sdim return !ClassDecl->hasTrivialDestructor(); 1241314564Sdim } 1242314564Sdim return !T.isTriviallyCopyableType(Context); 1243314564Sdim} 1244314564Sdim 1245309124Sdimvoid CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1246309124Sdim const CGFunctionInfo &FnInfo) { 1247309124Sdim const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1248309124Sdim CurGD = GD; 1249309124Sdim 1250309124Sdim FunctionArgList Args; 1251309124Sdim QualType ResTy = BuildFunctionArgList(GD, Args); 1252309124Sdim 1253309124Sdim // Check if we should generate debug info for this function. 1254309124Sdim if (FD->hasAttr<NoDebugAttr>()) 1255309124Sdim DebugInfo = nullptr; // disable debug info indefinitely for this function 1256309124Sdim 1257321369Sdim // The function might not have a body if we're generating thunks for a 1258321369Sdim // function declaration. 1259204643Srdivacky SourceRange BodyRange; 1260321369Sdim if (Stmt *Body = FD->getBody()) 1261321369Sdim BodyRange = Body->getSourceRange(); 1262321369Sdim else 1263321369Sdim BodyRange = FD->getLocation(); 1264261991Sdim CurEHLocation = BodyRange.getEnd(); 1265199482Srdivacky 1266276479Sdim // Use the location of the start of the function to determine where 1267276479Sdim // the function definition is located. By default use the location 1268276479Sdim // of the declaration as the location for the subprogram. A function 1269276479Sdim // may lack a declaration in the source code if it is created by code 1270276479Sdim // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 1271276479Sdim SourceLocation Loc = FD->getLocation(); 1272276479Sdim 1273276479Sdim // If this is a function specialization then use the pattern body 1274276479Sdim // as the location for the function. 1275276479Sdim if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 1276276479Sdim if (SpecDecl->hasBody(SpecDecl)) 1277276479Sdim Loc = SpecDecl->getLocation(); 1278276479Sdim 1279314564Sdim Stmt *Body = FD->getBody(); 1280314564Sdim 1281314564Sdim // Initialize helper which will detect jumps which can cause invalid lifetime 1282314564Sdim // markers. 1283314564Sdim if (Body && ShouldEmitLifetimeMarkers) 1284314564Sdim Bypasses.Init(Body); 1285314564Sdim 1286204643Srdivacky // Emit the standard function prologue. 1287276479Sdim StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1288199482Srdivacky 1289204643Srdivacky // Generate the body of the function. 1290296417Sdim PGO.assignRegionCounters(GD, CurFn); 1291204643Srdivacky if (isa<CXXDestructorDecl>(FD)) 1292204643Srdivacky EmitDestructorBody(Args); 1293204643Srdivacky else if (isa<CXXConstructorDecl>(FD)) 1294204643Srdivacky EmitConstructorBody(Args); 1295243830Sdim else if (getLangOpts().CUDA && 1296288943Sdim !getLangOpts().CUDAIsDevice && 1297226633Sdim FD->hasAttr<CUDAGlobalAttr>()) 1298288943Sdim CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1299327952Sdim else if (isa<CXXMethodDecl>(FD) && 1300327952Sdim cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1301261991Sdim // The lambda static invoker function is special, because it forwards or 1302234353Sdim // clones the body of the function call operator (but is actually static). 1303327952Sdim EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD)); 1304249423Sdim } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1305261991Sdim (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1306261991Sdim cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1307249423Sdim // Implicit copy-assignment gets the same special treatment as implicit 1308249423Sdim // copy-constructors. 1309249423Sdim emitImplicitAssignmentOperatorBody(Args); 1310314564Sdim } else if (Body) { 1311344779Sdim EmitFunctionBody(Body); 1312261991Sdim } else 1313261991Sdim llvm_unreachable("no definition for emitted function"); 1314203955Srdivacky 1315243830Sdim // C++11 [stmt.return]p2: 1316243830Sdim // Flowing off the end of a function [...] results in undefined behavior in 1317243830Sdim // a value-returning function. 1318243830Sdim // C11 6.9.1p12: 1319243830Sdim // If the '}' that terminates a function is reached, and the value of the 1320243830Sdim // function call is used by the caller, the behavior is undefined. 1321280031Sdim if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 1322276479Sdim !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 1323314564Sdim bool ShouldEmitUnreachable = 1324314564Sdim CGM.getCodeGenOpts().StrictReturn || 1325314564Sdim shouldUseUndefinedBehaviorReturnOptimization(FD, getContext()); 1326280031Sdim if (SanOpts.has(SanitizerKind::Return)) { 1327276479Sdim SanitizerScope SanScope(this); 1328280031Sdim llvm::Value *IsFalse = Builder.getFalse(); 1329280031Sdim EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 1330314564Sdim SanitizerHandler::MissingReturn, 1331314564Sdim EmitCheckSourceLocation(FD->getLocation()), None); 1332314564Sdim } else if (ShouldEmitUnreachable) { 1333314564Sdim if (CGM.getCodeGenOpts().OptimizationLevel == 0) 1334314564Sdim EmitTrapCall(llvm::Intrinsic::trap); 1335288943Sdim } 1336314564Sdim if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 1337314564Sdim Builder.CreateUnreachable(); 1338314564Sdim Builder.ClearInsertionPoint(); 1339314564Sdim } 1340243830Sdim } 1341243830Sdim 1342204643Srdivacky // Emit the standard function epilogue. 1343204643Srdivacky FinishFunction(BodyRange.getEnd()); 1344198092Srdivacky 1345212904Sdim // If we haven't marked the function nothrow through other means, do 1346212904Sdim // a quick pass now to see if we can. 1347212904Sdim if (!CurFn->doesNotThrow()) 1348212904Sdim TryMarkNoThrow(CurFn); 1349193326Sed} 1350193326Sed 1351193326Sed/// ContainsLabel - Return true if the statement contains a label in it. If 1352193326Sed/// this statement is not executed normally, it not containing a label means 1353193326Sed/// that we can just remove the code. 1354193326Sedbool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1355193326Sed // Null statement, not a label! 1356276479Sdim if (!S) return false; 1357198092Srdivacky 1358193326Sed // If this is a label, we have to emit the code, consider something like: 1359193326Sed // if (0) { ... foo: bar(); } goto foo; 1360221345Sdim // 1361221345Sdim // TODO: If anyone cared, we could track __label__'s, since we know that you 1362221345Sdim // can't jump to one from outside their declared region. 1363193326Sed if (isa<LabelStmt>(S)) 1364193326Sed return true; 1365249423Sdim 1366193326Sed // If this is a case/default statement, and we haven't seen a switch, we have 1367193326Sed // to emit the code. 1368193326Sed if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1369193326Sed return true; 1370198092Srdivacky 1371193326Sed // If this is a switch statement, we want to ignore cases below it. 1372193326Sed if (isa<SwitchStmt>(S)) 1373193326Sed IgnoreCaseStmts = true; 1374198092Srdivacky 1375193326Sed // Scan subexpressions for verboten labels. 1376288943Sdim for (const Stmt *SubStmt : S->children()) 1377288943Sdim if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1378193326Sed return true; 1379198092Srdivacky 1380193326Sed return false; 1381193326Sed} 1382193326Sed 1383221345Sdim/// containsBreak - Return true if the statement contains a break out of it. 1384221345Sdim/// If the statement (recursively) contains a switch or loop with a break 1385221345Sdim/// inside of it, this is fine. 1386221345Sdimbool CodeGenFunction::containsBreak(const Stmt *S) { 1387221345Sdim // Null statement, not a label! 1388276479Sdim if (!S) return false; 1389193326Sed 1390221345Sdim // If this is a switch or loop that defines its own break scope, then we can 1391221345Sdim // include it and anything inside of it. 1392221345Sdim if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 1393221345Sdim isa<ForStmt>(S)) 1394221345Sdim return false; 1395249423Sdim 1396221345Sdim if (isa<BreakStmt>(S)) 1397221345Sdim return true; 1398249423Sdim 1399221345Sdim // Scan subexpressions for verboten breaks. 1400288943Sdim for (const Stmt *SubStmt : S->children()) 1401288943Sdim if (containsBreak(SubStmt)) 1402221345Sdim return true; 1403249423Sdim 1404221345Sdim return false; 1405221345Sdim} 1406221345Sdim 1407310194Sdimbool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 1408310194Sdim if (!S) return false; 1409221345Sdim 1410310194Sdim // Some statement kinds add a scope and thus never add a decl to the current 1411310194Sdim // scope. Note, this list is longer than the list of statements that might 1412310194Sdim // have an unscoped decl nested within them, but this way is conservatively 1413310194Sdim // correct even if more statement kinds are added. 1414310194Sdim if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 1415310194Sdim isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 1416310194Sdim isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 1417310194Sdim isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 1418310194Sdim return false; 1419310194Sdim 1420310194Sdim if (isa<DeclStmt>(S)) 1421310194Sdim return true; 1422310194Sdim 1423310194Sdim for (const Stmt *SubStmt : S->children()) 1424310194Sdim if (mightAddDeclToScope(SubStmt)) 1425310194Sdim return true; 1426310194Sdim 1427310194Sdim return false; 1428310194Sdim} 1429310194Sdim 1430221345Sdim/// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1431221345Sdim/// to a constant, or if it does but contains a label, return false. If it 1432221345Sdim/// constant folds return true and set the boolean result in Result. 1433221345Sdimbool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1434309124Sdim bool &ResultBool, 1435309124Sdim bool AllowLabels) { 1436239462Sdim llvm::APSInt ResultInt; 1437309124Sdim if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 1438221345Sdim return false; 1439249423Sdim 1440221345Sdim ResultBool = ResultInt.getBoolValue(); 1441221345Sdim return true; 1442221345Sdim} 1443221345Sdim 1444221345Sdim/// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1445221345Sdim/// to a constant, or if it does but contains a label, return false. If it 1446221345Sdim/// constant folds return true and set the folded value. 1447309124Sdimbool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1448309124Sdim llvm::APSInt &ResultInt, 1449309124Sdim bool AllowLabels) { 1450193326Sed // FIXME: Rename and handle conversion of other evaluatable things 1451193326Sed // to bool. 1452344779Sdim Expr::EvalResult Result; 1453344779Sdim if (!Cond->EvaluateAsInt(Result, getContext())) 1454221345Sdim return false; // Not foldable, not integer or not fully evaluatable. 1455234353Sdim 1456344779Sdim llvm::APSInt Int = Result.Val.getInt(); 1457309124Sdim if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 1458221345Sdim return false; // Contains a label. 1459234353Sdim 1460234353Sdim ResultInt = Int; 1461221345Sdim return true; 1462193326Sed} 1463193326Sed 1464193326Sed 1465221345Sdim 1466193326Sed/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1467193326Sed/// statement) to the specified blocks. Based on the condition, this might try 1468193326Sed/// to simplify the codegen of the conditional based on the branch. 1469193326Sed/// 1470193326Sedvoid CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1471193326Sed llvm::BasicBlock *TrueBlock, 1472276479Sdim llvm::BasicBlock *FalseBlock, 1473276479Sdim uint64_t TrueCount) { 1474221345Sdim Cond = Cond->IgnoreParens(); 1475198092Srdivacky 1476193326Sed if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1477276479Sdim 1478193326Sed // Handle X && Y in a condition. 1479212904Sdim if (CondBOp->getOpcode() == BO_LAnd) { 1480193326Sed // If we have "1 && X", simplify the code. "0 && X" would have constant 1481193326Sed // folded if the case was simple enough. 1482221345Sdim bool ConstantBool = false; 1483221345Sdim if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1484221345Sdim ConstantBool) { 1485193326Sed // br(1 && X) -> br(X). 1486288943Sdim incrementProfileCounter(CondBOp); 1487276479Sdim return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1488276479Sdim TrueCount); 1489193326Sed } 1490198092Srdivacky 1491193326Sed // If we have "X && 1", simplify the code to use an uncond branch. 1492193326Sed // "X && 0" would have been constant folded to 0. 1493221345Sdim if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1494221345Sdim ConstantBool) { 1495193326Sed // br(X && 1) -> br(X). 1496276479Sdim return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1497276479Sdim TrueCount); 1498193326Sed } 1499198092Srdivacky 1500193326Sed // Emit the LHS as a conditional. If the LHS conditional is false, we 1501193326Sed // want to jump to the FalseBlock. 1502193326Sed llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1503276479Sdim // The counter tells us how often we evaluate RHS, and all of TrueCount 1504276479Sdim // can be propagated to that branch. 1505288943Sdim uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1506218893Sdim 1507218893Sdim ConditionalEvaluation eval(*this); 1508288943Sdim { 1509288943Sdim ApplyDebugLocation DL(*this, Cond); 1510288943Sdim EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1511288943Sdim EmitBlock(LHSTrue); 1512288943Sdim } 1513198092Srdivacky 1514288943Sdim incrementProfileCounter(CondBOp); 1515288943Sdim setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1516288943Sdim 1517203955Srdivacky // Any temporaries created here are conditional. 1518218893Sdim eval.begin(*this); 1519276479Sdim EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1520218893Sdim eval.end(*this); 1521203955Srdivacky 1522193326Sed return; 1523221345Sdim } 1524249423Sdim 1525221345Sdim if (CondBOp->getOpcode() == BO_LOr) { 1526193326Sed // If we have "0 || X", simplify the code. "1 || X" would have constant 1527193326Sed // folded if the case was simple enough. 1528221345Sdim bool ConstantBool = false; 1529221345Sdim if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1530221345Sdim !ConstantBool) { 1531193326Sed // br(0 || X) -> br(X). 1532288943Sdim incrementProfileCounter(CondBOp); 1533276479Sdim return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1534276479Sdim TrueCount); 1535193326Sed } 1536198092Srdivacky 1537193326Sed // If we have "X || 0", simplify the code to use an uncond branch. 1538193326Sed // "X || 1" would have been constant folded to 1. 1539221345Sdim if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1540221345Sdim !ConstantBool) { 1541193326Sed // br(X || 0) -> br(X). 1542276479Sdim return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1543276479Sdim TrueCount); 1544193326Sed } 1545198092Srdivacky 1546193326Sed // Emit the LHS as a conditional. If the LHS conditional is true, we 1547193326Sed // want to jump to the TrueBlock. 1548193326Sed llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1549276479Sdim // We have the count for entry to the RHS and for the whole expression 1550276479Sdim // being true, so we can divy up True count between the short circuit and 1551276479Sdim // the RHS. 1552288943Sdim uint64_t LHSCount = 1553288943Sdim getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1554276479Sdim uint64_t RHSCount = TrueCount - LHSCount; 1555218893Sdim 1556218893Sdim ConditionalEvaluation eval(*this); 1557288943Sdim { 1558288943Sdim ApplyDebugLocation DL(*this, Cond); 1559288943Sdim EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1560288943Sdim EmitBlock(LHSFalse); 1561288943Sdim } 1562198092Srdivacky 1563288943Sdim incrementProfileCounter(CondBOp); 1564288943Sdim setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1565288943Sdim 1566203955Srdivacky // Any temporaries created here are conditional. 1567218893Sdim eval.begin(*this); 1568276479Sdim EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1569276479Sdim 1570218893Sdim eval.end(*this); 1571203955Srdivacky 1572193326Sed return; 1573193326Sed } 1574193326Sed } 1575198092Srdivacky 1576193326Sed if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1577193326Sed // br(!x, t, f) -> br(x, f, t) 1578276479Sdim if (CondUOp->getOpcode() == UO_LNot) { 1579276479Sdim // Negate the count. 1580288943Sdim uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1581276479Sdim // Negate the condition and swap the destination blocks. 1582276479Sdim return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1583276479Sdim FalseCount); 1584276479Sdim } 1585193326Sed } 1586198092Srdivacky 1587193326Sed if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1588234353Sdim // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1589234353Sdim llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1590234353Sdim llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1591193326Sed 1592234353Sdim ConditionalEvaluation cond(*this); 1593288943Sdim EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1594288943Sdim getProfileCount(CondOp)); 1595218893Sdim 1596276479Sdim // When computing PGO branch weights, we only know the overall count for 1597276479Sdim // the true block. This code is essentially doing tail duplication of the 1598276479Sdim // naive code-gen, introducing new edges for which counts are not 1599276479Sdim // available. Divide the counts proportionally between the LHS and RHS of 1600276479Sdim // the conditional operator. 1601276479Sdim uint64_t LHSScaledTrueCount = 0; 1602276479Sdim if (TrueCount) { 1603288943Sdim double LHSRatio = 1604288943Sdim getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1605276479Sdim LHSScaledTrueCount = TrueCount * LHSRatio; 1606276479Sdim } 1607276479Sdim 1608234353Sdim cond.begin(*this); 1609234353Sdim EmitBlock(LHSBlock); 1610288943Sdim incrementProfileCounter(CondOp); 1611288943Sdim { 1612288943Sdim ApplyDebugLocation DL(*this, Cond); 1613288943Sdim EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1614288943Sdim LHSScaledTrueCount); 1615288943Sdim } 1616234353Sdim cond.end(*this); 1617218893Sdim 1618234353Sdim cond.begin(*this); 1619234353Sdim EmitBlock(RHSBlock); 1620276479Sdim EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1621276479Sdim TrueCount - LHSScaledTrueCount); 1622234353Sdim cond.end(*this); 1623218893Sdim 1624234353Sdim return; 1625193326Sed } 1626193326Sed 1627251662Sdim if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1628251662Sdim // Conditional operator handling can give us a throw expression as a 1629251662Sdim // condition for a case like: 1630251662Sdim // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1631251662Sdim // Fold this to: 1632251662Sdim // br(c, throw x, br(y, t, f)) 1633251662Sdim EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1634251662Sdim return; 1635251662Sdim } 1636251662Sdim 1637296417Sdim // If the branch has a condition wrapped by __builtin_unpredictable, 1638296417Sdim // create metadata that specifies that the branch is unpredictable. 1639296417Sdim // Don't bother if not optimizing because that metadata would not be used. 1640296417Sdim llvm::MDNode *Unpredictable = nullptr; 1641344779Sdim auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts()); 1642309124Sdim if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1643309124Sdim auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1644309124Sdim if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1645309124Sdim llvm::MDBuilder MDHelper(getLLVMContext()); 1646309124Sdim Unpredictable = MDHelper.createUnpredictable(); 1647296417Sdim } 1648296417Sdim } 1649296417Sdim 1650276479Sdim // Create branch weights based on the number of times we get here and the 1651276479Sdim // number of times the condition should be true. 1652288943Sdim uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1653288943Sdim llvm::MDNode *Weights = 1654288943Sdim createProfileWeights(TrueCount, CurrentCount - TrueCount); 1655276479Sdim 1656193326Sed // Emit the code with the fully general case. 1657288943Sdim llvm::Value *CondV; 1658288943Sdim { 1659288943Sdim ApplyDebugLocation DL(*this, Cond); 1660288943Sdim CondV = EvaluateExprAsBool(Cond); 1661288943Sdim } 1662296417Sdim Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1663193326Sed} 1664193326Sed 1665193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 1666193326Sed/// specified stmt yet. 1667261991Sdimvoid CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1668261991Sdim CGM.ErrorUnsupported(S, Type); 1669193326Sed} 1670193326Sed 1671218893Sdim/// emitNonZeroVLAInit - Emit the "zero" initialization of a 1672218893Sdim/// variable-length array whose elements have a non-zero bit-pattern. 1673218893Sdim/// 1674239462Sdim/// \param baseType the inner-most element type of the array 1675218893Sdim/// \param src - a char* pointing to the bit-pattern for a single 1676218893Sdim/// base element of the array 1677218893Sdim/// \param sizeInChars - the total size of the VLA, in chars 1678218893Sdimstatic void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1679296417Sdim Address dest, Address src, 1680218893Sdim llvm::Value *sizeInChars) { 1681218893Sdim CGBuilderTy &Builder = CGF.Builder; 1682218893Sdim 1683296417Sdim CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 1684218893Sdim llvm::Value *baseSizeInChars 1685296417Sdim = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 1686218893Sdim 1687296417Sdim Address begin = 1688296417Sdim Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 1689296417Sdim llvm::Value *end = 1690296417Sdim Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 1691218893Sdim 1692218893Sdim llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1693218893Sdim llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1694218893Sdim llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1695218893Sdim 1696218893Sdim // Make a loop over the VLA. C99 guarantees that the VLA element 1697218893Sdim // count must be nonzero. 1698218893Sdim CGF.EmitBlock(loopBB); 1699218893Sdim 1700296417Sdim llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 1701296417Sdim cur->addIncoming(begin.getPointer(), originBB); 1702218893Sdim 1703296417Sdim CharUnits curAlign = 1704296417Sdim dest.getAlignment().alignmentOfArrayElement(baseSize); 1705296417Sdim 1706218893Sdim // memcpy the individual element bit-pattern. 1707296417Sdim Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 1708218893Sdim /*volatile*/ false); 1709218893Sdim 1710218893Sdim // Go to the next element. 1711296417Sdim llvm::Value *next = 1712296417Sdim Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 1713218893Sdim 1714218893Sdim // Leave if that's the end of the VLA. 1715218893Sdim llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1716218893Sdim Builder.CreateCondBr(done, contBB, loopBB); 1717218893Sdim cur->addIncoming(next, loopBB); 1718218893Sdim 1719218893Sdim CGF.EmitBlock(contBB); 1720249423Sdim} 1721218893Sdim 1722208600Srdivackyvoid 1723296417SdimCodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1724207619Srdivacky // Ignore empty classes in C++. 1725243830Sdim if (getLangOpts().CPlusPlus) { 1726207619Srdivacky if (const RecordType *RT = Ty->getAs<RecordType>()) { 1727207619Srdivacky if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1728207619Srdivacky return; 1729207619Srdivacky } 1730207619Srdivacky } 1731212904Sdim 1732212904Sdim // Cast the dest ptr to the appropriate i8 pointer type. 1733296417Sdim if (DestPtr.getElementType() != Int8Ty) 1734296417Sdim DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1735193326Sed 1736193326Sed // Get size and alignment info for this aggregate. 1737296417Sdim CharUnits size = getContext().getTypeSizeInChars(Ty); 1738193326Sed 1739218893Sdim llvm::Value *SizeVal; 1740218893Sdim const VariableArrayType *vla; 1741218893Sdim 1742193326Sed // Don't bother emitting a zero-byte memset. 1743296417Sdim if (size.isZero()) { 1744218893Sdim // But note that getTypeInfo returns 0 for a VLA. 1745218893Sdim if (const VariableArrayType *vlaType = 1746218893Sdim dyn_cast_or_null<VariableArrayType>( 1747218893Sdim getContext().getAsArrayType(Ty))) { 1748341825Sdim auto VlaSize = getVLASize(vlaType); 1749341825Sdim SizeVal = VlaSize.NumElts; 1750341825Sdim CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type); 1751224145Sdim if (!eltSize.isOne()) 1752224145Sdim SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1753218893Sdim vla = vlaType; 1754218893Sdim } else { 1755218893Sdim return; 1756218893Sdim } 1757218893Sdim } else { 1758296417Sdim SizeVal = CGM.getSize(size); 1759276479Sdim vla = nullptr; 1760218893Sdim } 1761198092Srdivacky 1762212904Sdim // If the type contains a pointer to data member we can't memset it to zero. 1763212904Sdim // Instead, create a null constant and copy it to the destination. 1764218893Sdim // TODO: there are other patterns besides zero that we can usefully memset, 1765218893Sdim // like -1, which happens to be the pattern used by member-pointers. 1766212904Sdim if (!CGM.getTypes().isZeroInitializable(Ty)) { 1767218893Sdim // For a VLA, emit a single element, then splat that over the VLA. 1768218893Sdim if (vla) Ty = getContext().getBaseElementType(vla); 1769218893Sdim 1770212904Sdim llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1771212904Sdim 1772249423Sdim llvm::GlobalVariable *NullVariable = 1773212904Sdim new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1774249423Sdim /*isConstant=*/true, 1775212904Sdim llvm::GlobalVariable::PrivateLinkage, 1776226633Sdim NullConstant, Twine()); 1777296417Sdim CharUnits NullAlign = DestPtr.getAlignment(); 1778360784Sdim NullVariable->setAlignment(NullAlign.getAsAlign()); 1779296417Sdim Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 1780296417Sdim NullAlign); 1781212904Sdim 1782218893Sdim if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1783212904Sdim 1784212904Sdim // Get and call the appropriate llvm.memcpy overload. 1785296417Sdim Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1786212904Sdim return; 1787249423Sdim } 1788249423Sdim 1789212904Sdim // Otherwise, just memset the whole thing to zero. This is legal 1790212904Sdim // because in LLVM, all default initializers (other than the ones we just 1791212904Sdim // handled above) are guaranteed to have a bit pattern of all zeros. 1792296417Sdim Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1793193326Sed} 1794193326Sed 1795218893Sdimllvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1796198893Srdivacky // Make sure that there is a block for the indirect goto. 1797276479Sdim if (!IndirectBranch) 1798198893Srdivacky GetIndirectGotoBlock(); 1799249423Sdim 1800212904Sdim llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1801249423Sdim 1802198893Srdivacky // Make sure the indirect branch includes all of the address-taken blocks. 1803198893Srdivacky IndirectBranch->addDestination(BB); 1804198893Srdivacky return llvm::BlockAddress::get(CurFn, BB); 1805198092Srdivacky} 1806198092Srdivacky 1807198092Srdivackyllvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1808198893Srdivacky // If we already made the indirect branch for indirect goto, return its block. 1809198893Srdivacky if (IndirectBranch) return IndirectBranch->getParent(); 1810249423Sdim 1811296417Sdim CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1812249423Sdim 1813198092Srdivacky // Create the PHI node that indirect gotos will add entries to. 1814221345Sdim llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1815221345Sdim "indirect.goto.dest"); 1816249423Sdim 1817198893Srdivacky // Create the indirect branch instruction. 1818198893Srdivacky IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1819198893Srdivacky return IndirectBranch->getParent(); 1820193326Sed} 1821193326Sed 1822224145Sdim/// Computes the length of an array in elements, as well as the base 1823224145Sdim/// element type and a properly-typed first element pointer. 1824224145Sdimllvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1825224145Sdim QualType &baseType, 1826296417Sdim Address &addr) { 1827224145Sdim const ArrayType *arrayType = origArrayType; 1828198092Srdivacky 1829224145Sdim // If it's a VLA, we have to load the stored size. Note that 1830224145Sdim // this is the size of the VLA in bytes, not its size in elements. 1831276479Sdim llvm::Value *numVLAElements = nullptr; 1832224145Sdim if (isa<VariableArrayType>(arrayType)) { 1833341825Sdim numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts; 1834224145Sdim 1835224145Sdim // Walk into all VLAs. This doesn't require changes to addr, 1836224145Sdim // which has type T* where T is the first non-VLA element type. 1837224145Sdim do { 1838224145Sdim QualType elementType = arrayType->getElementType(); 1839224145Sdim arrayType = getContext().getAsArrayType(elementType); 1840224145Sdim 1841224145Sdim // If we only have VLA components, 'addr' requires no adjustment. 1842224145Sdim if (!arrayType) { 1843224145Sdim baseType = elementType; 1844224145Sdim return numVLAElements; 1845224145Sdim } 1846224145Sdim } while (isa<VariableArrayType>(arrayType)); 1847224145Sdim 1848224145Sdim // We get out here only if we find a constant array type 1849224145Sdim // inside the VLA. 1850224145Sdim } 1851224145Sdim 1852224145Sdim // We have some number of constant-length arrays, so addr should 1853224145Sdim // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1854224145Sdim // down to the first element of addr. 1855226633Sdim SmallVector<llvm::Value*, 8> gepIndices; 1856224145Sdim 1857224145Sdim // GEP down to the array type. 1858224145Sdim llvm::ConstantInt *zero = Builder.getInt32(0); 1859224145Sdim gepIndices.push_back(zero); 1860224145Sdim 1861224145Sdim uint64_t countFromCLAs = 1; 1862239462Sdim QualType eltType; 1863224145Sdim 1864226633Sdim llvm::ArrayType *llvmArrayType = 1865296417Sdim dyn_cast<llvm::ArrayType>(addr.getElementType()); 1866239462Sdim while (llvmArrayType) { 1867224145Sdim assert(isa<ConstantArrayType>(arrayType)); 1868224145Sdim assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1869224145Sdim == llvmArrayType->getNumElements()); 1870224145Sdim 1871224145Sdim gepIndices.push_back(zero); 1872224145Sdim countFromCLAs *= llvmArrayType->getNumElements(); 1873239462Sdim eltType = arrayType->getElementType(); 1874224145Sdim 1875224145Sdim llvmArrayType = 1876224145Sdim dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1877224145Sdim arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1878239462Sdim assert((!llvmArrayType || arrayType) && 1879239462Sdim "LLVM and Clang types are out-of-synch"); 1880224145Sdim } 1881224145Sdim 1882239462Sdim if (arrayType) { 1883239462Sdim // From this point onwards, the Clang array type has been emitted 1884239462Sdim // as some other type (probably a packed struct). Compute the array 1885239462Sdim // size, and just emit the 'begin' expression as a bitcast. 1886239462Sdim while (arrayType) { 1887239462Sdim countFromCLAs *= 1888239462Sdim cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1889239462Sdim eltType = arrayType->getElementType(); 1890239462Sdim arrayType = getContext().getAsArrayType(eltType); 1891239462Sdim } 1892224145Sdim 1893296417Sdim llvm::Type *baseType = ConvertType(eltType); 1894296417Sdim addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 1895239462Sdim } else { 1896239462Sdim // Create the actual GEP. 1897296417Sdim addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 1898296417Sdim gepIndices, "array.begin"), 1899296417Sdim addr.getAlignment()); 1900239462Sdim } 1901224145Sdim 1902239462Sdim baseType = eltType; 1903239462Sdim 1904224145Sdim llvm::Value *numElements 1905224145Sdim = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1906224145Sdim 1907224145Sdim // If we had any VLA dimensions, factor them in. 1908224145Sdim if (numVLAElements) 1909224145Sdim numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1910224145Sdim 1911224145Sdim return numElements; 1912193326Sed} 1913193326Sed 1914341825SdimCodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) { 1915224145Sdim const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1916224145Sdim assert(vla && "type was not a variable array type!"); 1917224145Sdim return getVLASize(vla); 1918224145Sdim} 1919224145Sdim 1920341825SdimCodeGenFunction::VlaSizePair 1921224145SdimCodeGenFunction::getVLASize(const VariableArrayType *type) { 1922224145Sdim // The number of elements so far; always size_t. 1923276479Sdim llvm::Value *numElements = nullptr; 1924224145Sdim 1925224145Sdim QualType elementType; 1926224145Sdim do { 1927224145Sdim elementType = type->getElementType(); 1928224145Sdim llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1929224145Sdim assert(vlaSize && "no size for VLA!"); 1930224145Sdim assert(vlaSize->getType() == SizeTy); 1931224145Sdim 1932224145Sdim if (!numElements) { 1933224145Sdim numElements = vlaSize; 1934224145Sdim } else { 1935224145Sdim // It's undefined behavior if this wraps around, so mark it that way. 1936276479Sdim // FIXME: Teach -fsanitize=undefined to trap this. 1937224145Sdim numElements = Builder.CreateNUWMul(numElements, vlaSize); 1938224145Sdim } 1939224145Sdim } while ((type = getContext().getAsVariableArrayType(elementType))); 1940224145Sdim 1941341825Sdim return { numElements, elementType }; 1942224145Sdim} 1943224145Sdim 1944341825SdimCodeGenFunction::VlaSizePair 1945341825SdimCodeGenFunction::getVLAElements1D(QualType type) { 1946341825Sdim const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1947341825Sdim assert(vla && "type was not a variable array type!"); 1948341825Sdim return getVLAElements1D(vla); 1949341825Sdim} 1950341825Sdim 1951341825SdimCodeGenFunction::VlaSizePair 1952341825SdimCodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) { 1953341825Sdim llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()]; 1954341825Sdim assert(VlaSize && "no size for VLA!"); 1955341825Sdim assert(VlaSize->getType() == SizeTy); 1956341825Sdim return { VlaSize, Vla->getElementType() }; 1957341825Sdim} 1958341825Sdim 1959224145Sdimvoid CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1960224145Sdim assert(type->isVariablyModifiedType() && 1961193326Sed "Must pass variably modified type to EmitVLASizes!"); 1962198092Srdivacky 1963198092Srdivacky EnsureInsertPoint(); 1964198092Srdivacky 1965224145Sdim // We're going to walk down into the type and look for VLA 1966224145Sdim // expressions. 1967224145Sdim do { 1968224145Sdim assert(type->isVariablyModifiedType()); 1969198092Srdivacky 1970224145Sdim const Type *ty = type.getTypePtr(); 1971224145Sdim switch (ty->getTypeClass()) { 1972234353Sdim 1973224145Sdim#define TYPE(Class, Base) 1974224145Sdim#define ABSTRACT_TYPE(Class, Base) 1975234353Sdim#define NON_CANONICAL_TYPE(Class, Base) 1976224145Sdim#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1977234353Sdim#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1978360784Sdim#include "clang/AST/TypeNodes.inc" 1979234353Sdim llvm_unreachable("unexpected dependent type!"); 1980198092Srdivacky 1981224145Sdim // These types are never variably-modified. 1982224145Sdim case Type::Builtin: 1983224145Sdim case Type::Complex: 1984224145Sdim case Type::Vector: 1985224145Sdim case Type::ExtVector: 1986224145Sdim case Type::Record: 1987224145Sdim case Type::Enum: 1988234353Sdim case Type::Elaborated: 1989234353Sdim case Type::TemplateSpecialization: 1990314564Sdim case Type::ObjCTypeParam: 1991224145Sdim case Type::ObjCObject: 1992224145Sdim case Type::ObjCInterface: 1993224145Sdim case Type::ObjCObjectPointer: 1994224145Sdim llvm_unreachable("type class is never variably-modified!"); 1995198092Srdivacky 1996276479Sdim case Type::Adjusted: 1997276479Sdim type = cast<AdjustedType>(ty)->getAdjustedType(); 1998276479Sdim break; 1999276479Sdim 2000261991Sdim case Type::Decayed: 2001261991Sdim type = cast<DecayedType>(ty)->getPointeeType(); 2002261991Sdim break; 2003261991Sdim 2004224145Sdim case Type::Pointer: 2005224145Sdim type = cast<PointerType>(ty)->getPointeeType(); 2006224145Sdim break; 2007198092Srdivacky 2008224145Sdim case Type::BlockPointer: 2009224145Sdim type = cast<BlockPointerType>(ty)->getPointeeType(); 2010224145Sdim break; 2011198092Srdivacky 2012224145Sdim case Type::LValueReference: 2013224145Sdim case Type::RValueReference: 2014224145Sdim type = cast<ReferenceType>(ty)->getPointeeType(); 2015224145Sdim break; 2016198092Srdivacky 2017224145Sdim case Type::MemberPointer: 2018224145Sdim type = cast<MemberPointerType>(ty)->getPointeeType(); 2019224145Sdim break; 2020198092Srdivacky 2021224145Sdim case Type::ConstantArray: 2022224145Sdim case Type::IncompleteArray: 2023224145Sdim // Losing element qualification here is fine. 2024224145Sdim type = cast<ArrayType>(ty)->getElementType(); 2025224145Sdim break; 2026218893Sdim 2027224145Sdim case Type::VariableArray: { 2028224145Sdim // Losing element qualification here is fine. 2029224145Sdim const VariableArrayType *vat = cast<VariableArrayType>(ty); 2030224145Sdim 2031224145Sdim // Unknown size indication requires no size computation. 2032224145Sdim // Otherwise, evaluate and record it. 2033224145Sdim if (const Expr *size = vat->getSizeExpr()) { 2034224145Sdim // It's possible that we might have emitted this already, 2035224145Sdim // e.g. with a typedef and a pointer to it. 2036224145Sdim llvm::Value *&entry = VLASizeMap[size]; 2037224145Sdim if (!entry) { 2038243830Sdim llvm::Value *Size = EmitScalarExpr(size); 2039243830Sdim 2040243830Sdim // C11 6.7.6.2p5: 2041243830Sdim // If the size is an expression that is not an integer constant 2042243830Sdim // expression [...] each time it is evaluated it shall have a value 2043243830Sdim // greater than zero. 2044280031Sdim if (SanOpts.has(SanitizerKind::VLABound) && 2045243830Sdim size->getType()->isSignedIntegerType()) { 2046276479Sdim SanitizerScope SanScope(this); 2047243830Sdim llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 2048243830Sdim llvm::Constant *StaticArgs[] = { 2049344779Sdim EmitCheckSourceLocation(size->getBeginLoc()), 2050344779Sdim EmitCheckTypeDescriptor(size->getType())}; 2051280031Sdim EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 2052280031Sdim SanitizerKind::VLABound), 2053314564Sdim SanitizerHandler::VLABoundNotPositive, StaticArgs, Size); 2054243830Sdim } 2055243830Sdim 2056224145Sdim // Always zexting here would be wrong if it weren't 2057224145Sdim // undefined behavior to have a negative bound. 2058243830Sdim entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 2059224145Sdim } 2060224145Sdim } 2061224145Sdim type = vat->getElementType(); 2062224145Sdim break; 2063224145Sdim } 2064224145Sdim 2065234353Sdim case Type::FunctionProto: 2066224145Sdim case Type::FunctionNoProto: 2067276479Sdim type = cast<FunctionType>(ty)->getReturnType(); 2068224145Sdim break; 2069226633Sdim 2070234353Sdim case Type::Paren: 2071234353Sdim case Type::TypeOf: 2072234353Sdim case Type::UnaryTransform: 2073234353Sdim case Type::Attributed: 2074234353Sdim case Type::SubstTemplateTypeParm: 2075261991Sdim case Type::PackExpansion: 2076353358Sdim case Type::MacroQualified: 2077234353Sdim // Keep walking after single level desugaring. 2078234353Sdim type = type.getSingleStepDesugaredType(getContext()); 2079234353Sdim break; 2080234353Sdim 2081234353Sdim case Type::Typedef: 2082234353Sdim case Type::Decltype: 2083234353Sdim case Type::Auto: 2084321369Sdim case Type::DeducedTemplateSpecialization: 2085234353Sdim // Stop walking: nothing to do. 2086234353Sdim return; 2087234353Sdim 2088234353Sdim case Type::TypeOfExpr: 2089234353Sdim // Stop walking: emit typeof expression. 2090234353Sdim EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 2091234353Sdim return; 2092234353Sdim 2093226633Sdim case Type::Atomic: 2094226633Sdim type = cast<AtomicType>(ty)->getValueType(); 2095226633Sdim break; 2096296417Sdim 2097296417Sdim case Type::Pipe: 2098296417Sdim type = cast<PipeType>(ty)->getElementType(); 2099296417Sdim break; 2100224145Sdim } 2101224145Sdim } while (type->isVariablyModifiedType()); 2102193326Sed} 2103193326Sed 2104296417SdimAddress CodeGenFunction::EmitVAListRef(const Expr* E) { 2105218893Sdim if (getContext().getBuiltinVaListType()->isArrayType()) 2106296417Sdim return EmitPointerWithAlignment(E); 2107360784Sdim return EmitLValue(E).getAddress(*this); 2108193326Sed} 2109193326Sed 2110296417SdimAddress CodeGenFunction::EmitMSVAListRef(const Expr *E) { 2111360784Sdim return EmitLValue(E).getAddress(*this); 2112296417Sdim} 2113296417Sdim 2114249423Sdimvoid CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 2115314564Sdim const APValue &Init) { 2116353358Sdim assert(Init.hasValue() && "Invalid DeclRefExpr initializer!"); 2117218893Sdim if (CGDebugInfo *Dbg = getDebugInfo()) 2118360784Sdim if (CGM.getCodeGenOpts().hasReducedDebugInfo()) 2119239462Sdim Dbg->EmitGlobalVariable(E->getDecl(), Init); 2120212904Sdim} 2121210299Sed 2122218893SdimCodeGenFunction::PeepholeProtection 2123218893SdimCodeGenFunction::protectFromPeepholes(RValue rvalue) { 2124218893Sdim // At the moment, the only aggressive peephole we do in IR gen 2125218893Sdim // is trunc(zext) folding, but if we add more, we can easily 2126218893Sdim // extend this protection. 2127193326Sed 2128218893Sdim if (!rvalue.isScalar()) return PeepholeProtection(); 2129218893Sdim llvm::Value *value = rvalue.getScalarVal(); 2130218893Sdim if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 2131198092Srdivacky 2132218893Sdim // Just make an extra bitcast. 2133218893Sdim assert(HaveInsertPoint()); 2134218893Sdim llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 2135218893Sdim Builder.GetInsertBlock()); 2136198092Srdivacky 2137218893Sdim PeepholeProtection protection; 2138218893Sdim protection.Inst = inst; 2139218893Sdim return protection; 2140210299Sed} 2141198092Srdivacky 2142218893Sdimvoid CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 2143218893Sdim if (!protection.Inst) return; 2144198092Srdivacky 2145218893Sdim // In theory, we could try to duplicate the peepholes now, but whatever. 2146218893Sdim protection.Inst->eraseFromParent(); 2147210299Sed} 2148226633Sdim 2149344779Sdimvoid CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue, 2150344779Sdim QualType Ty, SourceLocation Loc, 2151344779Sdim SourceLocation AssumptionLoc, 2152344779Sdim llvm::Value *Alignment, 2153344779Sdim llvm::Value *OffsetValue) { 2154344779Sdim llvm::Value *TheCheck; 2155344779Sdim llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption( 2156344779Sdim CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck); 2157344779Sdim if (SanOpts.has(SanitizerKind::Alignment)) { 2158344779Sdim EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2159344779Sdim OffsetValue, TheCheck, Assumption); 2160344779Sdim } 2161344779Sdim} 2162344779Sdim 2163344779Sdimvoid CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue, 2164344779Sdim const Expr *E, 2165344779Sdim SourceLocation AssumptionLoc, 2166360661Sdim llvm::Value *Alignment, 2167344779Sdim llvm::Value *OffsetValue) { 2168344779Sdim if (auto *CE = dyn_cast<CastExpr>(E)) 2169344779Sdim E = CE->getSubExprAsWritten(); 2170344779Sdim QualType Ty = E->getType(); 2171344779Sdim SourceLocation Loc = E->getExprLoc(); 2172344779Sdim 2173344779Sdim EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 2174344779Sdim OffsetValue); 2175344779Sdim} 2176344779Sdim 2177353358Sdimllvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn, 2178226633Sdim llvm::Value *AnnotatedVal, 2179249423Sdim StringRef AnnotationStr, 2180226633Sdim SourceLocation Location) { 2181226633Sdim llvm::Value *Args[4] = { 2182226633Sdim AnnotatedVal, 2183226633Sdim Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 2184226633Sdim Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 2185226633Sdim CGM.EmitAnnotationLineNo(Location) 2186226633Sdim }; 2187226633Sdim return Builder.CreateCall(AnnotationFn, Args); 2188226633Sdim} 2189226633Sdim 2190226633Sdimvoid CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 2191226633Sdim assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2192226633Sdim // FIXME We create a new bitcast for every annotation because that's what 2193226633Sdim // llvm-gcc was doing. 2194276479Sdim for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2195226633Sdim EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 2196226633Sdim Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 2197276479Sdim I->getAnnotation(), D->getLocation()); 2198226633Sdim} 2199226633Sdim 2200296417SdimAddress CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 2201296417Sdim Address Addr) { 2202226633Sdim assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2203296417Sdim llvm::Value *V = Addr.getPointer(); 2204226633Sdim llvm::Type *VTy = V->getType(); 2205353358Sdim llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 2206226633Sdim CGM.Int8PtrTy); 2207226633Sdim 2208276479Sdim for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 2209226633Sdim // FIXME Always emit the cast inst so we can differentiate between 2210226633Sdim // annotation on the first field of a struct and annotation on the struct 2211226633Sdim // itself. 2212226633Sdim if (VTy != CGM.Int8PtrTy) 2213344779Sdim V = Builder.CreateBitCast(V, CGM.Int8PtrTy); 2214276479Sdim V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 2215226633Sdim V = Builder.CreateBitCast(V, VTy); 2216226633Sdim } 2217226633Sdim 2218296417Sdim return Address(V, Addr.getAlignment()); 2219226633Sdim} 2220261991Sdim 2221261991SdimCodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 2222276479Sdim 2223276479SdimCodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 2224276479Sdim : CGF(CGF) { 2225276479Sdim assert(!CGF->IsSanitizerScope); 2226276479Sdim CGF->IsSanitizerScope = true; 2227276479Sdim} 2228276479Sdim 2229276479SdimCodeGenFunction::SanitizerScope::~SanitizerScope() { 2230276479Sdim CGF->IsSanitizerScope = false; 2231276479Sdim} 2232276479Sdim 2233276479Sdimvoid CodeGenFunction::InsertHelper(llvm::Instruction *I, 2234276479Sdim const llvm::Twine &Name, 2235276479Sdim llvm::BasicBlock *BB, 2236276479Sdim llvm::BasicBlock::iterator InsertPt) const { 2237276479Sdim LoopStack.InsertHelper(I); 2238280031Sdim if (IsSanitizerScope) 2239280031Sdim CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 2240276479Sdim} 2241276479Sdim 2242309124Sdimvoid CGBuilderInserter::InsertHelper( 2243276479Sdim llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 2244276479Sdim llvm::BasicBlock::iterator InsertPt) const { 2245309124Sdim llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 2246276479Sdim if (CGF) 2247276479Sdim CGF->InsertHelper(I, Name, BB, InsertPt); 2248276479Sdim} 2249276479Sdim 2250296417Sdimstatic bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures, 2251296417Sdim CodeGenModule &CGM, const FunctionDecl *FD, 2252296417Sdim std::string &FirstMissing) { 2253296417Sdim // If there aren't any required features listed then go ahead and return. 2254296417Sdim if (ReqFeatures.empty()) 2255296417Sdim return false; 2256296417Sdim 2257296417Sdim // Now build up the set of caller features and verify that all the required 2258296417Sdim // features are there. 2259296417Sdim llvm::StringMap<bool> CallerFeatureMap; 2260360784Sdim CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD); 2261296417Sdim 2262296417Sdim // If we have at least one of the features in the feature list return 2263296417Sdim // true, otherwise return false. 2264296417Sdim return std::all_of( 2265296417Sdim ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) { 2266296417Sdim SmallVector<StringRef, 1> OrFeatures; 2267341825Sdim Feature.split(OrFeatures, '|'); 2268344779Sdim return llvm::any_of(OrFeatures, [&](StringRef Feature) { 2269344779Sdim if (!CallerFeatureMap.lookup(Feature)) { 2270344779Sdim FirstMissing = Feature.str(); 2271344779Sdim return false; 2272344779Sdim } 2273344779Sdim return true; 2274344779Sdim }); 2275296417Sdim }); 2276296417Sdim} 2277296417Sdim 2278296417Sdim// Emits an error if we don't have a valid set of target features for the 2279296417Sdim// called function. 2280296417Sdimvoid CodeGenFunction::checkTargetFeatures(const CallExpr *E, 2281296417Sdim const FunctionDecl *TargetDecl) { 2282353358Sdim return checkTargetFeatures(E->getBeginLoc(), TargetDecl); 2283353358Sdim} 2284353358Sdim 2285353358Sdim// Emits an error if we don't have a valid set of target features for the 2286353358Sdim// called function. 2287353358Sdimvoid CodeGenFunction::checkTargetFeatures(SourceLocation Loc, 2288353358Sdim const FunctionDecl *TargetDecl) { 2289296417Sdim // Early exit if this is an indirect call. 2290296417Sdim if (!TargetDecl) 2291296417Sdim return; 2292296417Sdim 2293296417Sdim // Get the current enclosing function if it exists. If it doesn't 2294296417Sdim // we can't check the target features anyhow. 2295360784Sdim const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl); 2296296417Sdim if (!FD) 2297296417Sdim return; 2298296417Sdim 2299296417Sdim // Grab the required features for the call. For a builtin this is listed in 2300296417Sdim // the td file with the default cpu, for an always_inline function this is any 2301296417Sdim // listed cpu and any listed features. 2302296417Sdim unsigned BuiltinID = TargetDecl->getBuiltinID(); 2303296417Sdim std::string MissingFeature; 2304296417Sdim if (BuiltinID) { 2305296417Sdim SmallVector<StringRef, 1> ReqFeatures; 2306296417Sdim const char *FeatureList = 2307296417Sdim CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2308296417Sdim // Return if the builtin doesn't have any required features. 2309296417Sdim if (!FeatureList || StringRef(FeatureList) == "") 2310296417Sdim return; 2311341825Sdim StringRef(FeatureList).split(ReqFeatures, ','); 2312296417Sdim if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2313353358Sdim CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature) 2314296417Sdim << TargetDecl->getDeclName() 2315296417Sdim << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2316296417Sdim 2317360784Sdim } else if (!TargetDecl->isMultiVersion() && 2318360784Sdim TargetDecl->hasAttr<TargetAttr>()) { 2319296417Sdim // Get the required features for the callee. 2320341825Sdim 2321341825Sdim const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>(); 2322360784Sdim ParsedTargetAttr ParsedAttr = 2323360784Sdim CGM.getContext().filterFunctionTargetAttrs(TD); 2324341825Sdim 2325296417Sdim SmallVector<StringRef, 1> ReqFeatures; 2326296417Sdim llvm::StringMap<bool> CalleeFeatureMap; 2327360784Sdim CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2328341825Sdim 2329341825Sdim for (const auto &F : ParsedAttr.Features) { 2330341825Sdim if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1))) 2331341825Sdim ReqFeatures.push_back(StringRef(F).substr(1)); 2332341825Sdim } 2333341825Sdim 2334296417Sdim for (const auto &F : CalleeFeatureMap) { 2335296417Sdim // Only positive features are "required". 2336296417Sdim if (F.getValue()) 2337296417Sdim ReqFeatures.push_back(F.getKey()); 2338296417Sdim } 2339296417Sdim if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2340353358Sdim CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 2341296417Sdim << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 2342296417Sdim } 2343296417Sdim} 2344309124Sdim 2345309124Sdimvoid CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2346309124Sdim if (!CGM.getCodeGenOpts().SanitizeStats) 2347309124Sdim return; 2348309124Sdim 2349309124Sdim llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2350309124Sdim IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2351309124Sdim CGM.getSanStats().create(IRB, SSK); 2352309124Sdim} 2353314564Sdim 2354341825Sdimllvm::Value * 2355341825SdimCodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) { 2356341825Sdim llvm::Value *Condition = nullptr; 2357341825Sdim 2358341825Sdim if (!RO.Conditions.Architecture.empty()) 2359341825Sdim Condition = EmitX86CpuIs(RO.Conditions.Architecture); 2360341825Sdim 2361341825Sdim if (!RO.Conditions.Features.empty()) { 2362341825Sdim llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features); 2363341825Sdim Condition = 2364341825Sdim Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond; 2365341825Sdim } 2366341825Sdim return Condition; 2367341825Sdim} 2368341825Sdim 2369344779Sdimstatic void CreateMultiVersionResolverReturn(CodeGenModule &CGM, 2370344779Sdim llvm::Function *Resolver, 2371344779Sdim CGBuilderTy &Builder, 2372344779Sdim llvm::Function *FuncToReturn, 2373344779Sdim bool SupportsIFunc) { 2374344779Sdim if (SupportsIFunc) { 2375344779Sdim Builder.CreateRet(FuncToReturn); 2376344779Sdim return; 2377344779Sdim } 2378344779Sdim 2379344779Sdim llvm::SmallVector<llvm::Value *, 10> Args; 2380344779Sdim llvm::for_each(Resolver->args(), 2381344779Sdim [&](llvm::Argument &Arg) { Args.push_back(&Arg); }); 2382344779Sdim 2383344779Sdim llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args); 2384344779Sdim Result->setTailCallKind(llvm::CallInst::TCK_MustTail); 2385344779Sdim 2386344779Sdim if (Resolver->getReturnType()->isVoidTy()) 2387344779Sdim Builder.CreateRetVoid(); 2388344779Sdim else 2389344779Sdim Builder.CreateRet(Result); 2390344779Sdim} 2391344779Sdim 2392341825Sdimvoid CodeGenFunction::EmitMultiVersionResolver( 2393341825Sdim llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2394360784Sdim assert(getContext().getTargetInfo().getTriple().isX86() && 2395341825Sdim "Only implemented for x86 targets"); 2396344779Sdim 2397344779Sdim bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 2398344779Sdim 2399341825Sdim // Main function's basic block. 2400341825Sdim llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 2401341825Sdim Builder.SetInsertPoint(CurBlock); 2402341825Sdim EmitX86CpuInit(); 2403341825Sdim 2404341825Sdim for (const MultiVersionResolverOption &RO : Options) { 2405341825Sdim Builder.SetInsertPoint(CurBlock); 2406341825Sdim llvm::Value *Condition = FormResolverCondition(RO); 2407341825Sdim 2408341825Sdim // The 'default' or 'generic' case. 2409341825Sdim if (!Condition) { 2410341825Sdim assert(&RO == Options.end() - 1 && 2411341825Sdim "Default or Generic case must be last"); 2412344779Sdim CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 2413344779Sdim SupportsIFunc); 2414341825Sdim return; 2415341825Sdim } 2416341825Sdim 2417341825Sdim llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 2418344779Sdim CGBuilderTy RetBuilder(*this, RetBlock); 2419344779Sdim CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 2420344779Sdim SupportsIFunc); 2421341825Sdim CurBlock = createBasicBlock("resolver_else", Resolver); 2422341825Sdim Builder.CreateCondBr(Condition, RetBlock, CurBlock); 2423341825Sdim } 2424341825Sdim 2425341825Sdim // If no generic/default, emit an unreachable. 2426341825Sdim Builder.SetInsertPoint(CurBlock); 2427341825Sdim llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2428341825Sdim TrapCall->setDoesNotReturn(); 2429341825Sdim TrapCall->setDoesNotThrow(); 2430341825Sdim Builder.CreateUnreachable(); 2431341825Sdim Builder.ClearInsertionPoint(); 2432341825Sdim} 2433341825Sdim 2434344779Sdim// Loc - where the diagnostic will point, where in the source code this 2435344779Sdim// alignment has failed. 2436344779Sdim// SecondaryLoc - if present (will be present if sufficiently different from 2437344779Sdim// Loc), the diagnostic will additionally point a "Note:" to this location. 2438344779Sdim// It should be the location where the __attribute__((assume_aligned)) 2439344779Sdim// was written e.g. 2440344779Sdimvoid CodeGenFunction::EmitAlignmentAssumptionCheck( 2441344779Sdim llvm::Value *Ptr, QualType Ty, SourceLocation Loc, 2442344779Sdim SourceLocation SecondaryLoc, llvm::Value *Alignment, 2443344779Sdim llvm::Value *OffsetValue, llvm::Value *TheCheck, 2444344779Sdim llvm::Instruction *Assumption) { 2445344779Sdim assert(Assumption && isa<llvm::CallInst>(Assumption) && 2446344779Sdim cast<llvm::CallInst>(Assumption)->getCalledValue() == 2447344779Sdim llvm::Intrinsic::getDeclaration( 2448344779Sdim Builder.GetInsertBlock()->getParent()->getParent(), 2449344779Sdim llvm::Intrinsic::assume) && 2450344779Sdim "Assumption should be a call to llvm.assume()."); 2451344779Sdim assert(&(Builder.GetInsertBlock()->back()) == Assumption && 2452344779Sdim "Assumption should be the last instruction of the basic block, " 2453344779Sdim "since the basic block is still being generated."); 2454344779Sdim 2455344779Sdim if (!SanOpts.has(SanitizerKind::Alignment)) 2456344779Sdim return; 2457344779Sdim 2458344779Sdim // Don't check pointers to volatile data. The behavior here is implementation- 2459344779Sdim // defined. 2460344779Sdim if (Ty->getPointeeType().isVolatileQualified()) 2461344779Sdim return; 2462344779Sdim 2463344779Sdim // We need to temorairly remove the assumption so we can insert the 2464344779Sdim // sanitizer check before it, else the check will be dropped by optimizations. 2465344779Sdim Assumption->removeFromParent(); 2466344779Sdim 2467344779Sdim { 2468344779Sdim SanitizerScope SanScope(this); 2469344779Sdim 2470344779Sdim if (!OffsetValue) 2471344779Sdim OffsetValue = Builder.getInt1(0); // no offset. 2472344779Sdim 2473344779Sdim llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc), 2474344779Sdim EmitCheckSourceLocation(SecondaryLoc), 2475344779Sdim EmitCheckTypeDescriptor(Ty)}; 2476344779Sdim llvm::Value *DynamicData[] = {EmitCheckValue(Ptr), 2477344779Sdim EmitCheckValue(Alignment), 2478344779Sdim EmitCheckValue(OffsetValue)}; 2479344779Sdim EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)}, 2480344779Sdim SanitizerHandler::AlignmentAssumption, StaticData, DynamicData); 2481344779Sdim } 2482344779Sdim 2483344779Sdim // We are now in the (new, empty) "cont" basic block. 2484344779Sdim // Reintroduce the assumption. 2485344779Sdim Builder.Insert(Assumption); 2486344779Sdim // FIXME: Assumption still has it's original basic block as it's Parent. 2487344779Sdim} 2488344779Sdim 2489314564Sdimllvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 2490314564Sdim if (CGDebugInfo *DI = getDebugInfo()) 2491314564Sdim return DI->SourceLocToDebugLoc(Location); 2492314564Sdim 2493314564Sdim return llvm::DebugLoc(); 2494314564Sdim} 2495