xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 62987288060ff68c817b7056815aa9fb8ba8ecd7)
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"
19bdd1243dSDimitry Andric #include "CGHLSLRuntime.h"
200b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
210b57cec5SDimitry Andric #include "CodeGenModule.h"
220b57cec5SDimitry Andric #include "CodeGenPGO.h"
230b57cec5SDimitry Andric #include "TargetInfo.h"
240b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
250b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
26480093f4SDimitry Andric #include "clang/AST/Attr.h"
270b57cec5SDimitry Andric #include "clang/AST/Decl.h"
280b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
29e8d8bef9SDimitry Andric #include "clang/AST/Expr.h"
300b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
310b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h"
320b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
330b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
340fca6ea1SDimitry Andric #include "clang/Basic/TargetBuiltins.h"
350b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
360b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
370b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
38e8d8bef9SDimitry Andric #include "llvm/ADT/ArrayRef.h"
395ffd83dbSDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
400b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
410b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
42480093f4SDimitry Andric #include "llvm/IR/FPEnv.h"
43480093f4SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
440b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
450b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
460b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
47e8d8bef9SDimitry Andric #include "llvm/Support/CRC.h"
4806c3fb27SDimitry Andric #include "llvm/Support/xxhash.h"
49e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
500b57cec5SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
51bdd1243dSDimitry Andric #include <optional>
52349cc55cSDimitry Andric 
530b57cec5SDimitry Andric using namespace clang;
540b57cec5SDimitry Andric using namespace CodeGen;
550b57cec5SDimitry Andric 
560fca6ea1SDimitry Andric namespace llvm {
570fca6ea1SDimitry Andric extern cl::opt<bool> EnableSingleByteCoverage;
580fca6ea1SDimitry Andric } // namespace llvm
590fca6ea1SDimitry Andric 
600b57cec5SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
610b57cec5SDimitry Andric /// markers.
620b57cec5SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
630b57cec5SDimitry Andric                                       const LangOptions &LangOpts) {
640b57cec5SDimitry Andric   if (CGOpts.DisableLifetimeMarkers)
650b57cec5SDimitry Andric     return false;
660b57cec5SDimitry Andric 
67a7dea167SDimitry Andric   // Sanitizers may use markers.
68a7dea167SDimitry Andric   if (CGOpts.SanitizeAddressUseAfterScope ||
69a7dea167SDimitry Andric       LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
70a7dea167SDimitry Andric       LangOpts.Sanitize.has(SanitizerKind::Memory))
710b57cec5SDimitry Andric     return true;
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   // For now, only in optimized builds.
740b57cec5SDimitry Andric   return CGOpts.OptimizationLevel != 0;
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
780b57cec5SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
790b57cec5SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
800b57cec5SDimitry Andric               CGBuilderInserterTy(this)),
815ffd83dbSDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
825ffd83dbSDimitry Andric       DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
835ffd83dbSDimitry Andric       ShouldEmitLifetimeMarkers(
845ffd83dbSDimitry Andric           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
850b57cec5SDimitry Andric   if (!suppressNewContext)
860b57cec5SDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
87fe6060f1SDimitry Andric   EHStack.setCGF(this);
880b57cec5SDimitry Andric 
895ffd83dbSDimitry Andric   SetFastMathFlags(CurFPFeatures);
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric CodeGenFunction::~CodeGenFunction() {
930b57cec5SDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
940fca6ea1SDimitry Andric   assert(DeferredDeactivationCleanupStack.empty() &&
950fca6ea1SDimitry Andric          "missed to deactivate a cleanup");
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric   if (getLangOpts().OpenMP && CurFn)
980b57cec5SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
990b57cec5SDimitry Andric 
1005ffd83dbSDimitry Andric   // If we have an OpenMPIRBuilder we want to finalize functions (incl.
1015ffd83dbSDimitry Andric   // outlining etc) at some point. Doing it once the function codegen is done
1025ffd83dbSDimitry Andric   // seems to be a reasonable spot. We do it here, as opposed to the deletion
1035ffd83dbSDimitry Andric   // time of the CodeGenModule, because we have to ensure the IR has not yet
1045ffd83dbSDimitry Andric   // been "emitted" to the outside, thus, modifications are still sensible.
105fe6060f1SDimitry Andric   if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
106fe6060f1SDimitry Andric     CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
107480093f4SDimitry Andric }
108480093f4SDimitry Andric 
109480093f4SDimitry Andric // Map the LangOption for exception behavior into
110480093f4SDimitry Andric // the corresponding enum in the IR.
1115ffd83dbSDimitry Andric llvm::fp::ExceptionBehavior
1125ffd83dbSDimitry Andric clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
113480093f4SDimitry Andric 
114480093f4SDimitry Andric   switch (Kind) {
115480093f4SDimitry Andric   case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
116480093f4SDimitry Andric   case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
117480093f4SDimitry Andric   case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
11881ad6265SDimitry Andric   default:
119480093f4SDimitry Andric     llvm_unreachable("Unsupported FP Exception Behavior");
120480093f4SDimitry Andric   }
12181ad6265SDimitry Andric }
122480093f4SDimitry Andric 
1235ffd83dbSDimitry Andric void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
1245ffd83dbSDimitry Andric   llvm::FastMathFlags FMF;
1255ffd83dbSDimitry Andric   FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
1265ffd83dbSDimitry Andric   FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
1275ffd83dbSDimitry Andric   FMF.setNoInfs(FPFeatures.getNoHonorInfs());
1285ffd83dbSDimitry Andric   FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
1295ffd83dbSDimitry Andric   FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
1305ffd83dbSDimitry Andric   FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
1315ffd83dbSDimitry Andric   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
1325ffd83dbSDimitry Andric   Builder.setFastMathFlags(FMF);
1330b57cec5SDimitry Andric }
1340b57cec5SDimitry Andric 
1355ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
136e8d8bef9SDimitry Andric                                                   const Expr *E)
137e8d8bef9SDimitry Andric     : CGF(CGF) {
138e8d8bef9SDimitry Andric   ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
139e8d8bef9SDimitry Andric }
140e8d8bef9SDimitry Andric 
141e8d8bef9SDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
1425ffd83dbSDimitry Andric                                                   FPOptions FPFeatures)
143e8d8bef9SDimitry Andric     : CGF(CGF) {
144e8d8bef9SDimitry Andric   ConstructorHelper(FPFeatures);
145e8d8bef9SDimitry Andric }
146e8d8bef9SDimitry Andric 
147e8d8bef9SDimitry Andric void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
148e8d8bef9SDimitry Andric   OldFPFeatures = CGF.CurFPFeatures;
1495ffd83dbSDimitry Andric   CGF.CurFPFeatures = FPFeatures;
1500b57cec5SDimitry Andric 
151e8d8bef9SDimitry Andric   OldExcept = CGF.Builder.getDefaultConstrainedExcept();
152e8d8bef9SDimitry Andric   OldRounding = CGF.Builder.getDefaultConstrainedRounding();
153e8d8bef9SDimitry Andric 
1545ffd83dbSDimitry Andric   if (OldFPFeatures == FPFeatures)
1555ffd83dbSDimitry Andric     return;
1565ffd83dbSDimitry Andric 
1575ffd83dbSDimitry Andric   FMFGuard.emplace(CGF.Builder);
1585ffd83dbSDimitry Andric 
15981ad6265SDimitry Andric   llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
1605ffd83dbSDimitry Andric   CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
1615ffd83dbSDimitry Andric   auto NewExceptionBehavior =
1625ffd83dbSDimitry Andric       ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
16381ad6265SDimitry Andric           FPFeatures.getExceptionMode()));
1645ffd83dbSDimitry Andric   CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
1655ffd83dbSDimitry Andric 
1665ffd83dbSDimitry Andric   CGF.SetFastMathFlags(FPFeatures);
1675ffd83dbSDimitry Andric 
1685ffd83dbSDimitry Andric   assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
1695ffd83dbSDimitry Andric           isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
1705ffd83dbSDimitry Andric           isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
1715ffd83dbSDimitry Andric           (NewExceptionBehavior == llvm::fp::ebIgnore &&
1725ffd83dbSDimitry Andric            NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
1735ffd83dbSDimitry Andric          "FPConstrained should be enabled on entire function");
1745ffd83dbSDimitry Andric 
1755ffd83dbSDimitry Andric   auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
1765ffd83dbSDimitry Andric     auto OldValue =
177fe6060f1SDimitry Andric         CGF.CurFn->getFnAttribute(Name).getValueAsBool();
1785ffd83dbSDimitry Andric     auto NewValue = OldValue & Value;
1795ffd83dbSDimitry Andric     if (OldValue != NewValue)
1805ffd83dbSDimitry Andric       CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
1815ffd83dbSDimitry Andric   };
1825ffd83dbSDimitry Andric   mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
1835ffd83dbSDimitry Andric   mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
1845ffd83dbSDimitry Andric   mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
185bdd1243dSDimitry Andric   mergeFnAttrValue(
186bdd1243dSDimitry Andric       "unsafe-fp-math",
187bdd1243dSDimitry Andric       FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() &&
188bdd1243dSDimitry Andric           FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() &&
189bdd1243dSDimitry Andric           FPFeatures.allowFPContractAcrossStatement());
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric 
1925ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
1935ffd83dbSDimitry Andric   CGF.CurFPFeatures = OldFPFeatures;
194e8d8bef9SDimitry Andric   CGF.Builder.setDefaultConstrainedExcept(OldExcept);
195e8d8bef9SDimitry Andric   CGF.Builder.setDefaultConstrainedRounding(OldRounding);
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980fca6ea1SDimitry Andric static LValue
1990fca6ea1SDimitry Andric makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType,
2000fca6ea1SDimitry Andric                            bool MightBeSigned, CodeGenFunction &CGF,
2010fca6ea1SDimitry Andric                            KnownNonNull_t IsKnownNonNull = NotKnownNonNull) {
2020b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
2030b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
2040fca6ea1SDimitry Andric   CharUnits Alignment =
2050fca6ea1SDimitry Andric       CGF.CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, ForPointeeType);
2060fca6ea1SDimitry Andric   Address Addr =
2070fca6ea1SDimitry Andric       MightBeSigned
2080fca6ea1SDimitry Andric           ? CGF.makeNaturalAddressForPointer(V, T, Alignment, false, nullptr,
2090fca6ea1SDimitry Andric                                              nullptr, IsKnownNonNull)
2100fca6ea1SDimitry Andric           : Address(V, CGF.ConvertTypeForMem(T), Alignment, IsKnownNonNull);
2110fca6ea1SDimitry Andric   return CGF.MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric 
2140fca6ea1SDimitry Andric LValue
2150fca6ea1SDimitry Andric CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T,
2160fca6ea1SDimitry Andric                                             KnownNonNull_t IsKnownNonNull) {
2170fca6ea1SDimitry Andric   return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
2180fca6ea1SDimitry Andric                                       /*MightBeSigned*/ true, *this,
2190fca6ea1SDimitry Andric                                       IsKnownNonNull);
2200fca6ea1SDimitry Andric }
2210fca6ea1SDimitry Andric 
2220b57cec5SDimitry Andric LValue
2230b57cec5SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
2240fca6ea1SDimitry Andric   return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
2250fca6ea1SDimitry Andric                                       /*MightBeSigned*/ true, *this);
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
2280fca6ea1SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignRawAddrLValue(llvm::Value *V,
2290fca6ea1SDimitry Andric                                                       QualType T) {
2300fca6ea1SDimitry Andric   return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ false,
2310fca6ea1SDimitry Andric                                       /*MightBeSigned*/ false, *this);
2320fca6ea1SDimitry Andric }
2330fca6ea1SDimitry Andric 
2340fca6ea1SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V,
2350fca6ea1SDimitry Andric                                                              QualType T) {
2360fca6ea1SDimitry Andric   return ::makeNaturalAlignAddrLValue(V, T, /*ForPointeeType*/ true,
2370fca6ea1SDimitry Andric                                       /*MightBeSigned*/ false, *this);
2380fca6ea1SDimitry Andric }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
2410b57cec5SDimitry Andric   return CGM.getTypes().ConvertTypeForMem(T);
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
2450b57cec5SDimitry Andric   return CGM.getTypes().ConvertType(T);
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
2480fca6ea1SDimitry Andric llvm::Type *CodeGenFunction::convertTypeForLoadStore(QualType ASTTy,
2490fca6ea1SDimitry Andric                                                      llvm::Type *LLVMTy) {
2500fca6ea1SDimitry Andric   return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
2510fca6ea1SDimitry Andric }
2520fca6ea1SDimitry Andric 
2530b57cec5SDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
2540b57cec5SDimitry Andric   type = type.getCanonicalType();
2550b57cec5SDimitry Andric   while (true) {
2560b57cec5SDimitry Andric     switch (type->getTypeClass()) {
2570b57cec5SDimitry Andric #define TYPE(name, parent)
2580b57cec5SDimitry Andric #define ABSTRACT_TYPE(name, parent)
2590b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
2600b57cec5SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
2610b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
262a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
2630b57cec5SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric     case Type::Auto:
2660b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
2670b57cec5SDimitry Andric       llvm_unreachable("undeduced type in IR-generation");
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric     // Various scalar types.
2700b57cec5SDimitry Andric     case Type::Builtin:
2710b57cec5SDimitry Andric     case Type::Pointer:
2720b57cec5SDimitry Andric     case Type::BlockPointer:
2730b57cec5SDimitry Andric     case Type::LValueReference:
2740b57cec5SDimitry Andric     case Type::RValueReference:
2750b57cec5SDimitry Andric     case Type::MemberPointer:
2760b57cec5SDimitry Andric     case Type::Vector:
2770b57cec5SDimitry Andric     case Type::ExtVector:
2785ffd83dbSDimitry Andric     case Type::ConstantMatrix:
2790b57cec5SDimitry Andric     case Type::FunctionProto:
2800b57cec5SDimitry Andric     case Type::FunctionNoProto:
2810b57cec5SDimitry Andric     case Type::Enum:
2820b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
2830b57cec5SDimitry Andric     case Type::Pipe:
2840eae32dcSDimitry Andric     case Type::BitInt:
2850b57cec5SDimitry Andric       return TEK_Scalar;
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric     // Complexes.
2880b57cec5SDimitry Andric     case Type::Complex:
2890b57cec5SDimitry Andric       return TEK_Complex;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     // Arrays, records, and Objective-C objects.
2920b57cec5SDimitry Andric     case Type::ConstantArray:
2930b57cec5SDimitry Andric     case Type::IncompleteArray:
2940b57cec5SDimitry Andric     case Type::VariableArray:
2950b57cec5SDimitry Andric     case Type::Record:
2960b57cec5SDimitry Andric     case Type::ObjCObject:
2970b57cec5SDimitry Andric     case Type::ObjCInterface:
2980fca6ea1SDimitry Andric     case Type::ArrayParameter:
2990b57cec5SDimitry Andric       return TEK_Aggregate;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric     // We operate on atomic values according to their underlying type.
3020b57cec5SDimitry Andric     case Type::Atomic:
3030b57cec5SDimitry Andric       type = cast<AtomicType>(type)->getValueType();
3040b57cec5SDimitry Andric       continue;
3050b57cec5SDimitry Andric     }
3060b57cec5SDimitry Andric     llvm_unreachable("unknown type kind!");
3070b57cec5SDimitry Andric   }
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
3110b57cec5SDimitry Andric   // For cleanliness, we try to avoid emitting the return block for
3120b57cec5SDimitry Andric   // simple cases.
3130b57cec5SDimitry Andric   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   if (CurBB) {
3160b57cec5SDimitry Andric     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric     // We have a valid insert point, reuse it if it is empty or there are no
3190b57cec5SDimitry Andric     // explicit jumps to the return block.
3200b57cec5SDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
3210b57cec5SDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
3220b57cec5SDimitry Andric       delete ReturnBlock.getBlock();
3230b57cec5SDimitry Andric       ReturnBlock = JumpDest();
3240b57cec5SDimitry Andric     } else
3250b57cec5SDimitry Andric       EmitBlock(ReturnBlock.getBlock());
3260b57cec5SDimitry Andric     return llvm::DebugLoc();
3270b57cec5SDimitry Andric   }
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   // Otherwise, if the return block is the target of a single direct
3300b57cec5SDimitry Andric   // branch then we can just put the code in that block instead. This
3310b57cec5SDimitry Andric   // cleans up functions which started with a unified return block.
3320b57cec5SDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
3330b57cec5SDimitry Andric     llvm::BranchInst *BI =
3340b57cec5SDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
3350b57cec5SDimitry Andric     if (BI && BI->isUnconditional() &&
3360b57cec5SDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
3370b57cec5SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
3380b57cec5SDimitry Andric       // later by the actual 'ret' instruction.
3390b57cec5SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
3400b57cec5SDimitry Andric       Builder.SetInsertPoint(BI->getParent());
3410b57cec5SDimitry Andric       BI->eraseFromParent();
3420b57cec5SDimitry Andric       delete ReturnBlock.getBlock();
3430b57cec5SDimitry Andric       ReturnBlock = JumpDest();
3440b57cec5SDimitry Andric       return Loc;
3450b57cec5SDimitry Andric     }
3460b57cec5SDimitry Andric   }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   // FIXME: We are at an unreachable point, there is no reason to emit the block
3490b57cec5SDimitry Andric   // unless it has uses. However, we still need a place to put the debug
3500b57cec5SDimitry Andric   // region.end for now.
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   EmitBlock(ReturnBlock.getBlock());
3530b57cec5SDimitry Andric   return llvm::DebugLoc();
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
3570b57cec5SDimitry Andric   if (!BB) return;
358bdd1243dSDimitry Andric   if (!BB->use_empty()) {
359bdd1243dSDimitry Andric     CGF.CurFn->insert(CGF.CurFn->end(), BB);
360bdd1243dSDimitry Andric     return;
361bdd1243dSDimitry Andric   }
3620b57cec5SDimitry Andric   delete BB;
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
3660b57cec5SDimitry Andric   assert(BreakContinueStack.empty() &&
3670b57cec5SDimitry Andric          "mismatched push/pop in break/continue stack!");
3680fca6ea1SDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() &&
3690fca6ea1SDimitry Andric          "mismatched push/pop of cleanups in EHStack!");
3700fca6ea1SDimitry Andric   assert(DeferredDeactivationCleanupStack.empty() &&
3710fca6ea1SDimitry Andric          "mismatched activate/deactivate of cleanups!");
3720fca6ea1SDimitry Andric 
3730fca6ea1SDimitry Andric   if (CGM.shouldEmitConvergenceTokens()) {
3740fca6ea1SDimitry Andric     ConvergenceTokenStack.pop_back();
3750fca6ea1SDimitry Andric     assert(ConvergenceTokenStack.empty() &&
3760fca6ea1SDimitry Andric            "mismatched push/pop in convergence stack!");
3770fca6ea1SDimitry Andric   }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
3800b57cec5SDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
3810b57cec5SDimitry Andric     && ReturnBlock.getBlock()->use_empty();
3820b57cec5SDimitry Andric   // Usually the return expression is evaluated before the cleanup
3830b57cec5SDimitry Andric   // code.  If the function contains only a simple return statement,
3840b57cec5SDimitry Andric   // such as a constant, the location before the cleanup code becomes
3850b57cec5SDimitry Andric   // the last useful breakpoint in the function, because the simple
3860b57cec5SDimitry Andric   // return expression will be evaluated after the cleanup code. To be
3870b57cec5SDimitry Andric   // safe, set the debug location for cleanup code to the location of
3880b57cec5SDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
3890b57cec5SDimitry Andric   // end of the function's lexical scope.
3900b57cec5SDimitry Andric   //
3910b57cec5SDimitry Andric   // If there are multiple branches to the return block, the branch
3920b57cec5SDimitry Andric   // instructions will get the location of the return statements and
3930b57cec5SDimitry Andric   // all will be fine.
3940b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
3950b57cec5SDimitry Andric     if (OnlySimpleReturnStmts)
3960b57cec5SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
3970b57cec5SDimitry Andric     else
3980b57cec5SDimitry Andric       DI->EmitLocation(Builder, EndLoc);
3990b57cec5SDimitry Andric   }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   // Pop any cleanups that might have been associated with the
4020b57cec5SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
4030b57cec5SDimitry Andric   // important to do this before we enter the return block or return
4040b57cec5SDimitry Andric   // edges will be *really* confused.
4050b57cec5SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
4060b57cec5SDimitry Andric   bool HasOnlyLifetimeMarkers =
4070b57cec5SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
4080b57cec5SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
409bdd1243dSDimitry Andric 
410bdd1243dSDimitry Andric   std::optional<ApplyDebugLocation> OAL;
4110b57cec5SDimitry Andric   if (HasCleanups) {
4120b57cec5SDimitry Andric     // Make sure the line table doesn't jump back into the body for
4130b57cec5SDimitry Andric     // the ret after it's been at EndLoc.
414480093f4SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo()) {
4150b57cec5SDimitry Andric       if (OnlySimpleReturnStmts)
4160b57cec5SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
417480093f4SDimitry Andric       else
418480093f4SDimitry Andric         // We may not have a valid end location. Try to apply it anyway, and
419480093f4SDimitry Andric         // fall back to an artificial location if needed.
420bdd1243dSDimitry Andric         OAL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
421480093f4SDimitry Andric     }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // Emit function epilog (to return).
4270b57cec5SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   if (ShouldInstrumentFunction()) {
4300b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
4310b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
4320b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
4330b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-exit-inlined",
4340b57cec5SDimitry Andric                        "__cyg_profile_func_exit");
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   // Emit debug descriptor for function end.
4380b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
4390b57cec5SDimitry Andric     DI->EmitFunctionEnd(Builder, CurFn);
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
4420b57cec5SDimitry Andric   // rather than that of the end of the function's scope '}'.
4430b57cec5SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
4440b57cec5SDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
4450b57cec5SDimitry Andric   EmitEndEHSpec(CurCodeDecl);
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   assert(EHStack.empty() &&
4480b57cec5SDimitry Andric          "did not remove all scopes from cleanup stack!");
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   // If someone did an indirect goto, emit the indirect goto block at the end of
4510b57cec5SDimitry Andric   // the function.
4520b57cec5SDimitry Andric   if (IndirectBranch) {
4530b57cec5SDimitry Andric     EmitBlock(IndirectBranch->getParent());
4540b57cec5SDimitry Andric     Builder.ClearInsertionPoint();
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
4580b57cec5SDimitry Andric   // entry block.
4590b57cec5SDimitry Andric   if (!EscapedLocals.empty()) {
4600b57cec5SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
4610b57cec5SDimitry Andric     // no holes.
4620b57cec5SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
4630b57cec5SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
4640b57cec5SDimitry Andric     for (auto &Pair : EscapedLocals)
4650b57cec5SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
4660b57cec5SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
4670b57cec5SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
4680b57cec5SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
4690b57cec5SDimitry Andric   }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
4720b57cec5SDimitry Andric   llvm::Instruction *Ptr = AllocaInsertPt;
4730b57cec5SDimitry Andric   AllocaInsertPt = nullptr;
4740b57cec5SDimitry Andric   Ptr->eraseFromParent();
4750b57cec5SDimitry Andric 
476349cc55cSDimitry Andric   // PostAllocaInsertPt, if created, was lazily created when it was required,
477349cc55cSDimitry Andric   // remove it now since it was just created for our own convenience.
478349cc55cSDimitry Andric   if (PostAllocaInsertPt) {
479349cc55cSDimitry Andric     llvm::Instruction *PostPtr = PostAllocaInsertPt;
480349cc55cSDimitry Andric     PostAllocaInsertPt = nullptr;
481349cc55cSDimitry Andric     PostPtr->eraseFromParent();
482349cc55cSDimitry Andric   }
483349cc55cSDimitry Andric 
4840b57cec5SDimitry Andric   // If someone took the address of a label but never did an indirect goto, we
4850b57cec5SDimitry Andric   // made a zero entry PHI node, which is illegal, zap it now.
4860b57cec5SDimitry Andric   if (IndirectBranch) {
4870b57cec5SDimitry Andric     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
4880b57cec5SDimitry Andric     if (PN->getNumIncomingValues() == 0) {
4890b57cec5SDimitry Andric       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
4900b57cec5SDimitry Andric       PN->eraseFromParent();
4910b57cec5SDimitry Andric     }
4920b57cec5SDimitry Andric   }
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
4950b57cec5SDimitry Andric   EmitIfUsed(*this, TerminateLandingPad);
4960b57cec5SDimitry Andric   EmitIfUsed(*this, TerminateHandler);
4970b57cec5SDimitry Andric   EmitIfUsed(*this, UnreachableBlock);
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   for (const auto &FuncletAndParent : TerminateFunclets)
5000b57cec5SDimitry Andric     EmitIfUsed(*this, FuncletAndParent.second);
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().EmitDeclMetadata)
5030b57cec5SDimitry Andric     EmitDeclMetadata();
5040b57cec5SDimitry Andric 
505fe6060f1SDimitry Andric   for (const auto &R : DeferredReplacements) {
506fe6060f1SDimitry Andric     if (llvm::Value *Old = R.first) {
507fe6060f1SDimitry Andric       Old->replaceAllUsesWith(R.second);
508fe6060f1SDimitry Andric       cast<llvm::Instruction>(Old)->eraseFromParent();
5090b57cec5SDimitry Andric     }
510fe6060f1SDimitry Andric   }
511fe6060f1SDimitry Andric   DeferredReplacements.clear();
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
5140b57cec5SDimitry Andric   // PHIs if the current function is a coroutine. We don't do it for all
5150b57cec5SDimitry Andric   // functions as it may result in slight increase in numbers of instructions
5160b57cec5SDimitry Andric   // if compiled with no optimizations. We do it for coroutine as the lifetime
5170b57cec5SDimitry Andric   // of CleanupDestSlot alloca make correct coroutine frame building very
5180b57cec5SDimitry Andric   // difficult.
5190b57cec5SDimitry Andric   if (NormalCleanupDest.isValid() && isCoroutine()) {
5200b57cec5SDimitry Andric     llvm::DominatorTree DT(*CurFn);
5210b57cec5SDimitry Andric     llvm::PromoteMemToReg(
5220b57cec5SDimitry Andric         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
5230b57cec5SDimitry Andric     NormalCleanupDest = Address::invalid();
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   // Scan function arguments for vector width.
5270b57cec5SDimitry Andric   for (llvm::Argument &A : CurFn->args())
5280b57cec5SDimitry Andric     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
5295ffd83dbSDimitry Andric       LargestVectorWidth =
5305ffd83dbSDimitry Andric           std::max((uint64_t)LargestVectorWidth,
531bdd1243dSDimitry Andric                    VT->getPrimitiveSizeInBits().getKnownMinValue());
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   // Update vector width based on return type.
5340b57cec5SDimitry Andric   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
5355ffd83dbSDimitry Andric     LargestVectorWidth =
5365ffd83dbSDimitry Andric         std::max((uint64_t)LargestVectorWidth,
537bdd1243dSDimitry Andric                  VT->getPrimitiveSizeInBits().getKnownMinValue());
5380b57cec5SDimitry Andric 
53981ad6265SDimitry Andric   if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
54081ad6265SDimitry Andric     LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
54181ad6265SDimitry Andric 
5425f757f3fSDimitry Andric   // Add the min-legal-vector-width attribute. This contains the max width from:
5430b57cec5SDimitry Andric   // 1. min-vector-width attribute used in the source program.
5440b57cec5SDimitry Andric   // 2. Any builtins used that have a vector width specified.
5450b57cec5SDimitry Andric   // 3. Values passed in and out of inline assembly.
5460b57cec5SDimitry Andric   // 4. Width of vector arguments and return types for this function.
5475f757f3fSDimitry Andric   // 5. Width of vector arguments and return types for functions called by this
5480b57cec5SDimitry Andric   //    function.
549bdd1243dSDimitry Andric   if (getContext().getTargetInfo().getTriple().isX86())
550bdd1243dSDimitry Andric     CurFn->addFnAttr("min-legal-vector-width",
551bdd1243dSDimitry Andric                      llvm::utostr(LargestVectorWidth));
5520b57cec5SDimitry Andric 
553349cc55cSDimitry Andric   // Add vscale_range attribute if appropriate.
554bdd1243dSDimitry Andric   std::optional<std::pair<unsigned, unsigned>> VScaleRange =
555349cc55cSDimitry Andric       getContext().getTargetInfo().getVScaleRange(getLangOpts());
556349cc55cSDimitry Andric   if (VScaleRange) {
557349cc55cSDimitry Andric     CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
55881ad6265SDimitry Andric         getLLVMContext(), VScaleRange->first, VScaleRange->second));
559fe6060f1SDimitry Andric   }
560fe6060f1SDimitry Andric 
5610b57cec5SDimitry Andric   // If we generated an unreachable return block, delete it now.
5620b57cec5SDimitry Andric   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
5630b57cec5SDimitry Andric     Builder.ClearInsertionPoint();
5640b57cec5SDimitry Andric     ReturnBlock.getBlock()->eraseFromParent();
5650b57cec5SDimitry Andric   }
5660b57cec5SDimitry Andric   if (ReturnValue.isValid()) {
5670fca6ea1SDimitry Andric     auto *RetAlloca =
5680fca6ea1SDimitry Andric         dyn_cast<llvm::AllocaInst>(ReturnValue.emitRawPointer(*this));
5690b57cec5SDimitry Andric     if (RetAlloca && RetAlloca->use_empty()) {
5700b57cec5SDimitry Andric       RetAlloca->eraseFromParent();
5710b57cec5SDimitry Andric       ReturnValue = Address::invalid();
5720b57cec5SDimitry Andric     }
5730b57cec5SDimitry Andric   }
5740b57cec5SDimitry Andric }
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric /// ShouldInstrumentFunction - Return true if the current function should be
5770b57cec5SDimitry Andric /// instrumented with __cyg_profile_func_* calls
5780b57cec5SDimitry Andric bool CodeGenFunction::ShouldInstrumentFunction() {
5790b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
5800b57cec5SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
5810b57cec5SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
5820b57cec5SDimitry Andric     return false;
5830b57cec5SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
5840b57cec5SDimitry Andric     return false;
5850b57cec5SDimitry Andric   return true;
5860b57cec5SDimitry Andric }
5870b57cec5SDimitry Andric 
588349cc55cSDimitry Andric bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
589349cc55cSDimitry Andric   if (!CurFuncDecl)
590349cc55cSDimitry Andric     return false;
591349cc55cSDimitry Andric   return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
592349cc55cSDimitry Andric }
593349cc55cSDimitry Andric 
5940b57cec5SDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
5950b57cec5SDimitry Andric /// instrumented with XRay nop sleds.
5960b57cec5SDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
5970b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
6010b57cec5SDimitry Andric /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
6020b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
6030b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
6040b57cec5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
6050b57cec5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
6060b57cec5SDimitry Andric               XRayInstrKind::Custom);
6070b57cec5SDimitry Andric }
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
6100b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
6110b57cec5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
6120b57cec5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
6130b57cec5SDimitry Andric               XRayInstrKind::Typed);
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric 
61606c3fb27SDimitry Andric llvm::ConstantInt *
61706c3fb27SDimitry Andric CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const {
61806c3fb27SDimitry Andric   // Remove any (C++17) exception specifications, to allow calling e.g. a
61906c3fb27SDimitry Andric   // noexcept function through a non-noexcept pointer.
6208a4dda33SDimitry Andric   if (!Ty->isFunctionNoProtoType())
62106c3fb27SDimitry Andric     Ty = getContext().getFunctionTypeWithExceptionSpec(Ty, EST_None);
62206c3fb27SDimitry Andric   std::string Mangled;
62306c3fb27SDimitry Andric   llvm::raw_string_ostream Out(Mangled);
6245f757f3fSDimitry Andric   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out, false);
62506c3fb27SDimitry Andric   return llvm::ConstantInt::get(
62606c3fb27SDimitry Andric       CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled)));
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
62981ad6265SDimitry Andric void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
63081ad6265SDimitry Andric                                          llvm::Function *Fn) {
63181ad6265SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
6320b57cec5SDimitry Andric     return;
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
6350b57cec5SDimitry Andric 
63681ad6265SDimitry Andric   CGM.GenKernelArgMetadata(Fn, FD, this);
63781ad6265SDimitry Andric 
63881ad6265SDimitry Andric   if (!getLangOpts().OpenCL)
63981ad6265SDimitry Andric     return;
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
6420b57cec5SDimitry Andric     QualType HintQTy = A->getTypeHint();
6430b57cec5SDimitry Andric     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
6440b57cec5SDimitry Andric     bool IsSignedInteger =
6450b57cec5SDimitry Andric         HintQTy->isSignedIntegerType() ||
6460b57cec5SDimitry Andric         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
6470b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6480b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
6490b57cec5SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
6500b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6510b57cec5SDimitry Andric             llvm::IntegerType::get(Context, 32),
6520b57cec5SDimitry Andric             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
6530b57cec5SDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
6570b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6580b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
6590b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
6600b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6610b57cec5SDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
6620b57cec5SDimitry Andric   }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
6650b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6660b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
6670b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
6680b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6690b57cec5SDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
6700b57cec5SDimitry Andric   }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
6730b57cec5SDimitry Andric           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6740b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6750b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
6760b57cec5SDimitry Andric     Fn->setMetadata("intel_reqd_sub_group_size",
6770b57cec5SDimitry Andric                     llvm::MDNode::get(Context, AttrMDArgs));
6780b57cec5SDimitry Andric   }
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric /// Determine whether the function F ends with a return stmt.
6820b57cec5SDimitry Andric static bool endsWithReturn(const Decl* F) {
6830b57cec5SDimitry Andric   const Stmt *Body = nullptr;
6840b57cec5SDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
6850b57cec5SDimitry Andric     Body = FD->getBody();
6860b57cec5SDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
6870b57cec5SDimitry Andric     Body = OMD->getBody();
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
6900b57cec5SDimitry Andric     auto LastStmt = CS->body_rbegin();
6910b57cec5SDimitry Andric     if (LastStmt != CS->body_rend())
6920b57cec5SDimitry Andric       return isa<ReturnStmt>(*LastStmt);
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric   return false;
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
6980b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
6990b57cec5SDimitry Andric     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
7000b57cec5SDimitry Andric     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
7010b57cec5SDimitry Andric   }
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric 
704480093f4SDimitry Andric /// Check if the return value of this function requires sanitization.
705480093f4SDimitry Andric bool CodeGenFunction::requiresReturnValueCheck() const {
706480093f4SDimitry Andric   return requiresReturnValueNullabilityCheck() ||
707480093f4SDimitry Andric          (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
708480093f4SDimitry Andric           CurCodeDecl->getAttr<ReturnsNonNullAttr>());
709480093f4SDimitry Andric }
710480093f4SDimitry Andric 
7110b57cec5SDimitry Andric static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
7120b57cec5SDimitry Andric   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
7130b57cec5SDimitry Andric   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
7140b57cec5SDimitry Andric       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
7150b57cec5SDimitry Andric       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
7160b57cec5SDimitry Andric     return false;
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
7190b57cec5SDimitry Andric     return false;
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   if (MD->getNumParams() == 2) {
7220b57cec5SDimitry Andric     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
7230b57cec5SDimitry Andric     if (!PT || !PT->isVoidPointerType() ||
7240b57cec5SDimitry Andric         !PT->getPointeeType().isConstQualified())
7250b57cec5SDimitry Andric       return false;
7260b57cec5SDimitry Andric   }
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   return true;
7290b57cec5SDimitry Andric }
7300b57cec5SDimitry Andric 
7318a4dda33SDimitry Andric bool CodeGenFunction::isInAllocaArgument(CGCXXABI &ABI, QualType Ty) {
7328a4dda33SDimitry Andric   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7338a4dda33SDimitry Andric   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
7348a4dda33SDimitry Andric }
7358a4dda33SDimitry Andric 
7368a4dda33SDimitry Andric bool CodeGenFunction::hasInAllocaArg(const CXXMethodDecl *MD) {
7378a4dda33SDimitry Andric   return getTarget().getTriple().getArch() == llvm::Triple::x86 &&
7388a4dda33SDimitry Andric          getTarget().getCXXABI().isMicrosoft() &&
7398a4dda33SDimitry Andric          llvm::any_of(MD->parameters(), [&](ParmVarDecl *P) {
7408a4dda33SDimitry Andric            return isInAllocaArgument(CGM.getCXXABI(), P->getType());
7418a4dda33SDimitry Andric          });
7428a4dda33SDimitry Andric }
7438a4dda33SDimitry Andric 
7440b57cec5SDimitry Andric /// Return the UBSan prologue signature for \p FD if one is available.
7450b57cec5SDimitry Andric static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
7460b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
7470b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7480b57cec5SDimitry Andric     if (!MD->isStatic())
7490b57cec5SDimitry Andric       return nullptr;
7500b57cec5SDimitry Andric   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
753480093f4SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
7540b57cec5SDimitry Andric                                     llvm::Function *Fn,
7550b57cec5SDimitry Andric                                     const CGFunctionInfo &FnInfo,
7560b57cec5SDimitry Andric                                     const FunctionArgList &Args,
7570b57cec5SDimitry Andric                                     SourceLocation Loc,
7580b57cec5SDimitry Andric                                     SourceLocation StartLoc) {
7590b57cec5SDimitry Andric   assert(!CurFn &&
7600b57cec5SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   DidCallStackSave = false;
7650b57cec5SDimitry Andric   CurCodeDecl = D;
766fe6060f1SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
767fe6060f1SDimitry Andric   if (FD && FD->usesSEHTry())
768bdd1243dSDimitry Andric     CurSEHParent = GD;
7690b57cec5SDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
7700b57cec5SDimitry Andric   FnRetTy = RetTy;
7710b57cec5SDimitry Andric   CurFn = Fn;
7720b57cec5SDimitry Andric   CurFnInfo = &FnInfo;
7730b57cec5SDimitry Andric   assert(CurFn->isDeclaration() && "Function already has body?");
7740b57cec5SDimitry Andric 
775fe6060f1SDimitry Andric   // If this function is ignored for any of the enabled sanitizers,
7760b57cec5SDimitry Andric   // disable the sanitizer for the function.
7770b57cec5SDimitry Andric   do {
7780b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
7790b57cec5SDimitry Andric   if (SanOpts.empty())                                                         \
7800b57cec5SDimitry Andric     break;                                                                     \
7810b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ID))                                          \
782fe6060f1SDimitry Andric     if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc))                    \
7830b57cec5SDimitry Andric       SanOpts.set(SanitizerKind::ID, false);
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
7860b57cec5SDimitry Andric #undef SANITIZER
78704eeddc0SDimitry Andric   } while (false);
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   if (D) {
79081ad6265SDimitry Andric     const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
79106c3fb27SDimitry Andric     SanitizerMask no_sanitize_mask;
792fe6060f1SDimitry Andric     bool NoSanitizeCoverage = false;
793fe6060f1SDimitry Andric 
794bdd1243dSDimitry Andric     for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) {
79506c3fb27SDimitry Andric       no_sanitize_mask |= Attr->getMask();
796fe6060f1SDimitry Andric       // SanitizeCoverage is not handled by SanOpts.
797fe6060f1SDimitry Andric       if (Attr->hasCoverage())
798fe6060f1SDimitry Andric         NoSanitizeCoverage = true;
7990b57cec5SDimitry Andric     }
800fe6060f1SDimitry Andric 
80106c3fb27SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
80206c3fb27SDimitry Andric     SanOpts.Mask &= ~no_sanitize_mask;
80306c3fb27SDimitry Andric     if (no_sanitize_mask & SanitizerKind::Address)
80406c3fb27SDimitry Andric       SanOpts.set(SanitizerKind::KernelAddress, false);
80506c3fb27SDimitry Andric     if (no_sanitize_mask & SanitizerKind::KernelAddress)
80606c3fb27SDimitry Andric       SanOpts.set(SanitizerKind::Address, false);
80706c3fb27SDimitry Andric     if (no_sanitize_mask & SanitizerKind::HWAddress)
80806c3fb27SDimitry Andric       SanOpts.set(SanitizerKind::KernelHWAddress, false);
80906c3fb27SDimitry Andric     if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
81006c3fb27SDimitry Andric       SanOpts.set(SanitizerKind::HWAddress, false);
81106c3fb27SDimitry Andric 
81281ad6265SDimitry Andric     if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
81381ad6265SDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
81481ad6265SDimitry Andric 
815fe6060f1SDimitry Andric     if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
816fe6060f1SDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
81706c3fb27SDimitry Andric 
81806c3fb27SDimitry Andric     // Some passes need the non-negated no_sanitize attribute. Pass them on.
81906c3fb27SDimitry Andric     if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
82006c3fb27SDimitry Andric       if (no_sanitize_mask & SanitizerKind::Thread)
82106c3fb27SDimitry Andric         Fn->addFnAttr("no_sanitize_thread");
82206c3fb27SDimitry Andric     }
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric 
82581ad6265SDimitry Andric   if (ShouldSkipSanitizerInstrumentation()) {
82681ad6265SDimitry Andric     CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
82781ad6265SDimitry Andric   } else {
8280b57cec5SDimitry Andric     // Apply sanitizer attributes to the function.
8290b57cec5SDimitry Andric     if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
8300b57cec5SDimitry Andric       Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
83181ad6265SDimitry Andric     if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
83281ad6265SDimitry Andric                          SanitizerKind::KernelHWAddress))
8330b57cec5SDimitry Andric       Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
83481ad6265SDimitry Andric     if (SanOpts.has(SanitizerKind::MemtagStack))
8350b57cec5SDimitry Andric       Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
8360b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Thread))
8370b57cec5SDimitry Andric       Fn->addFnAttr(llvm::Attribute::SanitizeThread);
8380fca6ea1SDimitry Andric     if (SanOpts.has(SanitizerKind::NumericalStability))
8390fca6ea1SDimitry Andric       Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
8400b57cec5SDimitry Andric     if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
8410b57cec5SDimitry Andric       Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
84281ad6265SDimitry Andric   }
8430b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
8440b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
8450b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ShadowCallStack))
8460b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // Apply fuzzing attribute to the function.
8490b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
8500b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
8530b57cec5SDimitry Andric   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
8540b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
8550b57cec5SDimitry Andric     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
8560fca6ea1SDimitry Andric       const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
8570b57cec5SDimitry Andric       if (OMD->getMethodFamily() == OMF_dealloc ||
8580b57cec5SDimitry Andric           OMD->getMethodFamily() == OMF_initialize ||
8590b57cec5SDimitry Andric           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
8600b57cec5SDimitry Andric         markAsIgnoreThreadCheckingAtRuntime(Fn);
8610b57cec5SDimitry Andric       }
8620b57cec5SDimitry Andric     }
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   // Ignore unrelated casts in STL allocate() since the allocator must cast
8660b57cec5SDimitry Andric   // from void* to T* before object initialization completes. Don't match on the
8670b57cec5SDimitry Andric   // namespace because not all allocators are in std::
8680b57cec5SDimitry Andric   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
8690b57cec5SDimitry Andric     if (matchesStlAllocatorFn(D, getContext()))
8700b57cec5SDimitry Andric       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
8710b57cec5SDimitry Andric   }
8720b57cec5SDimitry Andric 
873a7dea167SDimitry Andric   // Ignore null checks in coroutine functions since the coroutines passes
874a7dea167SDimitry Andric   // are not aware of how to move the extra UBSan instructions across the split
875a7dea167SDimitry Andric   // coroutine boundaries.
876a7dea167SDimitry Andric   if (D && SanOpts.has(SanitizerKind::Null))
877fe6060f1SDimitry Andric     if (FD && FD->getBody() &&
878a7dea167SDimitry Andric         FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
879a7dea167SDimitry Andric       SanOpts.Mask &= ~SanitizerKind::Null;
880a7dea167SDimitry Andric 
8810fca6ea1SDimitry Andric   // Add pointer authentication attributes.
8820fca6ea1SDimitry Andric   const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
883*62987288SDimitry Andric   if (CodeGenOpts.PointerAuth.ReturnAddresses)
884*62987288SDimitry Andric     Fn->addFnAttr("ptrauth-returns");
8850fca6ea1SDimitry Andric   if (CodeGenOpts.PointerAuth.FunctionPointers)
8860fca6ea1SDimitry Andric     Fn->addFnAttr("ptrauth-calls");
887*62987288SDimitry Andric   if (CodeGenOpts.PointerAuth.AuthTraps)
888*62987288SDimitry Andric     Fn->addFnAttr("ptrauth-auth-traps");
8890fca6ea1SDimitry Andric   if (CodeGenOpts.PointerAuth.IndirectGotos)
8900fca6ea1SDimitry Andric     Fn->addFnAttr("ptrauth-indirect-gotos");
8910fca6ea1SDimitry Andric 
892480093f4SDimitry Andric   // Apply xray attributes to the function (as a string, for now)
893e8d8bef9SDimitry Andric   bool AlwaysXRayAttr = false;
8945ffd83dbSDimitry Andric   if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
8950b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8965ffd83dbSDimitry Andric             XRayInstrKind::FunctionEntry) ||
8975ffd83dbSDimitry Andric         CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8985ffd83dbSDimitry Andric             XRayInstrKind::FunctionExit)) {
899e8d8bef9SDimitry Andric       if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
9000b57cec5SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
901e8d8bef9SDimitry Andric         AlwaysXRayAttr = true;
902e8d8bef9SDimitry Andric       }
9030b57cec5SDimitry Andric       if (XRayAttr->neverXRayInstrument())
9040b57cec5SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
9050b57cec5SDimitry Andric       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
9060b57cec5SDimitry Andric         if (ShouldXRayInstrumentFunction())
9070b57cec5SDimitry Andric           Fn->addFnAttr("xray-log-args",
9080b57cec5SDimitry Andric                         llvm::utostr(LogArgs->getArgumentCount()));
9090b57cec5SDimitry Andric     }
9100b57cec5SDimitry Andric   } else {
9110b57cec5SDimitry Andric     if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
9120b57cec5SDimitry Andric       Fn->addFnAttr(
9130b57cec5SDimitry Andric           "xray-instruction-threshold",
9140b57cec5SDimitry Andric           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
9150b57cec5SDimitry Andric   }
916480093f4SDimitry Andric 
9175ffd83dbSDimitry Andric   if (ShouldXRayInstrumentFunction()) {
9185ffd83dbSDimitry Andric     if (CGM.getCodeGenOpts().XRayIgnoreLoops)
9195ffd83dbSDimitry Andric       Fn->addFnAttr("xray-ignore-loops");
9205ffd83dbSDimitry Andric 
9215ffd83dbSDimitry Andric     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
9225ffd83dbSDimitry Andric             XRayInstrKind::FunctionExit))
9235ffd83dbSDimitry Andric       Fn->addFnAttr("xray-skip-exit");
9245ffd83dbSDimitry Andric 
9255ffd83dbSDimitry Andric     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
9265ffd83dbSDimitry Andric             XRayInstrKind::FunctionEntry))
9275ffd83dbSDimitry Andric       Fn->addFnAttr("xray-skip-entry");
928e8d8bef9SDimitry Andric 
929e8d8bef9SDimitry Andric     auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
930e8d8bef9SDimitry Andric     if (FuncGroups > 1) {
931bdd1243dSDimitry Andric       auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
932bdd1243dSDimitry Andric                                               CurFn->getName().bytes_end());
933e8d8bef9SDimitry Andric       auto Group = crc32(FuncName) % FuncGroups;
934e8d8bef9SDimitry Andric       if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
935e8d8bef9SDimitry Andric           !AlwaysXRayAttr)
936e8d8bef9SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
9375ffd83dbSDimitry Andric     }
938e8d8bef9SDimitry Andric   }
939e8d8bef9SDimitry Andric 
940bdd1243dSDimitry Andric   if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone) {
941bdd1243dSDimitry Andric     switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
942bdd1243dSDimitry Andric     case ProfileList::Skip:
943bdd1243dSDimitry Andric       Fn->addFnAttr(llvm::Attribute::SkipProfile);
944bdd1243dSDimitry Andric       break;
945bdd1243dSDimitry Andric     case ProfileList::Forbid:
946e8d8bef9SDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoProfile);
947bdd1243dSDimitry Andric       break;
948bdd1243dSDimitry Andric     case ProfileList::Allow:
949bdd1243dSDimitry Andric       break;
950bdd1243dSDimitry Andric     }
951bdd1243dSDimitry Andric   }
9525ffd83dbSDimitry Andric 
95355e4f9d5SDimitry Andric   unsigned Count, Offset;
9545ffd83dbSDimitry Andric   if (const auto *Attr =
9555ffd83dbSDimitry Andric           D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
95655e4f9d5SDimitry Andric     Count = Attr->getCount();
95755e4f9d5SDimitry Andric     Offset = Attr->getOffset();
95855e4f9d5SDimitry Andric   } else {
95955e4f9d5SDimitry Andric     Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
96055e4f9d5SDimitry Andric     Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
96155e4f9d5SDimitry Andric   }
96255e4f9d5SDimitry Andric   if (Count && Offset <= Count) {
96355e4f9d5SDimitry Andric     Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
96455e4f9d5SDimitry Andric     if (Offset)
96555e4f9d5SDimitry Andric       Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
966480093f4SDimitry Andric   }
96704eeddc0SDimitry Andric   // Instruct that functions for COFF/CodeView targets should start with a
96804eeddc0SDimitry Andric   // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
96904eeddc0SDimitry Andric   // backends as they don't need it -- instructions on these architectures are
97004eeddc0SDimitry Andric   // always atomically patchable at runtime.
97104eeddc0SDimitry Andric   if (CGM.getCodeGenOpts().HotPatch &&
972bdd1243dSDimitry Andric       getContext().getTargetInfo().getTriple().isX86() &&
973bdd1243dSDimitry Andric       getContext().getTargetInfo().getTriple().getEnvironment() !=
974bdd1243dSDimitry Andric           llvm::Triple::CODE16)
97504eeddc0SDimitry Andric     Fn->addFnAttr("patchable-function", "prologue-short-redirect");
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   // Add no-jump-tables value.
978fe6060f1SDimitry Andric   if (CGM.getCodeGenOpts().NoUseJumpTables)
979fe6060f1SDimitry Andric     Fn->addFnAttr("no-jump-tables", "true");
9800b57cec5SDimitry Andric 
981480093f4SDimitry Andric   // Add no-inline-line-tables value.
982480093f4SDimitry Andric   if (CGM.getCodeGenOpts().NoInlineLineTables)
983480093f4SDimitry Andric     Fn->addFnAttr("no-inline-line-tables");
984480093f4SDimitry Andric 
9850b57cec5SDimitry Andric   // Add profile-sample-accurate value.
9860b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
9870b57cec5SDimitry Andric     Fn->addFnAttr("profile-sample-accurate");
9880b57cec5SDimitry Andric 
9895ffd83dbSDimitry Andric   if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
9905ffd83dbSDimitry Andric     Fn->addFnAttr("use-sample-profile");
9915ffd83dbSDimitry Andric 
992a7dea167SDimitry Andric   if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
993a7dea167SDimitry Andric     Fn->addFnAttr("cfi-canonical-jump-table");
994a7dea167SDimitry Andric 
995fe6060f1SDimitry Andric   if (D && D->hasAttr<NoProfileFunctionAttr>())
996fe6060f1SDimitry Andric     Fn->addFnAttr(llvm::Attribute::NoProfile);
997fe6060f1SDimitry Andric 
99852418fc2SDimitry Andric   if (D && D->hasAttr<HybridPatchableAttr>())
99952418fc2SDimitry Andric     Fn->addFnAttr(llvm::Attribute::HybridPatchable);
100052418fc2SDimitry Andric 
1001753f127fSDimitry Andric   if (D) {
1002753f127fSDimitry Andric     // Function attributes take precedence over command line flags.
1003753f127fSDimitry Andric     if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1004753f127fSDimitry Andric       switch (A->getThunkType()) {
1005753f127fSDimitry Andric       case FunctionReturnThunksAttr::Kind::Keep:
1006753f127fSDimitry Andric         break;
1007753f127fSDimitry Andric       case FunctionReturnThunksAttr::Kind::Extern:
1008753f127fSDimitry Andric         Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1009753f127fSDimitry Andric         break;
1010753f127fSDimitry Andric       }
1011753f127fSDimitry Andric     } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1012753f127fSDimitry Andric       Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1013753f127fSDimitry Andric   }
1014753f127fSDimitry Andric 
101581ad6265SDimitry Andric   if (FD && (getLangOpts().OpenCL ||
101681ad6265SDimitry Andric              (getLangOpts().HIP && getLangOpts().CUDAIsDevice))) {
10170b57cec5SDimitry Andric     // Add metadata for a kernel function.
101881ad6265SDimitry Andric     EmitKernelMetadata(FD, Fn);
10190b57cec5SDimitry Andric   }
10200b57cec5SDimitry Andric 
10210fca6ea1SDimitry Andric   if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
10220fca6ea1SDimitry Andric     Fn->setMetadata("clspv_libclc_builtin",
10230fca6ea1SDimitry Andric                     llvm::MDNode::get(getLLVMContext(), {}));
10240fca6ea1SDimitry Andric   }
10250fca6ea1SDimitry Andric 
10260b57cec5SDimitry Andric   // If we are checking function types, emit a function type signature as
10270b57cec5SDimitry Andric   // prologue data.
102806c3fb27SDimitry Andric   if (FD && SanOpts.has(SanitizerKind::Function)) {
10290b57cec5SDimitry Andric     if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
103081ad6265SDimitry Andric       llvm::LLVMContext &Ctx = Fn->getContext();
103181ad6265SDimitry Andric       llvm::MDBuilder MDB(Ctx);
103206c3fb27SDimitry Andric       Fn->setMetadata(
103306c3fb27SDimitry Andric           llvm::LLVMContext::MD_func_sanitize,
103406c3fb27SDimitry Andric           MDB.createRTTIPointerPrologue(
103506c3fb27SDimitry Andric               PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
10360b57cec5SDimitry Andric     }
10370b57cec5SDimitry Andric   }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   // If we're checking nullability, we need to know whether we can check the
10400b57cec5SDimitry Andric   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
10410b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1042bdd1243dSDimitry Andric     auto Nullability = FnRetTy->getNullability();
10430fca6ea1SDimitry Andric     if (Nullability && *Nullability == NullabilityKind::NonNull &&
10440fca6ea1SDimitry Andric         !FnRetTy->isRecordType()) {
10450b57cec5SDimitry Andric       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
10460b57cec5SDimitry Andric             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
10470b57cec5SDimitry Andric         RetValNullabilityPrecondition =
10480b57cec5SDimitry Andric             llvm::ConstantInt::getTrue(getLLVMContext());
10490b57cec5SDimitry Andric     }
10500b57cec5SDimitry Andric   }
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
10530b57cec5SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
10540b57cec5SDimitry Andric   // used within a program").
10555ffd83dbSDimitry Andric   //
10565ffd83dbSDimitry Andric   // OpenCL C 2.0 v2.2-11 s6.9.i:
10575ffd83dbSDimitry Andric   //     Recursion is not supported.
10585ffd83dbSDimitry Andric   //
10595ffd83dbSDimitry Andric   // SYCL v1.2.1 s3.10:
10605ffd83dbSDimitry Andric   //     kernels cannot include RTTI information, exception classes,
10615ffd83dbSDimitry Andric   //     recursive code, virtual functions or make use of C++ libraries that
10625ffd83dbSDimitry Andric   //     are not compiled for the device.
1063fe6060f1SDimitry Andric   if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
1064fe6060f1SDimitry Andric              getLangOpts().OpenCL || getLangOpts().SYCLIsDevice ||
1065fe6060f1SDimitry Andric              (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
10660b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::NoRecurse);
10670b57cec5SDimitry Andric 
106881ad6265SDimitry Andric   llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1069349cc55cSDimitry Andric   llvm::fp::ExceptionBehavior FPExceptionBehavior =
107081ad6265SDimitry Andric       ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1071349cc55cSDimitry Andric   Builder.setDefaultConstrainedRounding(RM);
1072349cc55cSDimitry Andric   Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1073349cc55cSDimitry Andric   if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1074349cc55cSDimitry Andric       (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1075349cc55cSDimitry Andric                RM != llvm::RoundingMode::NearestTiesToEven))) {
1076349cc55cSDimitry Andric     Builder.setIsFPConstrained(true);
1077480093f4SDimitry Andric     Fn->addFnAttr(llvm::Attribute::StrictFP);
10785ffd83dbSDimitry Andric   }
1079480093f4SDimitry Andric 
10800b57cec5SDimitry Andric   // If a custom alignment is used, force realigning to this alignment on
10810b57cec5SDimitry Andric   // any main function which certainly will need it.
1082fe6060f1SDimitry Andric   if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1083fe6060f1SDimitry Andric              CGM.getCodeGenOpts().StackAlignment))
10840b57cec5SDimitry Andric     Fn->addFnAttr("stackrealign");
10850b57cec5SDimitry Andric 
108681ad6265SDimitry Andric   // "main" doesn't need to zero out call-used registers.
108781ad6265SDimitry Andric   if (FD && FD->isMain())
108881ad6265SDimitry Andric     Fn->removeFnAttr("zero-call-used-regs");
108981ad6265SDimitry Andric 
10900b57cec5SDimitry Andric   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   // Create a marker to make it easy to insert allocas into the entryblock
10930b57cec5SDimitry Andric   // later.  Don't create this with the builder, because we don't want it
10940b57cec5SDimitry Andric   // folded.
10950b57cec5SDimitry Andric   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
10960b57cec5SDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric   ReturnBlock = getJumpDestInCurrentScope("return");
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric   Builder.SetInsertPoint(EntryBB);
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric   // If we're checking the return value, allocate space for a pointer to a
11030b57cec5SDimitry Andric   // precise source location of the checked return statement.
11040b57cec5SDimitry Andric   if (requiresReturnValueCheck()) {
11050b57cec5SDimitry Andric     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1106349cc55cSDimitry Andric     Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1107349cc55cSDimitry Andric                         ReturnLocation);
11080b57cec5SDimitry Andric   }
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric   // Emit subprogram debug descriptor.
11110b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
11120b57cec5SDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
11130b57cec5SDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
11140b57cec5SDimitry Andric     // convention.
1115349cc55cSDimitry Andric     DI->emitFunctionStart(GD, Loc, StartLoc,
1116349cc55cSDimitry Andric                           DI->getFunctionType(FD, RetTy, Args), CurFn,
1117349cc55cSDimitry Andric                           CurFuncIsThunk);
11180b57cec5SDimitry Andric   }
11190b57cec5SDimitry Andric 
11200b57cec5SDimitry Andric   if (ShouldInstrumentFunction()) {
11210b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
11220b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
11230b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
11240b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
11250b57cec5SDimitry Andric                        "__cyg_profile_func_enter");
11260b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
11270b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
11280b57cec5SDimitry Andric                        "__cyg_profile_func_enter_bare");
11290b57cec5SDimitry Andric   }
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric   // Since emitting the mcount call here impacts optimizations such as function
11320b57cec5SDimitry Andric   // inlining, we just add an attribute to insert a mcount call in backend.
11330b57cec5SDimitry Andric   // The attribute "counting-function" is set to mcount function name which is
11340b57cec5SDimitry Andric   // architecture dependent.
11350b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
11360b57cec5SDimitry Andric     // Calls to fentry/mcount should not be generated if function has
11370b57cec5SDimitry Andric     // the no_instrument_function attribute.
11380b57cec5SDimitry Andric     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
11390b57cec5SDimitry Andric       if (CGM.getCodeGenOpts().CallFEntry)
11400b57cec5SDimitry Andric         Fn->addFnAttr("fentry-call", "true");
11410b57cec5SDimitry Andric       else {
11420b57cec5SDimitry Andric         Fn->addFnAttr("instrument-function-entry-inlined",
11430b57cec5SDimitry Andric                       getTarget().getMCountName());
11440b57cec5SDimitry Andric       }
1145480093f4SDimitry Andric       if (CGM.getCodeGenOpts().MNopMCount) {
1146480093f4SDimitry Andric         if (!CGM.getCodeGenOpts().CallFEntry)
1147480093f4SDimitry Andric           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1148480093f4SDimitry Andric             << "-mnop-mcount" << "-mfentry";
1149480093f4SDimitry Andric         Fn->addFnAttr("mnop-mcount");
11500b57cec5SDimitry Andric       }
1151480093f4SDimitry Andric 
1152480093f4SDimitry Andric       if (CGM.getCodeGenOpts().RecordMCount) {
1153480093f4SDimitry Andric         if (!CGM.getCodeGenOpts().CallFEntry)
1154480093f4SDimitry Andric           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1155480093f4SDimitry Andric             << "-mrecord-mcount" << "-mfentry";
1156480093f4SDimitry Andric         Fn->addFnAttr("mrecord-mcount");
1157480093f4SDimitry Andric       }
1158480093f4SDimitry Andric     }
1159480093f4SDimitry Andric   }
1160480093f4SDimitry Andric 
1161480093f4SDimitry Andric   if (CGM.getCodeGenOpts().PackedStack) {
1162480093f4SDimitry Andric     if (getContext().getTargetInfo().getTriple().getArch() !=
1163480093f4SDimitry Andric         llvm::Triple::systemz)
1164480093f4SDimitry Andric       CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1165480093f4SDimitry Andric         << "-mpacked-stack";
1166480093f4SDimitry Andric     Fn->addFnAttr("packed-stack");
11670b57cec5SDimitry Andric   }
11680b57cec5SDimitry Andric 
1169349cc55cSDimitry Andric   if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1170349cc55cSDimitry Andric       !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1171fe6060f1SDimitry Andric     Fn->addFnAttr("warn-stack-size",
1172fe6060f1SDimitry Andric                   std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1173fe6060f1SDimitry Andric 
11740b57cec5SDimitry Andric   if (RetTy->isVoidType()) {
11750b57cec5SDimitry Andric     // Void type; nothing to return.
11760b57cec5SDimitry Andric     ReturnValue = Address::invalid();
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric     // Count the implicit return.
11790b57cec5SDimitry Andric     if (!endsWithReturn(D))
11800b57cec5SDimitry Andric       ++NumReturnExprs;
11810b57cec5SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
11820b57cec5SDimitry Andric     // Indirect return; emit returned value directly into sret slot.
11830b57cec5SDimitry Andric     // This reduces code size, and affects correctness in C++.
11840b57cec5SDimitry Andric     auto AI = CurFn->arg_begin();
11850b57cec5SDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
11860b57cec5SDimitry Andric       ++AI;
11870fca6ea1SDimitry Andric     ReturnValue = makeNaturalAddressForPointer(
11880fca6ea1SDimitry Andric         &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
11890fca6ea1SDimitry Andric         nullptr, nullptr, KnownNonNull);
11900b57cec5SDimitry Andric     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
11910fca6ea1SDimitry Andric       ReturnValuePointer =
11920fca6ea1SDimitry Andric           CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
11930fca6ea1SDimitry Andric       Builder.CreateStore(ReturnValue.emitRawPointer(*this),
11940fca6ea1SDimitry Andric                           ReturnValuePointer);
11950b57cec5SDimitry Andric     }
11960b57cec5SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
11970b57cec5SDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
11980b57cec5SDimitry Andric     // Load the sret pointer from the argument struct and return into that.
11990b57cec5SDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
12000b57cec5SDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
12010b57cec5SDimitry Andric     --EI;
1202fe6060f1SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(
120381ad6265SDimitry Andric         CurFnInfo->getArgStruct(), &*EI, Idx);
1204fe6060f1SDimitry Andric     llvm::Type *Ty =
1205fe6060f1SDimitry Andric         cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
120681ad6265SDimitry Andric     ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
1207fe6060f1SDimitry Andric     Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
120806c3fb27SDimitry Andric     ReturnValue = Address(Addr, ConvertType(RetTy),
120906c3fb27SDimitry Andric                           CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
12100b57cec5SDimitry Andric   } else {
12110b57cec5SDimitry Andric     ReturnValue = CreateIRTemp(RetTy, "retval");
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
12140b57cec5SDimitry Andric     // now so that various specialized functions can suppress it
12150b57cec5SDimitry Andric     // during their IR-generation.
12160b57cec5SDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
12170b57cec5SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
12180b57cec5SDimitry Andric         RetTy->isObjCRetainableType())
12190b57cec5SDimitry Andric       AutoreleaseResult = true;
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   EmitStartEHSpec(CurCodeDecl);
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric   // Emit OpenMP specific initialization of the device functions.
12270b57cec5SDimitry Andric   if (getLangOpts().OpenMP && CurCodeDecl)
12280b57cec5SDimitry Andric     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
12290b57cec5SDimitry Andric 
1230bdd1243dSDimitry Andric   // Handle emitting HLSL entry functions.
1231bdd1243dSDimitry Andric   if (D && D->hasAttr<HLSLShaderAttr>())
1232bdd1243dSDimitry Andric     CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1233bdd1243dSDimitry Andric 
12340b57cec5SDimitry Andric   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
12350b57cec5SDimitry Andric 
12365f757f3fSDimitry Andric   if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
12375f757f3fSDimitry Andric       MD && !MD->isStatic()) {
12385f757f3fSDimitry Andric     bool IsInLambda =
12395f757f3fSDimitry Andric         MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
12405f757f3fSDimitry Andric     if (MD->isImplicitObjectMemberFunction())
12410b57cec5SDimitry Andric       CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
12425f757f3fSDimitry Andric     if (IsInLambda) {
12430b57cec5SDimitry Andric       // We're in a lambda; figure out the captures.
12440b57cec5SDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
12450b57cec5SDimitry Andric                                         LambdaThisCaptureField);
12460b57cec5SDimitry Andric       if (LambdaThisCaptureField) {
12470b57cec5SDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
12480b57cec5SDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
12490b57cec5SDimitry Andric         // object.
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
12520b57cec5SDimitry Andric         // or contains the address of the enclosing object).
12530b57cec5SDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
12540b57cec5SDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
12550fca6ea1SDimitry Andric           // If the enclosing object was captured by value, just use its
12560fca6ea1SDimitry Andric           // address. Sign this pointer.
12570fca6ea1SDimitry Andric           CXXThisValue = ThisFieldLValue.getPointer(*this);
12580b57cec5SDimitry Andric         } else {
12590b57cec5SDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
12600b57cec5SDimitry Andric           // by reference.
12610b57cec5SDimitry Andric           CXXThisValue =
12620b57cec5SDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
12630b57cec5SDimitry Andric         }
12640b57cec5SDimitry Andric       }
12650b57cec5SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
12660b57cec5SDimitry Andric         if (FD->hasCapturedVLAType()) {
12670b57cec5SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
12680b57cec5SDimitry Andric                                            SourceLocation()).getScalarVal();
12690b57cec5SDimitry Andric           auto VAT = FD->getCapturedVLAType();
12700b57cec5SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
12710b57cec5SDimitry Andric         }
12720b57cec5SDimitry Andric       }
12735f757f3fSDimitry Andric     } else if (MD->isImplicitObjectMemberFunction()) {
12740b57cec5SDimitry Andric       // Not in a lambda; just use 'this' from the method.
12750b57cec5SDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
12760b57cec5SDimitry Andric       // fast register allocator would be happier...
12770b57cec5SDimitry Andric       CXXThisValue = CXXABIThisValue;
12780b57cec5SDimitry Andric     }
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric     // Check the 'this' pointer once per function, if it's available.
12810b57cec5SDimitry Andric     if (CXXABIThisValue) {
12820b57cec5SDimitry Andric       SanitizerSet SkippedChecks;
12830b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::ObjectSize, true);
12840b57cec5SDimitry Andric       QualType ThisTy = MD->getThisType();
12850b57cec5SDimitry Andric 
12865f757f3fSDimitry Andric       // If this is the call operator of a lambda with no captures, it
12870b57cec5SDimitry Andric       // may have a static invoker function, which may call this operator with
12880b57cec5SDimitry Andric       // a null 'this' pointer.
12895f757f3fSDimitry Andric       if (isLambdaCallOperator(MD) && MD->getParent()->isCapturelessLambda())
12900b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
12910b57cec5SDimitry Andric 
1292e8d8bef9SDimitry Andric       EmitTypeCheck(
1293e8d8bef9SDimitry Andric           isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1294e8d8bef9SDimitry Andric           Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
12950b57cec5SDimitry Andric     }
12960b57cec5SDimitry Andric   }
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   // If any of the arguments have a variably modified type, make sure to
129981ad6265SDimitry Andric   // emit the type size, but only if the function is not naked. Naked functions
130081ad6265SDimitry Andric   // have no prolog to run this evaluation.
130181ad6265SDimitry Andric   if (!FD || !FD->hasAttr<NakedAttr>()) {
130281ad6265SDimitry Andric     for (const VarDecl *VD : Args) {
13030b57cec5SDimitry Andric       // Dig out the type as written from ParmVarDecls; it's unclear whether
13040b57cec5SDimitry Andric       // the standard (C99 6.9.1p10) requires this, but we're following the
13050b57cec5SDimitry Andric       // precedent set by gcc.
13060b57cec5SDimitry Andric       QualType Ty;
13070b57cec5SDimitry Andric       if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
13080b57cec5SDimitry Andric         Ty = PVD->getOriginalType();
13090b57cec5SDimitry Andric       else
13100b57cec5SDimitry Andric         Ty = VD->getType();
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric       if (Ty->isVariablyModifiedType())
13130b57cec5SDimitry Andric         EmitVariablyModifiedType(Ty);
13140b57cec5SDimitry Andric     }
131581ad6265SDimitry Andric   }
13160b57cec5SDimitry Andric   // Emit a location at the end of the prologue.
13170b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
13180b57cec5SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
13190b57cec5SDimitry Andric   // TODO: Do we need to handle this in two places like we do with
13200b57cec5SDimitry Andric   // target-features/target-cpu?
13210b57cec5SDimitry Andric   if (CurFuncDecl)
13220b57cec5SDimitry Andric     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
13230b57cec5SDimitry Andric       LargestVectorWidth = VecWidth->getVectorWidth();
13240fca6ea1SDimitry Andric 
13250fca6ea1SDimitry Andric   if (CGM.shouldEmitConvergenceTokens())
13260fca6ea1SDimitry Andric     ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
13300b57cec5SDimitry Andric   incrementProfileCounter(Body);
13311db9f3b2SDimitry Andric   maybeCreateMCDCCondBitmap();
13320b57cec5SDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
13330b57cec5SDimitry Andric     EmitCompoundStmtWithoutScope(*S);
13340b57cec5SDimitry Andric   else
13350b57cec5SDimitry Andric     EmitStmt(Body);
13360b57cec5SDimitry Andric }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
13390b57cec5SDimitry Andric /// such as switch cases need to not include the fall-through counts, so
13400b57cec5SDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
13410b57cec5SDimitry Andric /// this just calls EmitBlock().
13420b57cec5SDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
13430b57cec5SDimitry Andric                                                const Stmt *S) {
13440b57cec5SDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
13450fca6ea1SDimitry Andric   // Do not skip over the instrumentation when single byte coverage mode is
13460fca6ea1SDimitry Andric   // enabled.
13470fca6ea1SDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr() &&
13480fca6ea1SDimitry Andric       !llvm::EnableSingleByteCoverage) {
13490b57cec5SDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
13500b57cec5SDimitry Andric     // statements needs to skip over the instrumentation code so that we
13510b57cec5SDimitry Andric     // get an accurate count.
13520b57cec5SDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
13530b57cec5SDimitry Andric     EmitBranch(SkipCountBB);
13540b57cec5SDimitry Andric   }
13550b57cec5SDimitry Andric   EmitBlock(BB);
13560b57cec5SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
13570b57cec5SDimitry Andric   incrementProfileCounter(S);
13580b57cec5SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
13590b57cec5SDimitry Andric   if (SkipCountBB)
13600b57cec5SDimitry Andric     EmitBlock(SkipCountBB);
13610b57cec5SDimitry Andric }
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric /// Tries to mark the given function nounwind based on the
13640b57cec5SDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
13650b57cec5SDimitry Andric /// lightweight enough to do at -O0.
13660b57cec5SDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
13670b57cec5SDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
13680b57cec5SDimitry Andric   // can't do this on functions that can be overwritten.
13690b57cec5SDimitry Andric   if (F->isInterposable()) return;
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   for (llvm::BasicBlock &BB : *F)
13720b57cec5SDimitry Andric     for (llvm::Instruction &I : BB)
13730b57cec5SDimitry Andric       if (I.mayThrow())
13740b57cec5SDimitry Andric         return;
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric   F->setDoesNotThrow();
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
13800b57cec5SDimitry Andric                                                FunctionArgList &Args) {
13810b57cec5SDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
13820b57cec5SDimitry Andric   QualType ResTy = FD->getReturnType();
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13855f757f3fSDimitry Andric   if (MD && MD->isImplicitObjectMemberFunction()) {
13860b57cec5SDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
13870b57cec5SDimitry Andric       ResTy = MD->getThisType();
13880b57cec5SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
13890b57cec5SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
13900b57cec5SDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
13910b57cec5SDimitry Andric   }
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
13940b57cec5SDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
13950b57cec5SDimitry Andric   // the inherited constructor).
13960b57cec5SDimitry Andric   bool PassedParams = true;
13970b57cec5SDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
13980b57cec5SDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
13990b57cec5SDimitry Andric       PassedParams =
14000b57cec5SDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric   if (PassedParams) {
14030b57cec5SDimitry Andric     for (auto *Param : FD->parameters()) {
14040b57cec5SDimitry Andric       Args.push_back(Param);
14050b57cec5SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
14060b57cec5SDimitry Andric         continue;
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
14090b57cec5SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(),
14105f757f3fSDimitry Andric           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
14110b57cec5SDimitry Andric       SizeArguments[Param] = Implicit;
14120b57cec5SDimitry Andric       Args.push_back(Implicit);
14130b57cec5SDimitry Andric     }
14140b57cec5SDimitry Andric   }
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
14170b57cec5SDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   return ResTy;
14200b57cec5SDimitry Andric }
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
14230b57cec5SDimitry Andric                                    const CGFunctionInfo &FnInfo) {
14240eae32dcSDimitry Andric   assert(Fn && "generating code for null Function");
14250b57cec5SDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
14260b57cec5SDimitry Andric   CurGD = GD;
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric   FunctionArgList Args;
14290b57cec5SDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
14300b57cec5SDimitry Andric 
14310fca6ea1SDimitry Andric   CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
14320fca6ea1SDimitry Andric 
1433349cc55cSDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
14340eae32dcSDimitry Andric     // When generating code for a builtin with an inline declaration, use a
14350eae32dcSDimitry Andric     // mangled name to hold the actual body, while keeping an external
14360eae32dcSDimitry Andric     // definition in case the function pointer is referenced somewhere.
1437349cc55cSDimitry Andric     std::string FDInlineName = (Fn->getName() + ".inline").str();
1438349cc55cSDimitry Andric     llvm::Module *M = Fn->getParent();
1439349cc55cSDimitry Andric     llvm::Function *Clone = M->getFunction(FDInlineName);
1440349cc55cSDimitry Andric     if (!Clone) {
1441349cc55cSDimitry Andric       Clone = llvm::Function::Create(Fn->getFunctionType(),
1442349cc55cSDimitry Andric                                      llvm::GlobalValue::InternalLinkage,
1443349cc55cSDimitry Andric                                      Fn->getAddressSpace(), FDInlineName, M);
1444349cc55cSDimitry Andric       Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1445349cc55cSDimitry Andric     }
1446349cc55cSDimitry Andric     Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1447349cc55cSDimitry Andric     Fn = Clone;
14480eae32dcSDimitry Andric   } else {
1449349cc55cSDimitry Andric     // Detect the unusual situation where an inline version is shadowed by a
1450349cc55cSDimitry Andric     // non-inline version. In that case we should pick the external one
1451349cc55cSDimitry Andric     // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1452349cc55cSDimitry Andric     // to detect that situation before we reach codegen, so do some late
1453349cc55cSDimitry Andric     // replacement.
1454349cc55cSDimitry Andric     for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1455349cc55cSDimitry Andric          PD = PD->getPreviousDecl()) {
1456349cc55cSDimitry Andric       if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1457349cc55cSDimitry Andric         std::string FDInlineName = (Fn->getName() + ".inline").str();
1458349cc55cSDimitry Andric         llvm::Module *M = Fn->getParent();
1459349cc55cSDimitry Andric         if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1460349cc55cSDimitry Andric           Clone->replaceAllUsesWith(Fn);
1461349cc55cSDimitry Andric           Clone->eraseFromParent();
1462349cc55cSDimitry Andric         }
1463349cc55cSDimitry Andric         break;
1464349cc55cSDimitry Andric       }
1465349cc55cSDimitry Andric     }
1466349cc55cSDimitry Andric   }
1467349cc55cSDimitry Andric 
14680b57cec5SDimitry Andric   // Check if we should generate debug info for this function.
1469fe6060f1SDimitry Andric   if (FD->hasAttr<NoDebugAttr>()) {
1470fe6060f1SDimitry Andric     // Clear non-distinct debug info that was possibly attached to the function
1471fe6060f1SDimitry Andric     // due to an earlier declaration without the nodebug attribute
1472fe6060f1SDimitry Andric     Fn->setSubprogram(nullptr);
1473fe6060f1SDimitry Andric     // Disable debug info indefinitely for this function
1474fe6060f1SDimitry Andric     DebugInfo = nullptr;
1475fe6060f1SDimitry Andric   }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   // The function might not have a body if we're generating thunks for a
14780b57cec5SDimitry Andric   // function declaration.
14790b57cec5SDimitry Andric   SourceRange BodyRange;
14800b57cec5SDimitry Andric   if (Stmt *Body = FD->getBody())
14810b57cec5SDimitry Andric     BodyRange = Body->getSourceRange();
14820b57cec5SDimitry Andric   else
14830b57cec5SDimitry Andric     BodyRange = FD->getLocation();
14840b57cec5SDimitry Andric   CurEHLocation = BodyRange.getEnd();
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   // Use the location of the start of the function to determine where
14870b57cec5SDimitry Andric   // the function definition is located. By default use the location
14880b57cec5SDimitry Andric   // of the declaration as the location for the subprogram. A function
14890b57cec5SDimitry Andric   // may lack a declaration in the source code if it is created by code
14900b57cec5SDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
14910b57cec5SDimitry Andric   SourceLocation Loc = FD->getLocation();
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric   // If this is a function specialization then use the pattern body
14940b57cec5SDimitry Andric   // as the location for the function.
14950b57cec5SDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
14960b57cec5SDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
14970b57cec5SDimitry Andric       Loc = SpecDecl->getLocation();
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric   Stmt *Body = FD->getBody();
15000b57cec5SDimitry Andric 
1501fe6060f1SDimitry Andric   if (Body) {
1502fe6060f1SDimitry Andric     // Coroutines always emit lifetime markers.
1503fe6060f1SDimitry Andric     if (isa<CoroutineBodyStmt>(Body))
1504fe6060f1SDimitry Andric       ShouldEmitLifetimeMarkers = true;
1505fe6060f1SDimitry Andric 
1506fe6060f1SDimitry Andric     // Initialize helper which will detect jumps which can cause invalid
1507fe6060f1SDimitry Andric     // lifetime markers.
1508fe6060f1SDimitry Andric     if (ShouldEmitLifetimeMarkers)
15090b57cec5SDimitry Andric       Bypasses.Init(Body);
1510fe6060f1SDimitry Andric   }
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric   // Emit the standard function prologue.
15130b57cec5SDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
15140b57cec5SDimitry Andric 
1515fe6060f1SDimitry Andric   // Save parameters for coroutine function.
1516fe6060f1SDimitry Andric   if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
151781ad6265SDimitry Andric     llvm::append_range(FnArgs, FD->parameters());
1518fe6060f1SDimitry Andric 
15195f757f3fSDimitry Andric   // Ensure that the function adheres to the forward progress guarantee, which
15205f757f3fSDimitry Andric   // is required by certain optimizations.
15210fca6ea1SDimitry Andric   // In C++11 and up, the attribute will be removed if the body contains a
15220fca6ea1SDimitry Andric   // trivial empty loop.
15235f757f3fSDimitry Andric   if (checkIfFunctionMustProgress())
15245f757f3fSDimitry Andric     CurFn->addFnAttr(llvm::Attribute::MustProgress);
15255f757f3fSDimitry Andric 
15260b57cec5SDimitry Andric   // Generate the body of the function.
15270b57cec5SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
15280b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(FD))
15290b57cec5SDimitry Andric     EmitDestructorBody(Args);
15300b57cec5SDimitry Andric   else if (isa<CXXConstructorDecl>(FD))
15310b57cec5SDimitry Andric     EmitConstructorBody(Args);
15320b57cec5SDimitry Andric   else if (getLangOpts().CUDA &&
15330b57cec5SDimitry Andric            !getLangOpts().CUDAIsDevice &&
15340b57cec5SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
15350b57cec5SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
15360b57cec5SDimitry Andric   else if (isa<CXXMethodDecl>(FD) &&
15370b57cec5SDimitry Andric            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
15380b57cec5SDimitry Andric     // The lambda static invoker function is special, because it forwards or
15390b57cec5SDimitry Andric     // clones the body of the function call operator (but is actually static).
15400b57cec5SDimitry Andric     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
15418a4dda33SDimitry Andric   } else if (isa<CXXMethodDecl>(FD) &&
15428a4dda33SDimitry Andric              isLambdaCallOperator(cast<CXXMethodDecl>(FD)) &&
15438a4dda33SDimitry Andric              !FnInfo.isDelegateCall() &&
15448a4dda33SDimitry Andric              cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
15458a4dda33SDimitry Andric              hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
15468a4dda33SDimitry Andric     // If emitting a lambda with static invoker on X86 Windows, change
15478a4dda33SDimitry Andric     // the call operator body.
15488a4dda33SDimitry Andric     // Make sure that this is a call operator with an inalloca arg and check
15498a4dda33SDimitry Andric     // for delegate call to make sure this is the original call op and not the
15508a4dda33SDimitry Andric     // new forwarding function for the static invoker.
15518a4dda33SDimitry Andric     EmitLambdaInAllocaCallOpBody(cast<CXXMethodDecl>(FD));
15520b57cec5SDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
15530b57cec5SDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
15540b57cec5SDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
15550b57cec5SDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
15560b57cec5SDimitry Andric     // copy-constructors.
15570b57cec5SDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
15580b57cec5SDimitry Andric   } else if (Body) {
15590b57cec5SDimitry Andric     EmitFunctionBody(Body);
15600b57cec5SDimitry Andric   } else
15610b57cec5SDimitry Andric     llvm_unreachable("no definition for emitted function");
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric   // C++11 [stmt.return]p2:
15640b57cec5SDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
15650b57cec5SDimitry Andric   //   a value-returning function.
15660b57cec5SDimitry Andric   // C11 6.9.1p12:
15670b57cec5SDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
15680b57cec5SDimitry Andric   //   function call is used by the caller, the behavior is undefined.
15690b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
15700b57cec5SDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
15710b57cec5SDimitry Andric     bool ShouldEmitUnreachable =
15720b57cec5SDimitry Andric         CGM.getCodeGenOpts().StrictReturn ||
1573fe6060f1SDimitry Andric         !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
15740b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
15750b57cec5SDimitry Andric       SanitizerScope SanScope(this);
15760b57cec5SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
15770b57cec5SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
15780b57cec5SDimitry Andric                 SanitizerHandler::MissingReturn,
1579bdd1243dSDimitry Andric                 EmitCheckSourceLocation(FD->getLocation()), std::nullopt);
15800b57cec5SDimitry Andric     } else if (ShouldEmitUnreachable) {
15810b57cec5SDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
15820b57cec5SDimitry Andric         EmitTrapCall(llvm::Intrinsic::trap);
15830b57cec5SDimitry Andric     }
15840b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
15850b57cec5SDimitry Andric       Builder.CreateUnreachable();
15860b57cec5SDimitry Andric       Builder.ClearInsertionPoint();
15870b57cec5SDimitry Andric     }
15880b57cec5SDimitry Andric   }
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric   // Emit the standard function epilogue.
15910b57cec5SDimitry Andric   FinishFunction(BodyRange.getEnd());
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric   // If we haven't marked the function nothrow through other means, do
15940b57cec5SDimitry Andric   // a quick pass now to see if we can.
15950b57cec5SDimitry Andric   if (!CurFn->doesNotThrow())
15960b57cec5SDimitry Andric     TryMarkNoThrow(CurFn);
15970b57cec5SDimitry Andric }
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric /// ContainsLabel - Return true if the statement contains a label in it.  If
16000b57cec5SDimitry Andric /// this statement is not executed normally, it not containing a label means
16010b57cec5SDimitry Andric /// that we can just remove the code.
16020b57cec5SDimitry Andric bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
16030b57cec5SDimitry Andric   // Null statement, not a label!
16040b57cec5SDimitry Andric   if (!S) return false;
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric   // If this is a label, we have to emit the code, consider something like:
16070b57cec5SDimitry Andric   // if (0) {  ...  foo:  bar(); }  goto foo;
16080b57cec5SDimitry Andric   //
16090b57cec5SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
16100b57cec5SDimitry Andric   // can't jump to one from outside their declared region.
16110b57cec5SDimitry Andric   if (isa<LabelStmt>(S))
16120b57cec5SDimitry Andric     return true;
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric   // If this is a case/default statement, and we haven't seen a switch, we have
16150b57cec5SDimitry Andric   // to emit the code.
16160b57cec5SDimitry Andric   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
16170b57cec5SDimitry Andric     return true;
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // If this is a switch statement, we want to ignore cases below it.
16200b57cec5SDimitry Andric   if (isa<SwitchStmt>(S))
16210b57cec5SDimitry Andric     IgnoreCaseStmts = true;
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   // Scan subexpressions for verboten labels.
16240b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
16250b57cec5SDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
16260b57cec5SDimitry Andric       return true;
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric   return false;
16290b57cec5SDimitry Andric }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
16320b57cec5SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
16330b57cec5SDimitry Andric /// inside of it, this is fine.
16340b57cec5SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
16350b57cec5SDimitry Andric   // Null statement, not a label!
16360b57cec5SDimitry Andric   if (!S) return false;
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
16390b57cec5SDimitry Andric   // include it and anything inside of it.
16400b57cec5SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
16410b57cec5SDimitry Andric       isa<ForStmt>(S))
16420b57cec5SDimitry Andric     return false;
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   if (isa<BreakStmt>(S))
16450b57cec5SDimitry Andric     return true;
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   // Scan subexpressions for verboten breaks.
16480b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
16490b57cec5SDimitry Andric     if (containsBreak(SubStmt))
16500b57cec5SDimitry Andric       return true;
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric   return false;
16530b57cec5SDimitry Andric }
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
16560b57cec5SDimitry Andric   if (!S) return false;
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
16590b57cec5SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
16600b57cec5SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
16610b57cec5SDimitry Andric   // correct even if more statement kinds are added.
16620b57cec5SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
16630b57cec5SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
16640b57cec5SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
16650b57cec5SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
16660b57cec5SDimitry Andric     return false;
16670b57cec5SDimitry Andric 
16680b57cec5SDimitry Andric   if (isa<DeclStmt>(S))
16690b57cec5SDimitry Andric     return true;
16700b57cec5SDimitry Andric 
16710b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
16720b57cec5SDimitry Andric     if (mightAddDeclToScope(SubStmt))
16730b57cec5SDimitry Andric       return true;
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric   return false;
16760b57cec5SDimitry Andric }
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
16790b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
16800b57cec5SDimitry Andric /// constant folds return true and set the boolean result in Result.
16810b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
16820b57cec5SDimitry Andric                                                    bool &ResultBool,
16830b57cec5SDimitry Andric                                                    bool AllowLabels) {
16841db9f3b2SDimitry Andric   // If MC/DC is enabled, disable folding so that we can instrument all
16851db9f3b2SDimitry Andric   // conditions to yield complete test vectors. We still keep track of
16861db9f3b2SDimitry Andric   // folded conditions during region mapping and visualization.
16871db9f3b2SDimitry Andric   if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
16881db9f3b2SDimitry Andric       CGM.getCodeGenOpts().MCDCCoverage)
16891db9f3b2SDimitry Andric     return false;
16901db9f3b2SDimitry Andric 
16910b57cec5SDimitry Andric   llvm::APSInt ResultInt;
16920b57cec5SDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
16930b57cec5SDimitry Andric     return false;
16940b57cec5SDimitry Andric 
16950b57cec5SDimitry Andric   ResultBool = ResultInt.getBoolValue();
16960b57cec5SDimitry Andric   return true;
16970b57cec5SDimitry Andric }
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
17000b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
17010b57cec5SDimitry Andric /// constant folds return true and set the folded value.
17020b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
17030b57cec5SDimitry Andric                                                    llvm::APSInt &ResultInt,
17040b57cec5SDimitry Andric                                                    bool AllowLabels) {
17050b57cec5SDimitry Andric   // FIXME: Rename and handle conversion of other evaluatable things
17060b57cec5SDimitry Andric   // to bool.
17070b57cec5SDimitry Andric   Expr::EvalResult Result;
17080b57cec5SDimitry Andric   if (!Cond->EvaluateAsInt(Result, getContext()))
17090b57cec5SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   llvm::APSInt Int = Result.Val.getInt();
17120b57cec5SDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
17130b57cec5SDimitry Andric     return false;  // Contains a label.
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   ResultInt = Int;
17160b57cec5SDimitry Andric   return true;
17170b57cec5SDimitry Andric }
17180b57cec5SDimitry Andric 
17191db9f3b2SDimitry Andric /// Strip parentheses and simplistic logical-NOT operators.
17201db9f3b2SDimitry Andric const Expr *CodeGenFunction::stripCond(const Expr *C) {
17211db9f3b2SDimitry Andric   while (const UnaryOperator *Op = dyn_cast<UnaryOperator>(C->IgnoreParens())) {
17221db9f3b2SDimitry Andric     if (Op->getOpcode() != UO_LNot)
17231db9f3b2SDimitry Andric       break;
17241db9f3b2SDimitry Andric     C = Op->getSubExpr();
17251db9f3b2SDimitry Andric   }
17261db9f3b2SDimitry Andric   return C->IgnoreParens();
17271db9f3b2SDimitry Andric }
17281db9f3b2SDimitry Andric 
1729e8d8bef9SDimitry Andric /// Determine whether the given condition is an instrumentable condition
1730e8d8bef9SDimitry Andric /// (i.e. no "&&" or "||").
1731e8d8bef9SDimitry Andric bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
17321db9f3b2SDimitry Andric   const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1733e8d8bef9SDimitry Andric   return (!BOp || !BOp->isLogicalOp());
1734e8d8bef9SDimitry Andric }
1735e8d8bef9SDimitry Andric 
1736e8d8bef9SDimitry Andric /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1737e8d8bef9SDimitry Andric /// increments a profile counter based on the semantics of the given logical
1738e8d8bef9SDimitry Andric /// operator opcode.  This is used to instrument branch condition coverage for
1739e8d8bef9SDimitry Andric /// logical operators.
1740e8d8bef9SDimitry Andric void CodeGenFunction::EmitBranchToCounterBlock(
1741e8d8bef9SDimitry Andric     const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1742e8d8bef9SDimitry Andric     llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1743e8d8bef9SDimitry Andric     Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1744e8d8bef9SDimitry Andric   // If not instrumenting, just emit a branch.
1745e8d8bef9SDimitry Andric   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1746e8d8bef9SDimitry Andric   if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1747e8d8bef9SDimitry Andric     return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1748e8d8bef9SDimitry Andric 
174904eeddc0SDimitry Andric   llvm::BasicBlock *ThenBlock = nullptr;
175004eeddc0SDimitry Andric   llvm::BasicBlock *ElseBlock = nullptr;
175104eeddc0SDimitry Andric   llvm::BasicBlock *NextBlock = nullptr;
1752e8d8bef9SDimitry Andric 
1753e8d8bef9SDimitry Andric   // Create the block we'll use to increment the appropriate counter.
1754e8d8bef9SDimitry Andric   llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1755e8d8bef9SDimitry Andric 
1756e8d8bef9SDimitry Andric   // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1757e8d8bef9SDimitry Andric   // means we need to evaluate the condition and increment the counter on TRUE:
1758e8d8bef9SDimitry Andric   //
1759e8d8bef9SDimitry Andric   // if (Cond)
1760e8d8bef9SDimitry Andric   //   goto CounterIncrBlock;
1761e8d8bef9SDimitry Andric   // else
1762e8d8bef9SDimitry Andric   //   goto FalseBlock;
1763e8d8bef9SDimitry Andric   //
1764e8d8bef9SDimitry Andric   // CounterIncrBlock:
1765e8d8bef9SDimitry Andric   //   Counter++;
1766e8d8bef9SDimitry Andric   //   goto TrueBlock;
1767e8d8bef9SDimitry Andric 
1768e8d8bef9SDimitry Andric   if (LOp == BO_LAnd) {
1769e8d8bef9SDimitry Andric     ThenBlock = CounterIncrBlock;
1770e8d8bef9SDimitry Andric     ElseBlock = FalseBlock;
1771e8d8bef9SDimitry Andric     NextBlock = TrueBlock;
1772e8d8bef9SDimitry Andric   }
1773e8d8bef9SDimitry Andric 
1774e8d8bef9SDimitry Andric   // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1775e8d8bef9SDimitry Andric   // we need to evaluate the condition and increment the counter on FALSE:
1776e8d8bef9SDimitry Andric   //
1777e8d8bef9SDimitry Andric   // if (Cond)
1778e8d8bef9SDimitry Andric   //   goto TrueBlock;
1779e8d8bef9SDimitry Andric   // else
1780e8d8bef9SDimitry Andric   //   goto CounterIncrBlock;
1781e8d8bef9SDimitry Andric   //
1782e8d8bef9SDimitry Andric   // CounterIncrBlock:
1783e8d8bef9SDimitry Andric   //   Counter++;
1784e8d8bef9SDimitry Andric   //   goto FalseBlock;
1785e8d8bef9SDimitry Andric 
1786e8d8bef9SDimitry Andric   else if (LOp == BO_LOr) {
1787e8d8bef9SDimitry Andric     ThenBlock = TrueBlock;
1788e8d8bef9SDimitry Andric     ElseBlock = CounterIncrBlock;
1789e8d8bef9SDimitry Andric     NextBlock = FalseBlock;
1790e8d8bef9SDimitry Andric   } else {
1791e8d8bef9SDimitry Andric     llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1792e8d8bef9SDimitry Andric   }
1793e8d8bef9SDimitry Andric 
1794e8d8bef9SDimitry Andric   // Emit Branch based on condition.
1795e8d8bef9SDimitry Andric   EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1796e8d8bef9SDimitry Andric 
1797e8d8bef9SDimitry Andric   // Emit the block containing the counter increment(s).
1798e8d8bef9SDimitry Andric   EmitBlock(CounterIncrBlock);
1799e8d8bef9SDimitry Andric 
1800e8d8bef9SDimitry Andric   // Increment corresponding counter; if index not provided, use Cond as index.
1801e8d8bef9SDimitry Andric   incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
1802e8d8bef9SDimitry Andric 
1803e8d8bef9SDimitry Andric   // Go to the next block.
1804e8d8bef9SDimitry Andric   EmitBranch(NextBlock);
1805e8d8bef9SDimitry Andric }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
18080b57cec5SDimitry Andric /// statement) to the specified blocks.  Based on the condition, this might try
18090b57cec5SDimitry Andric /// to simplify the codegen of the conditional based on the branch.
1810e8d8bef9SDimitry Andric /// \param LH The value of the likelihood attribute on the True branch.
18111db9f3b2SDimitry Andric /// \param ConditionalOp Used by MC/DC code coverage to track the result of the
18121db9f3b2SDimitry Andric /// ConditionalOperator (ternary) through a recursive call for the operator's
18131db9f3b2SDimitry Andric /// LHS and RHS nodes.
18141db9f3b2SDimitry Andric void CodeGenFunction::EmitBranchOnBoolExpr(
18151db9f3b2SDimitry Andric     const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
18161db9f3b2SDimitry Andric     uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp) {
18170b57cec5SDimitry Andric   Cond = Cond->IgnoreParens();
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
18200b57cec5SDimitry Andric     // Handle X && Y in a condition.
18210b57cec5SDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
18221db9f3b2SDimitry Andric       MCDCLogOpStack.push_back(CondBOp);
18231db9f3b2SDimitry Andric 
18240b57cec5SDimitry Andric       // If we have "1 && X", simplify the code.  "0 && X" would have constant
18250b57cec5SDimitry Andric       // folded if the case was simple enough.
18260b57cec5SDimitry Andric       bool ConstantBool = false;
18270b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
18280b57cec5SDimitry Andric           ConstantBool) {
18290b57cec5SDimitry Andric         // br(1 && X) -> br(X).
18300b57cec5SDimitry Andric         incrementProfileCounter(CondBOp);
18311db9f3b2SDimitry Andric         EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1832e8d8bef9SDimitry Andric                                  FalseBlock, TrueCount, LH);
18331db9f3b2SDimitry Andric         MCDCLogOpStack.pop_back();
18341db9f3b2SDimitry Andric         return;
18350b57cec5SDimitry Andric       }
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric       // If we have "X && 1", simplify the code to use an uncond branch.
18380b57cec5SDimitry Andric       // "X && 0" would have been constant folded to 0.
18390b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
18400b57cec5SDimitry Andric           ConstantBool) {
18410b57cec5SDimitry Andric         // br(X && 1) -> br(X).
18421db9f3b2SDimitry Andric         EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1843e8d8bef9SDimitry Andric                                  FalseBlock, TrueCount, LH, CondBOp);
18441db9f3b2SDimitry Andric         MCDCLogOpStack.pop_back();
18451db9f3b2SDimitry Andric         return;
18460b57cec5SDimitry Andric       }
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric       // Emit the LHS as a conditional.  If the LHS conditional is false, we
18490b57cec5SDimitry Andric       // want to jump to the FalseBlock.
18500b57cec5SDimitry Andric       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
18510b57cec5SDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
18520b57cec5SDimitry Andric       // can be propagated to that branch.
18530b57cec5SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric       ConditionalEvaluation eval(*this);
18560b57cec5SDimitry Andric       {
18570b57cec5SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
1858e8d8bef9SDimitry Andric         // Propagate the likelihood attribute like __builtin_expect
1859e8d8bef9SDimitry Andric         // __builtin_expect(X && Y, 1) -> X and Y are likely
1860e8d8bef9SDimitry Andric         // __builtin_expect(X && Y, 0) -> only Y is unlikely
1861e8d8bef9SDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1862e8d8bef9SDimitry Andric                              LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
18630b57cec5SDimitry Andric         EmitBlock(LHSTrue);
18640b57cec5SDimitry Andric       }
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric       incrementProfileCounter(CondBOp);
18670b57cec5SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric       // Any temporaries created here are conditional.
18700b57cec5SDimitry Andric       eval.begin(*this);
1871e8d8bef9SDimitry Andric       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1872e8d8bef9SDimitry Andric                                FalseBlock, TrueCount, LH);
18730b57cec5SDimitry Andric       eval.end(*this);
18741db9f3b2SDimitry Andric       MCDCLogOpStack.pop_back();
18750b57cec5SDimitry Andric       return;
18760b57cec5SDimitry Andric     }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
18791db9f3b2SDimitry Andric       MCDCLogOpStack.push_back(CondBOp);
18801db9f3b2SDimitry Andric 
18810b57cec5SDimitry Andric       // If we have "0 || X", simplify the code.  "1 || X" would have constant
18820b57cec5SDimitry Andric       // folded if the case was simple enough.
18830b57cec5SDimitry Andric       bool ConstantBool = false;
18840b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
18850b57cec5SDimitry Andric           !ConstantBool) {
18860b57cec5SDimitry Andric         // br(0 || X) -> br(X).
18870b57cec5SDimitry Andric         incrementProfileCounter(CondBOp);
18881db9f3b2SDimitry Andric         EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1889e8d8bef9SDimitry Andric                                  FalseBlock, TrueCount, LH);
18901db9f3b2SDimitry Andric         MCDCLogOpStack.pop_back();
18911db9f3b2SDimitry Andric         return;
18920b57cec5SDimitry Andric       }
18930b57cec5SDimitry Andric 
18940b57cec5SDimitry Andric       // If we have "X || 0", simplify the code to use an uncond branch.
18950b57cec5SDimitry Andric       // "X || 1" would have been constant folded to 1.
18960b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
18970b57cec5SDimitry Andric           !ConstantBool) {
18980b57cec5SDimitry Andric         // br(X || 0) -> br(X).
18991db9f3b2SDimitry Andric         EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1900e8d8bef9SDimitry Andric                                  FalseBlock, TrueCount, LH, CondBOp);
19011db9f3b2SDimitry Andric         MCDCLogOpStack.pop_back();
19021db9f3b2SDimitry Andric         return;
19030b57cec5SDimitry Andric       }
19040b57cec5SDimitry Andric       // Emit the LHS as a conditional.  If the LHS conditional is true, we
19050b57cec5SDimitry Andric       // want to jump to the TrueBlock.
19060b57cec5SDimitry Andric       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
19070b57cec5SDimitry Andric       // We have the count for entry to the RHS and for the whole expression
19080b57cec5SDimitry Andric       // being true, so we can divy up True count between the short circuit and
19090b57cec5SDimitry Andric       // the RHS.
19100b57cec5SDimitry Andric       uint64_t LHSCount =
19110b57cec5SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
19120b57cec5SDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric       ConditionalEvaluation eval(*this);
19150b57cec5SDimitry Andric       {
1916e8d8bef9SDimitry Andric         // Propagate the likelihood attribute like __builtin_expect
1917e8d8bef9SDimitry Andric         // __builtin_expect(X || Y, 1) -> only Y is likely
1918e8d8bef9SDimitry Andric         // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
19190b57cec5SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
1920e8d8bef9SDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1921e8d8bef9SDimitry Andric                              LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
19220b57cec5SDimitry Andric         EmitBlock(LHSFalse);
19230b57cec5SDimitry Andric       }
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric       incrementProfileCounter(CondBOp);
19260b57cec5SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric       // Any temporaries created here are conditional.
19290b57cec5SDimitry Andric       eval.begin(*this);
1930e8d8bef9SDimitry Andric       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1931e8d8bef9SDimitry Andric                                RHSCount, LH);
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric       eval.end(*this);
19341db9f3b2SDimitry Andric       MCDCLogOpStack.pop_back();
19350b57cec5SDimitry Andric       return;
19360b57cec5SDimitry Andric     }
19370b57cec5SDimitry Andric   }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
19400b57cec5SDimitry Andric     // br(!x, t, f) -> br(x, f, t)
19411db9f3b2SDimitry Andric     // Avoid doing this optimization when instrumenting a condition for MC/DC.
19421db9f3b2SDimitry Andric     // LNot is taken as part of the condition for simplicity, and changing its
19431db9f3b2SDimitry Andric     // sense negatively impacts test vector tracking.
19441db9f3b2SDimitry Andric     bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
19451db9f3b2SDimitry Andric                          CGM.getCodeGenOpts().MCDCCoverage &&
19461db9f3b2SDimitry Andric                          isInstrumentedCondition(Cond);
19471db9f3b2SDimitry Andric     if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
19480b57cec5SDimitry Andric       // Negate the count.
19490b57cec5SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1950e8d8bef9SDimitry Andric       // The values of the enum are chosen to make this negation possible.
1951e8d8bef9SDimitry Andric       LH = static_cast<Stmt::Likelihood>(-LH);
19520b57cec5SDimitry Andric       // Negate the condition and swap the destination blocks.
19530b57cec5SDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1954e8d8bef9SDimitry Andric                                   FalseCount, LH);
19550b57cec5SDimitry Andric     }
19560b57cec5SDimitry Andric   }
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
19590b57cec5SDimitry Andric     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
19600b57cec5SDimitry Andric     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
19610b57cec5SDimitry Andric     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
19620b57cec5SDimitry Andric 
1963e8d8bef9SDimitry Andric     // The ConditionalOperator itself has no likelihood information for its
1964e8d8bef9SDimitry Andric     // true and false branches. This matches the behavior of __builtin_expect.
19650b57cec5SDimitry Andric     ConditionalEvaluation cond(*this);
19660b57cec5SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1967e8d8bef9SDimitry Andric                          getProfileCount(CondOp), Stmt::LH_None);
19680b57cec5SDimitry Andric 
19690b57cec5SDimitry Andric     // When computing PGO branch weights, we only know the overall count for
19700b57cec5SDimitry Andric     // the true block. This code is essentially doing tail duplication of the
19710b57cec5SDimitry Andric     // naive code-gen, introducing new edges for which counts are not
19720b57cec5SDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
19730b57cec5SDimitry Andric     // the conditional operator.
19740b57cec5SDimitry Andric     uint64_t LHSScaledTrueCount = 0;
19750b57cec5SDimitry Andric     if (TrueCount) {
19760b57cec5SDimitry Andric       double LHSRatio =
19770b57cec5SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
19780b57cec5SDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
19790b57cec5SDimitry Andric     }
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric     cond.begin(*this);
19820b57cec5SDimitry Andric     EmitBlock(LHSBlock);
19830b57cec5SDimitry Andric     incrementProfileCounter(CondOp);
19840b57cec5SDimitry Andric     {
19850b57cec5SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
19860b57cec5SDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
19871db9f3b2SDimitry Andric                            LHSScaledTrueCount, LH, CondOp);
19880b57cec5SDimitry Andric     }
19890b57cec5SDimitry Andric     cond.end(*this);
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric     cond.begin(*this);
19920b57cec5SDimitry Andric     EmitBlock(RHSBlock);
19930b57cec5SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
19941db9f3b2SDimitry Andric                          TrueCount - LHSScaledTrueCount, LH, CondOp);
19950b57cec5SDimitry Andric     cond.end(*this);
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric     return;
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
20010b57cec5SDimitry Andric     // Conditional operator handling can give us a throw expression as a
20020b57cec5SDimitry Andric     // condition for a case like:
20030b57cec5SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
20040b57cec5SDimitry Andric     // Fold this to:
20050b57cec5SDimitry Andric     //   br(c, throw x, br(y, t, f))
20060b57cec5SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
20070b57cec5SDimitry Andric     return;
20080b57cec5SDimitry Andric   }
20090b57cec5SDimitry Andric 
2010fe6060f1SDimitry Andric   // Emit the code with the fully general case.
2011fe6060f1SDimitry Andric   llvm::Value *CondV;
2012fe6060f1SDimitry Andric   {
2013fe6060f1SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
2014fe6060f1SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
2015fe6060f1SDimitry Andric   }
2016fe6060f1SDimitry Andric 
20171db9f3b2SDimitry Andric   // If not at the top of the logical operator nest, update MCDC temp with the
20181db9f3b2SDimitry Andric   // boolean result of the evaluated condition.
20191db9f3b2SDimitry Andric   if (!MCDCLogOpStack.empty()) {
20201db9f3b2SDimitry Andric     const Expr *MCDCBaseExpr = Cond;
20211db9f3b2SDimitry Andric     // When a nested ConditionalOperator (ternary) is encountered in a boolean
20221db9f3b2SDimitry Andric     // expression, MC/DC tracks the result of the ternary, and this is tied to
20231db9f3b2SDimitry Andric     // the ConditionalOperator expression and not the ternary's LHS or RHS. If
20241db9f3b2SDimitry Andric     // this is the case, the ConditionalOperator expression is passed through
20251db9f3b2SDimitry Andric     // the ConditionalOp parameter and then used as the MCDC base expression.
20261db9f3b2SDimitry Andric     if (ConditionalOp)
20271db9f3b2SDimitry Andric       MCDCBaseExpr = ConditionalOp;
20281db9f3b2SDimitry Andric 
20291db9f3b2SDimitry Andric     maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
20301db9f3b2SDimitry Andric   }
20311db9f3b2SDimitry Andric 
2032fe6060f1SDimitry Andric   llvm::MDNode *Weights = nullptr;
2033fe6060f1SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
2034fe6060f1SDimitry Andric 
20350b57cec5SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
20360b57cec5SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
20370b57cec5SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
20380b57cec5SDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
20390b57cec5SDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
20400b57cec5SDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
20410b57cec5SDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
20420b57cec5SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
20430b57cec5SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
20440b57cec5SDimitry Andric     }
20450b57cec5SDimitry Andric   }
20460b57cec5SDimitry Andric 
2047fe6060f1SDimitry Andric   // If there is a Likelihood knowledge for the cond, lower it.
2048fe6060f1SDimitry Andric   // Note that if not optimizing this won't emit anything.
2049fe6060f1SDimitry Andric   llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2050fe6060f1SDimitry Andric   if (CondV != NewCondV)
2051fe6060f1SDimitry Andric     CondV = NewCondV;
2052fe6060f1SDimitry Andric   else {
2053fe6060f1SDimitry Andric     // Otherwise, lower profile counts. Note that we do this even at -O0.
20540b57cec5SDimitry Andric     uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2055e8d8bef9SDimitry Andric     Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2056e8d8bef9SDimitry Andric   }
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
20590b57cec5SDimitry Andric }
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
20620b57cec5SDimitry Andric /// specified stmt yet.
20630b57cec5SDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
20640b57cec5SDimitry Andric   CGM.ErrorUnsupported(S, Type);
20650b57cec5SDimitry Andric }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
20680b57cec5SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
20690b57cec5SDimitry Andric ///
20700b57cec5SDimitry Andric /// \param baseType the inner-most element type of the array
20710b57cec5SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
20720b57cec5SDimitry Andric /// base element of the array
20730b57cec5SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
20740b57cec5SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
20750b57cec5SDimitry Andric                                Address dest, Address src,
20760b57cec5SDimitry Andric                                llvm::Value *sizeInChars) {
20770b57cec5SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
20800b57cec5SDimitry Andric   llvm::Value *baseSizeInChars
20810b57cec5SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
20820b57cec5SDimitry Andric 
208306c3fb27SDimitry Andric   Address begin = dest.withElementType(CGF.Int8Ty);
20840fca6ea1SDimitry Andric   llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
20850fca6ea1SDimitry Andric                                                begin.emitRawPointer(CGF),
20860fca6ea1SDimitry Andric                                                sizeInChars, "vla.end");
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
20890b57cec5SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
20900b57cec5SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
20930b57cec5SDimitry Andric   // count must be nonzero.
20940b57cec5SDimitry Andric   CGF.EmitBlock(loopBB);
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
20970fca6ea1SDimitry Andric   cur->addIncoming(begin.emitRawPointer(CGF), originBB);
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric   CharUnits curAlign =
21000b57cec5SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   // memcpy the individual element bit-pattern.
210381ad6265SDimitry Andric   Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
21040b57cec5SDimitry Andric                        /*volatile*/ false);
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric   // Go to the next element.
21070b57cec5SDimitry Andric   llvm::Value *next =
21080b57cec5SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   // Leave if that's the end of the VLA.
21110b57cec5SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
21120b57cec5SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
21130b57cec5SDimitry Andric   cur->addIncoming(next, loopBB);
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric   CGF.EmitBlock(contBB);
21160b57cec5SDimitry Andric }
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric void
21190b57cec5SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
21200b57cec5SDimitry Andric   // Ignore empty classes in C++.
21210b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus) {
21220b57cec5SDimitry Andric     if (const RecordType *RT = Ty->getAs<RecordType>()) {
21230b57cec5SDimitry Andric       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
21240b57cec5SDimitry Andric         return;
21250b57cec5SDimitry Andric     }
21260b57cec5SDimitry Andric   }
21270b57cec5SDimitry Andric 
21280b57cec5SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
212906c3fb27SDimitry Andric     DestPtr = DestPtr.withElementType(Int8Ty);
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   // Get size and alignment info for this aggregate.
21320b57cec5SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   llvm::Value *SizeVal;
21350b57cec5SDimitry Andric   const VariableArrayType *vla;
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   // Don't bother emitting a zero-byte memset.
21380b57cec5SDimitry Andric   if (size.isZero()) {
21390b57cec5SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
21400b57cec5SDimitry Andric     if (const VariableArrayType *vlaType =
21410b57cec5SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
21420b57cec5SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
21430b57cec5SDimitry Andric       auto VlaSize = getVLASize(vlaType);
21440b57cec5SDimitry Andric       SizeVal = VlaSize.NumElts;
21450b57cec5SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
21460b57cec5SDimitry Andric       if (!eltSize.isOne())
21470b57cec5SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
21480b57cec5SDimitry Andric       vla = vlaType;
21490b57cec5SDimitry Andric     } else {
21500b57cec5SDimitry Andric       return;
21510b57cec5SDimitry Andric     }
21520b57cec5SDimitry Andric   } else {
21530b57cec5SDimitry Andric     SizeVal = CGM.getSize(size);
21540b57cec5SDimitry Andric     vla = nullptr;
21550b57cec5SDimitry Andric   }
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
21580b57cec5SDimitry Andric   // Instead, create a null constant and copy it to the destination.
21590b57cec5SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
21600b57cec5SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
21610b57cec5SDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
21620b57cec5SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
21630b57cec5SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric     llvm::GlobalVariable *NullVariable =
21680b57cec5SDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
21690b57cec5SDimitry Andric                                /*isConstant=*/true,
21700b57cec5SDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
21710b57cec5SDimitry Andric                                NullConstant, Twine());
21720b57cec5SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
2173a7dea167SDimitry Andric     NullVariable->setAlignment(NullAlign.getAsAlign());
21745f757f3fSDimitry Andric     Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
21790b57cec5SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
21800b57cec5SDimitry Andric     return;
21810b57cec5SDimitry Andric   }
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
21840b57cec5SDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
21850b57cec5SDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
21860b57cec5SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
21870b57cec5SDimitry Andric }
21880b57cec5SDimitry Andric 
21890b57cec5SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
21900b57cec5SDimitry Andric   // Make sure that there is a block for the indirect goto.
21910b57cec5SDimitry Andric   if (!IndirectBranch)
21920b57cec5SDimitry Andric     GetIndirectGotoBlock();
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric   // Make sure the indirect branch includes all of the address-taken blocks.
21970b57cec5SDimitry Andric   IndirectBranch->addDestination(BB);
21980b57cec5SDimitry Andric   return llvm::BlockAddress::get(CurFn, BB);
21990b57cec5SDimitry Andric }
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
22020b57cec5SDimitry Andric   // If we already made the indirect branch for indirect goto, return its block.
22030b57cec5SDimitry Andric   if (IndirectBranch) return IndirectBranch->getParent();
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric   // Create the PHI node that indirect gotos will add entries to.
22080b57cec5SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
22090b57cec5SDimitry Andric                                               "indirect.goto.dest");
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric   // Create the indirect branch instruction.
22120b57cec5SDimitry Andric   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
22130b57cec5SDimitry Andric   return IndirectBranch->getParent();
22140b57cec5SDimitry Andric }
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric /// Computes the length of an array in elements, as well as the base
22170b57cec5SDimitry Andric /// element type and a properly-typed first element pointer.
22180b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
22190b57cec5SDimitry Andric                                               QualType &baseType,
22200b57cec5SDimitry Andric                                               Address &addr) {
22210b57cec5SDimitry Andric   const ArrayType *arrayType = origArrayType;
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
22240b57cec5SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
22250b57cec5SDimitry Andric   llvm::Value *numVLAElements = nullptr;
22260b57cec5SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
22270b57cec5SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
22300b57cec5SDimitry Andric     // which has type T* where T is the first non-VLA element type.
22310b57cec5SDimitry Andric     do {
22320b57cec5SDimitry Andric       QualType elementType = arrayType->getElementType();
22330b57cec5SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
22340b57cec5SDimitry Andric 
22350b57cec5SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
22360b57cec5SDimitry Andric       if (!arrayType) {
22370b57cec5SDimitry Andric         baseType = elementType;
22380b57cec5SDimitry Andric         return numVLAElements;
22390b57cec5SDimitry Andric       }
22400b57cec5SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric     // We get out here only if we find a constant array type
22430b57cec5SDimitry Andric     // inside the VLA.
22440b57cec5SDimitry Andric   }
22450b57cec5SDimitry Andric 
22460b57cec5SDimitry Andric   // We have some number of constant-length arrays, so addr should
22470b57cec5SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
22480b57cec5SDimitry Andric   // down to the first element of addr.
22490b57cec5SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric   // GEP down to the array type.
22520b57cec5SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
22530b57cec5SDimitry Andric   gepIndices.push_back(zero);
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric   uint64_t countFromCLAs = 1;
22560b57cec5SDimitry Andric   QualType eltType;
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric   llvm::ArrayType *llvmArrayType =
22590b57cec5SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
22600b57cec5SDimitry Andric   while (llvmArrayType) {
22610b57cec5SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
22620fca6ea1SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
22630fca6ea1SDimitry Andric            llvmArrayType->getNumElements());
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric     gepIndices.push_back(zero);
22660b57cec5SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
22670b57cec5SDimitry Andric     eltType = arrayType->getElementType();
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric     llvmArrayType =
22700b57cec5SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
22710b57cec5SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
22720b57cec5SDimitry Andric     assert((!llvmArrayType || arrayType) &&
22730b57cec5SDimitry Andric            "LLVM and Clang types are out-of-synch");
22740b57cec5SDimitry Andric   }
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric   if (arrayType) {
22770b57cec5SDimitry Andric     // From this point onwards, the Clang array type has been emitted
22780b57cec5SDimitry Andric     // as some other type (probably a packed struct). Compute the array
22790b57cec5SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
22800b57cec5SDimitry Andric     while (arrayType) {
22810fca6ea1SDimitry Andric       countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
22820b57cec5SDimitry Andric       eltType = arrayType->getElementType();
22830b57cec5SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
22840b57cec5SDimitry Andric     }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
228706c3fb27SDimitry Andric     addr = addr.withElementType(baseType);
22880b57cec5SDimitry Andric   } else {
22890b57cec5SDimitry Andric     // Create the actual GEP.
22900fca6ea1SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
22910fca6ea1SDimitry Andric                                              addr.emitRawPointer(*this),
22920fca6ea1SDimitry Andric                                              gepIndices, "array.begin"),
22930fca6ea1SDimitry Andric                    ConvertTypeForMem(eltType), addr.getAlignment());
22940b57cec5SDimitry Andric   }
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric   baseType = eltType;
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   llvm::Value *numElements
22990b57cec5SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric   // If we had any VLA dimensions, factor them in.
23020b57cec5SDimitry Andric   if (numVLAElements)
23030b57cec5SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric   return numElements;
23060b57cec5SDimitry Andric }
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
23090b57cec5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
23100b57cec5SDimitry Andric   assert(vla && "type was not a variable array type!");
23110b57cec5SDimitry Andric   return getVLASize(vla);
23120b57cec5SDimitry Andric }
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
23150b57cec5SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
23160b57cec5SDimitry Andric   // The number of elements so far; always size_t.
23170b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric   QualType elementType;
23200b57cec5SDimitry Andric   do {
23210b57cec5SDimitry Andric     elementType = type->getElementType();
23220b57cec5SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
23230b57cec5SDimitry Andric     assert(vlaSize && "no size for VLA!");
23240b57cec5SDimitry Andric     assert(vlaSize->getType() == SizeTy);
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric     if (!numElements) {
23270b57cec5SDimitry Andric       numElements = vlaSize;
23280b57cec5SDimitry Andric     } else {
23290b57cec5SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
23300b57cec5SDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
23310b57cec5SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
23320b57cec5SDimitry Andric     }
23330b57cec5SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric   return { numElements, elementType };
23360b57cec5SDimitry Andric }
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
23390b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(QualType type) {
23400b57cec5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
23410b57cec5SDimitry Andric   assert(vla && "type was not a variable array type!");
23420b57cec5SDimitry Andric   return getVLAElements1D(vla);
23430b57cec5SDimitry Andric }
23440b57cec5SDimitry Andric 
23450b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
23460b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
23470b57cec5SDimitry Andric   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
23480b57cec5SDimitry Andric   assert(VlaSize && "no size for VLA!");
23490b57cec5SDimitry Andric   assert(VlaSize->getType() == SizeTy);
23500b57cec5SDimitry Andric   return { VlaSize, Vla->getElementType() };
23510b57cec5SDimitry Andric }
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
23540b57cec5SDimitry Andric   assert(type->isVariablyModifiedType() &&
23550b57cec5SDimitry Andric          "Must pass variably modified type to EmitVLASizes!");
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   EnsureInsertPoint();
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   // We're going to walk down into the type and look for VLA
23600b57cec5SDimitry Andric   // expressions.
23610b57cec5SDimitry Andric   do {
23620b57cec5SDimitry Andric     assert(type->isVariablyModifiedType());
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric     const Type *ty = type.getTypePtr();
23650b57cec5SDimitry Andric     switch (ty->getTypeClass()) {
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric #define TYPE(Class, Base)
23680b57cec5SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
23690b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
23700b57cec5SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
23710b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2372a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
23730b57cec5SDimitry Andric       llvm_unreachable("unexpected dependent type!");
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric     // These types are never variably-modified.
23760b57cec5SDimitry Andric     case Type::Builtin:
23770b57cec5SDimitry Andric     case Type::Complex:
23780b57cec5SDimitry Andric     case Type::Vector:
23790b57cec5SDimitry Andric     case Type::ExtVector:
23805ffd83dbSDimitry Andric     case Type::ConstantMatrix:
23810b57cec5SDimitry Andric     case Type::Record:
23820b57cec5SDimitry Andric     case Type::Enum:
23830eae32dcSDimitry Andric     case Type::Using:
23840b57cec5SDimitry Andric     case Type::TemplateSpecialization:
23850b57cec5SDimitry Andric     case Type::ObjCTypeParam:
23860b57cec5SDimitry Andric     case Type::ObjCObject:
23870b57cec5SDimitry Andric     case Type::ObjCInterface:
23880b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
23890eae32dcSDimitry Andric     case Type::BitInt:
23900b57cec5SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
23910b57cec5SDimitry Andric 
2392bdd1243dSDimitry Andric     case Type::Elaborated:
2393bdd1243dSDimitry Andric       type = cast<ElaboratedType>(ty)->getNamedType();
2394bdd1243dSDimitry Andric       break;
2395bdd1243dSDimitry Andric 
23960b57cec5SDimitry Andric     case Type::Adjusted:
23970b57cec5SDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
23980b57cec5SDimitry Andric       break;
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric     case Type::Decayed:
24010b57cec5SDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
24020b57cec5SDimitry Andric       break;
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric     case Type::Pointer:
24050b57cec5SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
24060b57cec5SDimitry Andric       break;
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric     case Type::BlockPointer:
24090b57cec5SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
24100b57cec5SDimitry Andric       break;
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric     case Type::LValueReference:
24130b57cec5SDimitry Andric     case Type::RValueReference:
24140b57cec5SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
24150b57cec5SDimitry Andric       break;
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric     case Type::MemberPointer:
24180b57cec5SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
24190b57cec5SDimitry Andric       break;
24200b57cec5SDimitry Andric 
24210fca6ea1SDimitry Andric     case Type::ArrayParameter:
24220b57cec5SDimitry Andric     case Type::ConstantArray:
24230b57cec5SDimitry Andric     case Type::IncompleteArray:
24240b57cec5SDimitry Andric       // Losing element qualification here is fine.
24250b57cec5SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
24260b57cec5SDimitry Andric       break;
24270b57cec5SDimitry Andric 
24280b57cec5SDimitry Andric     case Type::VariableArray: {
24290b57cec5SDimitry Andric       // Losing element qualification here is fine.
24300b57cec5SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric       // Unknown size indication requires no size computation.
24330b57cec5SDimitry Andric       // Otherwise, evaluate and record it.
243404eeddc0SDimitry Andric       if (const Expr *sizeExpr = vat->getSizeExpr()) {
24350b57cec5SDimitry Andric         // It's possible that we might have emitted this already,
24360b57cec5SDimitry Andric         // e.g. with a typedef and a pointer to it.
243704eeddc0SDimitry Andric         llvm::Value *&entry = VLASizeMap[sizeExpr];
24380b57cec5SDimitry Andric         if (!entry) {
243904eeddc0SDimitry Andric           llvm::Value *size = EmitScalarExpr(sizeExpr);
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric           // C11 6.7.6.2p5:
24420b57cec5SDimitry Andric           //   If the size is an expression that is not an integer constant
24430b57cec5SDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
24440b57cec5SDimitry Andric           //   greater than zero.
244504eeddc0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound)) {
24460b57cec5SDimitry Andric             SanitizerScope SanScope(this);
244704eeddc0SDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
244804eeddc0SDimitry Andric             clang::QualType SEType = sizeExpr->getType();
244904eeddc0SDimitry Andric             llvm::Value *CheckCondition =
245004eeddc0SDimitry Andric                 SEType->isSignedIntegerType()
245104eeddc0SDimitry Andric                     ? Builder.CreateICmpSGT(size, Zero)
245204eeddc0SDimitry Andric                     : Builder.CreateICmpUGT(size, Zero);
24530b57cec5SDimitry Andric             llvm::Constant *StaticArgs[] = {
245404eeddc0SDimitry Andric                 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
245504eeddc0SDimitry Andric                 EmitCheckTypeDescriptor(SEType)};
245604eeddc0SDimitry Andric             EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
245704eeddc0SDimitry Andric                       SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
24580b57cec5SDimitry Andric           }
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric           // Always zexting here would be wrong if it weren't
24610b57cec5SDimitry Andric           // undefined behavior to have a negative bound.
246204eeddc0SDimitry Andric           // FIXME: What about when size's type is larger than size_t?
246304eeddc0SDimitry Andric           entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
24640b57cec5SDimitry Andric         }
24650b57cec5SDimitry Andric       }
24660b57cec5SDimitry Andric       type = vat->getElementType();
24670b57cec5SDimitry Andric       break;
24680b57cec5SDimitry Andric     }
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric     case Type::FunctionProto:
24710b57cec5SDimitry Andric     case Type::FunctionNoProto:
24720b57cec5SDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
24730b57cec5SDimitry Andric       break;
24740b57cec5SDimitry Andric 
24750b57cec5SDimitry Andric     case Type::Paren:
24760b57cec5SDimitry Andric     case Type::TypeOf:
24770b57cec5SDimitry Andric     case Type::UnaryTransform:
24780b57cec5SDimitry Andric     case Type::Attributed:
247981ad6265SDimitry Andric     case Type::BTFTagAttributed:
24800b57cec5SDimitry Andric     case Type::SubstTemplateTypeParm:
24810b57cec5SDimitry Andric     case Type::MacroQualified:
24820fca6ea1SDimitry Andric     case Type::CountAttributed:
24830b57cec5SDimitry Andric       // Keep walking after single level desugaring.
24840b57cec5SDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
24850b57cec5SDimitry Andric       break;
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric     case Type::Typedef:
24880b57cec5SDimitry Andric     case Type::Decltype:
24890b57cec5SDimitry Andric     case Type::Auto:
24900b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
24910fca6ea1SDimitry Andric     case Type::PackIndexing:
24920b57cec5SDimitry Andric       // Stop walking: nothing to do.
24930b57cec5SDimitry Andric       return;
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric     case Type::TypeOfExpr:
24960b57cec5SDimitry Andric       // Stop walking: emit typeof expression.
24970b57cec5SDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
24980b57cec5SDimitry Andric       return;
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric     case Type::Atomic:
25010b57cec5SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
25020b57cec5SDimitry Andric       break;
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric     case Type::Pipe:
25050b57cec5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
25060b57cec5SDimitry Andric       break;
25070b57cec5SDimitry Andric     }
25080b57cec5SDimitry Andric   } while (type->isVariablyModifiedType());
25090b57cec5SDimitry Andric }
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
25120b57cec5SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
25130b57cec5SDimitry Andric     return EmitPointerWithAlignment(E);
25140fca6ea1SDimitry Andric   return EmitLValue(E).getAddress();
25150b57cec5SDimitry Andric }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
25180fca6ea1SDimitry Andric   return EmitLValue(E).getAddress();
25190b57cec5SDimitry Andric }
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
25220b57cec5SDimitry Andric                                               const APValue &Init) {
25230b57cec5SDimitry Andric   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
25240b57cec5SDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
2525480093f4SDimitry Andric     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
25260b57cec5SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
25270b57cec5SDimitry Andric }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric CodeGenFunction::PeepholeProtection
25300b57cec5SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
25310b57cec5SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
25320b57cec5SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
25330b57cec5SDimitry Andric   // extend this protection.
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
25360b57cec5SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
25370b57cec5SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric   // Just make an extra bitcast.
25400b57cec5SDimitry Andric   assert(HaveInsertPoint());
25410b57cec5SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
25420b57cec5SDimitry Andric                                                   Builder.GetInsertBlock());
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric   PeepholeProtection protection;
25450b57cec5SDimitry Andric   protection.Inst = inst;
25460b57cec5SDimitry Andric   return protection;
25470b57cec5SDimitry Andric }
25480b57cec5SDimitry Andric 
25490b57cec5SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
25500b57cec5SDimitry Andric   if (!protection.Inst) return;
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
25530b57cec5SDimitry Andric   protection.Inst->eraseFromParent();
25540b57cec5SDimitry Andric }
25550b57cec5SDimitry Andric 
25565ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
25570b57cec5SDimitry Andric                                               QualType Ty, SourceLocation Loc,
25580b57cec5SDimitry Andric                                               SourceLocation AssumptionLoc,
25590b57cec5SDimitry Andric                                               llvm::Value *Alignment,
25600b57cec5SDimitry Andric                                               llvm::Value *OffsetValue) {
2561e8d8bef9SDimitry Andric   if (Alignment->getType() != IntPtrTy)
2562e8d8bef9SDimitry Andric     Alignment =
2563e8d8bef9SDimitry Andric         Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2564e8d8bef9SDimitry Andric   if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2565e8d8bef9SDimitry Andric     OffsetValue =
2566e8d8bef9SDimitry Andric         Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2567e8d8bef9SDimitry Andric   llvm::Value *TheCheck = nullptr;
2568590d96feSDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment)) {
2569e8d8bef9SDimitry Andric     llvm::Value *PtrIntValue =
2570e8d8bef9SDimitry Andric         Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2571e8d8bef9SDimitry Andric 
2572e8d8bef9SDimitry Andric     if (OffsetValue) {
2573e8d8bef9SDimitry Andric       bool IsOffsetZero = false;
2574e8d8bef9SDimitry Andric       if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2575e8d8bef9SDimitry Andric         IsOffsetZero = CI->isZero();
2576e8d8bef9SDimitry Andric 
2577e8d8bef9SDimitry Andric       if (!IsOffsetZero)
2578e8d8bef9SDimitry Andric         PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2579e8d8bef9SDimitry Andric     }
2580e8d8bef9SDimitry Andric 
2581e8d8bef9SDimitry Andric     llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2582e8d8bef9SDimitry Andric     llvm::Value *Mask =
2583e8d8bef9SDimitry Andric         Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2584e8d8bef9SDimitry Andric     llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2585e8d8bef9SDimitry Andric     TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2586e8d8bef9SDimitry Andric   }
2587e8d8bef9SDimitry Andric   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2588e8d8bef9SDimitry Andric       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2589e8d8bef9SDimitry Andric 
2590e8d8bef9SDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
2591e8d8bef9SDimitry Andric     return;
25925ffd83dbSDimitry Andric   emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
25935ffd83dbSDimitry Andric                                OffsetValue, TheCheck, Assumption);
25945ffd83dbSDimitry Andric }
25955ffd83dbSDimitry Andric 
25965ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
25970b57cec5SDimitry Andric                                               const Expr *E,
25980b57cec5SDimitry Andric                                               SourceLocation AssumptionLoc,
2599a7dea167SDimitry Andric                                               llvm::Value *Alignment,
26000b57cec5SDimitry Andric                                               llvm::Value *OffsetValue) {
26010b57cec5SDimitry Andric   QualType Ty = E->getType();
26020b57cec5SDimitry Andric   SourceLocation Loc = E->getExprLoc();
26030b57cec5SDimitry Andric 
26045ffd83dbSDimitry Andric   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
26050b57cec5SDimitry Andric                           OffsetValue);
26060b57cec5SDimitry Andric }
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
26090b57cec5SDimitry Andric                                                  llvm::Value *AnnotatedVal,
26100b57cec5SDimitry Andric                                                  StringRef AnnotationStr,
2611e8d8bef9SDimitry Andric                                                  SourceLocation Location,
2612e8d8bef9SDimitry Andric                                                  const AnnotateAttr *Attr) {
2613e8d8bef9SDimitry Andric   SmallVector<llvm::Value *, 5> Args = {
26140b57cec5SDimitry Andric       AnnotatedVal,
26155f757f3fSDimitry Andric       CGM.EmitAnnotationString(AnnotationStr),
26165f757f3fSDimitry Andric       CGM.EmitAnnotationUnit(Location),
2617e8d8bef9SDimitry Andric       CGM.EmitAnnotationLineNo(Location),
26180b57cec5SDimitry Andric   };
2619e8d8bef9SDimitry Andric   if (Attr)
2620e8d8bef9SDimitry Andric     Args.push_back(CGM.EmitAnnotationArgs(Attr));
26210b57cec5SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
26220b57cec5SDimitry Andric }
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
26250b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
26260b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2627bdd1243dSDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
26285f757f3fSDimitry Andric                                         {V->getType(), CGM.ConstGlobalsPtrTy}),
26295f757f3fSDimitry Andric                        V, I->getAnnotation(), D->getLocation(), I);
26300b57cec5SDimitry Andric }
26310b57cec5SDimitry Andric 
26320b57cec5SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
26330b57cec5SDimitry Andric                                               Address Addr) {
26340b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
26350fca6ea1SDimitry Andric   llvm::Value *V = Addr.emitRawPointer(*this);
26360b57cec5SDimitry Andric   llvm::Type *VTy = V->getType();
2637349cc55cSDimitry Andric   auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2638349cc55cSDimitry Andric   unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2639349cc55cSDimitry Andric   llvm::PointerType *IntrinTy =
264006c3fb27SDimitry Andric       llvm::PointerType::get(CGM.getLLVMContext(), AS);
2641bdd1243dSDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2642bdd1243dSDimitry Andric                                        {IntrinTy, CGM.ConstGlobalsPtrTy});
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
26450b57cec5SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
26460b57cec5SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
26470b57cec5SDimitry Andric     // itself.
2648349cc55cSDimitry Andric     if (VTy != IntrinTy)
2649349cc55cSDimitry Andric       V = Builder.CreateBitCast(V, IntrinTy);
2650e8d8bef9SDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
26510b57cec5SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
26520b57cec5SDimitry Andric   }
26530b57cec5SDimitry Andric 
265481ad6265SDimitry Andric   return Address(V, Addr.getElementType(), Addr.getAlignment());
26550b57cec5SDimitry Andric }
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
26580b57cec5SDimitry Andric 
26590b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
26600b57cec5SDimitry Andric     : CGF(CGF) {
26610b57cec5SDimitry Andric   assert(!CGF->IsSanitizerScope);
26620b57cec5SDimitry Andric   CGF->IsSanitizerScope = true;
26630b57cec5SDimitry Andric }
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
26660b57cec5SDimitry Andric   CGF->IsSanitizerScope = false;
26670b57cec5SDimitry Andric }
26680b57cec5SDimitry Andric 
26690b57cec5SDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
26700b57cec5SDimitry Andric                                    const llvm::Twine &Name,
26710b57cec5SDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
26720b57cec5SDimitry Andric   LoopStack.InsertHelper(I);
26730b57cec5SDimitry Andric   if (IsSanitizerScope)
267406c3fb27SDimitry Andric     I->setNoSanitizeMetadata();
26750b57cec5SDimitry Andric }
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric void CGBuilderInserter::InsertHelper(
26780fca6ea1SDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name,
26790b57cec5SDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
26800fca6ea1SDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
26810b57cec5SDimitry Andric   if (CGF)
26820fca6ea1SDimitry Andric     CGF->InsertHelper(I, Name, InsertPt);
26830b57cec5SDimitry Andric }
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the
26860b57cec5SDimitry Andric // called function.
26870b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
26880b57cec5SDimitry Andric                                           const FunctionDecl *TargetDecl) {
26890fca6ea1SDimitry Andric   // SemaChecking cannot handle below x86 builtins because they have different
26900fca6ea1SDimitry Andric   // parameter ranges with different TargetAttribute of caller.
26910fca6ea1SDimitry Andric   if (CGM.getContext().getTargetInfo().getTriple().isX86()) {
26920fca6ea1SDimitry Andric     unsigned BuiltinID = TargetDecl->getBuiltinID();
26930fca6ea1SDimitry Andric     if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
26940fca6ea1SDimitry Andric         BuiltinID == X86::BI__builtin_ia32_cmpss ||
26950fca6ea1SDimitry Andric         BuiltinID == X86::BI__builtin_ia32_cmppd ||
26960fca6ea1SDimitry Andric         BuiltinID == X86::BI__builtin_ia32_cmpsd) {
26970fca6ea1SDimitry Andric       const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
26980fca6ea1SDimitry Andric       llvm::StringMap<bool> TargetFetureMap;
26990fca6ea1SDimitry Andric       CGM.getContext().getFunctionFeatureMap(TargetFetureMap, FD);
27000fca6ea1SDimitry Andric       llvm::APSInt Result =
27010fca6ea1SDimitry Andric           *(E->getArg(2)->getIntegerConstantExpr(CGM.getContext()));
27020fca6ea1SDimitry Andric       if (Result.getSExtValue() > 7 && !TargetFetureMap.lookup("avx"))
27030fca6ea1SDimitry Andric         CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
27040fca6ea1SDimitry Andric             << TargetDecl->getDeclName() << "avx";
27050fca6ea1SDimitry Andric     }
27060fca6ea1SDimitry Andric   }
27070b57cec5SDimitry Andric   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
27080b57cec5SDimitry Andric }
27090b57cec5SDimitry Andric 
27100b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the
27110b57cec5SDimitry Andric // called function.
27120b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
27130b57cec5SDimitry Andric                                           const FunctionDecl *TargetDecl) {
27140b57cec5SDimitry Andric   // Early exit if this is an indirect call.
27150b57cec5SDimitry Andric   if (!TargetDecl)
27160b57cec5SDimitry Andric     return;
27170b57cec5SDimitry Andric 
27180b57cec5SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
27190b57cec5SDimitry Andric   // we can't check the target features anyhow.
2720a7dea167SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
27210b57cec5SDimitry Andric   if (!FD)
27220b57cec5SDimitry Andric     return;
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
27250b57cec5SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
27260b57cec5SDimitry Andric   // listed cpu and any listed features.
27270b57cec5SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
27280b57cec5SDimitry Andric   std::string MissingFeature;
2729e8d8bef9SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
2730e8d8bef9SDimitry Andric   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
27315f757f3fSDimitry Andric   // When compiling in HipStdPar mode we have to be conservative in rejecting
27325f757f3fSDimitry Andric   // target specific features in the FE, and defer the possible error to the
27335f757f3fSDimitry Andric   // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
27345f757f3fSDimitry Andric   // referenced by an accelerator executable function, we emit an error.
27355f757f3fSDimitry Andric   bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
27360b57cec5SDimitry Andric   if (BuiltinID) {
273781ad6265SDimitry Andric     StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
273881ad6265SDimitry Andric     if (!Builtin::evaluateRequiredTargetFeatures(
27395f757f3fSDimitry Andric         FeatureList, CallerFeatureMap) && !IsHipStdPar) {
27400b57cec5SDimitry Andric       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
274181ad6265SDimitry Andric           << TargetDecl->getDeclName()
274281ad6265SDimitry Andric           << FeatureList;
274381ad6265SDimitry Andric     }
2744480093f4SDimitry Andric   } else if (!TargetDecl->isMultiVersion() &&
2745480093f4SDimitry Andric              TargetDecl->hasAttr<TargetAttr>()) {
27460b57cec5SDimitry Andric     // Get the required features for the callee.
27470b57cec5SDimitry Andric 
27480b57cec5SDimitry Andric     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2749480093f4SDimitry Andric     ParsedTargetAttr ParsedAttr =
2750480093f4SDimitry Andric         CGM.getContext().filterFunctionTargetAttrs(TD);
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
27530b57cec5SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
2754c3ca3130SDimitry Andric     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
27550b57cec5SDimitry Andric 
27560b57cec5SDimitry Andric     for (const auto &F : ParsedAttr.Features) {
27570b57cec5SDimitry Andric       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
27580b57cec5SDimitry Andric         ReqFeatures.push_back(StringRef(F).substr(1));
27590b57cec5SDimitry Andric     }
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
27620b57cec5SDimitry Andric       // Only positive features are "required".
27630b57cec5SDimitry Andric       if (F.getValue())
27640b57cec5SDimitry Andric         ReqFeatures.push_back(F.getKey());
27650b57cec5SDimitry Andric     }
2766e8d8bef9SDimitry Andric     if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2767e8d8bef9SDimitry Andric       if (!CallerFeatureMap.lookup(Feature)) {
2768e8d8bef9SDimitry Andric         MissingFeature = Feature.str();
2769e8d8bef9SDimitry Andric         return false;
2770e8d8bef9SDimitry Andric       }
2771e8d8bef9SDimitry Andric       return true;
27725f757f3fSDimitry Andric     }) && !IsHipStdPar)
27730b57cec5SDimitry Andric       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
27740b57cec5SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
277506c3fb27SDimitry Andric   } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) {
277606c3fb27SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
277706c3fb27SDimitry Andric     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
277806c3fb27SDimitry Andric 
277906c3fb27SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
278006c3fb27SDimitry Andric       if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
27815f757f3fSDimitry Andric                            !CallerFeatureMap.find(F.getKey())->getValue()) &&
27825f757f3fSDimitry Andric           !IsHipStdPar)
278306c3fb27SDimitry Andric         CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
278406c3fb27SDimitry Andric             << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
278506c3fb27SDimitry Andric     }
27860b57cec5SDimitry Andric   }
27870b57cec5SDimitry Andric }
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
27900b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
27910b57cec5SDimitry Andric     return;
27920b57cec5SDimitry Andric 
27930b57cec5SDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
27940b57cec5SDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
27950b57cec5SDimitry Andric   CGM.getSanStats().create(IRB, SSK);
27960b57cec5SDimitry Andric }
27970b57cec5SDimitry Andric 
2798bdd1243dSDimitry Andric void CodeGenFunction::EmitKCFIOperandBundle(
2799bdd1243dSDimitry Andric     const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2800bdd1243dSDimitry Andric   const FunctionProtoType *FP =
2801bdd1243dSDimitry Andric       Callee.getAbstractInfo().getCalleeFunctionProtoType();
2802bdd1243dSDimitry Andric   if (FP)
2803bdd1243dSDimitry Andric     Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar()));
2804bdd1243dSDimitry Andric }
2805bdd1243dSDimitry Andric 
2806bdd1243dSDimitry Andric llvm::Value *CodeGenFunction::FormAArch64ResolverCondition(
2807bdd1243dSDimitry Andric     const MultiVersionResolverOption &RO) {
2808bdd1243dSDimitry Andric   llvm::SmallVector<StringRef, 8> CondFeatures;
28090fca6ea1SDimitry Andric   for (const StringRef &Feature : RO.Conditions.Features)
2810bdd1243dSDimitry Andric     CondFeatures.push_back(Feature);
2811bdd1243dSDimitry Andric   if (!CondFeatures.empty()) {
2812bdd1243dSDimitry Andric     return EmitAArch64CpuSupports(CondFeatures);
2813bdd1243dSDimitry Andric   }
2814bdd1243dSDimitry Andric   return nullptr;
2815bdd1243dSDimitry Andric }
2816bdd1243dSDimitry Andric 
2817bdd1243dSDimitry Andric llvm::Value *CodeGenFunction::FormX86ResolverCondition(
2818bdd1243dSDimitry Andric     const MultiVersionResolverOption &RO) {
28190b57cec5SDimitry Andric   llvm::Value *Condition = nullptr;
28200b57cec5SDimitry Andric 
28215f757f3fSDimitry Andric   if (!RO.Conditions.Architecture.empty()) {
28225f757f3fSDimitry Andric     StringRef Arch = RO.Conditions.Architecture;
28235f757f3fSDimitry Andric     // If arch= specifies an x86-64 micro-architecture level, test the feature
28245f757f3fSDimitry Andric     // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
28255f757f3fSDimitry Andric     if (Arch.starts_with("x86-64"))
28265f757f3fSDimitry Andric       Condition = EmitX86CpuSupports({Arch});
28275f757f3fSDimitry Andric     else
28285f757f3fSDimitry Andric       Condition = EmitX86CpuIs(Arch);
28295f757f3fSDimitry Andric   }
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric   if (!RO.Conditions.Features.empty()) {
28320b57cec5SDimitry Andric     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
28330b57cec5SDimitry Andric     Condition =
28340b57cec5SDimitry Andric         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
28350b57cec5SDimitry Andric   }
28360b57cec5SDimitry Andric   return Condition;
28370b57cec5SDimitry Andric }
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
28400b57cec5SDimitry Andric                                              llvm::Function *Resolver,
28410b57cec5SDimitry Andric                                              CGBuilderTy &Builder,
28420b57cec5SDimitry Andric                                              llvm::Function *FuncToReturn,
28430b57cec5SDimitry Andric                                              bool SupportsIFunc) {
28440b57cec5SDimitry Andric   if (SupportsIFunc) {
28450b57cec5SDimitry Andric     Builder.CreateRet(FuncToReturn);
28460b57cec5SDimitry Andric     return;
28470b57cec5SDimitry Andric   }
28480b57cec5SDimitry Andric 
284981ad6265SDimitry Andric   llvm::SmallVector<llvm::Value *, 10> Args(
285081ad6265SDimitry Andric       llvm::make_pointer_range(Resolver->args()));
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
28530b57cec5SDimitry Andric   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric   if (Resolver->getReturnType()->isVoidTy())
28560b57cec5SDimitry Andric     Builder.CreateRetVoid();
28570b57cec5SDimitry Andric   else
28580b57cec5SDimitry Andric     Builder.CreateRet(Result);
28590b57cec5SDimitry Andric }
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric void CodeGenFunction::EmitMultiVersionResolver(
28620b57cec5SDimitry Andric     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2863bdd1243dSDimitry Andric 
2864bdd1243dSDimitry Andric   llvm::Triple::ArchType ArchType =
2865bdd1243dSDimitry Andric       getContext().getTargetInfo().getTriple().getArch();
2866bdd1243dSDimitry Andric 
2867bdd1243dSDimitry Andric   switch (ArchType) {
2868bdd1243dSDimitry Andric   case llvm::Triple::x86:
2869bdd1243dSDimitry Andric   case llvm::Triple::x86_64:
2870bdd1243dSDimitry Andric     EmitX86MultiVersionResolver(Resolver, Options);
2871bdd1243dSDimitry Andric     return;
2872bdd1243dSDimitry Andric   case llvm::Triple::aarch64:
2873bdd1243dSDimitry Andric     EmitAArch64MultiVersionResolver(Resolver, Options);
2874bdd1243dSDimitry Andric     return;
2875bdd1243dSDimitry Andric 
2876bdd1243dSDimitry Andric   default:
2877bdd1243dSDimitry Andric     assert(false && "Only implemented for x86 and AArch64 targets");
2878bdd1243dSDimitry Andric   }
2879bdd1243dSDimitry Andric }
2880bdd1243dSDimitry Andric 
2881bdd1243dSDimitry Andric void CodeGenFunction::EmitAArch64MultiVersionResolver(
2882bdd1243dSDimitry Andric     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2883bdd1243dSDimitry Andric   assert(!Options.empty() && "No multiversion resolver options found");
2884bdd1243dSDimitry Andric   assert(Options.back().Conditions.Features.size() == 0 &&
2885bdd1243dSDimitry Andric          "Default case must be last");
2886bdd1243dSDimitry Andric   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2887bdd1243dSDimitry Andric   assert(SupportsIFunc &&
2888bdd1243dSDimitry Andric          "Multiversion resolver requires target IFUNC support");
2889bdd1243dSDimitry Andric   bool AArch64CpuInitialized = false;
2890bdd1243dSDimitry Andric   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2891bdd1243dSDimitry Andric 
2892bdd1243dSDimitry Andric   for (const MultiVersionResolverOption &RO : Options) {
2893bdd1243dSDimitry Andric     Builder.SetInsertPoint(CurBlock);
2894bdd1243dSDimitry Andric     llvm::Value *Condition = FormAArch64ResolverCondition(RO);
2895bdd1243dSDimitry Andric 
2896bdd1243dSDimitry Andric     // The 'default' or 'all features enabled' case.
2897bdd1243dSDimitry Andric     if (!Condition) {
2898bdd1243dSDimitry Andric       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2899bdd1243dSDimitry Andric                                        SupportsIFunc);
2900bdd1243dSDimitry Andric       return;
2901bdd1243dSDimitry Andric     }
2902bdd1243dSDimitry Andric 
2903bdd1243dSDimitry Andric     if (!AArch64CpuInitialized) {
2904bdd1243dSDimitry Andric       Builder.SetInsertPoint(CurBlock, CurBlock->begin());
2905bdd1243dSDimitry Andric       EmitAArch64CpuInit();
2906bdd1243dSDimitry Andric       AArch64CpuInitialized = true;
2907bdd1243dSDimitry Andric       Builder.SetInsertPoint(CurBlock);
2908bdd1243dSDimitry Andric     }
2909bdd1243dSDimitry Andric 
2910bdd1243dSDimitry Andric     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2911bdd1243dSDimitry Andric     CGBuilderTy RetBuilder(*this, RetBlock);
2912bdd1243dSDimitry Andric     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2913bdd1243dSDimitry Andric                                      SupportsIFunc);
2914bdd1243dSDimitry Andric     CurBlock = createBasicBlock("resolver_else", Resolver);
2915bdd1243dSDimitry Andric     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2916bdd1243dSDimitry Andric   }
2917bdd1243dSDimitry Andric 
2918bdd1243dSDimitry Andric   // If no default, emit an unreachable.
2919bdd1243dSDimitry Andric   Builder.SetInsertPoint(CurBlock);
2920bdd1243dSDimitry Andric   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2921bdd1243dSDimitry Andric   TrapCall->setDoesNotReturn();
2922bdd1243dSDimitry Andric   TrapCall->setDoesNotThrow();
2923bdd1243dSDimitry Andric   Builder.CreateUnreachable();
2924bdd1243dSDimitry Andric   Builder.ClearInsertionPoint();
2925bdd1243dSDimitry Andric }
2926bdd1243dSDimitry Andric 
2927bdd1243dSDimitry Andric void CodeGenFunction::EmitX86MultiVersionResolver(
2928bdd1243dSDimitry Andric     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric   // Main function's basic block.
29330b57cec5SDimitry Andric   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
29340b57cec5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
29350b57cec5SDimitry Andric   EmitX86CpuInit();
29360b57cec5SDimitry Andric 
29370b57cec5SDimitry Andric   for (const MultiVersionResolverOption &RO : Options) {
29380b57cec5SDimitry Andric     Builder.SetInsertPoint(CurBlock);
2939bdd1243dSDimitry Andric     llvm::Value *Condition = FormX86ResolverCondition(RO);
29400b57cec5SDimitry Andric 
29410b57cec5SDimitry Andric     // The 'default' or 'generic' case.
29420b57cec5SDimitry Andric     if (!Condition) {
29430b57cec5SDimitry Andric       assert(&RO == Options.end() - 1 &&
29440b57cec5SDimitry Andric              "Default or Generic case must be last");
29450b57cec5SDimitry Andric       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
29460b57cec5SDimitry Andric                                        SupportsIFunc);
29470b57cec5SDimitry Andric       return;
29480b57cec5SDimitry Andric     }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
29510b57cec5SDimitry Andric     CGBuilderTy RetBuilder(*this, RetBlock);
29520b57cec5SDimitry Andric     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
29530b57cec5SDimitry Andric                                      SupportsIFunc);
29540b57cec5SDimitry Andric     CurBlock = createBasicBlock("resolver_else", Resolver);
29550b57cec5SDimitry Andric     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
29560b57cec5SDimitry Andric   }
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   // If no generic/default, emit an unreachable.
29590b57cec5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
29600b57cec5SDimitry Andric   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
29610b57cec5SDimitry Andric   TrapCall->setDoesNotReturn();
29620b57cec5SDimitry Andric   TrapCall->setDoesNotThrow();
29630b57cec5SDimitry Andric   Builder.CreateUnreachable();
29640b57cec5SDimitry Andric   Builder.ClearInsertionPoint();
29650b57cec5SDimitry Andric }
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric // Loc - where the diagnostic will point, where in the source code this
29680b57cec5SDimitry Andric //  alignment has failed.
29690b57cec5SDimitry Andric // SecondaryLoc - if present (will be present if sufficiently different from
29700b57cec5SDimitry Andric //  Loc), the diagnostic will additionally point a "Note:" to this location.
29710b57cec5SDimitry Andric //  It should be the location where the __attribute__((assume_aligned))
29720b57cec5SDimitry Andric //  was written e.g.
29735ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumptionCheck(
29740b57cec5SDimitry Andric     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
29750b57cec5SDimitry Andric     SourceLocation SecondaryLoc, llvm::Value *Alignment,
29760b57cec5SDimitry Andric     llvm::Value *OffsetValue, llvm::Value *TheCheck,
29770b57cec5SDimitry Andric     llvm::Instruction *Assumption) {
29780fca6ea1SDimitry Andric   assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
29795ffd83dbSDimitry Andric          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
29800b57cec5SDimitry Andric              llvm::Intrinsic::getDeclaration(
29810b57cec5SDimitry Andric                  Builder.GetInsertBlock()->getParent()->getParent(),
29820b57cec5SDimitry Andric                  llvm::Intrinsic::assume) &&
29830b57cec5SDimitry Andric          "Assumption should be a call to llvm.assume().");
29840b57cec5SDimitry Andric   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
29850b57cec5SDimitry Andric          "Assumption should be the last instruction of the basic block, "
29860b57cec5SDimitry Andric          "since the basic block is still being generated.");
29870b57cec5SDimitry Andric 
29880b57cec5SDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
29890b57cec5SDimitry Andric     return;
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
29920b57cec5SDimitry Andric   // defined.
29930b57cec5SDimitry Andric   if (Ty->getPointeeType().isVolatileQualified())
29940b57cec5SDimitry Andric     return;
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric   // We need to temorairly remove the assumption so we can insert the
29970b57cec5SDimitry Andric   // sanitizer check before it, else the check will be dropped by optimizations.
29980b57cec5SDimitry Andric   Assumption->removeFromParent();
29990b57cec5SDimitry Andric 
30000b57cec5SDimitry Andric   {
30010b57cec5SDimitry Andric     SanitizerScope SanScope(this);
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric     if (!OffsetValue)
300404eeddc0SDimitry Andric       OffsetValue = Builder.getInt1(false); // no offset.
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
30070b57cec5SDimitry Andric                                     EmitCheckSourceLocation(SecondaryLoc),
30080b57cec5SDimitry Andric                                     EmitCheckTypeDescriptor(Ty)};
30090b57cec5SDimitry Andric     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
30100b57cec5SDimitry Andric                                   EmitCheckValue(Alignment),
30110b57cec5SDimitry Andric                                   EmitCheckValue(OffsetValue)};
30120b57cec5SDimitry Andric     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
30130b57cec5SDimitry Andric               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
30140b57cec5SDimitry Andric   }
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric   // We are now in the (new, empty) "cont" basic block.
30170b57cec5SDimitry Andric   // Reintroduce the assumption.
30180b57cec5SDimitry Andric   Builder.Insert(Assumption);
30190b57cec5SDimitry Andric   // FIXME: Assumption still has it's original basic block as it's Parent.
30200b57cec5SDimitry Andric }
30210b57cec5SDimitry Andric 
30220b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
30230b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
30240b57cec5SDimitry Andric     return DI->SourceLocToDebugLoc(Location);
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric   return llvm::DebugLoc();
30270b57cec5SDimitry Andric }
3028e8d8bef9SDimitry Andric 
3029fe6060f1SDimitry Andric llvm::Value *
3030fe6060f1SDimitry Andric CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3031fe6060f1SDimitry Andric                                                       Stmt::Likelihood LH) {
3032e8d8bef9SDimitry Andric   switch (LH) {
3033e8d8bef9SDimitry Andric   case Stmt::LH_None:
3034fe6060f1SDimitry Andric     return Cond;
3035e8d8bef9SDimitry Andric   case Stmt::LH_Likely:
3036fe6060f1SDimitry Andric   case Stmt::LH_Unlikely:
3037fe6060f1SDimitry Andric     // Don't generate llvm.expect on -O0 as the backend won't use it for
3038fe6060f1SDimitry Andric     // anything.
3039fe6060f1SDimitry Andric     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3040fe6060f1SDimitry Andric       return Cond;
3041fe6060f1SDimitry Andric     llvm::Type *CondTy = Cond->getType();
3042fe6060f1SDimitry Andric     assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3043fe6060f1SDimitry Andric     llvm::Function *FnExpect =
3044fe6060f1SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3045fe6060f1SDimitry Andric     llvm::Value *ExpectedValueOfCond =
3046fe6060f1SDimitry Andric         llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3047fe6060f1SDimitry Andric     return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3048fe6060f1SDimitry Andric                               Cond->getName() + ".expval");
3049e8d8bef9SDimitry Andric   }
3050e8d8bef9SDimitry Andric   llvm_unreachable("Unknown Likelihood");
3051e8d8bef9SDimitry Andric }
305281ad6265SDimitry Andric 
305381ad6265SDimitry Andric llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
305481ad6265SDimitry Andric                                                     unsigned NumElementsDst,
305581ad6265SDimitry Andric                                                     const llvm::Twine &Name) {
305681ad6265SDimitry Andric   auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
305781ad6265SDimitry Andric   unsigned NumElementsSrc = SrcTy->getNumElements();
305881ad6265SDimitry Andric   if (NumElementsSrc == NumElementsDst)
305981ad6265SDimitry Andric     return SrcVec;
306081ad6265SDimitry Andric 
306181ad6265SDimitry Andric   std::vector<int> ShuffleMask(NumElementsDst, -1);
306281ad6265SDimitry Andric   for (unsigned MaskIdx = 0;
306381ad6265SDimitry Andric        MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
306481ad6265SDimitry Andric     ShuffleMask[MaskIdx] = MaskIdx;
306581ad6265SDimitry Andric 
306681ad6265SDimitry Andric   return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
306781ad6265SDimitry Andric }
30680fca6ea1SDimitry Andric 
30690fca6ea1SDimitry Andric void CodeGenFunction::EmitPointerAuthOperandBundle(
30700fca6ea1SDimitry Andric     const CGPointerAuthInfo &PointerAuth,
30710fca6ea1SDimitry Andric     SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
30720fca6ea1SDimitry Andric   if (!PointerAuth.isSigned())
30730fca6ea1SDimitry Andric     return;
30740fca6ea1SDimitry Andric 
30750fca6ea1SDimitry Andric   auto *Key = Builder.getInt32(PointerAuth.getKey());
30760fca6ea1SDimitry Andric 
30770fca6ea1SDimitry Andric   llvm::Value *Discriminator = PointerAuth.getDiscriminator();
30780fca6ea1SDimitry Andric   if (!Discriminator)
30790fca6ea1SDimitry Andric     Discriminator = Builder.getSize(0);
30800fca6ea1SDimitry Andric 
30810fca6ea1SDimitry Andric   llvm::Value *Args[] = {Key, Discriminator};
30820fca6ea1SDimitry Andric   Bundles.emplace_back("ptrauth", Args);
30830fca6ea1SDimitry Andric }
30840fca6ea1SDimitry Andric 
30850fca6ea1SDimitry Andric static llvm::Value *EmitPointerAuthCommon(CodeGenFunction &CGF,
30860fca6ea1SDimitry Andric                                           const CGPointerAuthInfo &PointerAuth,
30870fca6ea1SDimitry Andric                                           llvm::Value *Pointer,
30880fca6ea1SDimitry Andric                                           unsigned IntrinsicID) {
30890fca6ea1SDimitry Andric   if (!PointerAuth)
30900fca6ea1SDimitry Andric     return Pointer;
30910fca6ea1SDimitry Andric 
30920fca6ea1SDimitry Andric   auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
30930fca6ea1SDimitry Andric 
30940fca6ea1SDimitry Andric   llvm::Value *Discriminator = PointerAuth.getDiscriminator();
30950fca6ea1SDimitry Andric   if (!Discriminator) {
30960fca6ea1SDimitry Andric     Discriminator = CGF.Builder.getSize(0);
30970fca6ea1SDimitry Andric   }
30980fca6ea1SDimitry Andric 
30990fca6ea1SDimitry Andric   // Convert the pointer to intptr_t before signing it.
31000fca6ea1SDimitry Andric   auto OrigType = Pointer->getType();
31010fca6ea1SDimitry Andric   Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
31020fca6ea1SDimitry Andric 
31030fca6ea1SDimitry Andric   // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
31040fca6ea1SDimitry Andric   auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
31050fca6ea1SDimitry Andric   Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
31060fca6ea1SDimitry Andric 
31070fca6ea1SDimitry Andric   // Convert back to the original type.
31080fca6ea1SDimitry Andric   Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
31090fca6ea1SDimitry Andric   return Pointer;
31100fca6ea1SDimitry Andric }
31110fca6ea1SDimitry Andric 
31120fca6ea1SDimitry Andric llvm::Value *
31130fca6ea1SDimitry Andric CodeGenFunction::EmitPointerAuthSign(const CGPointerAuthInfo &PointerAuth,
31140fca6ea1SDimitry Andric                                      llvm::Value *Pointer) {
31150fca6ea1SDimitry Andric   if (!PointerAuth.shouldSign())
31160fca6ea1SDimitry Andric     return Pointer;
31170fca6ea1SDimitry Andric   return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
31180fca6ea1SDimitry Andric                                llvm::Intrinsic::ptrauth_sign);
31190fca6ea1SDimitry Andric }
31200fca6ea1SDimitry Andric 
31210fca6ea1SDimitry Andric static llvm::Value *EmitStrip(CodeGenFunction &CGF,
31220fca6ea1SDimitry Andric                               const CGPointerAuthInfo &PointerAuth,
31230fca6ea1SDimitry Andric                               llvm::Value *Pointer) {
31240fca6ea1SDimitry Andric   auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
31250fca6ea1SDimitry Andric 
31260fca6ea1SDimitry Andric   auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
31270fca6ea1SDimitry Andric   // Convert the pointer to intptr_t before signing it.
31280fca6ea1SDimitry Andric   auto OrigType = Pointer->getType();
31290fca6ea1SDimitry Andric   Pointer = CGF.EmitRuntimeCall(
31300fca6ea1SDimitry Andric       StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
31310fca6ea1SDimitry Andric   return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
31320fca6ea1SDimitry Andric }
31330fca6ea1SDimitry Andric 
31340fca6ea1SDimitry Andric llvm::Value *
31350fca6ea1SDimitry Andric CodeGenFunction::EmitPointerAuthAuth(const CGPointerAuthInfo &PointerAuth,
31360fca6ea1SDimitry Andric                                      llvm::Value *Pointer) {
31370fca6ea1SDimitry Andric   if (PointerAuth.shouldStrip()) {
31380fca6ea1SDimitry Andric     return EmitStrip(*this, PointerAuth, Pointer);
31390fca6ea1SDimitry Andric   }
31400fca6ea1SDimitry Andric   if (!PointerAuth.shouldAuth()) {
31410fca6ea1SDimitry Andric     return Pointer;
31420fca6ea1SDimitry Andric   }
31430fca6ea1SDimitry Andric 
31440fca6ea1SDimitry Andric   return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
31450fca6ea1SDimitry Andric                                llvm::Intrinsic::ptrauth_auth);
31460fca6ea1SDimitry Andric }
3147