10b57cec5SDimitry Andric //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-function state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenFunction.h"
140b57cec5SDimitry Andric #include "CGBlocks.h"
150b57cec5SDimitry Andric #include "CGCUDARuntime.h"
160b57cec5SDimitry Andric #include "CGCXXABI.h"
17480093f4SDimitry Andric #include "CGCleanup.h"
180b57cec5SDimitry Andric #include "CGDebugInfo.h"
190b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
200b57cec5SDimitry Andric #include "CodeGenModule.h"
210b57cec5SDimitry Andric #include "CodeGenPGO.h"
220b57cec5SDimitry Andric #include "TargetInfo.h"
230b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
240b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
25480093f4SDimitry Andric #include "clang/AST/Attr.h"
260b57cec5SDimitry Andric #include "clang/AST/Decl.h"
270b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
280b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
290b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h"
300b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
310b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
320b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
330b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
340b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
355ffd83dbSDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
370b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
38480093f4SDimitry Andric #include "llvm/IR/FPEnv.h"
39480093f4SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
400b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
410b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
420b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
430b57cec5SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
440b57cec5SDimitry Andric using namespace clang;
450b57cec5SDimitry Andric using namespace CodeGen;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
480b57cec5SDimitry Andric /// markers.
490b57cec5SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
500b57cec5SDimitry Andric                                       const LangOptions &LangOpts) {
510b57cec5SDimitry Andric   if (CGOpts.DisableLifetimeMarkers)
520b57cec5SDimitry Andric     return false;
530b57cec5SDimitry Andric 
54a7dea167SDimitry Andric   // Sanitizers may use markers.
55a7dea167SDimitry Andric   if (CGOpts.SanitizeAddressUseAfterScope ||
56a7dea167SDimitry Andric       LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
57a7dea167SDimitry Andric       LangOpts.Sanitize.has(SanitizerKind::Memory))
580b57cec5SDimitry Andric     return true;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric   // For now, only in optimized builds.
610b57cec5SDimitry Andric   return CGOpts.OptimizationLevel != 0;
620b57cec5SDimitry Andric }
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
650b57cec5SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
660b57cec5SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
670b57cec5SDimitry Andric               CGBuilderInserterTy(this)),
685ffd83dbSDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
695ffd83dbSDimitry Andric       DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
705ffd83dbSDimitry Andric       ShouldEmitLifetimeMarkers(
715ffd83dbSDimitry Andric           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
720b57cec5SDimitry Andric   if (!suppressNewContext)
730b57cec5SDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
740b57cec5SDimitry Andric 
755ffd83dbSDimitry Andric   SetFastMathFlags(CurFPFeatures);
76480093f4SDimitry Andric   SetFPModel();
770b57cec5SDimitry Andric }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric CodeGenFunction::~CodeGenFunction() {
800b57cec5SDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   if (getLangOpts().OpenMP && CurFn)
830b57cec5SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
840b57cec5SDimitry Andric 
855ffd83dbSDimitry Andric   // If we have an OpenMPIRBuilder we want to finalize functions (incl.
865ffd83dbSDimitry Andric   // outlining etc) at some point. Doing it once the function codegen is done
875ffd83dbSDimitry Andric   // seems to be a reasonable spot. We do it here, as opposed to the deletion
885ffd83dbSDimitry Andric   // time of the CodeGenModule, because we have to ensure the IR has not yet
895ffd83dbSDimitry Andric   // been "emitted" to the outside, thus, modifications are still sensible.
905ffd83dbSDimitry Andric   if (CGM.getLangOpts().OpenMPIRBuilder)
915ffd83dbSDimitry Andric     CGM.getOpenMPRuntime().getOMPBuilder().finalize();
92480093f4SDimitry Andric }
93480093f4SDimitry Andric 
94480093f4SDimitry Andric // Map the LangOption for exception behavior into
95480093f4SDimitry Andric // the corresponding enum in the IR.
965ffd83dbSDimitry Andric llvm::fp::ExceptionBehavior
975ffd83dbSDimitry Andric clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
98480093f4SDimitry Andric 
99480093f4SDimitry Andric   switch (Kind) {
100480093f4SDimitry Andric   case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
101480093f4SDimitry Andric   case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
102480093f4SDimitry Andric   case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
103480093f4SDimitry Andric   }
104480093f4SDimitry Andric   llvm_unreachable("Unsupported FP Exception Behavior");
105480093f4SDimitry Andric }
106480093f4SDimitry Andric 
107480093f4SDimitry Andric void CodeGenFunction::SetFPModel() {
1085ffd83dbSDimitry Andric   llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
109480093f4SDimitry Andric   auto fpExceptionBehavior = ToConstrainedExceptMD(
110480093f4SDimitry Andric                                getLangOpts().getFPExceptionMode());
111480093f4SDimitry Andric 
1125ffd83dbSDimitry Andric   Builder.setDefaultConstrainedRounding(RM);
113480093f4SDimitry Andric   Builder.setDefaultConstrainedExcept(fpExceptionBehavior);
1145ffd83dbSDimitry Andric   Builder.setIsFPConstrained(fpExceptionBehavior != llvm::fp::ebIgnore ||
1155ffd83dbSDimitry Andric                              RM != llvm::RoundingMode::NearestTiesToEven);
116480093f4SDimitry Andric }
117480093f4SDimitry Andric 
1185ffd83dbSDimitry Andric void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
1195ffd83dbSDimitry Andric   llvm::FastMathFlags FMF;
1205ffd83dbSDimitry Andric   FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
1215ffd83dbSDimitry Andric   FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
1225ffd83dbSDimitry Andric   FMF.setNoInfs(FPFeatures.getNoHonorInfs());
1235ffd83dbSDimitry Andric   FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
1245ffd83dbSDimitry Andric   FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
1255ffd83dbSDimitry Andric   FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
1265ffd83dbSDimitry Andric   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
1275ffd83dbSDimitry Andric   Builder.setFastMathFlags(FMF);
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric 
1305ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
1315ffd83dbSDimitry Andric                                                   FPOptions FPFeatures)
1325ffd83dbSDimitry Andric     : CGF(CGF), OldFPFeatures(CGF.CurFPFeatures) {
1335ffd83dbSDimitry Andric   CGF.CurFPFeatures = FPFeatures;
1340b57cec5SDimitry Andric 
1355ffd83dbSDimitry Andric   if (OldFPFeatures == FPFeatures)
1365ffd83dbSDimitry Andric     return;
1375ffd83dbSDimitry Andric 
1385ffd83dbSDimitry Andric   FMFGuard.emplace(CGF.Builder);
1395ffd83dbSDimitry Andric 
1405ffd83dbSDimitry Andric   llvm::RoundingMode NewRoundingBehavior =
1415ffd83dbSDimitry Andric       static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
1425ffd83dbSDimitry Andric   CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
1435ffd83dbSDimitry Andric   auto NewExceptionBehavior =
1445ffd83dbSDimitry Andric       ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
1455ffd83dbSDimitry Andric           FPFeatures.getFPExceptionMode()));
1465ffd83dbSDimitry Andric   CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
1475ffd83dbSDimitry Andric 
1485ffd83dbSDimitry Andric   CGF.SetFastMathFlags(FPFeatures);
1495ffd83dbSDimitry Andric 
1505ffd83dbSDimitry Andric   assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
1515ffd83dbSDimitry Andric           isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
1525ffd83dbSDimitry Andric           isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
1535ffd83dbSDimitry Andric           (NewExceptionBehavior == llvm::fp::ebIgnore &&
1545ffd83dbSDimitry Andric            NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
1555ffd83dbSDimitry Andric          "FPConstrained should be enabled on entire function");
1565ffd83dbSDimitry Andric 
1575ffd83dbSDimitry Andric   auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
1585ffd83dbSDimitry Andric     auto OldValue =
1595ffd83dbSDimitry Andric         CGF.CurFn->getFnAttribute(Name).getValueAsString() == "true";
1605ffd83dbSDimitry Andric     auto NewValue = OldValue & Value;
1615ffd83dbSDimitry Andric     if (OldValue != NewValue)
1625ffd83dbSDimitry Andric       CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
1635ffd83dbSDimitry Andric   };
1645ffd83dbSDimitry Andric   mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
1655ffd83dbSDimitry Andric   mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
1665ffd83dbSDimitry Andric   mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
1675ffd83dbSDimitry Andric   mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
1685ffd83dbSDimitry Andric                                          FPFeatures.getAllowReciprocal() &&
1695ffd83dbSDimitry Andric                                          FPFeatures.getAllowApproxFunc() &&
1705ffd83dbSDimitry Andric                                          FPFeatures.getNoSignedZero());
1710b57cec5SDimitry Andric }
1720b57cec5SDimitry Andric 
1735ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
1745ffd83dbSDimitry Andric   CGF.CurFPFeatures = OldFPFeatures;
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1780b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
1790b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
1805ffd83dbSDimitry Andric   CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
1810b57cec5SDimitry Andric   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
1820b57cec5SDimitry Andric                           TBAAInfo);
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1860b57cec5SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1870b57cec5SDimitry Andric LValue
1880b57cec5SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
1890b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
1900b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
1915ffd83dbSDimitry Andric   CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
1920b57cec5SDimitry Andric                                                 /* forPointeeType= */ true);
1930b57cec5SDimitry Andric   return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
1980b57cec5SDimitry Andric   return CGM.getTypes().ConvertTypeForMem(T);
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
2020b57cec5SDimitry Andric   return CGM.getTypes().ConvertType(T);
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
2060b57cec5SDimitry Andric   type = type.getCanonicalType();
2070b57cec5SDimitry Andric   while (true) {
2080b57cec5SDimitry Andric     switch (type->getTypeClass()) {
2090b57cec5SDimitry Andric #define TYPE(name, parent)
2100b57cec5SDimitry Andric #define ABSTRACT_TYPE(name, parent)
2110b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
2120b57cec5SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
2130b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
214a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
2150b57cec5SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric     case Type::Auto:
2180b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
2190b57cec5SDimitry Andric       llvm_unreachable("undeduced type in IR-generation");
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric     // Various scalar types.
2220b57cec5SDimitry Andric     case Type::Builtin:
2230b57cec5SDimitry Andric     case Type::Pointer:
2240b57cec5SDimitry Andric     case Type::BlockPointer:
2250b57cec5SDimitry Andric     case Type::LValueReference:
2260b57cec5SDimitry Andric     case Type::RValueReference:
2270b57cec5SDimitry Andric     case Type::MemberPointer:
2280b57cec5SDimitry Andric     case Type::Vector:
2290b57cec5SDimitry Andric     case Type::ExtVector:
2305ffd83dbSDimitry Andric     case Type::ConstantMatrix:
2310b57cec5SDimitry Andric     case Type::FunctionProto:
2320b57cec5SDimitry Andric     case Type::FunctionNoProto:
2330b57cec5SDimitry Andric     case Type::Enum:
2340b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
2350b57cec5SDimitry Andric     case Type::Pipe:
2365ffd83dbSDimitry Andric     case Type::ExtInt:
2370b57cec5SDimitry Andric       return TEK_Scalar;
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     // Complexes.
2400b57cec5SDimitry Andric     case Type::Complex:
2410b57cec5SDimitry Andric       return TEK_Complex;
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric     // Arrays, records, and Objective-C objects.
2440b57cec5SDimitry Andric     case Type::ConstantArray:
2450b57cec5SDimitry Andric     case Type::IncompleteArray:
2460b57cec5SDimitry Andric     case Type::VariableArray:
2470b57cec5SDimitry Andric     case Type::Record:
2480b57cec5SDimitry Andric     case Type::ObjCObject:
2490b57cec5SDimitry Andric     case Type::ObjCInterface:
2500b57cec5SDimitry Andric       return TEK_Aggregate;
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric     // We operate on atomic values according to their underlying type.
2530b57cec5SDimitry Andric     case Type::Atomic:
2540b57cec5SDimitry Andric       type = cast<AtomicType>(type)->getValueType();
2550b57cec5SDimitry Andric       continue;
2560b57cec5SDimitry Andric     }
2570b57cec5SDimitry Andric     llvm_unreachable("unknown type kind!");
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric }
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
2620b57cec5SDimitry Andric   // For cleanliness, we try to avoid emitting the return block for
2630b57cec5SDimitry Andric   // simple cases.
2640b57cec5SDimitry Andric   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   if (CurBB) {
2670b57cec5SDimitry Andric     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric     // We have a valid insert point, reuse it if it is empty or there are no
2700b57cec5SDimitry Andric     // explicit jumps to the return block.
2710b57cec5SDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
2720b57cec5SDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
2730b57cec5SDimitry Andric       delete ReturnBlock.getBlock();
2740b57cec5SDimitry Andric       ReturnBlock = JumpDest();
2750b57cec5SDimitry Andric     } else
2760b57cec5SDimitry Andric       EmitBlock(ReturnBlock.getBlock());
2770b57cec5SDimitry Andric     return llvm::DebugLoc();
2780b57cec5SDimitry Andric   }
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   // Otherwise, if the return block is the target of a single direct
2810b57cec5SDimitry Andric   // branch then we can just put the code in that block instead. This
2820b57cec5SDimitry Andric   // cleans up functions which started with a unified return block.
2830b57cec5SDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
2840b57cec5SDimitry Andric     llvm::BranchInst *BI =
2850b57cec5SDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
2860b57cec5SDimitry Andric     if (BI && BI->isUnconditional() &&
2870b57cec5SDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
2880b57cec5SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
2890b57cec5SDimitry Andric       // later by the actual 'ret' instruction.
2900b57cec5SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
2910b57cec5SDimitry Andric       Builder.SetInsertPoint(BI->getParent());
2920b57cec5SDimitry Andric       BI->eraseFromParent();
2930b57cec5SDimitry Andric       delete ReturnBlock.getBlock();
2940b57cec5SDimitry Andric       ReturnBlock = JumpDest();
2950b57cec5SDimitry Andric       return Loc;
2960b57cec5SDimitry Andric     }
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // FIXME: We are at an unreachable point, there is no reason to emit the block
3000b57cec5SDimitry Andric   // unless it has uses. However, we still need a place to put the debug
3010b57cec5SDimitry Andric   // region.end for now.
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   EmitBlock(ReturnBlock.getBlock());
3040b57cec5SDimitry Andric   return llvm::DebugLoc();
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
3080b57cec5SDimitry Andric   if (!BB) return;
3090b57cec5SDimitry Andric   if (!BB->use_empty())
3100b57cec5SDimitry Andric     return CGF.CurFn->getBasicBlockList().push_back(BB);
3110b57cec5SDimitry Andric   delete BB;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
3150b57cec5SDimitry Andric   assert(BreakContinueStack.empty() &&
3160b57cec5SDimitry Andric          "mismatched push/pop in break/continue stack!");
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
3190b57cec5SDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
3200b57cec5SDimitry Andric     && ReturnBlock.getBlock()->use_empty();
3210b57cec5SDimitry Andric   // Usually the return expression is evaluated before the cleanup
3220b57cec5SDimitry Andric   // code.  If the function contains only a simple return statement,
3230b57cec5SDimitry Andric   // such as a constant, the location before the cleanup code becomes
3240b57cec5SDimitry Andric   // the last useful breakpoint in the function, because the simple
3250b57cec5SDimitry Andric   // return expression will be evaluated after the cleanup code. To be
3260b57cec5SDimitry Andric   // safe, set the debug location for cleanup code to the location of
3270b57cec5SDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
3280b57cec5SDimitry Andric   // end of the function's lexical scope.
3290b57cec5SDimitry Andric   //
3300b57cec5SDimitry Andric   // If there are multiple branches to the return block, the branch
3310b57cec5SDimitry Andric   // instructions will get the location of the return statements and
3320b57cec5SDimitry Andric   // all will be fine.
3330b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
3340b57cec5SDimitry Andric     if (OnlySimpleReturnStmts)
3350b57cec5SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
3360b57cec5SDimitry Andric     else
3370b57cec5SDimitry Andric       DI->EmitLocation(Builder, EndLoc);
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // Pop any cleanups that might have been associated with the
3410b57cec5SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
3420b57cec5SDimitry Andric   // important to do this before we enter the return block or return
3430b57cec5SDimitry Andric   // edges will be *really* confused.
3440b57cec5SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
3450b57cec5SDimitry Andric   bool HasOnlyLifetimeMarkers =
3460b57cec5SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
3470b57cec5SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
3480b57cec5SDimitry Andric   if (HasCleanups) {
3490b57cec5SDimitry Andric     // Make sure the line table doesn't jump back into the body for
3500b57cec5SDimitry Andric     // the ret after it's been at EndLoc.
351480093f4SDimitry Andric     Optional<ApplyDebugLocation> AL;
352480093f4SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo()) {
3530b57cec5SDimitry Andric       if (OnlySimpleReturnStmts)
3540b57cec5SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
355480093f4SDimitry Andric       else
356480093f4SDimitry Andric         // We may not have a valid end location. Try to apply it anyway, and
357480093f4SDimitry Andric         // fall back to an artificial location if needed.
358480093f4SDimitry Andric         AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
359480093f4SDimitry Andric     }
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // Emit function epilog (to return).
3650b57cec5SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   if (ShouldInstrumentFunction()) {
3680b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
3690b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
3700b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
3710b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-exit-inlined",
3720b57cec5SDimitry Andric                        "__cyg_profile_func_exit");
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   // Emit debug descriptor for function end.
3760b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
3770b57cec5SDimitry Andric     DI->EmitFunctionEnd(Builder, CurFn);
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
3800b57cec5SDimitry Andric   // rather than that of the end of the function's scope '}'.
3810b57cec5SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
3820b57cec5SDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
3830b57cec5SDimitry Andric   EmitEndEHSpec(CurCodeDecl);
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   assert(EHStack.empty() &&
3860b57cec5SDimitry Andric          "did not remove all scopes from cleanup stack!");
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   // If someone did an indirect goto, emit the indirect goto block at the end of
3890b57cec5SDimitry Andric   // the function.
3900b57cec5SDimitry Andric   if (IndirectBranch) {
3910b57cec5SDimitry Andric     EmitBlock(IndirectBranch->getParent());
3920b57cec5SDimitry Andric     Builder.ClearInsertionPoint();
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
3960b57cec5SDimitry Andric   // entry block.
3970b57cec5SDimitry Andric   if (!EscapedLocals.empty()) {
3980b57cec5SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
3990b57cec5SDimitry Andric     // no holes.
4000b57cec5SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
4010b57cec5SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
4020b57cec5SDimitry Andric     for (auto &Pair : EscapedLocals)
4030b57cec5SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
4040b57cec5SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
4050b57cec5SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
4060b57cec5SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
4070b57cec5SDimitry Andric   }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
4100b57cec5SDimitry Andric   llvm::Instruction *Ptr = AllocaInsertPt;
4110b57cec5SDimitry Andric   AllocaInsertPt = nullptr;
4120b57cec5SDimitry Andric   Ptr->eraseFromParent();
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   // If someone took the address of a label but never did an indirect goto, we
4150b57cec5SDimitry Andric   // made a zero entry PHI node, which is illegal, zap it now.
4160b57cec5SDimitry Andric   if (IndirectBranch) {
4170b57cec5SDimitry Andric     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
4180b57cec5SDimitry Andric     if (PN->getNumIncomingValues() == 0) {
4190b57cec5SDimitry Andric       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
4200b57cec5SDimitry Andric       PN->eraseFromParent();
4210b57cec5SDimitry Andric     }
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
4250b57cec5SDimitry Andric   EmitIfUsed(*this, TerminateLandingPad);
4260b57cec5SDimitry Andric   EmitIfUsed(*this, TerminateHandler);
4270b57cec5SDimitry Andric   EmitIfUsed(*this, UnreachableBlock);
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   for (const auto &FuncletAndParent : TerminateFunclets)
4300b57cec5SDimitry Andric     EmitIfUsed(*this, FuncletAndParent.second);
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().EmitDeclMetadata)
4330b57cec5SDimitry Andric     EmitDeclMetadata();
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
4360b57cec5SDimitry Andric            I = DeferredReplacements.begin(),
4370b57cec5SDimitry Andric            E = DeferredReplacements.end();
4380b57cec5SDimitry Andric        I != E; ++I) {
4390b57cec5SDimitry Andric     I->first->replaceAllUsesWith(I->second);
4400b57cec5SDimitry Andric     I->first->eraseFromParent();
4410b57cec5SDimitry Andric   }
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
4440b57cec5SDimitry Andric   // PHIs if the current function is a coroutine. We don't do it for all
4450b57cec5SDimitry Andric   // functions as it may result in slight increase in numbers of instructions
4460b57cec5SDimitry Andric   // if compiled with no optimizations. We do it for coroutine as the lifetime
4470b57cec5SDimitry Andric   // of CleanupDestSlot alloca make correct coroutine frame building very
4480b57cec5SDimitry Andric   // difficult.
4490b57cec5SDimitry Andric   if (NormalCleanupDest.isValid() && isCoroutine()) {
4500b57cec5SDimitry Andric     llvm::DominatorTree DT(*CurFn);
4510b57cec5SDimitry Andric     llvm::PromoteMemToReg(
4520b57cec5SDimitry Andric         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
4530b57cec5SDimitry Andric     NormalCleanupDest = Address::invalid();
4540b57cec5SDimitry Andric   }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   // Scan function arguments for vector width.
4570b57cec5SDimitry Andric   for (llvm::Argument &A : CurFn->args())
4580b57cec5SDimitry Andric     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
4595ffd83dbSDimitry Andric       LargestVectorWidth =
4605ffd83dbSDimitry Andric           std::max((uint64_t)LargestVectorWidth,
4615ffd83dbSDimitry Andric                    VT->getPrimitiveSizeInBits().getKnownMinSize());
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   // Update vector width based on return type.
4640b57cec5SDimitry Andric   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
4655ffd83dbSDimitry Andric     LargestVectorWidth =
4665ffd83dbSDimitry Andric         std::max((uint64_t)LargestVectorWidth,
4675ffd83dbSDimitry Andric                  VT->getPrimitiveSizeInBits().getKnownMinSize());
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // Add the required-vector-width attribute. This contains the max width from:
4700b57cec5SDimitry Andric   // 1. min-vector-width attribute used in the source program.
4710b57cec5SDimitry Andric   // 2. Any builtins used that have a vector width specified.
4720b57cec5SDimitry Andric   // 3. Values passed in and out of inline assembly.
4730b57cec5SDimitry Andric   // 4. Width of vector arguments and return types for this function.
4740b57cec5SDimitry Andric   // 5. Width of vector aguments and return types for functions called by this
4750b57cec5SDimitry Andric   //    function.
4760b57cec5SDimitry Andric   CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   // If we generated an unreachable return block, delete it now.
4790b57cec5SDimitry Andric   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
4800b57cec5SDimitry Andric     Builder.ClearInsertionPoint();
4810b57cec5SDimitry Andric     ReturnBlock.getBlock()->eraseFromParent();
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric   if (ReturnValue.isValid()) {
4840b57cec5SDimitry Andric     auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
4850b57cec5SDimitry Andric     if (RetAlloca && RetAlloca->use_empty()) {
4860b57cec5SDimitry Andric       RetAlloca->eraseFromParent();
4870b57cec5SDimitry Andric       ReturnValue = Address::invalid();
4880b57cec5SDimitry Andric     }
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric }
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric /// ShouldInstrumentFunction - Return true if the current function should be
4930b57cec5SDimitry Andric /// instrumented with __cyg_profile_func_* calls
4940b57cec5SDimitry Andric bool CodeGenFunction::ShouldInstrumentFunction() {
4950b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
4960b57cec5SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
4970b57cec5SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
4980b57cec5SDimitry Andric     return false;
4990b57cec5SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
5000b57cec5SDimitry Andric     return false;
5010b57cec5SDimitry Andric   return true;
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
5050b57cec5SDimitry Andric /// instrumented with XRay nop sleds.
5060b57cec5SDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
5070b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
5110b57cec5SDimitry Andric /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
5120b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
5130b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
5140b57cec5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
5150b57cec5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
5160b57cec5SDimitry Andric               XRayInstrKind::Custom);
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
5200b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
5210b57cec5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
5220b57cec5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
5230b57cec5SDimitry Andric               XRayInstrKind::Typed);
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric llvm::Constant *
5270b57cec5SDimitry Andric CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
5280b57cec5SDimitry Andric                                             llvm::Constant *Addr) {
5290b57cec5SDimitry Andric   // Addresses stored in prologue data can't require run-time fixups and must
5300b57cec5SDimitry Andric   // be PC-relative. Run-time fixups are undesirable because they necessitate
5310b57cec5SDimitry Andric   // writable text segments, which are unsafe. And absolute addresses are
5320b57cec5SDimitry Andric   // undesirable because they break PIE mode.
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // Add a layer of indirection through a private global. Taking its address
5350b57cec5SDimitry Andric   // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
5360b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
5370b57cec5SDimitry Andric                                       /*isConstant=*/true,
5380b57cec5SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Addr);
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   // Create a PC-relative address.
5410b57cec5SDimitry Andric   auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
5420b57cec5SDimitry Andric   auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
5430b57cec5SDimitry Andric   auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
5440b57cec5SDimitry Andric   return (IntPtrTy == Int32Ty)
5450b57cec5SDimitry Andric              ? PCRelAsInt
5460b57cec5SDimitry Andric              : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric llvm::Value *
5500b57cec5SDimitry Andric CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
5510b57cec5SDimitry Andric                                           llvm::Value *EncodedAddr) {
5520b57cec5SDimitry Andric   // Reconstruct the address of the global.
5530b57cec5SDimitry Andric   auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
5540b57cec5SDimitry Andric   auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
5550b57cec5SDimitry Andric   auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
5560b57cec5SDimitry Andric   auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   // Load the original pointer through the global.
5590b57cec5SDimitry Andric   return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
5600b57cec5SDimitry Andric                             "decoded_addr");
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
5640b57cec5SDimitry Andric                                                llvm::Function *Fn)
5650b57cec5SDimitry Andric {
5660b57cec5SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
5670b57cec5SDimitry Andric     return;
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   CGM.GenOpenCLArgMetadata(Fn, FD, this);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
5740b57cec5SDimitry Andric     QualType HintQTy = A->getTypeHint();
5750b57cec5SDimitry Andric     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
5760b57cec5SDimitry Andric     bool IsSignedInteger =
5770b57cec5SDimitry Andric         HintQTy->isSignedIntegerType() ||
5780b57cec5SDimitry Andric         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
5790b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
5800b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
5810b57cec5SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
5820b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5830b57cec5SDimitry Andric             llvm::IntegerType::get(Context, 32),
5840b57cec5SDimitry Andric             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
5850b57cec5SDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
5860b57cec5SDimitry Andric   }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
5890b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
5900b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
5910b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
5920b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
5930b57cec5SDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
5940b57cec5SDimitry Andric   }
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
5970b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
5980b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
5990b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
6000b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6010b57cec5SDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
6020b57cec5SDimitry Andric   }
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
6050b57cec5SDimitry Andric           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6060b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6070b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
6080b57cec5SDimitry Andric     Fn->setMetadata("intel_reqd_sub_group_size",
6090b57cec5SDimitry Andric                     llvm::MDNode::get(Context, AttrMDArgs));
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric /// Determine whether the function F ends with a return stmt.
6140b57cec5SDimitry Andric static bool endsWithReturn(const Decl* F) {
6150b57cec5SDimitry Andric   const Stmt *Body = nullptr;
6160b57cec5SDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
6170b57cec5SDimitry Andric     Body = FD->getBody();
6180b57cec5SDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
6190b57cec5SDimitry Andric     Body = OMD->getBody();
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
6220b57cec5SDimitry Andric     auto LastStmt = CS->body_rbegin();
6230b57cec5SDimitry Andric     if (LastStmt != CS->body_rend())
6240b57cec5SDimitry Andric       return isa<ReturnStmt>(*LastStmt);
6250b57cec5SDimitry Andric   }
6260b57cec5SDimitry Andric   return false;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
6300b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
6310b57cec5SDimitry Andric     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
6320b57cec5SDimitry Andric     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
6330b57cec5SDimitry Andric   }
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric 
636480093f4SDimitry Andric /// Check if the return value of this function requires sanitization.
637480093f4SDimitry Andric bool CodeGenFunction::requiresReturnValueCheck() const {
638480093f4SDimitry Andric   return requiresReturnValueNullabilityCheck() ||
639480093f4SDimitry Andric          (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
640480093f4SDimitry Andric           CurCodeDecl->getAttr<ReturnsNonNullAttr>());
641480093f4SDimitry Andric }
642480093f4SDimitry Andric 
6430b57cec5SDimitry Andric static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
6440b57cec5SDimitry Andric   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
6450b57cec5SDimitry Andric   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
6460b57cec5SDimitry Andric       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
6470b57cec5SDimitry Andric       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
6480b57cec5SDimitry Andric     return false;
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
6510b57cec5SDimitry Andric     return false;
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric   if (MD->getNumParams() == 2) {
6540b57cec5SDimitry Andric     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
6550b57cec5SDimitry Andric     if (!PT || !PT->isVoidPointerType() ||
6560b57cec5SDimitry Andric         !PT->getPointeeType().isConstQualified())
6570b57cec5SDimitry Andric       return false;
6580b57cec5SDimitry Andric   }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric   return true;
6610b57cec5SDimitry Andric }
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric /// Return the UBSan prologue signature for \p FD if one is available.
6640b57cec5SDimitry Andric static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
6650b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
6660b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
6670b57cec5SDimitry Andric     if (!MD->isStatic())
6680b57cec5SDimitry Andric       return nullptr;
6690b57cec5SDimitry Andric   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric 
672480093f4SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
6730b57cec5SDimitry Andric                                     llvm::Function *Fn,
6740b57cec5SDimitry Andric                                     const CGFunctionInfo &FnInfo,
6750b57cec5SDimitry Andric                                     const FunctionArgList &Args,
6760b57cec5SDimitry Andric                                     SourceLocation Loc,
6770b57cec5SDimitry Andric                                     SourceLocation StartLoc) {
6780b57cec5SDimitry Andric   assert(!CurFn &&
6790b57cec5SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   DidCallStackSave = false;
6840b57cec5SDimitry Andric   CurCodeDecl = D;
6850b57cec5SDimitry Andric   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
6860b57cec5SDimitry Andric     if (FD->usesSEHTry())
6870b57cec5SDimitry Andric       CurSEHParent = FD;
6880b57cec5SDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
6890b57cec5SDimitry Andric   FnRetTy = RetTy;
6900b57cec5SDimitry Andric   CurFn = Fn;
6910b57cec5SDimitry Andric   CurFnInfo = &FnInfo;
6920b57cec5SDimitry Andric   assert(CurFn->isDeclaration() && "Function already has body?");
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric   // If this function has been blacklisted for any of the enabled sanitizers,
6950b57cec5SDimitry Andric   // disable the sanitizer for the function.
6960b57cec5SDimitry Andric   do {
6970b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
6980b57cec5SDimitry Andric   if (SanOpts.empty())                                                         \
6990b57cec5SDimitry Andric     break;                                                                     \
7000b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ID))                                          \
7010b57cec5SDimitry Andric     if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc))                \
7020b57cec5SDimitry Andric       SanOpts.set(SanitizerKind::ID, false);
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
7050b57cec5SDimitry Andric #undef SANITIZER
7060b57cec5SDimitry Andric   } while (0);
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   if (D) {
7090b57cec5SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
7100b57cec5SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
7110b57cec5SDimitry Andric       SanitizerMask mask = Attr->getMask();
7120b57cec5SDimitry Andric       SanOpts.Mask &= ~mask;
7130b57cec5SDimitry Andric       if (mask & SanitizerKind::Address)
7140b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::KernelAddress, false);
7150b57cec5SDimitry Andric       if (mask & SanitizerKind::KernelAddress)
7160b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::Address, false);
7170b57cec5SDimitry Andric       if (mask & SanitizerKind::HWAddress)
7180b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::KernelHWAddress, false);
7190b57cec5SDimitry Andric       if (mask & SanitizerKind::KernelHWAddress)
7200b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::HWAddress, false);
7210b57cec5SDimitry Andric     }
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   // Apply sanitizer attributes to the function.
7250b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
7260b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
7270b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
7280b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
7290b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::MemTag))
7300b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
7310b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
7320b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
7330b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
7340b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
7350b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
7360b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
7370b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ShadowCallStack))
7380b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   // Apply fuzzing attribute to the function.
7410b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
7420b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
7450b57cec5SDimitry Andric   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
7460b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
7470b57cec5SDimitry Andric     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
7480b57cec5SDimitry Andric       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
7490b57cec5SDimitry Andric       if (OMD->getMethodFamily() == OMF_dealloc ||
7500b57cec5SDimitry Andric           OMD->getMethodFamily() == OMF_initialize ||
7510b57cec5SDimitry Andric           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
7520b57cec5SDimitry Andric         markAsIgnoreThreadCheckingAtRuntime(Fn);
7530b57cec5SDimitry Andric       }
7540b57cec5SDimitry Andric     }
7550b57cec5SDimitry Andric   }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   // Ignore unrelated casts in STL allocate() since the allocator must cast
7580b57cec5SDimitry Andric   // from void* to T* before object initialization completes. Don't match on the
7590b57cec5SDimitry Andric   // namespace because not all allocators are in std::
7600b57cec5SDimitry Andric   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
7610b57cec5SDimitry Andric     if (matchesStlAllocatorFn(D, getContext()))
7620b57cec5SDimitry Andric       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
7630b57cec5SDimitry Andric   }
7640b57cec5SDimitry Andric 
765a7dea167SDimitry Andric   // Ignore null checks in coroutine functions since the coroutines passes
766a7dea167SDimitry Andric   // are not aware of how to move the extra UBSan instructions across the split
767a7dea167SDimitry Andric   // coroutine boundaries.
768a7dea167SDimitry Andric   if (D && SanOpts.has(SanitizerKind::Null))
769a7dea167SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(D))
770a7dea167SDimitry Andric       if (FD->getBody() &&
771a7dea167SDimitry Andric           FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
772a7dea167SDimitry Andric         SanOpts.Mask &= ~SanitizerKind::Null;
773a7dea167SDimitry Andric 
774480093f4SDimitry Andric   // Apply xray attributes to the function (as a string, for now)
7755ffd83dbSDimitry Andric   if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
7760b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
7775ffd83dbSDimitry Andric             XRayInstrKind::FunctionEntry) ||
7785ffd83dbSDimitry Andric         CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
7795ffd83dbSDimitry Andric             XRayInstrKind::FunctionExit)) {
7800b57cec5SDimitry Andric       if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
7810b57cec5SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
7820b57cec5SDimitry Andric       if (XRayAttr->neverXRayInstrument())
7830b57cec5SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
7840b57cec5SDimitry Andric       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
7850b57cec5SDimitry Andric         if (ShouldXRayInstrumentFunction())
7860b57cec5SDimitry Andric           Fn->addFnAttr("xray-log-args",
7870b57cec5SDimitry Andric                         llvm::utostr(LogArgs->getArgumentCount()));
7880b57cec5SDimitry Andric     }
7890b57cec5SDimitry Andric   } else {
7900b57cec5SDimitry Andric     if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
7910b57cec5SDimitry Andric       Fn->addFnAttr(
7920b57cec5SDimitry Andric           "xray-instruction-threshold",
7930b57cec5SDimitry Andric           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
7940b57cec5SDimitry Andric   }
795480093f4SDimitry Andric 
7965ffd83dbSDimitry Andric   if (ShouldXRayInstrumentFunction()) {
7975ffd83dbSDimitry Andric     if (CGM.getCodeGenOpts().XRayIgnoreLoops)
7985ffd83dbSDimitry Andric       Fn->addFnAttr("xray-ignore-loops");
7995ffd83dbSDimitry Andric 
8005ffd83dbSDimitry Andric     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8015ffd83dbSDimitry Andric             XRayInstrKind::FunctionExit))
8025ffd83dbSDimitry Andric       Fn->addFnAttr("xray-skip-exit");
8035ffd83dbSDimitry Andric 
8045ffd83dbSDimitry Andric     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8055ffd83dbSDimitry Andric             XRayInstrKind::FunctionEntry))
8065ffd83dbSDimitry Andric       Fn->addFnAttr("xray-skip-entry");
8075ffd83dbSDimitry Andric   }
8085ffd83dbSDimitry Andric 
80955e4f9d5SDimitry Andric   unsigned Count, Offset;
8105ffd83dbSDimitry Andric   if (const auto *Attr =
8115ffd83dbSDimitry Andric           D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
81255e4f9d5SDimitry Andric     Count = Attr->getCount();
81355e4f9d5SDimitry Andric     Offset = Attr->getOffset();
81455e4f9d5SDimitry Andric   } else {
81555e4f9d5SDimitry Andric     Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
81655e4f9d5SDimitry Andric     Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
81755e4f9d5SDimitry Andric   }
81855e4f9d5SDimitry Andric   if (Count && Offset <= Count) {
81955e4f9d5SDimitry Andric     Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
82055e4f9d5SDimitry Andric     if (Offset)
82155e4f9d5SDimitry Andric       Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
822480093f4SDimitry Andric   }
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   // Add no-jump-tables value.
8250b57cec5SDimitry Andric   Fn->addFnAttr("no-jump-tables",
8260b57cec5SDimitry Andric                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
8270b57cec5SDimitry Andric 
828480093f4SDimitry Andric   // Add no-inline-line-tables value.
829480093f4SDimitry Andric   if (CGM.getCodeGenOpts().NoInlineLineTables)
830480093f4SDimitry Andric     Fn->addFnAttr("no-inline-line-tables");
831480093f4SDimitry Andric 
8320b57cec5SDimitry Andric   // Add profile-sample-accurate value.
8330b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
8340b57cec5SDimitry Andric     Fn->addFnAttr("profile-sample-accurate");
8350b57cec5SDimitry Andric 
8365ffd83dbSDimitry Andric   if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
8375ffd83dbSDimitry Andric     Fn->addFnAttr("use-sample-profile");
8385ffd83dbSDimitry Andric 
839a7dea167SDimitry Andric   if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
840a7dea167SDimitry Andric     Fn->addFnAttr("cfi-canonical-jump-table");
841a7dea167SDimitry Andric 
8420b57cec5SDimitry Andric   if (getLangOpts().OpenCL) {
8430b57cec5SDimitry Andric     // Add metadata for a kernel function.
8440b57cec5SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
8450b57cec5SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // If we are checking function types, emit a function type signature as
8490b57cec5SDimitry Andric   // prologue data.
8500b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
8510b57cec5SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8520b57cec5SDimitry Andric       if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
8530b57cec5SDimitry Andric         // Remove any (C++17) exception specifications, to allow calling e.g. a
8540b57cec5SDimitry Andric         // noexcept function through a non-noexcept pointer.
8550b57cec5SDimitry Andric         auto ProtoTy =
8560b57cec5SDimitry Andric           getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
8570b57cec5SDimitry Andric                                                         EST_None);
8580b57cec5SDimitry Andric         llvm::Constant *FTRTTIConst =
8590b57cec5SDimitry Andric             CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
8600b57cec5SDimitry Andric         llvm::Constant *FTRTTIConstEncoded =
8610b57cec5SDimitry Andric             EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
8620b57cec5SDimitry Andric         llvm::Constant *PrologueStructElems[] = {PrologueSig,
8630b57cec5SDimitry Andric                                                  FTRTTIConstEncoded};
8640b57cec5SDimitry Andric         llvm::Constant *PrologueStructConst =
8650b57cec5SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
8660b57cec5SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
8670b57cec5SDimitry Andric       }
8680b57cec5SDimitry Andric     }
8690b57cec5SDimitry Andric   }
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric   // If we're checking nullability, we need to know whether we can check the
8720b57cec5SDimitry Andric   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
8730b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
8740b57cec5SDimitry Andric     auto Nullability = FnRetTy->getNullability(getContext());
8750b57cec5SDimitry Andric     if (Nullability && *Nullability == NullabilityKind::NonNull) {
8760b57cec5SDimitry Andric       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
8770b57cec5SDimitry Andric             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
8780b57cec5SDimitry Andric         RetValNullabilityPrecondition =
8790b57cec5SDimitry Andric             llvm::ConstantInt::getTrue(getLLVMContext());
8800b57cec5SDimitry Andric     }
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
8840b57cec5SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
8850b57cec5SDimitry Andric   // used within a program").
8865ffd83dbSDimitry Andric   //
8875ffd83dbSDimitry Andric   // OpenCL C 2.0 v2.2-11 s6.9.i:
8885ffd83dbSDimitry Andric   //     Recursion is not supported.
8895ffd83dbSDimitry Andric   //
8905ffd83dbSDimitry Andric   // SYCL v1.2.1 s3.10:
8915ffd83dbSDimitry Andric   //     kernels cannot include RTTI information, exception classes,
8925ffd83dbSDimitry Andric   //     recursive code, virtual functions or make use of C++ libraries that
8935ffd83dbSDimitry Andric   //     are not compiled for the device.
8945ffd83dbSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8955ffd83dbSDimitry Andric     if ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
8965ffd83dbSDimitry Andric         getLangOpts().SYCLIsDevice ||
8975ffd83dbSDimitry Andric         (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>()))
8980b57cec5SDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoRecurse);
8995ffd83dbSDimitry Andric   }
9000b57cec5SDimitry Andric 
9015ffd83dbSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
9025ffd83dbSDimitry Andric     Builder.setIsFPConstrained(FD->usesFPIntrin());
903480093f4SDimitry Andric     if (FD->usesFPIntrin())
904480093f4SDimitry Andric       Fn->addFnAttr(llvm::Attribute::StrictFP);
9055ffd83dbSDimitry Andric   }
906480093f4SDimitry Andric 
9070b57cec5SDimitry Andric   // If a custom alignment is used, force realigning to this alignment on
9080b57cec5SDimitry Andric   // any main function which certainly will need it.
9090b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
9100b57cec5SDimitry Andric     if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
9110b57cec5SDimitry Andric         CGM.getCodeGenOpts().StackAlignment)
9120b57cec5SDimitry Andric       Fn->addFnAttr("stackrealign");
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   // Create a marker to make it easy to insert allocas into the entryblock
9170b57cec5SDimitry Andric   // later.  Don't create this with the builder, because we don't want it
9180b57cec5SDimitry Andric   // folded.
9190b57cec5SDimitry Andric   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
9200b57cec5SDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   ReturnBlock = getJumpDestInCurrentScope("return");
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   Builder.SetInsertPoint(EntryBB);
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   // If we're checking the return value, allocate space for a pointer to a
9270b57cec5SDimitry Andric   // precise source location of the checked return statement.
9280b57cec5SDimitry Andric   if (requiresReturnValueCheck()) {
9290b57cec5SDimitry Andric     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
9300b57cec5SDimitry Andric     InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
9310b57cec5SDimitry Andric   }
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric   // Emit subprogram debug descriptor.
9340b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
9350b57cec5SDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
9360b57cec5SDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
9370b57cec5SDimitry Andric     // convention.
9380b57cec5SDimitry Andric     CallingConv CC = CallingConv::CC_C;
9390b57cec5SDimitry Andric     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
9400b57cec5SDimitry Andric       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
9410b57cec5SDimitry Andric         CC = SrcFnTy->getCallConv();
9420b57cec5SDimitry Andric     SmallVector<QualType, 16> ArgTypes;
9430b57cec5SDimitry Andric     for (const VarDecl *VD : Args)
9440b57cec5SDimitry Andric       ArgTypes.push_back(VD->getType());
9450b57cec5SDimitry Andric     QualType FnType = getContext().getFunctionType(
9460b57cec5SDimitry Andric         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
9470b57cec5SDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
9480b57cec5SDimitry Andric                           Builder);
9490b57cec5SDimitry Andric   }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   if (ShouldInstrumentFunction()) {
9520b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
9530b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
9540b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
9550b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
9560b57cec5SDimitry Andric                        "__cyg_profile_func_enter");
9570b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
9580b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
9590b57cec5SDimitry Andric                        "__cyg_profile_func_enter_bare");
9600b57cec5SDimitry Andric   }
9610b57cec5SDimitry Andric 
9620b57cec5SDimitry Andric   // Since emitting the mcount call here impacts optimizations such as function
9630b57cec5SDimitry Andric   // inlining, we just add an attribute to insert a mcount call in backend.
9640b57cec5SDimitry Andric   // The attribute "counting-function" is set to mcount function name which is
9650b57cec5SDimitry Andric   // architecture dependent.
9660b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
9670b57cec5SDimitry Andric     // Calls to fentry/mcount should not be generated if function has
9680b57cec5SDimitry Andric     // the no_instrument_function attribute.
9690b57cec5SDimitry Andric     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
9700b57cec5SDimitry Andric       if (CGM.getCodeGenOpts().CallFEntry)
9710b57cec5SDimitry Andric         Fn->addFnAttr("fentry-call", "true");
9720b57cec5SDimitry Andric       else {
9730b57cec5SDimitry Andric         Fn->addFnAttr("instrument-function-entry-inlined",
9740b57cec5SDimitry Andric                       getTarget().getMCountName());
9750b57cec5SDimitry Andric       }
976480093f4SDimitry Andric       if (CGM.getCodeGenOpts().MNopMCount) {
977480093f4SDimitry Andric         if (!CGM.getCodeGenOpts().CallFEntry)
978480093f4SDimitry Andric           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
979480093f4SDimitry Andric             << "-mnop-mcount" << "-mfentry";
980480093f4SDimitry Andric         Fn->addFnAttr("mnop-mcount");
9810b57cec5SDimitry Andric       }
982480093f4SDimitry Andric 
983480093f4SDimitry Andric       if (CGM.getCodeGenOpts().RecordMCount) {
984480093f4SDimitry Andric         if (!CGM.getCodeGenOpts().CallFEntry)
985480093f4SDimitry Andric           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
986480093f4SDimitry Andric             << "-mrecord-mcount" << "-mfentry";
987480093f4SDimitry Andric         Fn->addFnAttr("mrecord-mcount");
988480093f4SDimitry Andric       }
989480093f4SDimitry Andric     }
990480093f4SDimitry Andric   }
991480093f4SDimitry Andric 
992480093f4SDimitry Andric   if (CGM.getCodeGenOpts().PackedStack) {
993480093f4SDimitry Andric     if (getContext().getTargetInfo().getTriple().getArch() !=
994480093f4SDimitry Andric         llvm::Triple::systemz)
995480093f4SDimitry Andric       CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
996480093f4SDimitry Andric         << "-mpacked-stack";
997480093f4SDimitry Andric     Fn->addFnAttr("packed-stack");
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   if (RetTy->isVoidType()) {
10010b57cec5SDimitry Andric     // Void type; nothing to return.
10020b57cec5SDimitry Andric     ReturnValue = Address::invalid();
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric     // Count the implicit return.
10050b57cec5SDimitry Andric     if (!endsWithReturn(D))
10060b57cec5SDimitry Andric       ++NumReturnExprs;
10070b57cec5SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
10080b57cec5SDimitry Andric     // Indirect return; emit returned value directly into sret slot.
10090b57cec5SDimitry Andric     // This reduces code size, and affects correctness in C++.
10100b57cec5SDimitry Andric     auto AI = CurFn->arg_begin();
10110b57cec5SDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
10120b57cec5SDimitry Andric       ++AI;
10130b57cec5SDimitry Andric     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
10140b57cec5SDimitry Andric     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
10150b57cec5SDimitry Andric       ReturnValuePointer =
10160b57cec5SDimitry Andric           CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
10170b57cec5SDimitry Andric       Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
10180b57cec5SDimitry Andric                               ReturnValue.getPointer(), Int8PtrTy),
10190b57cec5SDimitry Andric                           ReturnValuePointer);
10200b57cec5SDimitry Andric     }
10210b57cec5SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
10220b57cec5SDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
10230b57cec5SDimitry Andric     // Load the sret pointer from the argument struct and return into that.
10240b57cec5SDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
10250b57cec5SDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
10260b57cec5SDimitry Andric     --EI;
10270b57cec5SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
10280b57cec5SDimitry Andric     ReturnValuePointer = Address(Addr, getPointerAlign());
10290b57cec5SDimitry Andric     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
10305ffd83dbSDimitry Andric     ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
10310b57cec5SDimitry Andric   } else {
10320b57cec5SDimitry Andric     ReturnValue = CreateIRTemp(RetTy, "retval");
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
10350b57cec5SDimitry Andric     // now so that various specialized functions can suppress it
10360b57cec5SDimitry Andric     // during their IR-generation.
10370b57cec5SDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
10380b57cec5SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
10390b57cec5SDimitry Andric         RetTy->isObjCRetainableType())
10400b57cec5SDimitry Andric       AutoreleaseResult = true;
10410b57cec5SDimitry Andric   }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   EmitStartEHSpec(CurCodeDecl);
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric   // Emit OpenMP specific initialization of the device functions.
10480b57cec5SDimitry Andric   if (getLangOpts().OpenMP && CurCodeDecl)
10490b57cec5SDimitry Andric     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
10540b57cec5SDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
10550b57cec5SDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
10560b57cec5SDimitry Andric     if (MD->getParent()->isLambda() &&
10570b57cec5SDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
10580b57cec5SDimitry Andric       // We're in a lambda; figure out the captures.
10590b57cec5SDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
10600b57cec5SDimitry Andric                                         LambdaThisCaptureField);
10610b57cec5SDimitry Andric       if (LambdaThisCaptureField) {
10620b57cec5SDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
10630b57cec5SDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
10640b57cec5SDimitry Andric         // object.
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
10670b57cec5SDimitry Andric         // or contains the address of the enclosing object).
10680b57cec5SDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
10690b57cec5SDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
10700b57cec5SDimitry Andric           // If the enclosing object was captured by value, just use its address.
1071480093f4SDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
10720b57cec5SDimitry Andric         } else {
10730b57cec5SDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
10740b57cec5SDimitry Andric           // by reference.
10750b57cec5SDimitry Andric           CXXThisValue =
10760b57cec5SDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
10770b57cec5SDimitry Andric         }
10780b57cec5SDimitry Andric       }
10790b57cec5SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
10800b57cec5SDimitry Andric         if (FD->hasCapturedVLAType()) {
10810b57cec5SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
10820b57cec5SDimitry Andric                                            SourceLocation()).getScalarVal();
10830b57cec5SDimitry Andric           auto VAT = FD->getCapturedVLAType();
10840b57cec5SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
10850b57cec5SDimitry Andric         }
10860b57cec5SDimitry Andric       }
10870b57cec5SDimitry Andric     } else {
10880b57cec5SDimitry Andric       // Not in a lambda; just use 'this' from the method.
10890b57cec5SDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
10900b57cec5SDimitry Andric       // fast register allocator would be happier...
10910b57cec5SDimitry Andric       CXXThisValue = CXXABIThisValue;
10920b57cec5SDimitry Andric     }
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric     // Check the 'this' pointer once per function, if it's available.
10950b57cec5SDimitry Andric     if (CXXABIThisValue) {
10960b57cec5SDimitry Andric       SanitizerSet SkippedChecks;
10970b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::ObjectSize, true);
10980b57cec5SDimitry Andric       QualType ThisTy = MD->getThisType();
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric       // If this is the call operator of a lambda with no capture-default, it
11010b57cec5SDimitry Andric       // may have a static invoker function, which may call this operator with
11020b57cec5SDimitry Andric       // a null 'this' pointer.
11030b57cec5SDimitry Andric       if (isLambdaCallOperator(MD) &&
11040b57cec5SDimitry Andric           MD->getParent()->getLambdaCaptureDefault() == LCD_None)
11050b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric       EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
11080b57cec5SDimitry Andric                                                 : TCK_MemberCall,
11090b57cec5SDimitry Andric                     Loc, CXXABIThisValue, ThisTy,
11100b57cec5SDimitry Andric                     getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
11110b57cec5SDimitry Andric                     SkippedChecks);
11120b57cec5SDimitry Andric     }
11130b57cec5SDimitry Andric   }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   // If any of the arguments have a variably modified type, make sure to
11160b57cec5SDimitry Andric   // emit the type size.
11170b57cec5SDimitry Andric   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
11180b57cec5SDimitry Andric        i != e; ++i) {
11190b57cec5SDimitry Andric     const VarDecl *VD = *i;
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
11220b57cec5SDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
11230b57cec5SDimitry Andric     // precedent set by gcc.
11240b57cec5SDimitry Andric     QualType Ty;
11250b57cec5SDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
11260b57cec5SDimitry Andric       Ty = PVD->getOriginalType();
11270b57cec5SDimitry Andric     else
11280b57cec5SDimitry Andric       Ty = VD->getType();
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric     if (Ty->isVariablyModifiedType())
11310b57cec5SDimitry Andric       EmitVariablyModifiedType(Ty);
11320b57cec5SDimitry Andric   }
11330b57cec5SDimitry Andric   // Emit a location at the end of the prologue.
11340b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
11350b57cec5SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric   // TODO: Do we need to handle this in two places like we do with
11380b57cec5SDimitry Andric   // target-features/target-cpu?
11390b57cec5SDimitry Andric   if (CurFuncDecl)
11400b57cec5SDimitry Andric     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
11410b57cec5SDimitry Andric       LargestVectorWidth = VecWidth->getVectorWidth();
11420b57cec5SDimitry Andric }
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
11450b57cec5SDimitry Andric   incrementProfileCounter(Body);
11460b57cec5SDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
11470b57cec5SDimitry Andric     EmitCompoundStmtWithoutScope(*S);
11480b57cec5SDimitry Andric   else
11490b57cec5SDimitry Andric     EmitStmt(Body);
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
11530b57cec5SDimitry Andric /// such as switch cases need to not include the fall-through counts, so
11540b57cec5SDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
11550b57cec5SDimitry Andric /// this just calls EmitBlock().
11560b57cec5SDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
11570b57cec5SDimitry Andric                                                const Stmt *S) {
11580b57cec5SDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
11590b57cec5SDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
11600b57cec5SDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
11610b57cec5SDimitry Andric     // statements needs to skip over the instrumentation code so that we
11620b57cec5SDimitry Andric     // get an accurate count.
11630b57cec5SDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
11640b57cec5SDimitry Andric     EmitBranch(SkipCountBB);
11650b57cec5SDimitry Andric   }
11660b57cec5SDimitry Andric   EmitBlock(BB);
11670b57cec5SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
11680b57cec5SDimitry Andric   incrementProfileCounter(S);
11690b57cec5SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
11700b57cec5SDimitry Andric   if (SkipCountBB)
11710b57cec5SDimitry Andric     EmitBlock(SkipCountBB);
11720b57cec5SDimitry Andric }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric /// Tries to mark the given function nounwind based on the
11750b57cec5SDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
11760b57cec5SDimitry Andric /// lightweight enough to do at -O0.
11770b57cec5SDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
11780b57cec5SDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
11790b57cec5SDimitry Andric   // can't do this on functions that can be overwritten.
11800b57cec5SDimitry Andric   if (F->isInterposable()) return;
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric   for (llvm::BasicBlock &BB : *F)
11830b57cec5SDimitry Andric     for (llvm::Instruction &I : BB)
11840b57cec5SDimitry Andric       if (I.mayThrow())
11850b57cec5SDimitry Andric         return;
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   F->setDoesNotThrow();
11880b57cec5SDimitry Andric }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
11910b57cec5SDimitry Andric                                                FunctionArgList &Args) {
11920b57cec5SDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
11930b57cec5SDimitry Andric   QualType ResTy = FD->getReturnType();
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11960b57cec5SDimitry Andric   if (MD && MD->isInstance()) {
11970b57cec5SDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
11980b57cec5SDimitry Andric       ResTy = MD->getThisType();
11990b57cec5SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
12000b57cec5SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
12010b57cec5SDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
12020b57cec5SDimitry Andric   }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
12050b57cec5SDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
12060b57cec5SDimitry Andric   // the inherited constructor).
12070b57cec5SDimitry Andric   bool PassedParams = true;
12080b57cec5SDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
12090b57cec5SDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
12100b57cec5SDimitry Andric       PassedParams =
12110b57cec5SDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   if (PassedParams) {
12140b57cec5SDimitry Andric     for (auto *Param : FD->parameters()) {
12150b57cec5SDimitry Andric       Args.push_back(Param);
12160b57cec5SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
12170b57cec5SDimitry Andric         continue;
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
12200b57cec5SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(),
12210b57cec5SDimitry Andric           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
12220b57cec5SDimitry Andric       SizeArguments[Param] = Implicit;
12230b57cec5SDimitry Andric       Args.push_back(Implicit);
12240b57cec5SDimitry Andric     }
12250b57cec5SDimitry Andric   }
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
12280b57cec5SDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   return ResTy;
12310b57cec5SDimitry Andric }
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric static bool
12340b57cec5SDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
12350b57cec5SDimitry Andric                                              const ASTContext &Context) {
12360b57cec5SDimitry Andric   QualType T = FD->getReturnType();
12370b57cec5SDimitry Andric   // Avoid the optimization for functions that return a record type with a
12380b57cec5SDimitry Andric   // trivial destructor or another trivially copyable type.
12390b57cec5SDimitry Andric   if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
12400b57cec5SDimitry Andric     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
12410b57cec5SDimitry Andric       return !ClassDecl->hasTrivialDestructor();
12420b57cec5SDimitry Andric   }
12430b57cec5SDimitry Andric   return !T.isTriviallyCopyableType(Context);
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
12470b57cec5SDimitry Andric                                    const CGFunctionInfo &FnInfo) {
12480b57cec5SDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
12490b57cec5SDimitry Andric   CurGD = GD;
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric   FunctionArgList Args;
12520b57cec5SDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric   // Check if we should generate debug info for this function.
12550b57cec5SDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
12560b57cec5SDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric   // The function might not have a body if we're generating thunks for a
12590b57cec5SDimitry Andric   // function declaration.
12600b57cec5SDimitry Andric   SourceRange BodyRange;
12610b57cec5SDimitry Andric   if (Stmt *Body = FD->getBody())
12620b57cec5SDimitry Andric     BodyRange = Body->getSourceRange();
12630b57cec5SDimitry Andric   else
12640b57cec5SDimitry Andric     BodyRange = FD->getLocation();
12650b57cec5SDimitry Andric   CurEHLocation = BodyRange.getEnd();
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   // Use the location of the start of the function to determine where
12680b57cec5SDimitry Andric   // the function definition is located. By default use the location
12690b57cec5SDimitry Andric   // of the declaration as the location for the subprogram. A function
12700b57cec5SDimitry Andric   // may lack a declaration in the source code if it is created by code
12710b57cec5SDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
12720b57cec5SDimitry Andric   SourceLocation Loc = FD->getLocation();
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   // If this is a function specialization then use the pattern body
12750b57cec5SDimitry Andric   // as the location for the function.
12760b57cec5SDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
12770b57cec5SDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
12780b57cec5SDimitry Andric       Loc = SpecDecl->getLocation();
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   Stmt *Body = FD->getBody();
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric   // Initialize helper which will detect jumps which can cause invalid lifetime
12830b57cec5SDimitry Andric   // markers.
12840b57cec5SDimitry Andric   if (Body && ShouldEmitLifetimeMarkers)
12850b57cec5SDimitry Andric     Bypasses.Init(Body);
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   // Emit the standard function prologue.
12880b57cec5SDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric   // Generate the body of the function.
12910b57cec5SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
12920b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(FD))
12930b57cec5SDimitry Andric     EmitDestructorBody(Args);
12940b57cec5SDimitry Andric   else if (isa<CXXConstructorDecl>(FD))
12950b57cec5SDimitry Andric     EmitConstructorBody(Args);
12960b57cec5SDimitry Andric   else if (getLangOpts().CUDA &&
12970b57cec5SDimitry Andric            !getLangOpts().CUDAIsDevice &&
12980b57cec5SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
12990b57cec5SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
13000b57cec5SDimitry Andric   else if (isa<CXXMethodDecl>(FD) &&
13010b57cec5SDimitry Andric            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
13020b57cec5SDimitry Andric     // The lambda static invoker function is special, because it forwards or
13030b57cec5SDimitry Andric     // clones the body of the function call operator (but is actually static).
13040b57cec5SDimitry Andric     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
13050b57cec5SDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
13060b57cec5SDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
13070b57cec5SDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
13080b57cec5SDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
13090b57cec5SDimitry Andric     // copy-constructors.
13100b57cec5SDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
13110b57cec5SDimitry Andric   } else if (Body) {
13120b57cec5SDimitry Andric     EmitFunctionBody(Body);
13130b57cec5SDimitry Andric   } else
13140b57cec5SDimitry Andric     llvm_unreachable("no definition for emitted function");
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric   // C++11 [stmt.return]p2:
13170b57cec5SDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
13180b57cec5SDimitry Andric   //   a value-returning function.
13190b57cec5SDimitry Andric   // C11 6.9.1p12:
13200b57cec5SDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
13210b57cec5SDimitry Andric   //   function call is used by the caller, the behavior is undefined.
13220b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
13230b57cec5SDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
13240b57cec5SDimitry Andric     bool ShouldEmitUnreachable =
13250b57cec5SDimitry Andric         CGM.getCodeGenOpts().StrictReturn ||
13260b57cec5SDimitry Andric         shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
13270b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
13280b57cec5SDimitry Andric       SanitizerScope SanScope(this);
13290b57cec5SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
13300b57cec5SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
13310b57cec5SDimitry Andric                 SanitizerHandler::MissingReturn,
13320b57cec5SDimitry Andric                 EmitCheckSourceLocation(FD->getLocation()), None);
13330b57cec5SDimitry Andric     } else if (ShouldEmitUnreachable) {
13340b57cec5SDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
13350b57cec5SDimitry Andric         EmitTrapCall(llvm::Intrinsic::trap);
13360b57cec5SDimitry Andric     }
13370b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
13380b57cec5SDimitry Andric       Builder.CreateUnreachable();
13390b57cec5SDimitry Andric       Builder.ClearInsertionPoint();
13400b57cec5SDimitry Andric     }
13410b57cec5SDimitry Andric   }
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // Emit the standard function epilogue.
13440b57cec5SDimitry Andric   FinishFunction(BodyRange.getEnd());
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric   // If we haven't marked the function nothrow through other means, do
13470b57cec5SDimitry Andric   // a quick pass now to see if we can.
13480b57cec5SDimitry Andric   if (!CurFn->doesNotThrow())
13490b57cec5SDimitry Andric     TryMarkNoThrow(CurFn);
13500b57cec5SDimitry Andric }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric /// ContainsLabel - Return true if the statement contains a label in it.  If
13530b57cec5SDimitry Andric /// this statement is not executed normally, it not containing a label means
13540b57cec5SDimitry Andric /// that we can just remove the code.
13550b57cec5SDimitry Andric bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
13560b57cec5SDimitry Andric   // Null statement, not a label!
13570b57cec5SDimitry Andric   if (!S) return false;
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric   // If this is a label, we have to emit the code, consider something like:
13600b57cec5SDimitry Andric   // if (0) {  ...  foo:  bar(); }  goto foo;
13610b57cec5SDimitry Andric   //
13620b57cec5SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
13630b57cec5SDimitry Andric   // can't jump to one from outside their declared region.
13640b57cec5SDimitry Andric   if (isa<LabelStmt>(S))
13650b57cec5SDimitry Andric     return true;
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   // If this is a case/default statement, and we haven't seen a switch, we have
13680b57cec5SDimitry Andric   // to emit the code.
13690b57cec5SDimitry Andric   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
13700b57cec5SDimitry Andric     return true;
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric   // If this is a switch statement, we want to ignore cases below it.
13730b57cec5SDimitry Andric   if (isa<SwitchStmt>(S))
13740b57cec5SDimitry Andric     IgnoreCaseStmts = true;
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric   // Scan subexpressions for verboten labels.
13770b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
13780b57cec5SDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
13790b57cec5SDimitry Andric       return true;
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric   return false;
13820b57cec5SDimitry Andric }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
13850b57cec5SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
13860b57cec5SDimitry Andric /// inside of it, this is fine.
13870b57cec5SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
13880b57cec5SDimitry Andric   // Null statement, not a label!
13890b57cec5SDimitry Andric   if (!S) return false;
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
13920b57cec5SDimitry Andric   // include it and anything inside of it.
13930b57cec5SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
13940b57cec5SDimitry Andric       isa<ForStmt>(S))
13950b57cec5SDimitry Andric     return false;
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric   if (isa<BreakStmt>(S))
13980b57cec5SDimitry Andric     return true;
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   // Scan subexpressions for verboten breaks.
14010b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
14020b57cec5SDimitry Andric     if (containsBreak(SubStmt))
14030b57cec5SDimitry Andric       return true;
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric   return false;
14060b57cec5SDimitry Andric }
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
14090b57cec5SDimitry Andric   if (!S) return false;
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
14120b57cec5SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
14130b57cec5SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
14140b57cec5SDimitry Andric   // correct even if more statement kinds are added.
14150b57cec5SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
14160b57cec5SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
14170b57cec5SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
14180b57cec5SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
14190b57cec5SDimitry Andric     return false;
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   if (isa<DeclStmt>(S))
14220b57cec5SDimitry Andric     return true;
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
14250b57cec5SDimitry Andric     if (mightAddDeclToScope(SubStmt))
14260b57cec5SDimitry Andric       return true;
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric   return false;
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
14320b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
14330b57cec5SDimitry Andric /// constant folds return true and set the boolean result in Result.
14340b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
14350b57cec5SDimitry Andric                                                    bool &ResultBool,
14360b57cec5SDimitry Andric                                                    bool AllowLabels) {
14370b57cec5SDimitry Andric   llvm::APSInt ResultInt;
14380b57cec5SDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
14390b57cec5SDimitry Andric     return false;
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   ResultBool = ResultInt.getBoolValue();
14420b57cec5SDimitry Andric   return true;
14430b57cec5SDimitry Andric }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
14460b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
14470b57cec5SDimitry Andric /// constant folds return true and set the folded value.
14480b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
14490b57cec5SDimitry Andric                                                    llvm::APSInt &ResultInt,
14500b57cec5SDimitry Andric                                                    bool AllowLabels) {
14510b57cec5SDimitry Andric   // FIXME: Rename and handle conversion of other evaluatable things
14520b57cec5SDimitry Andric   // to bool.
14530b57cec5SDimitry Andric   Expr::EvalResult Result;
14540b57cec5SDimitry Andric   if (!Cond->EvaluateAsInt(Result, getContext()))
14550b57cec5SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   llvm::APSInt Int = Result.Val.getInt();
14580b57cec5SDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
14590b57cec5SDimitry Andric     return false;  // Contains a label.
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric   ResultInt = Int;
14620b57cec5SDimitry Andric   return true;
14630b57cec5SDimitry Andric }
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
14680b57cec5SDimitry Andric /// statement) to the specified blocks.  Based on the condition, this might try
14690b57cec5SDimitry Andric /// to simplify the codegen of the conditional based on the branch.
14700b57cec5SDimitry Andric ///
14710b57cec5SDimitry Andric void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
14720b57cec5SDimitry Andric                                            llvm::BasicBlock *TrueBlock,
14730b57cec5SDimitry Andric                                            llvm::BasicBlock *FalseBlock,
14740b57cec5SDimitry Andric                                            uint64_t TrueCount) {
14750b57cec5SDimitry Andric   Cond = Cond->IgnoreParens();
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric     // Handle X && Y in a condition.
14800b57cec5SDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
14810b57cec5SDimitry Andric       // If we have "1 && X", simplify the code.  "0 && X" would have constant
14820b57cec5SDimitry Andric       // folded if the case was simple enough.
14830b57cec5SDimitry Andric       bool ConstantBool = false;
14840b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
14850b57cec5SDimitry Andric           ConstantBool) {
14860b57cec5SDimitry Andric         // br(1 && X) -> br(X).
14870b57cec5SDimitry Andric         incrementProfileCounter(CondBOp);
14880b57cec5SDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
14890b57cec5SDimitry Andric                                     TrueCount);
14900b57cec5SDimitry Andric       }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric       // If we have "X && 1", simplify the code to use an uncond branch.
14930b57cec5SDimitry Andric       // "X && 0" would have been constant folded to 0.
14940b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
14950b57cec5SDimitry Andric           ConstantBool) {
14960b57cec5SDimitry Andric         // br(X && 1) -> br(X).
14970b57cec5SDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
14980b57cec5SDimitry Andric                                     TrueCount);
14990b57cec5SDimitry Andric       }
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric       // Emit the LHS as a conditional.  If the LHS conditional is false, we
15020b57cec5SDimitry Andric       // want to jump to the FalseBlock.
15030b57cec5SDimitry Andric       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
15040b57cec5SDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
15050b57cec5SDimitry Andric       // can be propagated to that branch.
15060b57cec5SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric       ConditionalEvaluation eval(*this);
15090b57cec5SDimitry Andric       {
15100b57cec5SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
15110b57cec5SDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
15120b57cec5SDimitry Andric         EmitBlock(LHSTrue);
15130b57cec5SDimitry Andric       }
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric       incrementProfileCounter(CondBOp);
15160b57cec5SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric       // Any temporaries created here are conditional.
15190b57cec5SDimitry Andric       eval.begin(*this);
15200b57cec5SDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
15210b57cec5SDimitry Andric       eval.end(*this);
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric       return;
15240b57cec5SDimitry Andric     }
15250b57cec5SDimitry Andric 
15260b57cec5SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
15270b57cec5SDimitry Andric       // If we have "0 || X", simplify the code.  "1 || X" would have constant
15280b57cec5SDimitry Andric       // folded if the case was simple enough.
15290b57cec5SDimitry Andric       bool ConstantBool = false;
15300b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
15310b57cec5SDimitry Andric           !ConstantBool) {
15320b57cec5SDimitry Andric         // br(0 || X) -> br(X).
15330b57cec5SDimitry Andric         incrementProfileCounter(CondBOp);
15340b57cec5SDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
15350b57cec5SDimitry Andric                                     TrueCount);
15360b57cec5SDimitry Andric       }
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric       // If we have "X || 0", simplify the code to use an uncond branch.
15390b57cec5SDimitry Andric       // "X || 1" would have been constant folded to 1.
15400b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
15410b57cec5SDimitry Andric           !ConstantBool) {
15420b57cec5SDimitry Andric         // br(X || 0) -> br(X).
15430b57cec5SDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
15440b57cec5SDimitry Andric                                     TrueCount);
15450b57cec5SDimitry Andric       }
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric       // Emit the LHS as a conditional.  If the LHS conditional is true, we
15480b57cec5SDimitry Andric       // want to jump to the TrueBlock.
15490b57cec5SDimitry Andric       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
15500b57cec5SDimitry Andric       // We have the count for entry to the RHS and for the whole expression
15510b57cec5SDimitry Andric       // being true, so we can divy up True count between the short circuit and
15520b57cec5SDimitry Andric       // the RHS.
15530b57cec5SDimitry Andric       uint64_t LHSCount =
15540b57cec5SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
15550b57cec5SDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric       ConditionalEvaluation eval(*this);
15580b57cec5SDimitry Andric       {
15590b57cec5SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
15600b57cec5SDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
15610b57cec5SDimitry Andric         EmitBlock(LHSFalse);
15620b57cec5SDimitry Andric       }
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric       incrementProfileCounter(CondBOp);
15650b57cec5SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric       // Any temporaries created here are conditional.
15680b57cec5SDimitry Andric       eval.begin(*this);
15690b57cec5SDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric       eval.end(*this);
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric       return;
15740b57cec5SDimitry Andric     }
15750b57cec5SDimitry Andric   }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
15780b57cec5SDimitry Andric     // br(!x, t, f) -> br(x, f, t)
15790b57cec5SDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
15800b57cec5SDimitry Andric       // Negate the count.
15810b57cec5SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
15820b57cec5SDimitry Andric       // Negate the condition and swap the destination blocks.
15830b57cec5SDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
15840b57cec5SDimitry Andric                                   FalseCount);
15850b57cec5SDimitry Andric     }
15860b57cec5SDimitry Andric   }
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
15890b57cec5SDimitry Andric     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
15900b57cec5SDimitry Andric     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
15910b57cec5SDimitry Andric     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric     ConditionalEvaluation cond(*this);
15940b57cec5SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
15950b57cec5SDimitry Andric                          getProfileCount(CondOp));
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric     // When computing PGO branch weights, we only know the overall count for
15980b57cec5SDimitry Andric     // the true block. This code is essentially doing tail duplication of the
15990b57cec5SDimitry Andric     // naive code-gen, introducing new edges for which counts are not
16000b57cec5SDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
16010b57cec5SDimitry Andric     // the conditional operator.
16020b57cec5SDimitry Andric     uint64_t LHSScaledTrueCount = 0;
16030b57cec5SDimitry Andric     if (TrueCount) {
16040b57cec5SDimitry Andric       double LHSRatio =
16050b57cec5SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
16060b57cec5SDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
16070b57cec5SDimitry Andric     }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric     cond.begin(*this);
16100b57cec5SDimitry Andric     EmitBlock(LHSBlock);
16110b57cec5SDimitry Andric     incrementProfileCounter(CondOp);
16120b57cec5SDimitry Andric     {
16130b57cec5SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
16140b57cec5SDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
16150b57cec5SDimitry Andric                            LHSScaledTrueCount);
16160b57cec5SDimitry Andric     }
16170b57cec5SDimitry Andric     cond.end(*this);
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric     cond.begin(*this);
16200b57cec5SDimitry Andric     EmitBlock(RHSBlock);
16210b57cec5SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
16220b57cec5SDimitry Andric                          TrueCount - LHSScaledTrueCount);
16230b57cec5SDimitry Andric     cond.end(*this);
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric     return;
16260b57cec5SDimitry Andric   }
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
16290b57cec5SDimitry Andric     // Conditional operator handling can give us a throw expression as a
16300b57cec5SDimitry Andric     // condition for a case like:
16310b57cec5SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
16320b57cec5SDimitry Andric     // Fold this to:
16330b57cec5SDimitry Andric     //   br(c, throw x, br(y, t, f))
16340b57cec5SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
16350b57cec5SDimitry Andric     return;
16360b57cec5SDimitry Andric   }
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
16390b57cec5SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
16400b57cec5SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
16410b57cec5SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
16420b57cec5SDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
16430b57cec5SDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
16440b57cec5SDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
16450b57cec5SDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
16460b57cec5SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
16470b57cec5SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
16480b57cec5SDimitry Andric     }
16490b57cec5SDimitry Andric   }
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   // Create branch weights based on the number of times we get here and the
16520b57cec5SDimitry Andric   // number of times the condition should be true.
16530b57cec5SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
16540b57cec5SDimitry Andric   llvm::MDNode *Weights =
16550b57cec5SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
16560b57cec5SDimitry Andric 
16570b57cec5SDimitry Andric   // Emit the code with the fully general case.
16580b57cec5SDimitry Andric   llvm::Value *CondV;
16590b57cec5SDimitry Andric   {
16600b57cec5SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
16610b57cec5SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
16620b57cec5SDimitry Andric   }
16630b57cec5SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
16640b57cec5SDimitry Andric }
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
16670b57cec5SDimitry Andric /// specified stmt yet.
16680b57cec5SDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
16690b57cec5SDimitry Andric   CGM.ErrorUnsupported(S, Type);
16700b57cec5SDimitry Andric }
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
16730b57cec5SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
16740b57cec5SDimitry Andric ///
16750b57cec5SDimitry Andric /// \param baseType the inner-most element type of the array
16760b57cec5SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
16770b57cec5SDimitry Andric /// base element of the array
16780b57cec5SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
16790b57cec5SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
16800b57cec5SDimitry Andric                                Address dest, Address src,
16810b57cec5SDimitry Andric                                llvm::Value *sizeInChars) {
16820b57cec5SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
16850b57cec5SDimitry Andric   llvm::Value *baseSizeInChars
16860b57cec5SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric   Address begin =
16890b57cec5SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
16900b57cec5SDimitry Andric   llvm::Value *end =
16910b57cec5SDimitry Andric     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
16940b57cec5SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
16950b57cec5SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
16980b57cec5SDimitry Andric   // count must be nonzero.
16990b57cec5SDimitry Andric   CGF.EmitBlock(loopBB);
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
17020b57cec5SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric   CharUnits curAlign =
17050b57cec5SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   // memcpy the individual element bit-pattern.
17080b57cec5SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
17090b57cec5SDimitry Andric                        /*volatile*/ false);
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   // Go to the next element.
17120b57cec5SDimitry Andric   llvm::Value *next =
17130b57cec5SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   // Leave if that's the end of the VLA.
17160b57cec5SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
17170b57cec5SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
17180b57cec5SDimitry Andric   cur->addIncoming(next, loopBB);
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   CGF.EmitBlock(contBB);
17210b57cec5SDimitry Andric }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric void
17240b57cec5SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
17250b57cec5SDimitry Andric   // Ignore empty classes in C++.
17260b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus) {
17270b57cec5SDimitry Andric     if (const RecordType *RT = Ty->getAs<RecordType>()) {
17280b57cec5SDimitry Andric       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
17290b57cec5SDimitry Andric         return;
17300b57cec5SDimitry Andric     }
17310b57cec5SDimitry Andric   }
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
17340b57cec5SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
17350b57cec5SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric   // Get size and alignment info for this aggregate.
17380b57cec5SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric   llvm::Value *SizeVal;
17410b57cec5SDimitry Andric   const VariableArrayType *vla;
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   // Don't bother emitting a zero-byte memset.
17440b57cec5SDimitry Andric   if (size.isZero()) {
17450b57cec5SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
17460b57cec5SDimitry Andric     if (const VariableArrayType *vlaType =
17470b57cec5SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
17480b57cec5SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
17490b57cec5SDimitry Andric       auto VlaSize = getVLASize(vlaType);
17500b57cec5SDimitry Andric       SizeVal = VlaSize.NumElts;
17510b57cec5SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
17520b57cec5SDimitry Andric       if (!eltSize.isOne())
17530b57cec5SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
17540b57cec5SDimitry Andric       vla = vlaType;
17550b57cec5SDimitry Andric     } else {
17560b57cec5SDimitry Andric       return;
17570b57cec5SDimitry Andric     }
17580b57cec5SDimitry Andric   } else {
17590b57cec5SDimitry Andric     SizeVal = CGM.getSize(size);
17600b57cec5SDimitry Andric     vla = nullptr;
17610b57cec5SDimitry Andric   }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
17640b57cec5SDimitry Andric   // Instead, create a null constant and copy it to the destination.
17650b57cec5SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
17660b57cec5SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
17670b57cec5SDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
17680b57cec5SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
17690b57cec5SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric     llvm::GlobalVariable *NullVariable =
17740b57cec5SDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
17750b57cec5SDimitry Andric                                /*isConstant=*/true,
17760b57cec5SDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
17770b57cec5SDimitry Andric                                NullConstant, Twine());
17780b57cec5SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
1779a7dea167SDimitry Andric     NullVariable->setAlignment(NullAlign.getAsAlign());
17800b57cec5SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
17810b57cec5SDimitry Andric                    NullAlign);
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
17860b57cec5SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
17870b57cec5SDimitry Andric     return;
17880b57cec5SDimitry Andric   }
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
17910b57cec5SDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
17920b57cec5SDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
17930b57cec5SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
17940b57cec5SDimitry Andric }
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
17970b57cec5SDimitry Andric   // Make sure that there is a block for the indirect goto.
17980b57cec5SDimitry Andric   if (!IndirectBranch)
17990b57cec5SDimitry Andric     GetIndirectGotoBlock();
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   // Make sure the indirect branch includes all of the address-taken blocks.
18040b57cec5SDimitry Andric   IndirectBranch->addDestination(BB);
18050b57cec5SDimitry Andric   return llvm::BlockAddress::get(CurFn, BB);
18060b57cec5SDimitry Andric }
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
18090b57cec5SDimitry Andric   // If we already made the indirect branch for indirect goto, return its block.
18100b57cec5SDimitry Andric   if (IndirectBranch) return IndirectBranch->getParent();
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // Create the PHI node that indirect gotos will add entries to.
18150b57cec5SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
18160b57cec5SDimitry Andric                                               "indirect.goto.dest");
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric   // Create the indirect branch instruction.
18190b57cec5SDimitry Andric   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
18200b57cec5SDimitry Andric   return IndirectBranch->getParent();
18210b57cec5SDimitry Andric }
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric /// Computes the length of an array in elements, as well as the base
18240b57cec5SDimitry Andric /// element type and a properly-typed first element pointer.
18250b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
18260b57cec5SDimitry Andric                                               QualType &baseType,
18270b57cec5SDimitry Andric                                               Address &addr) {
18280b57cec5SDimitry Andric   const ArrayType *arrayType = origArrayType;
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
18310b57cec5SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
18320b57cec5SDimitry Andric   llvm::Value *numVLAElements = nullptr;
18330b57cec5SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
18340b57cec5SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
18370b57cec5SDimitry Andric     // which has type T* where T is the first non-VLA element type.
18380b57cec5SDimitry Andric     do {
18390b57cec5SDimitry Andric       QualType elementType = arrayType->getElementType();
18400b57cec5SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
18430b57cec5SDimitry Andric       if (!arrayType) {
18440b57cec5SDimitry Andric         baseType = elementType;
18450b57cec5SDimitry Andric         return numVLAElements;
18460b57cec5SDimitry Andric       }
18470b57cec5SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric     // We get out here only if we find a constant array type
18500b57cec5SDimitry Andric     // inside the VLA.
18510b57cec5SDimitry Andric   }
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric   // We have some number of constant-length arrays, so addr should
18540b57cec5SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
18550b57cec5SDimitry Andric   // down to the first element of addr.
18560b57cec5SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric   // GEP down to the array type.
18590b57cec5SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
18600b57cec5SDimitry Andric   gepIndices.push_back(zero);
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric   uint64_t countFromCLAs = 1;
18630b57cec5SDimitry Andric   QualType eltType;
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   llvm::ArrayType *llvmArrayType =
18660b57cec5SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
18670b57cec5SDimitry Andric   while (llvmArrayType) {
18680b57cec5SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
18690b57cec5SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
18700b57cec5SDimitry Andric              == llvmArrayType->getNumElements());
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric     gepIndices.push_back(zero);
18730b57cec5SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
18740b57cec5SDimitry Andric     eltType = arrayType->getElementType();
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric     llvmArrayType =
18770b57cec5SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
18780b57cec5SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
18790b57cec5SDimitry Andric     assert((!llvmArrayType || arrayType) &&
18800b57cec5SDimitry Andric            "LLVM and Clang types are out-of-synch");
18810b57cec5SDimitry Andric   }
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric   if (arrayType) {
18840b57cec5SDimitry Andric     // From this point onwards, the Clang array type has been emitted
18850b57cec5SDimitry Andric     // as some other type (probably a packed struct). Compute the array
18860b57cec5SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
18870b57cec5SDimitry Andric     while (arrayType) {
18880b57cec5SDimitry Andric       countFromCLAs *=
18890b57cec5SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
18900b57cec5SDimitry Andric       eltType = arrayType->getElementType();
18910b57cec5SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
18920b57cec5SDimitry Andric     }
18930b57cec5SDimitry Andric 
18940b57cec5SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
18950b57cec5SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
18960b57cec5SDimitry Andric   } else {
18970b57cec5SDimitry Andric     // Create the actual GEP.
18980b57cec5SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
18990b57cec5SDimitry Andric                                              gepIndices, "array.begin"),
19000b57cec5SDimitry Andric                    addr.getAlignment());
19010b57cec5SDimitry Andric   }
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric   baseType = eltType;
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric   llvm::Value *numElements
19060b57cec5SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric   // If we had any VLA dimensions, factor them in.
19090b57cec5SDimitry Andric   if (numVLAElements)
19100b57cec5SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   return numElements;
19130b57cec5SDimitry Andric }
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
19160b57cec5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
19170b57cec5SDimitry Andric   assert(vla && "type was not a variable array type!");
19180b57cec5SDimitry Andric   return getVLASize(vla);
19190b57cec5SDimitry Andric }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
19220b57cec5SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
19230b57cec5SDimitry Andric   // The number of elements so far; always size_t.
19240b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric   QualType elementType;
19270b57cec5SDimitry Andric   do {
19280b57cec5SDimitry Andric     elementType = type->getElementType();
19290b57cec5SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
19300b57cec5SDimitry Andric     assert(vlaSize && "no size for VLA!");
19310b57cec5SDimitry Andric     assert(vlaSize->getType() == SizeTy);
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric     if (!numElements) {
19340b57cec5SDimitry Andric       numElements = vlaSize;
19350b57cec5SDimitry Andric     } else {
19360b57cec5SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
19370b57cec5SDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
19380b57cec5SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
19390b57cec5SDimitry Andric     }
19400b57cec5SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric   return { numElements, elementType };
19430b57cec5SDimitry Andric }
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
19460b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(QualType type) {
19470b57cec5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
19480b57cec5SDimitry Andric   assert(vla && "type was not a variable array type!");
19490b57cec5SDimitry Andric   return getVLAElements1D(vla);
19500b57cec5SDimitry Andric }
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
19530b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
19540b57cec5SDimitry Andric   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
19550b57cec5SDimitry Andric   assert(VlaSize && "no size for VLA!");
19560b57cec5SDimitry Andric   assert(VlaSize->getType() == SizeTy);
19570b57cec5SDimitry Andric   return { VlaSize, Vla->getElementType() };
19580b57cec5SDimitry Andric }
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
19610b57cec5SDimitry Andric   assert(type->isVariablyModifiedType() &&
19620b57cec5SDimitry Andric          "Must pass variably modified type to EmitVLASizes!");
19630b57cec5SDimitry Andric 
19640b57cec5SDimitry Andric   EnsureInsertPoint();
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric   // We're going to walk down into the type and look for VLA
19670b57cec5SDimitry Andric   // expressions.
19680b57cec5SDimitry Andric   do {
19690b57cec5SDimitry Andric     assert(type->isVariablyModifiedType());
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric     const Type *ty = type.getTypePtr();
19720b57cec5SDimitry Andric     switch (ty->getTypeClass()) {
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric #define TYPE(Class, Base)
19750b57cec5SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
19760b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
19770b57cec5SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
19780b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1979a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
19800b57cec5SDimitry Andric       llvm_unreachable("unexpected dependent type!");
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric     // These types are never variably-modified.
19830b57cec5SDimitry Andric     case Type::Builtin:
19840b57cec5SDimitry Andric     case Type::Complex:
19850b57cec5SDimitry Andric     case Type::Vector:
19860b57cec5SDimitry Andric     case Type::ExtVector:
19875ffd83dbSDimitry Andric     case Type::ConstantMatrix:
19880b57cec5SDimitry Andric     case Type::Record:
19890b57cec5SDimitry Andric     case Type::Enum:
19900b57cec5SDimitry Andric     case Type::Elaborated:
19910b57cec5SDimitry Andric     case Type::TemplateSpecialization:
19920b57cec5SDimitry Andric     case Type::ObjCTypeParam:
19930b57cec5SDimitry Andric     case Type::ObjCObject:
19940b57cec5SDimitry Andric     case Type::ObjCInterface:
19950b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
19965ffd83dbSDimitry Andric     case Type::ExtInt:
19970b57cec5SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric     case Type::Adjusted:
20000b57cec5SDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
20010b57cec5SDimitry Andric       break;
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric     case Type::Decayed:
20040b57cec5SDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
20050b57cec5SDimitry Andric       break;
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric     case Type::Pointer:
20080b57cec5SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
20090b57cec5SDimitry Andric       break;
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric     case Type::BlockPointer:
20120b57cec5SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
20130b57cec5SDimitry Andric       break;
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric     case Type::LValueReference:
20160b57cec5SDimitry Andric     case Type::RValueReference:
20170b57cec5SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
20180b57cec5SDimitry Andric       break;
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric     case Type::MemberPointer:
20210b57cec5SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
20220b57cec5SDimitry Andric       break;
20230b57cec5SDimitry Andric 
20240b57cec5SDimitry Andric     case Type::ConstantArray:
20250b57cec5SDimitry Andric     case Type::IncompleteArray:
20260b57cec5SDimitry Andric       // Losing element qualification here is fine.
20270b57cec5SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
20280b57cec5SDimitry Andric       break;
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric     case Type::VariableArray: {
20310b57cec5SDimitry Andric       // Losing element qualification here is fine.
20320b57cec5SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric       // Unknown size indication requires no size computation.
20350b57cec5SDimitry Andric       // Otherwise, evaluate and record it.
20360b57cec5SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
20370b57cec5SDimitry Andric         // It's possible that we might have emitted this already,
20380b57cec5SDimitry Andric         // e.g. with a typedef and a pointer to it.
20390b57cec5SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
20400b57cec5SDimitry Andric         if (!entry) {
20410b57cec5SDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric           // C11 6.7.6.2p5:
20440b57cec5SDimitry Andric           //   If the size is an expression that is not an integer constant
20450b57cec5SDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
20460b57cec5SDimitry Andric           //   greater than zero.
20470b57cec5SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
20480b57cec5SDimitry Andric               size->getType()->isSignedIntegerType()) {
20490b57cec5SDimitry Andric             SanitizerScope SanScope(this);
20500b57cec5SDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
20510b57cec5SDimitry Andric             llvm::Constant *StaticArgs[] = {
20520b57cec5SDimitry Andric                 EmitCheckSourceLocation(size->getBeginLoc()),
20530b57cec5SDimitry Andric                 EmitCheckTypeDescriptor(size->getType())};
20540b57cec5SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
20550b57cec5SDimitry Andric                                      SanitizerKind::VLABound),
20560b57cec5SDimitry Andric                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
20570b57cec5SDimitry Andric           }
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric           // Always zexting here would be wrong if it weren't
20600b57cec5SDimitry Andric           // undefined behavior to have a negative bound.
20610b57cec5SDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
20620b57cec5SDimitry Andric         }
20630b57cec5SDimitry Andric       }
20640b57cec5SDimitry Andric       type = vat->getElementType();
20650b57cec5SDimitry Andric       break;
20660b57cec5SDimitry Andric     }
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric     case Type::FunctionProto:
20690b57cec5SDimitry Andric     case Type::FunctionNoProto:
20700b57cec5SDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
20710b57cec5SDimitry Andric       break;
20720b57cec5SDimitry Andric 
20730b57cec5SDimitry Andric     case Type::Paren:
20740b57cec5SDimitry Andric     case Type::TypeOf:
20750b57cec5SDimitry Andric     case Type::UnaryTransform:
20760b57cec5SDimitry Andric     case Type::Attributed:
20770b57cec5SDimitry Andric     case Type::SubstTemplateTypeParm:
20780b57cec5SDimitry Andric     case Type::PackExpansion:
20790b57cec5SDimitry Andric     case Type::MacroQualified:
20800b57cec5SDimitry Andric       // Keep walking after single level desugaring.
20810b57cec5SDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
20820b57cec5SDimitry Andric       break;
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric     case Type::Typedef:
20850b57cec5SDimitry Andric     case Type::Decltype:
20860b57cec5SDimitry Andric     case Type::Auto:
20870b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
20880b57cec5SDimitry Andric       // Stop walking: nothing to do.
20890b57cec5SDimitry Andric       return;
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric     case Type::TypeOfExpr:
20920b57cec5SDimitry Andric       // Stop walking: emit typeof expression.
20930b57cec5SDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
20940b57cec5SDimitry Andric       return;
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric     case Type::Atomic:
20970b57cec5SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
20980b57cec5SDimitry Andric       break;
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric     case Type::Pipe:
21010b57cec5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
21020b57cec5SDimitry Andric       break;
21030b57cec5SDimitry Andric     }
21040b57cec5SDimitry Andric   } while (type->isVariablyModifiedType());
21050b57cec5SDimitry Andric }
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
21080b57cec5SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
21090b57cec5SDimitry Andric     return EmitPointerWithAlignment(E);
2110480093f4SDimitry Andric   return EmitLValue(E).getAddress(*this);
21110b57cec5SDimitry Andric }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2114480093f4SDimitry Andric   return EmitLValue(E).getAddress(*this);
21150b57cec5SDimitry Andric }
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
21180b57cec5SDimitry Andric                                               const APValue &Init) {
21190b57cec5SDimitry Andric   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
21200b57cec5SDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
2121480093f4SDimitry Andric     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
21220b57cec5SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
21230b57cec5SDimitry Andric }
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric CodeGenFunction::PeepholeProtection
21260b57cec5SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
21270b57cec5SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
21280b57cec5SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
21290b57cec5SDimitry Andric   // extend this protection.
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
21320b57cec5SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
21330b57cec5SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric   // Just make an extra bitcast.
21360b57cec5SDimitry Andric   assert(HaveInsertPoint());
21370b57cec5SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
21380b57cec5SDimitry Andric                                                   Builder.GetInsertBlock());
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric   PeepholeProtection protection;
21410b57cec5SDimitry Andric   protection.Inst = inst;
21420b57cec5SDimitry Andric   return protection;
21430b57cec5SDimitry Andric }
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
21460b57cec5SDimitry Andric   if (!protection.Inst) return;
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
21490b57cec5SDimitry Andric   protection.Inst->eraseFromParent();
21500b57cec5SDimitry Andric }
21510b57cec5SDimitry Andric 
21525ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
21530b57cec5SDimitry Andric                                               QualType Ty, SourceLocation Loc,
21540b57cec5SDimitry Andric                                               SourceLocation AssumptionLoc,
21550b57cec5SDimitry Andric                                               llvm::Value *Alignment,
21560b57cec5SDimitry Andric                                               llvm::Value *OffsetValue) {
21575ffd83dbSDimitry Andric   if (Alignment->getType() != IntPtrTy)
21585ffd83dbSDimitry Andric     Alignment =
21595ffd83dbSDimitry Andric         Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
21605ffd83dbSDimitry Andric   if (OffsetValue && OffsetValue->getType() != IntPtrTy)
21615ffd83dbSDimitry Andric     OffsetValue =
21625ffd83dbSDimitry Andric         Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
21635ffd83dbSDimitry Andric   llvm::Value *TheCheck = nullptr;
21640b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment)) {
21655ffd83dbSDimitry Andric     llvm::Value *PtrIntValue =
21665ffd83dbSDimitry Andric         Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
21675ffd83dbSDimitry Andric 
21685ffd83dbSDimitry Andric     if (OffsetValue) {
21695ffd83dbSDimitry Andric       bool IsOffsetZero = false;
21705ffd83dbSDimitry Andric       if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
21715ffd83dbSDimitry Andric         IsOffsetZero = CI->isZero();
21725ffd83dbSDimitry Andric 
21735ffd83dbSDimitry Andric       if (!IsOffsetZero)
21745ffd83dbSDimitry Andric         PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
21750b57cec5SDimitry Andric     }
21760b57cec5SDimitry Andric 
21775ffd83dbSDimitry Andric     llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
21785ffd83dbSDimitry Andric     llvm::Value *Mask =
21795ffd83dbSDimitry Andric         Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
21805ffd83dbSDimitry Andric     llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
21815ffd83dbSDimitry Andric     TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
21825ffd83dbSDimitry Andric   }
21835ffd83dbSDimitry Andric   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
21845ffd83dbSDimitry Andric       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
21855ffd83dbSDimitry Andric 
21865ffd83dbSDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
21875ffd83dbSDimitry Andric     return;
21885ffd83dbSDimitry Andric   emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
21895ffd83dbSDimitry Andric                                OffsetValue, TheCheck, Assumption);
21905ffd83dbSDimitry Andric }
21915ffd83dbSDimitry Andric 
21925ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
21930b57cec5SDimitry Andric                                               const Expr *E,
21940b57cec5SDimitry Andric                                               SourceLocation AssumptionLoc,
2195a7dea167SDimitry Andric                                               llvm::Value *Alignment,
21960b57cec5SDimitry Andric                                               llvm::Value *OffsetValue) {
21970b57cec5SDimitry Andric   if (auto *CE = dyn_cast<CastExpr>(E))
21980b57cec5SDimitry Andric     E = CE->getSubExprAsWritten();
21990b57cec5SDimitry Andric   QualType Ty = E->getType();
22000b57cec5SDimitry Andric   SourceLocation Loc = E->getExprLoc();
22010b57cec5SDimitry Andric 
22025ffd83dbSDimitry Andric   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
22030b57cec5SDimitry Andric                           OffsetValue);
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
22070b57cec5SDimitry Andric                                                  llvm::Value *AnnotatedVal,
22080b57cec5SDimitry Andric                                                  StringRef AnnotationStr,
22090b57cec5SDimitry Andric                                                  SourceLocation Location) {
22100b57cec5SDimitry Andric   llvm::Value *Args[4] = {
22110b57cec5SDimitry Andric     AnnotatedVal,
22120b57cec5SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
22130b57cec5SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
22140b57cec5SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
22150b57cec5SDimitry Andric   };
22160b57cec5SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
22200b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
22210b57cec5SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
22220b57cec5SDimitry Andric   // llvm-gcc was doing.
22230b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
22240b57cec5SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
22250b57cec5SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
22260b57cec5SDimitry Andric                        I->getAnnotation(), D->getLocation());
22270b57cec5SDimitry Andric }
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
22300b57cec5SDimitry Andric                                               Address Addr) {
22310b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
22320b57cec5SDimitry Andric   llvm::Value *V = Addr.getPointer();
22330b57cec5SDimitry Andric   llvm::Type *VTy = V->getType();
22340b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
22350b57cec5SDimitry Andric                                     CGM.Int8PtrTy);
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
22380b57cec5SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
22390b57cec5SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
22400b57cec5SDimitry Andric     // itself.
22410b57cec5SDimitry Andric     if (VTy != CGM.Int8PtrTy)
22420b57cec5SDimitry Andric       V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
22430b57cec5SDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
22440b57cec5SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
22450b57cec5SDimitry Andric   }
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric   return Address(V, Addr.getAlignment());
22480b57cec5SDimitry Andric }
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
22530b57cec5SDimitry Andric     : CGF(CGF) {
22540b57cec5SDimitry Andric   assert(!CGF->IsSanitizerScope);
22550b57cec5SDimitry Andric   CGF->IsSanitizerScope = true;
22560b57cec5SDimitry Andric }
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
22590b57cec5SDimitry Andric   CGF->IsSanitizerScope = false;
22600b57cec5SDimitry Andric }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
22630b57cec5SDimitry Andric                                    const llvm::Twine &Name,
22640b57cec5SDimitry Andric                                    llvm::BasicBlock *BB,
22650b57cec5SDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
22660b57cec5SDimitry Andric   LoopStack.InsertHelper(I);
22670b57cec5SDimitry Andric   if (IsSanitizerScope)
22680b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
22690b57cec5SDimitry Andric }
22700b57cec5SDimitry Andric 
22710b57cec5SDimitry Andric void CGBuilderInserter::InsertHelper(
22720b57cec5SDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
22730b57cec5SDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
22740b57cec5SDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
22750b57cec5SDimitry Andric   if (CGF)
22760b57cec5SDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
22770b57cec5SDimitry Andric }
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
22800b57cec5SDimitry Andric                                 CodeGenModule &CGM, const FunctionDecl *FD,
22810b57cec5SDimitry Andric                                 std::string &FirstMissing) {
22820b57cec5SDimitry Andric   // If there aren't any required features listed then go ahead and return.
22830b57cec5SDimitry Andric   if (ReqFeatures.empty())
22840b57cec5SDimitry Andric     return false;
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric   // Now build up the set of caller features and verify that all the required
22870b57cec5SDimitry Andric   // features are there.
22880b57cec5SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
2289480093f4SDimitry Andric   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   // If we have at least one of the features in the feature list return
22920b57cec5SDimitry Andric   // true, otherwise return false.
22930b57cec5SDimitry Andric   return std::all_of(
22940b57cec5SDimitry Andric       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
22950b57cec5SDimitry Andric         SmallVector<StringRef, 1> OrFeatures;
22960b57cec5SDimitry Andric         Feature.split(OrFeatures, '|');
22970b57cec5SDimitry Andric         return llvm::any_of(OrFeatures, [&](StringRef Feature) {
22980b57cec5SDimitry Andric           if (!CallerFeatureMap.lookup(Feature)) {
22990b57cec5SDimitry Andric             FirstMissing = Feature.str();
23000b57cec5SDimitry Andric             return false;
23010b57cec5SDimitry Andric           }
23020b57cec5SDimitry Andric           return true;
23030b57cec5SDimitry Andric         });
23040b57cec5SDimitry Andric       });
23050b57cec5SDimitry Andric }
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the
23080b57cec5SDimitry Andric // called function.
23090b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
23100b57cec5SDimitry Andric                                           const FunctionDecl *TargetDecl) {
23110b57cec5SDimitry Andric   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
23120b57cec5SDimitry Andric }
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the
23150b57cec5SDimitry Andric // called function.
23160b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
23170b57cec5SDimitry Andric                                           const FunctionDecl *TargetDecl) {
23180b57cec5SDimitry Andric   // Early exit if this is an indirect call.
23190b57cec5SDimitry Andric   if (!TargetDecl)
23200b57cec5SDimitry Andric     return;
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
23230b57cec5SDimitry Andric   // we can't check the target features anyhow.
2324a7dea167SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
23250b57cec5SDimitry Andric   if (!FD)
23260b57cec5SDimitry Andric     return;
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
23290b57cec5SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
23300b57cec5SDimitry Andric   // listed cpu and any listed features.
23310b57cec5SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
23320b57cec5SDimitry Andric   std::string MissingFeature;
23330b57cec5SDimitry Andric   if (BuiltinID) {
23340b57cec5SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
23350b57cec5SDimitry Andric     const char *FeatureList =
23360b57cec5SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
23370b57cec5SDimitry Andric     // Return if the builtin doesn't have any required features.
23380b57cec5SDimitry Andric     if (!FeatureList || StringRef(FeatureList) == "")
23390b57cec5SDimitry Andric       return;
23400b57cec5SDimitry Andric     StringRef(FeatureList).split(ReqFeatures, ',');
23410b57cec5SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
23420b57cec5SDimitry Andric       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
23430b57cec5SDimitry Andric           << TargetDecl->getDeclName()
23440b57cec5SDimitry Andric           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
23450b57cec5SDimitry Andric 
2346480093f4SDimitry Andric   } else if (!TargetDecl->isMultiVersion() &&
2347480093f4SDimitry Andric              TargetDecl->hasAttr<TargetAttr>()) {
23480b57cec5SDimitry Andric     // Get the required features for the callee.
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2351480093f4SDimitry Andric     ParsedTargetAttr ParsedAttr =
2352480093f4SDimitry Andric         CGM.getContext().filterFunctionTargetAttrs(TD);
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
23550b57cec5SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
2356*c3ca3130SDimitry Andric     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric     for (const auto &F : ParsedAttr.Features) {
23590b57cec5SDimitry Andric       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
23600b57cec5SDimitry Andric         ReqFeatures.push_back(StringRef(F).substr(1));
23610b57cec5SDimitry Andric     }
23620b57cec5SDimitry Andric 
23630b57cec5SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
23640b57cec5SDimitry Andric       // Only positive features are "required".
23650b57cec5SDimitry Andric       if (F.getValue())
23660b57cec5SDimitry Andric         ReqFeatures.push_back(F.getKey());
23670b57cec5SDimitry Andric     }
23680b57cec5SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
23690b57cec5SDimitry Andric       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
23700b57cec5SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
23710b57cec5SDimitry Andric   }
23720b57cec5SDimitry Andric }
23730b57cec5SDimitry Andric 
23740b57cec5SDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
23750b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
23760b57cec5SDimitry Andric     return;
23770b57cec5SDimitry Andric 
23780b57cec5SDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
23790b57cec5SDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
23800b57cec5SDimitry Andric   CGM.getSanStats().create(IRB, SSK);
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric llvm::Value *
23840b57cec5SDimitry Andric CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
23850b57cec5SDimitry Andric   llvm::Value *Condition = nullptr;
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
23880b57cec5SDimitry Andric     Condition = EmitX86CpuIs(RO.Conditions.Architecture);
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   if (!RO.Conditions.Features.empty()) {
23910b57cec5SDimitry Andric     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
23920b57cec5SDimitry Andric     Condition =
23930b57cec5SDimitry Andric         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
23940b57cec5SDimitry Andric   }
23950b57cec5SDimitry Andric   return Condition;
23960b57cec5SDimitry Andric }
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
23990b57cec5SDimitry Andric                                              llvm::Function *Resolver,
24000b57cec5SDimitry Andric                                              CGBuilderTy &Builder,
24010b57cec5SDimitry Andric                                              llvm::Function *FuncToReturn,
24020b57cec5SDimitry Andric                                              bool SupportsIFunc) {
24030b57cec5SDimitry Andric   if (SupportsIFunc) {
24040b57cec5SDimitry Andric     Builder.CreateRet(FuncToReturn);
24050b57cec5SDimitry Andric     return;
24060b57cec5SDimitry Andric   }
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric   llvm::SmallVector<llvm::Value *, 10> Args;
24090b57cec5SDimitry Andric   llvm::for_each(Resolver->args(),
24100b57cec5SDimitry Andric                  [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
24130b57cec5SDimitry Andric   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric   if (Resolver->getReturnType()->isVoidTy())
24160b57cec5SDimitry Andric     Builder.CreateRetVoid();
24170b57cec5SDimitry Andric   else
24180b57cec5SDimitry Andric     Builder.CreateRet(Result);
24190b57cec5SDimitry Andric }
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric void CodeGenFunction::EmitMultiVersionResolver(
24220b57cec5SDimitry Andric     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2423480093f4SDimitry Andric   assert(getContext().getTargetInfo().getTriple().isX86() &&
24240b57cec5SDimitry Andric          "Only implemented for x86 targets");
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
24270b57cec5SDimitry Andric 
24280b57cec5SDimitry Andric   // Main function's basic block.
24290b57cec5SDimitry Andric   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
24300b57cec5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
24310b57cec5SDimitry Andric   EmitX86CpuInit();
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric   for (const MultiVersionResolverOption &RO : Options) {
24340b57cec5SDimitry Andric     Builder.SetInsertPoint(CurBlock);
24350b57cec5SDimitry Andric     llvm::Value *Condition = FormResolverCondition(RO);
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric     // The 'default' or 'generic' case.
24380b57cec5SDimitry Andric     if (!Condition) {
24390b57cec5SDimitry Andric       assert(&RO == Options.end() - 1 &&
24400b57cec5SDimitry Andric              "Default or Generic case must be last");
24410b57cec5SDimitry Andric       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
24420b57cec5SDimitry Andric                                        SupportsIFunc);
24430b57cec5SDimitry Andric       return;
24440b57cec5SDimitry Andric     }
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
24470b57cec5SDimitry Andric     CGBuilderTy RetBuilder(*this, RetBlock);
24480b57cec5SDimitry Andric     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
24490b57cec5SDimitry Andric                                      SupportsIFunc);
24500b57cec5SDimitry Andric     CurBlock = createBasicBlock("resolver_else", Resolver);
24510b57cec5SDimitry Andric     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
24520b57cec5SDimitry Andric   }
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric   // If no generic/default, emit an unreachable.
24550b57cec5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
24560b57cec5SDimitry Andric   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
24570b57cec5SDimitry Andric   TrapCall->setDoesNotReturn();
24580b57cec5SDimitry Andric   TrapCall->setDoesNotThrow();
24590b57cec5SDimitry Andric   Builder.CreateUnreachable();
24600b57cec5SDimitry Andric   Builder.ClearInsertionPoint();
24610b57cec5SDimitry Andric }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric // Loc - where the diagnostic will point, where in the source code this
24640b57cec5SDimitry Andric //  alignment has failed.
24650b57cec5SDimitry Andric // SecondaryLoc - if present (will be present if sufficiently different from
24660b57cec5SDimitry Andric //  Loc), the diagnostic will additionally point a "Note:" to this location.
24670b57cec5SDimitry Andric //  It should be the location where the __attribute__((assume_aligned))
24680b57cec5SDimitry Andric //  was written e.g.
24695ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumptionCheck(
24700b57cec5SDimitry Andric     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
24710b57cec5SDimitry Andric     SourceLocation SecondaryLoc, llvm::Value *Alignment,
24720b57cec5SDimitry Andric     llvm::Value *OffsetValue, llvm::Value *TheCheck,
24730b57cec5SDimitry Andric     llvm::Instruction *Assumption) {
24740b57cec5SDimitry Andric   assert(Assumption && isa<llvm::CallInst>(Assumption) &&
24755ffd83dbSDimitry Andric          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
24760b57cec5SDimitry Andric              llvm::Intrinsic::getDeclaration(
24770b57cec5SDimitry Andric                  Builder.GetInsertBlock()->getParent()->getParent(),
24780b57cec5SDimitry Andric                  llvm::Intrinsic::assume) &&
24790b57cec5SDimitry Andric          "Assumption should be a call to llvm.assume().");
24800b57cec5SDimitry Andric   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
24810b57cec5SDimitry Andric          "Assumption should be the last instruction of the basic block, "
24820b57cec5SDimitry Andric          "since the basic block is still being generated.");
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
24850b57cec5SDimitry Andric     return;
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
24880b57cec5SDimitry Andric   // defined.
24890b57cec5SDimitry Andric   if (Ty->getPointeeType().isVolatileQualified())
24900b57cec5SDimitry Andric     return;
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric   // We need to temorairly remove the assumption so we can insert the
24930b57cec5SDimitry Andric   // sanitizer check before it, else the check will be dropped by optimizations.
24940b57cec5SDimitry Andric   Assumption->removeFromParent();
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric   {
24970b57cec5SDimitry Andric     SanitizerScope SanScope(this);
24980b57cec5SDimitry Andric 
24990b57cec5SDimitry Andric     if (!OffsetValue)
25000b57cec5SDimitry Andric       OffsetValue = Builder.getInt1(0); // no offset.
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
25030b57cec5SDimitry Andric                                     EmitCheckSourceLocation(SecondaryLoc),
25040b57cec5SDimitry Andric                                     EmitCheckTypeDescriptor(Ty)};
25050b57cec5SDimitry Andric     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
25060b57cec5SDimitry Andric                                   EmitCheckValue(Alignment),
25070b57cec5SDimitry Andric                                   EmitCheckValue(OffsetValue)};
25080b57cec5SDimitry Andric     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
25090b57cec5SDimitry Andric               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
25100b57cec5SDimitry Andric   }
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   // We are now in the (new, empty) "cont" basic block.
25130b57cec5SDimitry Andric   // Reintroduce the assumption.
25140b57cec5SDimitry Andric   Builder.Insert(Assumption);
25150b57cec5SDimitry Andric   // FIXME: Assumption still has it's original basic block as it's Parent.
25160b57cec5SDimitry Andric }
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
25190b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
25200b57cec5SDimitry Andric     return DI->SourceLocToDebugLoc(Location);
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric   return llvm::DebugLoc();
25230b57cec5SDimitry Andric }
2524