10b57cec5SDimitry Andric //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-function state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenFunction.h"
140b57cec5SDimitry Andric #include "CGBlocks.h"
150b57cec5SDimitry Andric #include "CGCUDARuntime.h"
160b57cec5SDimitry Andric #include "CGCXXABI.h"
17480093f4SDimitry Andric #include "CGCleanup.h"
180b57cec5SDimitry Andric #include "CGDebugInfo.h"
190b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
200b57cec5SDimitry Andric #include "CodeGenModule.h"
210b57cec5SDimitry Andric #include "CodeGenPGO.h"
220b57cec5SDimitry Andric #include "TargetInfo.h"
230b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
240b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
25480093f4SDimitry Andric #include "clang/AST/Attr.h"
260b57cec5SDimitry Andric #include "clang/AST/Decl.h"
270b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
28e8d8bef9SDimitry Andric #include "clang/AST/Expr.h"
290b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
300b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h"
310b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
320b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
330b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
340b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
350b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
36e8d8bef9SDimitry Andric #include "llvm/ADT/ArrayRef.h"
375ffd83dbSDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
380b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
390b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
40480093f4SDimitry Andric #include "llvm/IR/FPEnv.h"
41480093f4SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
420b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
430b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
440b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
45e8d8bef9SDimitry Andric #include "llvm/Support/CRC.h"
46e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
470b57cec5SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
48349cc55cSDimitry Andric 
490b57cec5SDimitry Andric using namespace clang;
500b57cec5SDimitry Andric using namespace CodeGen;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
530b57cec5SDimitry Andric /// markers.
540b57cec5SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
550b57cec5SDimitry Andric                                       const LangOptions &LangOpts) {
560b57cec5SDimitry Andric   if (CGOpts.DisableLifetimeMarkers)
570b57cec5SDimitry Andric     return false;
580b57cec5SDimitry Andric 
59a7dea167SDimitry Andric   // Sanitizers may use markers.
60a7dea167SDimitry Andric   if (CGOpts.SanitizeAddressUseAfterScope ||
61a7dea167SDimitry Andric       LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
62a7dea167SDimitry Andric       LangOpts.Sanitize.has(SanitizerKind::Memory))
630b57cec5SDimitry Andric     return true;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   // For now, only in optimized builds.
660b57cec5SDimitry Andric   return CGOpts.OptimizationLevel != 0;
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
700b57cec5SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
710b57cec5SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
720b57cec5SDimitry Andric               CGBuilderInserterTy(this)),
735ffd83dbSDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
745ffd83dbSDimitry Andric       DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
755ffd83dbSDimitry Andric       ShouldEmitLifetimeMarkers(
765ffd83dbSDimitry Andric           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
770b57cec5SDimitry Andric   if (!suppressNewContext)
780b57cec5SDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
79fe6060f1SDimitry Andric   EHStack.setCGF(this);
800b57cec5SDimitry Andric 
815ffd83dbSDimitry Andric   SetFastMathFlags(CurFPFeatures);
820b57cec5SDimitry Andric }
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric CodeGenFunction::~CodeGenFunction() {
850b57cec5SDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric   if (getLangOpts().OpenMP && CurFn)
880b57cec5SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
890b57cec5SDimitry Andric 
905ffd83dbSDimitry Andric   // If we have an OpenMPIRBuilder we want to finalize functions (incl.
915ffd83dbSDimitry Andric   // outlining etc) at some point. Doing it once the function codegen is done
925ffd83dbSDimitry Andric   // seems to be a reasonable spot. We do it here, as opposed to the deletion
935ffd83dbSDimitry Andric   // time of the CodeGenModule, because we have to ensure the IR has not yet
945ffd83dbSDimitry Andric   // been "emitted" to the outside, thus, modifications are still sensible.
95fe6060f1SDimitry Andric   if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
96fe6060f1SDimitry Andric     CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
97480093f4SDimitry Andric }
98480093f4SDimitry Andric 
99480093f4SDimitry Andric // Map the LangOption for exception behavior into
100480093f4SDimitry Andric // the corresponding enum in the IR.
1015ffd83dbSDimitry Andric llvm::fp::ExceptionBehavior
1025ffd83dbSDimitry Andric clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
103480093f4SDimitry Andric 
104480093f4SDimitry Andric   switch (Kind) {
105480093f4SDimitry Andric   case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
106480093f4SDimitry Andric   case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
107480093f4SDimitry Andric   case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
108480093f4SDimitry Andric   }
109480093f4SDimitry Andric   llvm_unreachable("Unsupported FP Exception Behavior");
110480093f4SDimitry Andric }
111480093f4SDimitry Andric 
1125ffd83dbSDimitry Andric void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
1135ffd83dbSDimitry Andric   llvm::FastMathFlags FMF;
1145ffd83dbSDimitry Andric   FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
1155ffd83dbSDimitry Andric   FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
1165ffd83dbSDimitry Andric   FMF.setNoInfs(FPFeatures.getNoHonorInfs());
1175ffd83dbSDimitry Andric   FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
1185ffd83dbSDimitry Andric   FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
1195ffd83dbSDimitry Andric   FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
1205ffd83dbSDimitry Andric   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
1215ffd83dbSDimitry Andric   Builder.setFastMathFlags(FMF);
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
1245ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
125e8d8bef9SDimitry Andric                                                   const Expr *E)
126e8d8bef9SDimitry Andric     : CGF(CGF) {
127e8d8bef9SDimitry Andric   ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
128e8d8bef9SDimitry Andric }
129e8d8bef9SDimitry Andric 
130e8d8bef9SDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
1315ffd83dbSDimitry Andric                                                   FPOptions FPFeatures)
132e8d8bef9SDimitry Andric     : CGF(CGF) {
133e8d8bef9SDimitry Andric   ConstructorHelper(FPFeatures);
134e8d8bef9SDimitry Andric }
135e8d8bef9SDimitry Andric 
136e8d8bef9SDimitry Andric void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
137e8d8bef9SDimitry Andric   OldFPFeatures = CGF.CurFPFeatures;
1385ffd83dbSDimitry Andric   CGF.CurFPFeatures = FPFeatures;
1390b57cec5SDimitry Andric 
140e8d8bef9SDimitry Andric   OldExcept = CGF.Builder.getDefaultConstrainedExcept();
141e8d8bef9SDimitry Andric   OldRounding = CGF.Builder.getDefaultConstrainedRounding();
142e8d8bef9SDimitry Andric 
1435ffd83dbSDimitry Andric   if (OldFPFeatures == FPFeatures)
1445ffd83dbSDimitry Andric     return;
1455ffd83dbSDimitry Andric 
1465ffd83dbSDimitry Andric   FMFGuard.emplace(CGF.Builder);
1475ffd83dbSDimitry Andric 
1485ffd83dbSDimitry Andric   llvm::RoundingMode NewRoundingBehavior =
1495ffd83dbSDimitry Andric       static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
1505ffd83dbSDimitry Andric   CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
1515ffd83dbSDimitry Andric   auto NewExceptionBehavior =
1525ffd83dbSDimitry Andric       ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
1535ffd83dbSDimitry Andric           FPFeatures.getFPExceptionMode()));
1545ffd83dbSDimitry Andric   CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
1555ffd83dbSDimitry Andric 
1565ffd83dbSDimitry Andric   CGF.SetFastMathFlags(FPFeatures);
1575ffd83dbSDimitry Andric 
1585ffd83dbSDimitry Andric   assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
1595ffd83dbSDimitry Andric           isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
1605ffd83dbSDimitry Andric           isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
1615ffd83dbSDimitry Andric           (NewExceptionBehavior == llvm::fp::ebIgnore &&
1625ffd83dbSDimitry Andric            NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
1635ffd83dbSDimitry Andric          "FPConstrained should be enabled on entire function");
1645ffd83dbSDimitry Andric 
1655ffd83dbSDimitry Andric   auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
1665ffd83dbSDimitry Andric     auto OldValue =
167fe6060f1SDimitry Andric         CGF.CurFn->getFnAttribute(Name).getValueAsBool();
1685ffd83dbSDimitry Andric     auto NewValue = OldValue & Value;
1695ffd83dbSDimitry Andric     if (OldValue != NewValue)
1705ffd83dbSDimitry Andric       CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
1715ffd83dbSDimitry Andric   };
1725ffd83dbSDimitry Andric   mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
1735ffd83dbSDimitry Andric   mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
1745ffd83dbSDimitry Andric   mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
1755ffd83dbSDimitry Andric   mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
1765ffd83dbSDimitry Andric                                          FPFeatures.getAllowReciprocal() &&
1775ffd83dbSDimitry Andric                                          FPFeatures.getAllowApproxFunc() &&
1785ffd83dbSDimitry Andric                                          FPFeatures.getNoSignedZero());
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1815ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
1825ffd83dbSDimitry Andric   CGF.CurFPFeatures = OldFPFeatures;
183e8d8bef9SDimitry Andric   CGF.Builder.setDefaultConstrainedExcept(OldExcept);
184e8d8bef9SDimitry Andric   CGF.Builder.setDefaultConstrainedRounding(OldRounding);
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1880b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
1890b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
1905ffd83dbSDimitry Andric   CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
1910eae32dcSDimitry Andric   Address Addr(V, ConvertTypeForMem(T), Alignment);
1920eae32dcSDimitry Andric   return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1960b57cec5SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1970b57cec5SDimitry Andric LValue
1980b57cec5SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
1990b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
2000b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
2015ffd83dbSDimitry Andric   CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
2020b57cec5SDimitry Andric                                                 /* forPointeeType= */ true);
2030eae32dcSDimitry Andric   Address Addr(V, ConvertTypeForMem(T), Align);
2040eae32dcSDimitry Andric   return MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
2090b57cec5SDimitry Andric   return CGM.getTypes().ConvertTypeForMem(T);
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
2130b57cec5SDimitry Andric   return CGM.getTypes().ConvertType(T);
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
2170b57cec5SDimitry Andric   type = type.getCanonicalType();
2180b57cec5SDimitry Andric   while (true) {
2190b57cec5SDimitry Andric     switch (type->getTypeClass()) {
2200b57cec5SDimitry Andric #define TYPE(name, parent)
2210b57cec5SDimitry Andric #define ABSTRACT_TYPE(name, parent)
2220b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
2230b57cec5SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
2240b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
225a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
2260b57cec5SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric     case Type::Auto:
2290b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
2300b57cec5SDimitry Andric       llvm_unreachable("undeduced type in IR-generation");
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric     // Various scalar types.
2330b57cec5SDimitry Andric     case Type::Builtin:
2340b57cec5SDimitry Andric     case Type::Pointer:
2350b57cec5SDimitry Andric     case Type::BlockPointer:
2360b57cec5SDimitry Andric     case Type::LValueReference:
2370b57cec5SDimitry Andric     case Type::RValueReference:
2380b57cec5SDimitry Andric     case Type::MemberPointer:
2390b57cec5SDimitry Andric     case Type::Vector:
2400b57cec5SDimitry Andric     case Type::ExtVector:
2415ffd83dbSDimitry Andric     case Type::ConstantMatrix:
2420b57cec5SDimitry Andric     case Type::FunctionProto:
2430b57cec5SDimitry Andric     case Type::FunctionNoProto:
2440b57cec5SDimitry Andric     case Type::Enum:
2450b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
2460b57cec5SDimitry Andric     case Type::Pipe:
2470eae32dcSDimitry Andric     case Type::BitInt:
2480b57cec5SDimitry Andric       return TEK_Scalar;
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric     // Complexes.
2510b57cec5SDimitry Andric     case Type::Complex:
2520b57cec5SDimitry Andric       return TEK_Complex;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     // Arrays, records, and Objective-C objects.
2550b57cec5SDimitry Andric     case Type::ConstantArray:
2560b57cec5SDimitry Andric     case Type::IncompleteArray:
2570b57cec5SDimitry Andric     case Type::VariableArray:
2580b57cec5SDimitry Andric     case Type::Record:
2590b57cec5SDimitry Andric     case Type::ObjCObject:
2600b57cec5SDimitry Andric     case Type::ObjCInterface:
2610b57cec5SDimitry Andric       return TEK_Aggregate;
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     // We operate on atomic values according to their underlying type.
2640b57cec5SDimitry Andric     case Type::Atomic:
2650b57cec5SDimitry Andric       type = cast<AtomicType>(type)->getValueType();
2660b57cec5SDimitry Andric       continue;
2670b57cec5SDimitry Andric     }
2680b57cec5SDimitry Andric     llvm_unreachable("unknown type kind!");
2690b57cec5SDimitry Andric   }
2700b57cec5SDimitry Andric }
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
2730b57cec5SDimitry Andric   // For cleanliness, we try to avoid emitting the return block for
2740b57cec5SDimitry Andric   // simple cases.
2750b57cec5SDimitry Andric   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   if (CurBB) {
2780b57cec5SDimitry Andric     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     // We have a valid insert point, reuse it if it is empty or there are no
2810b57cec5SDimitry Andric     // explicit jumps to the return block.
2820b57cec5SDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
2830b57cec5SDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
2840b57cec5SDimitry Andric       delete ReturnBlock.getBlock();
2850b57cec5SDimitry Andric       ReturnBlock = JumpDest();
2860b57cec5SDimitry Andric     } else
2870b57cec5SDimitry Andric       EmitBlock(ReturnBlock.getBlock());
2880b57cec5SDimitry Andric     return llvm::DebugLoc();
2890b57cec5SDimitry Andric   }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   // Otherwise, if the return block is the target of a single direct
2920b57cec5SDimitry Andric   // branch then we can just put the code in that block instead. This
2930b57cec5SDimitry Andric   // cleans up functions which started with a unified return block.
2940b57cec5SDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
2950b57cec5SDimitry Andric     llvm::BranchInst *BI =
2960b57cec5SDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
2970b57cec5SDimitry Andric     if (BI && BI->isUnconditional() &&
2980b57cec5SDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
2990b57cec5SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
3000b57cec5SDimitry Andric       // later by the actual 'ret' instruction.
3010b57cec5SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
3020b57cec5SDimitry Andric       Builder.SetInsertPoint(BI->getParent());
3030b57cec5SDimitry Andric       BI->eraseFromParent();
3040b57cec5SDimitry Andric       delete ReturnBlock.getBlock();
3050b57cec5SDimitry Andric       ReturnBlock = JumpDest();
3060b57cec5SDimitry Andric       return Loc;
3070b57cec5SDimitry Andric     }
3080b57cec5SDimitry Andric   }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   // FIXME: We are at an unreachable point, there is no reason to emit the block
3110b57cec5SDimitry Andric   // unless it has uses. However, we still need a place to put the debug
3120b57cec5SDimitry Andric   // region.end for now.
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   EmitBlock(ReturnBlock.getBlock());
3150b57cec5SDimitry Andric   return llvm::DebugLoc();
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
3190b57cec5SDimitry Andric   if (!BB) return;
3200b57cec5SDimitry Andric   if (!BB->use_empty())
3210b57cec5SDimitry Andric     return CGF.CurFn->getBasicBlockList().push_back(BB);
3220b57cec5SDimitry Andric   delete BB;
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
3260b57cec5SDimitry Andric   assert(BreakContinueStack.empty() &&
3270b57cec5SDimitry Andric          "mismatched push/pop in break/continue stack!");
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
3300b57cec5SDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
3310b57cec5SDimitry Andric     && ReturnBlock.getBlock()->use_empty();
3320b57cec5SDimitry Andric   // Usually the return expression is evaluated before the cleanup
3330b57cec5SDimitry Andric   // code.  If the function contains only a simple return statement,
3340b57cec5SDimitry Andric   // such as a constant, the location before the cleanup code becomes
3350b57cec5SDimitry Andric   // the last useful breakpoint in the function, because the simple
3360b57cec5SDimitry Andric   // return expression will be evaluated after the cleanup code. To be
3370b57cec5SDimitry Andric   // safe, set the debug location for cleanup code to the location of
3380b57cec5SDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
3390b57cec5SDimitry Andric   // end of the function's lexical scope.
3400b57cec5SDimitry Andric   //
3410b57cec5SDimitry Andric   // If there are multiple branches to the return block, the branch
3420b57cec5SDimitry Andric   // instructions will get the location of the return statements and
3430b57cec5SDimitry Andric   // all will be fine.
3440b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
3450b57cec5SDimitry Andric     if (OnlySimpleReturnStmts)
3460b57cec5SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
3470b57cec5SDimitry Andric     else
3480b57cec5SDimitry Andric       DI->EmitLocation(Builder, EndLoc);
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   // Pop any cleanups that might have been associated with the
3520b57cec5SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
3530b57cec5SDimitry Andric   // important to do this before we enter the return block or return
3540b57cec5SDimitry Andric   // edges will be *really* confused.
3550b57cec5SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
3560b57cec5SDimitry Andric   bool HasOnlyLifetimeMarkers =
3570b57cec5SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
3580b57cec5SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
3590b57cec5SDimitry Andric   if (HasCleanups) {
3600b57cec5SDimitry Andric     // Make sure the line table doesn't jump back into the body for
3610b57cec5SDimitry Andric     // the ret after it's been at EndLoc.
362480093f4SDimitry Andric     Optional<ApplyDebugLocation> AL;
363480093f4SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo()) {
3640b57cec5SDimitry Andric       if (OnlySimpleReturnStmts)
3650b57cec5SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
366480093f4SDimitry Andric       else
367480093f4SDimitry Andric         // We may not have a valid end location. Try to apply it anyway, and
368480093f4SDimitry Andric         // fall back to an artificial location if needed.
369480093f4SDimitry Andric         AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
370480093f4SDimitry Andric     }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   // Emit function epilog (to return).
3760b57cec5SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   if (ShouldInstrumentFunction()) {
3790b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
3800b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
3810b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
3820b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-exit-inlined",
3830b57cec5SDimitry Andric                        "__cyg_profile_func_exit");
3840b57cec5SDimitry Andric   }
3850b57cec5SDimitry Andric 
386349cc55cSDimitry Andric   if (ShouldSkipSanitizerInstrumentation())
387349cc55cSDimitry Andric     CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
388349cc55cSDimitry Andric 
3890b57cec5SDimitry Andric   // Emit debug descriptor for function end.
3900b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
3910b57cec5SDimitry Andric     DI->EmitFunctionEnd(Builder, CurFn);
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
3940b57cec5SDimitry Andric   // rather than that of the end of the function's scope '}'.
3950b57cec5SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
3960b57cec5SDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
3970b57cec5SDimitry Andric   EmitEndEHSpec(CurCodeDecl);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   assert(EHStack.empty() &&
4000b57cec5SDimitry Andric          "did not remove all scopes from cleanup stack!");
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // If someone did an indirect goto, emit the indirect goto block at the end of
4030b57cec5SDimitry Andric   // the function.
4040b57cec5SDimitry Andric   if (IndirectBranch) {
4050b57cec5SDimitry Andric     EmitBlock(IndirectBranch->getParent());
4060b57cec5SDimitry Andric     Builder.ClearInsertionPoint();
4070b57cec5SDimitry Andric   }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
4100b57cec5SDimitry Andric   // entry block.
4110b57cec5SDimitry Andric   if (!EscapedLocals.empty()) {
4120b57cec5SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
4130b57cec5SDimitry Andric     // no holes.
4140b57cec5SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
4150b57cec5SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
4160b57cec5SDimitry Andric     for (auto &Pair : EscapedLocals)
4170b57cec5SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
4180b57cec5SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
4190b57cec5SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
4200b57cec5SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
4210b57cec5SDimitry Andric   }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
4240b57cec5SDimitry Andric   llvm::Instruction *Ptr = AllocaInsertPt;
4250b57cec5SDimitry Andric   AllocaInsertPt = nullptr;
4260b57cec5SDimitry Andric   Ptr->eraseFromParent();
4270b57cec5SDimitry Andric 
428349cc55cSDimitry Andric   // PostAllocaInsertPt, if created, was lazily created when it was required,
429349cc55cSDimitry Andric   // remove it now since it was just created for our own convenience.
430349cc55cSDimitry Andric   if (PostAllocaInsertPt) {
431349cc55cSDimitry Andric     llvm::Instruction *PostPtr = PostAllocaInsertPt;
432349cc55cSDimitry Andric     PostAllocaInsertPt = nullptr;
433349cc55cSDimitry Andric     PostPtr->eraseFromParent();
434349cc55cSDimitry Andric   }
435349cc55cSDimitry Andric 
4360b57cec5SDimitry Andric   // If someone took the address of a label but never did an indirect goto, we
4370b57cec5SDimitry Andric   // made a zero entry PHI node, which is illegal, zap it now.
4380b57cec5SDimitry Andric   if (IndirectBranch) {
4390b57cec5SDimitry Andric     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
4400b57cec5SDimitry Andric     if (PN->getNumIncomingValues() == 0) {
4410b57cec5SDimitry Andric       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
4420b57cec5SDimitry Andric       PN->eraseFromParent();
4430b57cec5SDimitry Andric     }
4440b57cec5SDimitry Andric   }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
4470b57cec5SDimitry Andric   EmitIfUsed(*this, TerminateLandingPad);
4480b57cec5SDimitry Andric   EmitIfUsed(*this, TerminateHandler);
4490b57cec5SDimitry Andric   EmitIfUsed(*this, UnreachableBlock);
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   for (const auto &FuncletAndParent : TerminateFunclets)
4520b57cec5SDimitry Andric     EmitIfUsed(*this, FuncletAndParent.second);
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().EmitDeclMetadata)
4550b57cec5SDimitry Andric     EmitDeclMetadata();
4560b57cec5SDimitry Andric 
457fe6060f1SDimitry Andric   for (const auto &R : DeferredReplacements) {
458fe6060f1SDimitry Andric     if (llvm::Value *Old = R.first) {
459fe6060f1SDimitry Andric       Old->replaceAllUsesWith(R.second);
460fe6060f1SDimitry Andric       cast<llvm::Instruction>(Old)->eraseFromParent();
4610b57cec5SDimitry Andric     }
462fe6060f1SDimitry Andric   }
463fe6060f1SDimitry Andric   DeferredReplacements.clear();
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
4660b57cec5SDimitry Andric   // PHIs if the current function is a coroutine. We don't do it for all
4670b57cec5SDimitry Andric   // functions as it may result in slight increase in numbers of instructions
4680b57cec5SDimitry Andric   // if compiled with no optimizations. We do it for coroutine as the lifetime
4690b57cec5SDimitry Andric   // of CleanupDestSlot alloca make correct coroutine frame building very
4700b57cec5SDimitry Andric   // difficult.
4710b57cec5SDimitry Andric   if (NormalCleanupDest.isValid() && isCoroutine()) {
4720b57cec5SDimitry Andric     llvm::DominatorTree DT(*CurFn);
4730b57cec5SDimitry Andric     llvm::PromoteMemToReg(
4740b57cec5SDimitry Andric         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
4750b57cec5SDimitry Andric     NormalCleanupDest = Address::invalid();
4760b57cec5SDimitry Andric   }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   // Scan function arguments for vector width.
4790b57cec5SDimitry Andric   for (llvm::Argument &A : CurFn->args())
4800b57cec5SDimitry Andric     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
4815ffd83dbSDimitry Andric       LargestVectorWidth =
4825ffd83dbSDimitry Andric           std::max((uint64_t)LargestVectorWidth,
4835ffd83dbSDimitry Andric                    VT->getPrimitiveSizeInBits().getKnownMinSize());
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   // Update vector width based on return type.
4860b57cec5SDimitry Andric   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
4875ffd83dbSDimitry Andric     LargestVectorWidth =
4885ffd83dbSDimitry Andric         std::max((uint64_t)LargestVectorWidth,
4895ffd83dbSDimitry Andric                  VT->getPrimitiveSizeInBits().getKnownMinSize());
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   // Add the required-vector-width attribute. This contains the max width from:
4920b57cec5SDimitry Andric   // 1. min-vector-width attribute used in the source program.
4930b57cec5SDimitry Andric   // 2. Any builtins used that have a vector width specified.
4940b57cec5SDimitry Andric   // 3. Values passed in and out of inline assembly.
4950b57cec5SDimitry Andric   // 4. Width of vector arguments and return types for this function.
4960b57cec5SDimitry Andric   // 5. Width of vector aguments and return types for functions called by this
4970b57cec5SDimitry Andric   //    function.
4980b57cec5SDimitry Andric   CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
4990b57cec5SDimitry Andric 
500349cc55cSDimitry Andric   // Add vscale_range attribute if appropriate.
501349cc55cSDimitry Andric   Optional<std::pair<unsigned, unsigned>> VScaleRange =
502349cc55cSDimitry Andric       getContext().getTargetInfo().getVScaleRange(getLangOpts());
503349cc55cSDimitry Andric   if (VScaleRange) {
504349cc55cSDimitry Andric     CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
505349cc55cSDimitry Andric         getLLVMContext(), VScaleRange.getValue().first,
506349cc55cSDimitry Andric         VScaleRange.getValue().second));
507fe6060f1SDimitry Andric   }
508fe6060f1SDimitry Andric 
5090b57cec5SDimitry Andric   // If we generated an unreachable return block, delete it now.
5100b57cec5SDimitry Andric   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
5110b57cec5SDimitry Andric     Builder.ClearInsertionPoint();
5120b57cec5SDimitry Andric     ReturnBlock.getBlock()->eraseFromParent();
5130b57cec5SDimitry Andric   }
5140b57cec5SDimitry Andric   if (ReturnValue.isValid()) {
5150b57cec5SDimitry Andric     auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
5160b57cec5SDimitry Andric     if (RetAlloca && RetAlloca->use_empty()) {
5170b57cec5SDimitry Andric       RetAlloca->eraseFromParent();
5180b57cec5SDimitry Andric       ReturnValue = Address::invalid();
5190b57cec5SDimitry Andric     }
5200b57cec5SDimitry Andric   }
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric /// ShouldInstrumentFunction - Return true if the current function should be
5240b57cec5SDimitry Andric /// instrumented with __cyg_profile_func_* calls
5250b57cec5SDimitry Andric bool CodeGenFunction::ShouldInstrumentFunction() {
5260b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
5270b57cec5SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
5280b57cec5SDimitry Andric       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
5290b57cec5SDimitry Andric     return false;
5300b57cec5SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
5310b57cec5SDimitry Andric     return false;
5320b57cec5SDimitry Andric   return true;
5330b57cec5SDimitry Andric }
5340b57cec5SDimitry Andric 
535349cc55cSDimitry Andric bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
536349cc55cSDimitry Andric   if (!CurFuncDecl)
537349cc55cSDimitry Andric     return false;
538349cc55cSDimitry Andric   return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
539349cc55cSDimitry Andric }
540349cc55cSDimitry Andric 
5410b57cec5SDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
5420b57cec5SDimitry Andric /// instrumented with XRay nop sleds.
5430b57cec5SDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
5440b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
5480b57cec5SDimitry Andric /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
5490b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
5500b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
5510b57cec5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
5520b57cec5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
5530b57cec5SDimitry Andric               XRayInstrKind::Custom);
5540b57cec5SDimitry Andric }
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
5570b57cec5SDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
5580b57cec5SDimitry Andric          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
5590b57cec5SDimitry Andric           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
5600b57cec5SDimitry Andric               XRayInstrKind::Typed);
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric llvm::Constant *
5640b57cec5SDimitry Andric CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
5650b57cec5SDimitry Andric                                             llvm::Constant *Addr) {
5660b57cec5SDimitry Andric   // Addresses stored in prologue data can't require run-time fixups and must
5670b57cec5SDimitry Andric   // be PC-relative. Run-time fixups are undesirable because they necessitate
5680b57cec5SDimitry Andric   // writable text segments, which are unsafe. And absolute addresses are
5690b57cec5SDimitry Andric   // undesirable because they break PIE mode.
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   // Add a layer of indirection through a private global. Taking its address
5720b57cec5SDimitry Andric   // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
5730b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
5740b57cec5SDimitry Andric                                       /*isConstant=*/true,
5750b57cec5SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Addr);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   // Create a PC-relative address.
5780b57cec5SDimitry Andric   auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
5790b57cec5SDimitry Andric   auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
5800b57cec5SDimitry Andric   auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
5810b57cec5SDimitry Andric   return (IntPtrTy == Int32Ty)
5820b57cec5SDimitry Andric              ? PCRelAsInt
5830b57cec5SDimitry Andric              : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric llvm::Value *
5870b57cec5SDimitry Andric CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
5880b57cec5SDimitry Andric                                           llvm::Value *EncodedAddr) {
5890b57cec5SDimitry Andric   // Reconstruct the address of the global.
5900b57cec5SDimitry Andric   auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
5910b57cec5SDimitry Andric   auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
5920b57cec5SDimitry Andric   auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
5930b57cec5SDimitry Andric   auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   // Load the original pointer through the global.
5960b57cec5SDimitry Andric   return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
5970b57cec5SDimitry Andric                             "decoded_addr");
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
6010b57cec5SDimitry Andric                                                llvm::Function *Fn)
6020b57cec5SDimitry Andric {
6030b57cec5SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
6040b57cec5SDimitry Andric     return;
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   CGM.GenOpenCLArgMetadata(Fn, FD, this);
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
6110b57cec5SDimitry Andric     QualType HintQTy = A->getTypeHint();
6120b57cec5SDimitry Andric     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
6130b57cec5SDimitry Andric     bool IsSignedInteger =
6140b57cec5SDimitry Andric         HintQTy->isSignedIntegerType() ||
6150b57cec5SDimitry Andric         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
6160b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6170b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
6180b57cec5SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
6190b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6200b57cec5SDimitry Andric             llvm::IntegerType::get(Context, 32),
6210b57cec5SDimitry Andric             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
6220b57cec5SDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
6230b57cec5SDimitry Andric   }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
6260b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6270b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
6280b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
6290b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6300b57cec5SDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
6340b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6350b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
6360b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
6370b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6380b57cec5SDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
6390b57cec5SDimitry Andric   }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
6420b57cec5SDimitry Andric           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6430b57cec5SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6440b57cec5SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
6450b57cec5SDimitry Andric     Fn->setMetadata("intel_reqd_sub_group_size",
6460b57cec5SDimitry Andric                     llvm::MDNode::get(Context, AttrMDArgs));
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric /// Determine whether the function F ends with a return stmt.
6510b57cec5SDimitry Andric static bool endsWithReturn(const Decl* F) {
6520b57cec5SDimitry Andric   const Stmt *Body = nullptr;
6530b57cec5SDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
6540b57cec5SDimitry Andric     Body = FD->getBody();
6550b57cec5SDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
6560b57cec5SDimitry Andric     Body = OMD->getBody();
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
6590b57cec5SDimitry Andric     auto LastStmt = CS->body_rbegin();
6600b57cec5SDimitry Andric     if (LastStmt != CS->body_rend())
6610b57cec5SDimitry Andric       return isa<ReturnStmt>(*LastStmt);
6620b57cec5SDimitry Andric   }
6630b57cec5SDimitry Andric   return false;
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
6670b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
6680b57cec5SDimitry Andric     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
6690b57cec5SDimitry Andric     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
6700b57cec5SDimitry Andric   }
6710b57cec5SDimitry Andric }
6720b57cec5SDimitry Andric 
673480093f4SDimitry Andric /// Check if the return value of this function requires sanitization.
674480093f4SDimitry Andric bool CodeGenFunction::requiresReturnValueCheck() const {
675480093f4SDimitry Andric   return requiresReturnValueNullabilityCheck() ||
676480093f4SDimitry Andric          (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
677480093f4SDimitry Andric           CurCodeDecl->getAttr<ReturnsNonNullAttr>());
678480093f4SDimitry Andric }
679480093f4SDimitry Andric 
6800b57cec5SDimitry Andric static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
6810b57cec5SDimitry Andric   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
6820b57cec5SDimitry Andric   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
6830b57cec5SDimitry Andric       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
6840b57cec5SDimitry Andric       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
6850b57cec5SDimitry Andric     return false;
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
6880b57cec5SDimitry Andric     return false;
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   if (MD->getNumParams() == 2) {
6910b57cec5SDimitry Andric     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
6920b57cec5SDimitry Andric     if (!PT || !PT->isVoidPointerType() ||
6930b57cec5SDimitry Andric         !PT->getPointeeType().isConstQualified())
6940b57cec5SDimitry Andric       return false;
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   return true;
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric /// Return the UBSan prologue signature for \p FD if one is available.
7010b57cec5SDimitry Andric static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
7020b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
7030b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7040b57cec5SDimitry Andric     if (!MD->isStatic())
7050b57cec5SDimitry Andric       return nullptr;
7060b57cec5SDimitry Andric   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
709480093f4SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
7100b57cec5SDimitry Andric                                     llvm::Function *Fn,
7110b57cec5SDimitry Andric                                     const CGFunctionInfo &FnInfo,
7120b57cec5SDimitry Andric                                     const FunctionArgList &Args,
7130b57cec5SDimitry Andric                                     SourceLocation Loc,
7140b57cec5SDimitry Andric                                     SourceLocation StartLoc) {
7150b57cec5SDimitry Andric   assert(!CurFn &&
7160b57cec5SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   DidCallStackSave = false;
7210b57cec5SDimitry Andric   CurCodeDecl = D;
722fe6060f1SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
723fe6060f1SDimitry Andric   if (FD && FD->usesSEHTry())
7240b57cec5SDimitry Andric     CurSEHParent = FD;
7250b57cec5SDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
7260b57cec5SDimitry Andric   FnRetTy = RetTy;
7270b57cec5SDimitry Andric   CurFn = Fn;
7280b57cec5SDimitry Andric   CurFnInfo = &FnInfo;
7290b57cec5SDimitry Andric   assert(CurFn->isDeclaration() && "Function already has body?");
7300b57cec5SDimitry Andric 
731fe6060f1SDimitry Andric   // If this function is ignored for any of the enabled sanitizers,
7320b57cec5SDimitry Andric   // disable the sanitizer for the function.
7330b57cec5SDimitry Andric   do {
7340b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
7350b57cec5SDimitry Andric   if (SanOpts.empty())                                                         \
7360b57cec5SDimitry Andric     break;                                                                     \
7370b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ID))                                          \
738fe6060f1SDimitry Andric     if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc))                    \
7390b57cec5SDimitry Andric       SanOpts.set(SanitizerKind::ID, false);
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
7420b57cec5SDimitry Andric #undef SANITIZER
74304eeddc0SDimitry Andric   } while (false);
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   if (D) {
746fe6060f1SDimitry Andric     bool NoSanitizeCoverage = false;
747fe6060f1SDimitry Andric 
7480b57cec5SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
749fe6060f1SDimitry Andric       // Apply the no_sanitize* attributes to SanOpts.
7500b57cec5SDimitry Andric       SanitizerMask mask = Attr->getMask();
7510b57cec5SDimitry Andric       SanOpts.Mask &= ~mask;
7520b57cec5SDimitry Andric       if (mask & SanitizerKind::Address)
7530b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::KernelAddress, false);
7540b57cec5SDimitry Andric       if (mask & SanitizerKind::KernelAddress)
7550b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::Address, false);
7560b57cec5SDimitry Andric       if (mask & SanitizerKind::HWAddress)
7570b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::KernelHWAddress, false);
7580b57cec5SDimitry Andric       if (mask & SanitizerKind::KernelHWAddress)
7590b57cec5SDimitry Andric         SanOpts.set(SanitizerKind::HWAddress, false);
760fe6060f1SDimitry Andric 
761fe6060f1SDimitry Andric       // SanitizeCoverage is not handled by SanOpts.
762fe6060f1SDimitry Andric       if (Attr->hasCoverage())
763fe6060f1SDimitry Andric         NoSanitizeCoverage = true;
7640b57cec5SDimitry Andric     }
765fe6060f1SDimitry Andric 
766fe6060f1SDimitry Andric     if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
767fe6060f1SDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   // Apply sanitizer attributes to the function.
7710b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
7720b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
7730b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
7740b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
7750b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::MemTag))
7760b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
7770b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
7780b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
7790b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
7800b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
7810b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
7820b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
7830b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ShadowCallStack))
7840b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   // Apply fuzzing attribute to the function.
7870b57cec5SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
7880b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
7910b57cec5SDimitry Andric   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
7920b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
7930b57cec5SDimitry Andric     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
7940b57cec5SDimitry Andric       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
7950b57cec5SDimitry Andric       if (OMD->getMethodFamily() == OMF_dealloc ||
7960b57cec5SDimitry Andric           OMD->getMethodFamily() == OMF_initialize ||
7970b57cec5SDimitry Andric           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
7980b57cec5SDimitry Andric         markAsIgnoreThreadCheckingAtRuntime(Fn);
7990b57cec5SDimitry Andric       }
8000b57cec5SDimitry Andric     }
8010b57cec5SDimitry Andric   }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   // Ignore unrelated casts in STL allocate() since the allocator must cast
8040b57cec5SDimitry Andric   // from void* to T* before object initialization completes. Don't match on the
8050b57cec5SDimitry Andric   // namespace because not all allocators are in std::
8060b57cec5SDimitry Andric   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
8070b57cec5SDimitry Andric     if (matchesStlAllocatorFn(D, getContext()))
8080b57cec5SDimitry Andric       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
8090b57cec5SDimitry Andric   }
8100b57cec5SDimitry Andric 
811a7dea167SDimitry Andric   // Ignore null checks in coroutine functions since the coroutines passes
812a7dea167SDimitry Andric   // are not aware of how to move the extra UBSan instructions across the split
813a7dea167SDimitry Andric   // coroutine boundaries.
814a7dea167SDimitry Andric   if (D && SanOpts.has(SanitizerKind::Null))
815fe6060f1SDimitry Andric     if (FD && FD->getBody() &&
816a7dea167SDimitry Andric         FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
817a7dea167SDimitry Andric       SanOpts.Mask &= ~SanitizerKind::Null;
818a7dea167SDimitry Andric 
819480093f4SDimitry Andric   // Apply xray attributes to the function (as a string, for now)
820e8d8bef9SDimitry Andric   bool AlwaysXRayAttr = false;
8215ffd83dbSDimitry Andric   if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
8220b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8235ffd83dbSDimitry Andric             XRayInstrKind::FunctionEntry) ||
8245ffd83dbSDimitry Andric         CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8255ffd83dbSDimitry Andric             XRayInstrKind::FunctionExit)) {
826e8d8bef9SDimitry Andric       if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
8270b57cec5SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
828e8d8bef9SDimitry Andric         AlwaysXRayAttr = true;
829e8d8bef9SDimitry Andric       }
8300b57cec5SDimitry Andric       if (XRayAttr->neverXRayInstrument())
8310b57cec5SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
8320b57cec5SDimitry Andric       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
8330b57cec5SDimitry Andric         if (ShouldXRayInstrumentFunction())
8340b57cec5SDimitry Andric           Fn->addFnAttr("xray-log-args",
8350b57cec5SDimitry Andric                         llvm::utostr(LogArgs->getArgumentCount()));
8360b57cec5SDimitry Andric     }
8370b57cec5SDimitry Andric   } else {
8380b57cec5SDimitry Andric     if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
8390b57cec5SDimitry Andric       Fn->addFnAttr(
8400b57cec5SDimitry Andric           "xray-instruction-threshold",
8410b57cec5SDimitry Andric           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
8420b57cec5SDimitry Andric   }
843480093f4SDimitry Andric 
8445ffd83dbSDimitry Andric   if (ShouldXRayInstrumentFunction()) {
8455ffd83dbSDimitry Andric     if (CGM.getCodeGenOpts().XRayIgnoreLoops)
8465ffd83dbSDimitry Andric       Fn->addFnAttr("xray-ignore-loops");
8475ffd83dbSDimitry Andric 
8485ffd83dbSDimitry Andric     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8495ffd83dbSDimitry Andric             XRayInstrKind::FunctionExit))
8505ffd83dbSDimitry Andric       Fn->addFnAttr("xray-skip-exit");
8515ffd83dbSDimitry Andric 
8525ffd83dbSDimitry Andric     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
8535ffd83dbSDimitry Andric             XRayInstrKind::FunctionEntry))
8545ffd83dbSDimitry Andric       Fn->addFnAttr("xray-skip-entry");
855e8d8bef9SDimitry Andric 
856e8d8bef9SDimitry Andric     auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
857e8d8bef9SDimitry Andric     if (FuncGroups > 1) {
858e8d8bef9SDimitry Andric       auto FuncName = llvm::makeArrayRef<uint8_t>(
859e8d8bef9SDimitry Andric           CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
860e8d8bef9SDimitry Andric       auto Group = crc32(FuncName) % FuncGroups;
861e8d8bef9SDimitry Andric       if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
862e8d8bef9SDimitry Andric           !AlwaysXRayAttr)
863e8d8bef9SDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
8645ffd83dbSDimitry Andric     }
865e8d8bef9SDimitry Andric   }
866e8d8bef9SDimitry Andric 
867e8d8bef9SDimitry Andric   if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
868e8d8bef9SDimitry Andric     if (CGM.isProfileInstrExcluded(Fn, Loc))
869e8d8bef9SDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoProfile);
8705ffd83dbSDimitry Andric 
87155e4f9d5SDimitry Andric   unsigned Count, Offset;
8725ffd83dbSDimitry Andric   if (const auto *Attr =
8735ffd83dbSDimitry Andric           D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
87455e4f9d5SDimitry Andric     Count = Attr->getCount();
87555e4f9d5SDimitry Andric     Offset = Attr->getOffset();
87655e4f9d5SDimitry Andric   } else {
87755e4f9d5SDimitry Andric     Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
87855e4f9d5SDimitry Andric     Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
87955e4f9d5SDimitry Andric   }
88055e4f9d5SDimitry Andric   if (Count && Offset <= Count) {
88155e4f9d5SDimitry Andric     Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
88255e4f9d5SDimitry Andric     if (Offset)
88355e4f9d5SDimitry Andric       Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
884480093f4SDimitry Andric   }
88504eeddc0SDimitry Andric   // Instruct that functions for COFF/CodeView targets should start with a
88604eeddc0SDimitry Andric   // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
88704eeddc0SDimitry Andric   // backends as they don't need it -- instructions on these architectures are
88804eeddc0SDimitry Andric   // always atomically patchable at runtime.
88904eeddc0SDimitry Andric   if (CGM.getCodeGenOpts().HotPatch &&
89004eeddc0SDimitry Andric       getContext().getTargetInfo().getTriple().isX86())
89104eeddc0SDimitry Andric     Fn->addFnAttr("patchable-function", "prologue-short-redirect");
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // Add no-jump-tables value.
894fe6060f1SDimitry Andric   if (CGM.getCodeGenOpts().NoUseJumpTables)
895fe6060f1SDimitry Andric     Fn->addFnAttr("no-jump-tables", "true");
8960b57cec5SDimitry Andric 
897480093f4SDimitry Andric   // Add no-inline-line-tables value.
898480093f4SDimitry Andric   if (CGM.getCodeGenOpts().NoInlineLineTables)
899480093f4SDimitry Andric     Fn->addFnAttr("no-inline-line-tables");
900480093f4SDimitry Andric 
9010b57cec5SDimitry Andric   // Add profile-sample-accurate value.
9020b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
9030b57cec5SDimitry Andric     Fn->addFnAttr("profile-sample-accurate");
9040b57cec5SDimitry Andric 
9055ffd83dbSDimitry Andric   if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
9065ffd83dbSDimitry Andric     Fn->addFnAttr("use-sample-profile");
9075ffd83dbSDimitry Andric 
908a7dea167SDimitry Andric   if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
909a7dea167SDimitry Andric     Fn->addFnAttr("cfi-canonical-jump-table");
910a7dea167SDimitry Andric 
911fe6060f1SDimitry Andric   if (D && D->hasAttr<NoProfileFunctionAttr>())
912fe6060f1SDimitry Andric     Fn->addFnAttr(llvm::Attribute::NoProfile);
913fe6060f1SDimitry Andric 
914fe6060f1SDimitry Andric   if (FD && getLangOpts().OpenCL) {
9150b57cec5SDimitry Andric     // Add metadata for a kernel function.
9160b57cec5SDimitry Andric     EmitOpenCLKernelMetadata(FD, Fn);
9170b57cec5SDimitry Andric   }
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric   // If we are checking function types, emit a function type signature as
9200b57cec5SDimitry Andric   // prologue data.
921fe6060f1SDimitry Andric   if (FD && getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
9220b57cec5SDimitry Andric     if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
9230b57cec5SDimitry Andric       // Remove any (C++17) exception specifications, to allow calling e.g. a
9240b57cec5SDimitry Andric       // noexcept function through a non-noexcept pointer.
925fe6060f1SDimitry Andric       auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
926fe6060f1SDimitry Andric           FD->getType(), EST_None);
9270b57cec5SDimitry Andric       llvm::Constant *FTRTTIConst =
9280b57cec5SDimitry Andric           CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
9290b57cec5SDimitry Andric       llvm::Constant *FTRTTIConstEncoded =
9300b57cec5SDimitry Andric           EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
931fe6060f1SDimitry Andric       llvm::Constant *PrologueStructElems[] = {PrologueSig, FTRTTIConstEncoded};
9320b57cec5SDimitry Andric       llvm::Constant *PrologueStructConst =
9330b57cec5SDimitry Andric           llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
9340b57cec5SDimitry Andric       Fn->setPrologueData(PrologueStructConst);
9350b57cec5SDimitry Andric     }
9360b57cec5SDimitry Andric   }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   // If we're checking nullability, we need to know whether we can check the
9390b57cec5SDimitry Andric   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
9400b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
9410b57cec5SDimitry Andric     auto Nullability = FnRetTy->getNullability(getContext());
9420b57cec5SDimitry Andric     if (Nullability && *Nullability == NullabilityKind::NonNull) {
9430b57cec5SDimitry Andric       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
9440b57cec5SDimitry Andric             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
9450b57cec5SDimitry Andric         RetValNullabilityPrecondition =
9460b57cec5SDimitry Andric             llvm::ConstantInt::getTrue(getLLVMContext());
9470b57cec5SDimitry Andric     }
9480b57cec5SDimitry Andric   }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
9510b57cec5SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
9520b57cec5SDimitry Andric   // used within a program").
9535ffd83dbSDimitry Andric   //
9545ffd83dbSDimitry Andric   // OpenCL C 2.0 v2.2-11 s6.9.i:
9555ffd83dbSDimitry Andric   //     Recursion is not supported.
9565ffd83dbSDimitry Andric   //
9575ffd83dbSDimitry Andric   // SYCL v1.2.1 s3.10:
9585ffd83dbSDimitry Andric   //     kernels cannot include RTTI information, exception classes,
9595ffd83dbSDimitry Andric   //     recursive code, virtual functions or make use of C++ libraries that
9605ffd83dbSDimitry Andric   //     are not compiled for the device.
961fe6060f1SDimitry Andric   if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
962fe6060f1SDimitry Andric              getLangOpts().OpenCL || getLangOpts().SYCLIsDevice ||
963fe6060f1SDimitry Andric              (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
9640b57cec5SDimitry Andric     Fn->addFnAttr(llvm::Attribute::NoRecurse);
9650b57cec5SDimitry Andric 
966349cc55cSDimitry Andric   llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
967349cc55cSDimitry Andric   llvm::fp::ExceptionBehavior FPExceptionBehavior =
968349cc55cSDimitry Andric       ToConstrainedExceptMD(getLangOpts().getFPExceptionMode());
969349cc55cSDimitry Andric   Builder.setDefaultConstrainedRounding(RM);
970349cc55cSDimitry Andric   Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
971349cc55cSDimitry Andric   if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
972349cc55cSDimitry Andric       (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
973349cc55cSDimitry Andric                RM != llvm::RoundingMode::NearestTiesToEven))) {
974349cc55cSDimitry Andric     Builder.setIsFPConstrained(true);
975480093f4SDimitry Andric     Fn->addFnAttr(llvm::Attribute::StrictFP);
9765ffd83dbSDimitry Andric   }
977480093f4SDimitry Andric 
9780b57cec5SDimitry Andric   // If a custom alignment is used, force realigning to this alignment on
9790b57cec5SDimitry Andric   // any main function which certainly will need it.
980fe6060f1SDimitry Andric   if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
981fe6060f1SDimitry Andric              CGM.getCodeGenOpts().StackAlignment))
9820b57cec5SDimitry Andric     Fn->addFnAttr("stackrealign");
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   // Create a marker to make it easy to insert allocas into the entryblock
9870b57cec5SDimitry Andric   // later.  Don't create this with the builder, because we don't want it
9880b57cec5SDimitry Andric   // folded.
9890b57cec5SDimitry Andric   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
9900b57cec5SDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   ReturnBlock = getJumpDestInCurrentScope("return");
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   Builder.SetInsertPoint(EntryBB);
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric   // If we're checking the return value, allocate space for a pointer to a
9970b57cec5SDimitry Andric   // precise source location of the checked return statement.
9980b57cec5SDimitry Andric   if (requiresReturnValueCheck()) {
9990b57cec5SDimitry Andric     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1000349cc55cSDimitry Andric     Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1001349cc55cSDimitry Andric                         ReturnLocation);
10020b57cec5SDimitry Andric   }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // Emit subprogram debug descriptor.
10050b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
10060b57cec5SDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
10070b57cec5SDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
10080b57cec5SDimitry Andric     // convention.
1009349cc55cSDimitry Andric     DI->emitFunctionStart(GD, Loc, StartLoc,
1010349cc55cSDimitry Andric                           DI->getFunctionType(FD, RetTy, Args), CurFn,
1011349cc55cSDimitry Andric                           CurFuncIsThunk);
10120b57cec5SDimitry Andric   }
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   if (ShouldInstrumentFunction()) {
10150b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctions)
10160b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
10170b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
10180b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
10190b57cec5SDimitry Andric                        "__cyg_profile_func_enter");
10200b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
10210b57cec5SDimitry Andric       CurFn->addFnAttr("instrument-function-entry-inlined",
10220b57cec5SDimitry Andric                        "__cyg_profile_func_enter_bare");
10230b57cec5SDimitry Andric   }
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   // Since emitting the mcount call here impacts optimizations such as function
10260b57cec5SDimitry Andric   // inlining, we just add an attribute to insert a mcount call in backend.
10270b57cec5SDimitry Andric   // The attribute "counting-function" is set to mcount function name which is
10280b57cec5SDimitry Andric   // architecture dependent.
10290b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
10300b57cec5SDimitry Andric     // Calls to fentry/mcount should not be generated if function has
10310b57cec5SDimitry Andric     // the no_instrument_function attribute.
10320b57cec5SDimitry Andric     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
10330b57cec5SDimitry Andric       if (CGM.getCodeGenOpts().CallFEntry)
10340b57cec5SDimitry Andric         Fn->addFnAttr("fentry-call", "true");
10350b57cec5SDimitry Andric       else {
10360b57cec5SDimitry Andric         Fn->addFnAttr("instrument-function-entry-inlined",
10370b57cec5SDimitry Andric                       getTarget().getMCountName());
10380b57cec5SDimitry Andric       }
1039480093f4SDimitry Andric       if (CGM.getCodeGenOpts().MNopMCount) {
1040480093f4SDimitry Andric         if (!CGM.getCodeGenOpts().CallFEntry)
1041480093f4SDimitry Andric           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1042480093f4SDimitry Andric             << "-mnop-mcount" << "-mfentry";
1043480093f4SDimitry Andric         Fn->addFnAttr("mnop-mcount");
10440b57cec5SDimitry Andric       }
1045480093f4SDimitry Andric 
1046480093f4SDimitry Andric       if (CGM.getCodeGenOpts().RecordMCount) {
1047480093f4SDimitry Andric         if (!CGM.getCodeGenOpts().CallFEntry)
1048480093f4SDimitry Andric           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1049480093f4SDimitry Andric             << "-mrecord-mcount" << "-mfentry";
1050480093f4SDimitry Andric         Fn->addFnAttr("mrecord-mcount");
1051480093f4SDimitry Andric       }
1052480093f4SDimitry Andric     }
1053480093f4SDimitry Andric   }
1054480093f4SDimitry Andric 
1055480093f4SDimitry Andric   if (CGM.getCodeGenOpts().PackedStack) {
1056480093f4SDimitry Andric     if (getContext().getTargetInfo().getTriple().getArch() !=
1057480093f4SDimitry Andric         llvm::Triple::systemz)
1058480093f4SDimitry Andric       CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1059480093f4SDimitry Andric         << "-mpacked-stack";
1060480093f4SDimitry Andric     Fn->addFnAttr("packed-stack");
10610b57cec5SDimitry Andric   }
10620b57cec5SDimitry Andric 
1063349cc55cSDimitry Andric   if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1064349cc55cSDimitry Andric       !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1065fe6060f1SDimitry Andric     Fn->addFnAttr("warn-stack-size",
1066fe6060f1SDimitry Andric                   std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1067fe6060f1SDimitry Andric 
10680b57cec5SDimitry Andric   if (RetTy->isVoidType()) {
10690b57cec5SDimitry Andric     // Void type; nothing to return.
10700b57cec5SDimitry Andric     ReturnValue = Address::invalid();
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric     // Count the implicit return.
10730b57cec5SDimitry Andric     if (!endsWithReturn(D))
10740b57cec5SDimitry Andric       ++NumReturnExprs;
10750b57cec5SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
10760b57cec5SDimitry Andric     // Indirect return; emit returned value directly into sret slot.
10770b57cec5SDimitry Andric     // This reduces code size, and affects correctness in C++.
10780b57cec5SDimitry Andric     auto AI = CurFn->arg_begin();
10790b57cec5SDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
10800b57cec5SDimitry Andric       ++AI;
10810eae32dcSDimitry Andric     ReturnValue = Address(&*AI, ConvertType(RetTy),
10820eae32dcSDimitry Andric                           CurFnInfo->getReturnInfo().getIndirectAlign());
10830b57cec5SDimitry Andric     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
10840b57cec5SDimitry Andric       ReturnValuePointer =
10850b57cec5SDimitry Andric           CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
10860b57cec5SDimitry Andric       Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
10870b57cec5SDimitry Andric                               ReturnValue.getPointer(), Int8PtrTy),
10880b57cec5SDimitry Andric                           ReturnValuePointer);
10890b57cec5SDimitry Andric     }
10900b57cec5SDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
10910b57cec5SDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
10920b57cec5SDimitry Andric     // Load the sret pointer from the argument struct and return into that.
10930b57cec5SDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
10940b57cec5SDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
10950b57cec5SDimitry Andric     --EI;
1096fe6060f1SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(
1097fe6060f1SDimitry Andric         EI->getType()->getPointerElementType(), &*EI, Idx);
1098fe6060f1SDimitry Andric     llvm::Type *Ty =
1099fe6060f1SDimitry Andric         cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
11000b57cec5SDimitry Andric     ReturnValuePointer = Address(Addr, getPointerAlign());
1101fe6060f1SDimitry Andric     Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
11025ffd83dbSDimitry Andric     ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
11030b57cec5SDimitry Andric   } else {
11040b57cec5SDimitry Andric     ReturnValue = CreateIRTemp(RetTy, "retval");
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
11070b57cec5SDimitry Andric     // now so that various specialized functions can suppress it
11080b57cec5SDimitry Andric     // during their IR-generation.
11090b57cec5SDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
11100b57cec5SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
11110b57cec5SDimitry Andric         RetTy->isObjCRetainableType())
11120b57cec5SDimitry Andric       AutoreleaseResult = true;
11130b57cec5SDimitry Andric   }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   EmitStartEHSpec(CurCodeDecl);
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   // Emit OpenMP specific initialization of the device functions.
11200b57cec5SDimitry Andric   if (getLangOpts().OpenMP && CurCodeDecl)
11210b57cec5SDimitry Andric     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
11240b57cec5SDimitry Andric 
11250b57cec5SDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
11260b57cec5SDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
11270b57cec5SDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
11280b57cec5SDimitry Andric     if (MD->getParent()->isLambda() &&
11290b57cec5SDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
11300b57cec5SDimitry Andric       // We're in a lambda; figure out the captures.
11310b57cec5SDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
11320b57cec5SDimitry Andric                                         LambdaThisCaptureField);
11330b57cec5SDimitry Andric       if (LambdaThisCaptureField) {
11340b57cec5SDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
11350b57cec5SDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
11360b57cec5SDimitry Andric         // object.
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
11390b57cec5SDimitry Andric         // or contains the address of the enclosing object).
11400b57cec5SDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
11410b57cec5SDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
11420b57cec5SDimitry Andric           // If the enclosing object was captured by value, just use its address.
1143480093f4SDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
11440b57cec5SDimitry Andric         } else {
11450b57cec5SDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
11460b57cec5SDimitry Andric           // by reference.
11470b57cec5SDimitry Andric           CXXThisValue =
11480b57cec5SDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
11490b57cec5SDimitry Andric         }
11500b57cec5SDimitry Andric       }
11510b57cec5SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
11520b57cec5SDimitry Andric         if (FD->hasCapturedVLAType()) {
11530b57cec5SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
11540b57cec5SDimitry Andric                                            SourceLocation()).getScalarVal();
11550b57cec5SDimitry Andric           auto VAT = FD->getCapturedVLAType();
11560b57cec5SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
11570b57cec5SDimitry Andric         }
11580b57cec5SDimitry Andric       }
11590b57cec5SDimitry Andric     } else {
11600b57cec5SDimitry Andric       // Not in a lambda; just use 'this' from the method.
11610b57cec5SDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
11620b57cec5SDimitry Andric       // fast register allocator would be happier...
11630b57cec5SDimitry Andric       CXXThisValue = CXXABIThisValue;
11640b57cec5SDimitry Andric     }
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric     // Check the 'this' pointer once per function, if it's available.
11670b57cec5SDimitry Andric     if (CXXABIThisValue) {
11680b57cec5SDimitry Andric       SanitizerSet SkippedChecks;
11690b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::ObjectSize, true);
11700b57cec5SDimitry Andric       QualType ThisTy = MD->getThisType();
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric       // If this is the call operator of a lambda with no capture-default, it
11730b57cec5SDimitry Andric       // may have a static invoker function, which may call this operator with
11740b57cec5SDimitry Andric       // a null 'this' pointer.
11750b57cec5SDimitry Andric       if (isLambdaCallOperator(MD) &&
11760b57cec5SDimitry Andric           MD->getParent()->getLambdaCaptureDefault() == LCD_None)
11770b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
11780b57cec5SDimitry Andric 
1179e8d8bef9SDimitry Andric       EmitTypeCheck(
1180e8d8bef9SDimitry Andric           isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1181e8d8bef9SDimitry Andric           Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
11820b57cec5SDimitry Andric     }
11830b57cec5SDimitry Andric   }
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   // If any of the arguments have a variably modified type, make sure to
11860b57cec5SDimitry Andric   // emit the type size.
11870b57cec5SDimitry Andric   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
11880b57cec5SDimitry Andric        i != e; ++i) {
11890b57cec5SDimitry Andric     const VarDecl *VD = *i;
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
11920b57cec5SDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
11930b57cec5SDimitry Andric     // precedent set by gcc.
11940b57cec5SDimitry Andric     QualType Ty;
11950b57cec5SDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
11960b57cec5SDimitry Andric       Ty = PVD->getOriginalType();
11970b57cec5SDimitry Andric     else
11980b57cec5SDimitry Andric       Ty = VD->getType();
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric     if (Ty->isVariablyModifiedType())
12010b57cec5SDimitry Andric       EmitVariablyModifiedType(Ty);
12020b57cec5SDimitry Andric   }
12030b57cec5SDimitry Andric   // Emit a location at the end of the prologue.
12040b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
12050b57cec5SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   // TODO: Do we need to handle this in two places like we do with
12080b57cec5SDimitry Andric   // target-features/target-cpu?
12090b57cec5SDimitry Andric   if (CurFuncDecl)
12100b57cec5SDimitry Andric     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
12110b57cec5SDimitry Andric       LargestVectorWidth = VecWidth->getVectorWidth();
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
12150b57cec5SDimitry Andric   incrementProfileCounter(Body);
12160b57cec5SDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
12170b57cec5SDimitry Andric     EmitCompoundStmtWithoutScope(*S);
12180b57cec5SDimitry Andric   else
12190b57cec5SDimitry Andric     EmitStmt(Body);
1220e8d8bef9SDimitry Andric 
1221e8d8bef9SDimitry Andric   // This is checked after emitting the function body so we know if there
1222e8d8bef9SDimitry Andric   // are any permitted infinite loops.
1223fe6060f1SDimitry Andric   if (checkIfFunctionMustProgress())
1224e8d8bef9SDimitry Andric     CurFn->addFnAttr(llvm::Attribute::MustProgress);
12250b57cec5SDimitry Andric }
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
12280b57cec5SDimitry Andric /// such as switch cases need to not include the fall-through counts, so
12290b57cec5SDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
12300b57cec5SDimitry Andric /// this just calls EmitBlock().
12310b57cec5SDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
12320b57cec5SDimitry Andric                                                const Stmt *S) {
12330b57cec5SDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
12340b57cec5SDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
12350b57cec5SDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
12360b57cec5SDimitry Andric     // statements needs to skip over the instrumentation code so that we
12370b57cec5SDimitry Andric     // get an accurate count.
12380b57cec5SDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
12390b57cec5SDimitry Andric     EmitBranch(SkipCountBB);
12400b57cec5SDimitry Andric   }
12410b57cec5SDimitry Andric   EmitBlock(BB);
12420b57cec5SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
12430b57cec5SDimitry Andric   incrementProfileCounter(S);
12440b57cec5SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
12450b57cec5SDimitry Andric   if (SkipCountBB)
12460b57cec5SDimitry Andric     EmitBlock(SkipCountBB);
12470b57cec5SDimitry Andric }
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric /// Tries to mark the given function nounwind based on the
12500b57cec5SDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
12510b57cec5SDimitry Andric /// lightweight enough to do at -O0.
12520b57cec5SDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
12530b57cec5SDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
12540b57cec5SDimitry Andric   // can't do this on functions that can be overwritten.
12550b57cec5SDimitry Andric   if (F->isInterposable()) return;
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   for (llvm::BasicBlock &BB : *F)
12580b57cec5SDimitry Andric     for (llvm::Instruction &I : BB)
12590b57cec5SDimitry Andric       if (I.mayThrow())
12600b57cec5SDimitry Andric         return;
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   F->setDoesNotThrow();
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
12660b57cec5SDimitry Andric                                                FunctionArgList &Args) {
12670b57cec5SDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
12680b57cec5SDimitry Andric   QualType ResTy = FD->getReturnType();
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
12710b57cec5SDimitry Andric   if (MD && MD->isInstance()) {
12720b57cec5SDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
12730b57cec5SDimitry Andric       ResTy = MD->getThisType();
12740b57cec5SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
12750b57cec5SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
12760b57cec5SDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
12770b57cec5SDimitry Andric   }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
12800b57cec5SDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
12810b57cec5SDimitry Andric   // the inherited constructor).
12820b57cec5SDimitry Andric   bool PassedParams = true;
12830b57cec5SDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
12840b57cec5SDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
12850b57cec5SDimitry Andric       PassedParams =
12860b57cec5SDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   if (PassedParams) {
12890b57cec5SDimitry Andric     for (auto *Param : FD->parameters()) {
12900b57cec5SDimitry Andric       Args.push_back(Param);
12910b57cec5SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
12920b57cec5SDimitry Andric         continue;
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
12950b57cec5SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(),
12960b57cec5SDimitry Andric           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
12970b57cec5SDimitry Andric       SizeArguments[Param] = Implicit;
12980b57cec5SDimitry Andric       Args.push_back(Implicit);
12990b57cec5SDimitry Andric     }
13000b57cec5SDimitry Andric   }
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
13030b57cec5SDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   return ResTy;
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
13090b57cec5SDimitry Andric                                    const CGFunctionInfo &FnInfo) {
13100eae32dcSDimitry Andric   assert(Fn && "generating code for null Function");
13110b57cec5SDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
13120b57cec5SDimitry Andric   CurGD = GD;
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric   FunctionArgList Args;
13150b57cec5SDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
13160b57cec5SDimitry Andric 
1317349cc55cSDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
13180eae32dcSDimitry Andric     // When generating code for a builtin with an inline declaration, use a
13190eae32dcSDimitry Andric     // mangled name to hold the actual body, while keeping an external
13200eae32dcSDimitry Andric     // definition in case the function pointer is referenced somewhere.
1321349cc55cSDimitry Andric     std::string FDInlineName = (Fn->getName() + ".inline").str();
1322349cc55cSDimitry Andric     llvm::Module *M = Fn->getParent();
1323349cc55cSDimitry Andric     llvm::Function *Clone = M->getFunction(FDInlineName);
1324349cc55cSDimitry Andric     if (!Clone) {
1325349cc55cSDimitry Andric       Clone = llvm::Function::Create(Fn->getFunctionType(),
1326349cc55cSDimitry Andric                                      llvm::GlobalValue::InternalLinkage,
1327349cc55cSDimitry Andric                                      Fn->getAddressSpace(), FDInlineName, M);
1328349cc55cSDimitry Andric       Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1329349cc55cSDimitry Andric     }
1330349cc55cSDimitry Andric     Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1331349cc55cSDimitry Andric     Fn = Clone;
13320eae32dcSDimitry Andric   } else {
1333349cc55cSDimitry Andric     // Detect the unusual situation where an inline version is shadowed by a
1334349cc55cSDimitry Andric     // non-inline version. In that case we should pick the external one
1335349cc55cSDimitry Andric     // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1336349cc55cSDimitry Andric     // to detect that situation before we reach codegen, so do some late
1337349cc55cSDimitry Andric     // replacement.
1338349cc55cSDimitry Andric     for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1339349cc55cSDimitry Andric          PD = PD->getPreviousDecl()) {
1340349cc55cSDimitry Andric       if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1341349cc55cSDimitry Andric         std::string FDInlineName = (Fn->getName() + ".inline").str();
1342349cc55cSDimitry Andric         llvm::Module *M = Fn->getParent();
1343349cc55cSDimitry Andric         if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1344349cc55cSDimitry Andric           Clone->replaceAllUsesWith(Fn);
1345349cc55cSDimitry Andric           Clone->eraseFromParent();
1346349cc55cSDimitry Andric         }
1347349cc55cSDimitry Andric         break;
1348349cc55cSDimitry Andric       }
1349349cc55cSDimitry Andric     }
1350349cc55cSDimitry Andric   }
1351349cc55cSDimitry Andric 
13520b57cec5SDimitry Andric   // Check if we should generate debug info for this function.
1353fe6060f1SDimitry Andric   if (FD->hasAttr<NoDebugAttr>()) {
1354fe6060f1SDimitry Andric     // Clear non-distinct debug info that was possibly attached to the function
1355fe6060f1SDimitry Andric     // due to an earlier declaration without the nodebug attribute
1356fe6060f1SDimitry Andric     Fn->setSubprogram(nullptr);
1357fe6060f1SDimitry Andric     // Disable debug info indefinitely for this function
1358fe6060f1SDimitry Andric     DebugInfo = nullptr;
1359fe6060f1SDimitry Andric   }
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric   // The function might not have a body if we're generating thunks for a
13620b57cec5SDimitry Andric   // function declaration.
13630b57cec5SDimitry Andric   SourceRange BodyRange;
13640b57cec5SDimitry Andric   if (Stmt *Body = FD->getBody())
13650b57cec5SDimitry Andric     BodyRange = Body->getSourceRange();
13660b57cec5SDimitry Andric   else
13670b57cec5SDimitry Andric     BodyRange = FD->getLocation();
13680b57cec5SDimitry Andric   CurEHLocation = BodyRange.getEnd();
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   // Use the location of the start of the function to determine where
13710b57cec5SDimitry Andric   // the function definition is located. By default use the location
13720b57cec5SDimitry Andric   // of the declaration as the location for the subprogram. A function
13730b57cec5SDimitry Andric   // may lack a declaration in the source code if it is created by code
13740b57cec5SDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
13750b57cec5SDimitry Andric   SourceLocation Loc = FD->getLocation();
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   // If this is a function specialization then use the pattern body
13780b57cec5SDimitry Andric   // as the location for the function.
13790b57cec5SDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
13800b57cec5SDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
13810b57cec5SDimitry Andric       Loc = SpecDecl->getLocation();
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric   Stmt *Body = FD->getBody();
13840b57cec5SDimitry Andric 
1385fe6060f1SDimitry Andric   if (Body) {
1386fe6060f1SDimitry Andric     // Coroutines always emit lifetime markers.
1387fe6060f1SDimitry Andric     if (isa<CoroutineBodyStmt>(Body))
1388fe6060f1SDimitry Andric       ShouldEmitLifetimeMarkers = true;
1389fe6060f1SDimitry Andric 
1390fe6060f1SDimitry Andric     // Initialize helper which will detect jumps which can cause invalid
1391fe6060f1SDimitry Andric     // lifetime markers.
1392fe6060f1SDimitry Andric     if (ShouldEmitLifetimeMarkers)
13930b57cec5SDimitry Andric       Bypasses.Init(Body);
1394fe6060f1SDimitry Andric   }
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric   // Emit the standard function prologue.
13970b57cec5SDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
13980b57cec5SDimitry Andric 
1399fe6060f1SDimitry Andric   // Save parameters for coroutine function.
1400fe6060f1SDimitry Andric   if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1401fe6060f1SDimitry Andric     for (const auto *ParamDecl : FD->parameters())
1402fe6060f1SDimitry Andric       FnArgs.push_back(ParamDecl);
1403fe6060f1SDimitry Andric 
14040b57cec5SDimitry Andric   // Generate the body of the function.
14050b57cec5SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
14060b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(FD))
14070b57cec5SDimitry Andric     EmitDestructorBody(Args);
14080b57cec5SDimitry Andric   else if (isa<CXXConstructorDecl>(FD))
14090b57cec5SDimitry Andric     EmitConstructorBody(Args);
14100b57cec5SDimitry Andric   else if (getLangOpts().CUDA &&
14110b57cec5SDimitry Andric            !getLangOpts().CUDAIsDevice &&
14120b57cec5SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
14130b57cec5SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
14140b57cec5SDimitry Andric   else if (isa<CXXMethodDecl>(FD) &&
14150b57cec5SDimitry Andric            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
14160b57cec5SDimitry Andric     // The lambda static invoker function is special, because it forwards or
14170b57cec5SDimitry Andric     // clones the body of the function call operator (but is actually static).
14180b57cec5SDimitry Andric     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
14190b57cec5SDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
14200b57cec5SDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
14210b57cec5SDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
14220b57cec5SDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
14230b57cec5SDimitry Andric     // copy-constructors.
14240b57cec5SDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
14250b57cec5SDimitry Andric   } else if (Body) {
14260b57cec5SDimitry Andric     EmitFunctionBody(Body);
14270b57cec5SDimitry Andric   } else
14280b57cec5SDimitry Andric     llvm_unreachable("no definition for emitted function");
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   // C++11 [stmt.return]p2:
14310b57cec5SDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
14320b57cec5SDimitry Andric   //   a value-returning function.
14330b57cec5SDimitry Andric   // C11 6.9.1p12:
14340b57cec5SDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
14350b57cec5SDimitry Andric   //   function call is used by the caller, the behavior is undefined.
14360b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
14370b57cec5SDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
14380b57cec5SDimitry Andric     bool ShouldEmitUnreachable =
14390b57cec5SDimitry Andric         CGM.getCodeGenOpts().StrictReturn ||
1440fe6060f1SDimitry Andric         !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
14410b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
14420b57cec5SDimitry Andric       SanitizerScope SanScope(this);
14430b57cec5SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
14440b57cec5SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
14450b57cec5SDimitry Andric                 SanitizerHandler::MissingReturn,
14460b57cec5SDimitry Andric                 EmitCheckSourceLocation(FD->getLocation()), None);
14470b57cec5SDimitry Andric     } else if (ShouldEmitUnreachable) {
14480b57cec5SDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
14490b57cec5SDimitry Andric         EmitTrapCall(llvm::Intrinsic::trap);
14500b57cec5SDimitry Andric     }
14510b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
14520b57cec5SDimitry Andric       Builder.CreateUnreachable();
14530b57cec5SDimitry Andric       Builder.ClearInsertionPoint();
14540b57cec5SDimitry Andric     }
14550b57cec5SDimitry Andric   }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // Emit the standard function epilogue.
14580b57cec5SDimitry Andric   FinishFunction(BodyRange.getEnd());
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // If we haven't marked the function nothrow through other means, do
14610b57cec5SDimitry Andric   // a quick pass now to see if we can.
14620b57cec5SDimitry Andric   if (!CurFn->doesNotThrow())
14630b57cec5SDimitry Andric     TryMarkNoThrow(CurFn);
14640b57cec5SDimitry Andric }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric /// ContainsLabel - Return true if the statement contains a label in it.  If
14670b57cec5SDimitry Andric /// this statement is not executed normally, it not containing a label means
14680b57cec5SDimitry Andric /// that we can just remove the code.
14690b57cec5SDimitry Andric bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
14700b57cec5SDimitry Andric   // Null statement, not a label!
14710b57cec5SDimitry Andric   if (!S) return false;
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   // If this is a label, we have to emit the code, consider something like:
14740b57cec5SDimitry Andric   // if (0) {  ...  foo:  bar(); }  goto foo;
14750b57cec5SDimitry Andric   //
14760b57cec5SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
14770b57cec5SDimitry Andric   // can't jump to one from outside their declared region.
14780b57cec5SDimitry Andric   if (isa<LabelStmt>(S))
14790b57cec5SDimitry Andric     return true;
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric   // If this is a case/default statement, and we haven't seen a switch, we have
14820b57cec5SDimitry Andric   // to emit the code.
14830b57cec5SDimitry Andric   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
14840b57cec5SDimitry Andric     return true;
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   // If this is a switch statement, we want to ignore cases below it.
14870b57cec5SDimitry Andric   if (isa<SwitchStmt>(S))
14880b57cec5SDimitry Andric     IgnoreCaseStmts = true;
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric   // Scan subexpressions for verboten labels.
14910b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
14920b57cec5SDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
14930b57cec5SDimitry Andric       return true;
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   return false;
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
14990b57cec5SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
15000b57cec5SDimitry Andric /// inside of it, this is fine.
15010b57cec5SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
15020b57cec5SDimitry Andric   // Null statement, not a label!
15030b57cec5SDimitry Andric   if (!S) return false;
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
15060b57cec5SDimitry Andric   // include it and anything inside of it.
15070b57cec5SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
15080b57cec5SDimitry Andric       isa<ForStmt>(S))
15090b57cec5SDimitry Andric     return false;
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric   if (isa<BreakStmt>(S))
15120b57cec5SDimitry Andric     return true;
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   // Scan subexpressions for verboten breaks.
15150b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
15160b57cec5SDimitry Andric     if (containsBreak(SubStmt))
15170b57cec5SDimitry Andric       return true;
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   return false;
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
15230b57cec5SDimitry Andric   if (!S) return false;
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
15260b57cec5SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
15270b57cec5SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
15280b57cec5SDimitry Andric   // correct even if more statement kinds are added.
15290b57cec5SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
15300b57cec5SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
15310b57cec5SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
15320b57cec5SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
15330b57cec5SDimitry Andric     return false;
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   if (isa<DeclStmt>(S))
15360b57cec5SDimitry Andric     return true;
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric   for (const Stmt *SubStmt : S->children())
15390b57cec5SDimitry Andric     if (mightAddDeclToScope(SubStmt))
15400b57cec5SDimitry Andric       return true;
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric   return false;
15430b57cec5SDimitry Andric }
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
15460b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
15470b57cec5SDimitry Andric /// constant folds return true and set the boolean result in Result.
15480b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
15490b57cec5SDimitry Andric                                                    bool &ResultBool,
15500b57cec5SDimitry Andric                                                    bool AllowLabels) {
15510b57cec5SDimitry Andric   llvm::APSInt ResultInt;
15520b57cec5SDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
15530b57cec5SDimitry Andric     return false;
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric   ResultBool = ResultInt.getBoolValue();
15560b57cec5SDimitry Andric   return true;
15570b57cec5SDimitry Andric }
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
15600b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
15610b57cec5SDimitry Andric /// constant folds return true and set the folded value.
15620b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
15630b57cec5SDimitry Andric                                                    llvm::APSInt &ResultInt,
15640b57cec5SDimitry Andric                                                    bool AllowLabels) {
15650b57cec5SDimitry Andric   // FIXME: Rename and handle conversion of other evaluatable things
15660b57cec5SDimitry Andric   // to bool.
15670b57cec5SDimitry Andric   Expr::EvalResult Result;
15680b57cec5SDimitry Andric   if (!Cond->EvaluateAsInt(Result, getContext()))
15690b57cec5SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   llvm::APSInt Int = Result.Val.getInt();
15720b57cec5SDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
15730b57cec5SDimitry Andric     return false;  // Contains a label.
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   ResultInt = Int;
15760b57cec5SDimitry Andric   return true;
15770b57cec5SDimitry Andric }
15780b57cec5SDimitry Andric 
1579e8d8bef9SDimitry Andric /// Determine whether the given condition is an instrumentable condition
1580e8d8bef9SDimitry Andric /// (i.e. no "&&" or "||").
1581e8d8bef9SDimitry Andric bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1582e8d8bef9SDimitry Andric   // Bypass simplistic logical-NOT operator before determining whether the
1583e8d8bef9SDimitry Andric   // condition contains any other logical operator.
1584e8d8bef9SDimitry Andric   if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
1585e8d8bef9SDimitry Andric     if (UnOp->getOpcode() == UO_LNot)
1586e8d8bef9SDimitry Andric       C = UnOp->getSubExpr();
15870b57cec5SDimitry Andric 
1588e8d8bef9SDimitry Andric   const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
1589e8d8bef9SDimitry Andric   return (!BOp || !BOp->isLogicalOp());
1590e8d8bef9SDimitry Andric }
1591e8d8bef9SDimitry Andric 
1592e8d8bef9SDimitry Andric /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1593e8d8bef9SDimitry Andric /// increments a profile counter based on the semantics of the given logical
1594e8d8bef9SDimitry Andric /// operator opcode.  This is used to instrument branch condition coverage for
1595e8d8bef9SDimitry Andric /// logical operators.
1596e8d8bef9SDimitry Andric void CodeGenFunction::EmitBranchToCounterBlock(
1597e8d8bef9SDimitry Andric     const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1598e8d8bef9SDimitry Andric     llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1599e8d8bef9SDimitry Andric     Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1600e8d8bef9SDimitry Andric   // If not instrumenting, just emit a branch.
1601e8d8bef9SDimitry Andric   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1602e8d8bef9SDimitry Andric   if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1603e8d8bef9SDimitry Andric     return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1604e8d8bef9SDimitry Andric 
160504eeddc0SDimitry Andric   llvm::BasicBlock *ThenBlock = nullptr;
160604eeddc0SDimitry Andric   llvm::BasicBlock *ElseBlock = nullptr;
160704eeddc0SDimitry Andric   llvm::BasicBlock *NextBlock = nullptr;
1608e8d8bef9SDimitry Andric 
1609e8d8bef9SDimitry Andric   // Create the block we'll use to increment the appropriate counter.
1610e8d8bef9SDimitry Andric   llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1611e8d8bef9SDimitry Andric 
1612e8d8bef9SDimitry Andric   // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1613e8d8bef9SDimitry Andric   // means we need to evaluate the condition and increment the counter on TRUE:
1614e8d8bef9SDimitry Andric   //
1615e8d8bef9SDimitry Andric   // if (Cond)
1616e8d8bef9SDimitry Andric   //   goto CounterIncrBlock;
1617e8d8bef9SDimitry Andric   // else
1618e8d8bef9SDimitry Andric   //   goto FalseBlock;
1619e8d8bef9SDimitry Andric   //
1620e8d8bef9SDimitry Andric   // CounterIncrBlock:
1621e8d8bef9SDimitry Andric   //   Counter++;
1622e8d8bef9SDimitry Andric   //   goto TrueBlock;
1623e8d8bef9SDimitry Andric 
1624e8d8bef9SDimitry Andric   if (LOp == BO_LAnd) {
1625e8d8bef9SDimitry Andric     ThenBlock = CounterIncrBlock;
1626e8d8bef9SDimitry Andric     ElseBlock = FalseBlock;
1627e8d8bef9SDimitry Andric     NextBlock = TrueBlock;
1628e8d8bef9SDimitry Andric   }
1629e8d8bef9SDimitry Andric 
1630e8d8bef9SDimitry Andric   // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1631e8d8bef9SDimitry Andric   // we need to evaluate the condition and increment the counter on FALSE:
1632e8d8bef9SDimitry Andric   //
1633e8d8bef9SDimitry Andric   // if (Cond)
1634e8d8bef9SDimitry Andric   //   goto TrueBlock;
1635e8d8bef9SDimitry Andric   // else
1636e8d8bef9SDimitry Andric   //   goto CounterIncrBlock;
1637e8d8bef9SDimitry Andric   //
1638e8d8bef9SDimitry Andric   // CounterIncrBlock:
1639e8d8bef9SDimitry Andric   //   Counter++;
1640e8d8bef9SDimitry Andric   //   goto FalseBlock;
1641e8d8bef9SDimitry Andric 
1642e8d8bef9SDimitry Andric   else if (LOp == BO_LOr) {
1643e8d8bef9SDimitry Andric     ThenBlock = TrueBlock;
1644e8d8bef9SDimitry Andric     ElseBlock = CounterIncrBlock;
1645e8d8bef9SDimitry Andric     NextBlock = FalseBlock;
1646e8d8bef9SDimitry Andric   } else {
1647e8d8bef9SDimitry Andric     llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1648e8d8bef9SDimitry Andric   }
1649e8d8bef9SDimitry Andric 
1650e8d8bef9SDimitry Andric   // Emit Branch based on condition.
1651e8d8bef9SDimitry Andric   EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1652e8d8bef9SDimitry Andric 
1653e8d8bef9SDimitry Andric   // Emit the block containing the counter increment(s).
1654e8d8bef9SDimitry Andric   EmitBlock(CounterIncrBlock);
1655e8d8bef9SDimitry Andric 
1656e8d8bef9SDimitry Andric   // Increment corresponding counter; if index not provided, use Cond as index.
1657e8d8bef9SDimitry Andric   incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
1658e8d8bef9SDimitry Andric 
1659e8d8bef9SDimitry Andric   // Go to the next block.
1660e8d8bef9SDimitry Andric   EmitBranch(NextBlock);
1661e8d8bef9SDimitry Andric }
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
16640b57cec5SDimitry Andric /// statement) to the specified blocks.  Based on the condition, this might try
16650b57cec5SDimitry Andric /// to simplify the codegen of the conditional based on the branch.
1666e8d8bef9SDimitry Andric /// \param LH The value of the likelihood attribute on the True branch.
16670b57cec5SDimitry Andric void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
16680b57cec5SDimitry Andric                                            llvm::BasicBlock *TrueBlock,
16690b57cec5SDimitry Andric                                            llvm::BasicBlock *FalseBlock,
1670e8d8bef9SDimitry Andric                                            uint64_t TrueCount,
1671e8d8bef9SDimitry Andric                                            Stmt::Likelihood LH) {
16720b57cec5SDimitry Andric   Cond = Cond->IgnoreParens();
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric     // Handle X && Y in a condition.
16770b57cec5SDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
16780b57cec5SDimitry Andric       // If we have "1 && X", simplify the code.  "0 && X" would have constant
16790b57cec5SDimitry Andric       // folded if the case was simple enough.
16800b57cec5SDimitry Andric       bool ConstantBool = false;
16810b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
16820b57cec5SDimitry Andric           ConstantBool) {
16830b57cec5SDimitry Andric         // br(1 && X) -> br(X).
16840b57cec5SDimitry Andric         incrementProfileCounter(CondBOp);
1685e8d8bef9SDimitry Andric         return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1686e8d8bef9SDimitry Andric                                         FalseBlock, TrueCount, LH);
16870b57cec5SDimitry Andric       }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric       // If we have "X && 1", simplify the code to use an uncond branch.
16900b57cec5SDimitry Andric       // "X && 0" would have been constant folded to 0.
16910b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
16920b57cec5SDimitry Andric           ConstantBool) {
16930b57cec5SDimitry Andric         // br(X && 1) -> br(X).
1694e8d8bef9SDimitry Andric         return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1695e8d8bef9SDimitry Andric                                         FalseBlock, TrueCount, LH, CondBOp);
16960b57cec5SDimitry Andric       }
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric       // Emit the LHS as a conditional.  If the LHS conditional is false, we
16990b57cec5SDimitry Andric       // want to jump to the FalseBlock.
17000b57cec5SDimitry Andric       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
17010b57cec5SDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
17020b57cec5SDimitry Andric       // can be propagated to that branch.
17030b57cec5SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric       ConditionalEvaluation eval(*this);
17060b57cec5SDimitry Andric       {
17070b57cec5SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
1708e8d8bef9SDimitry Andric         // Propagate the likelihood attribute like __builtin_expect
1709e8d8bef9SDimitry Andric         // __builtin_expect(X && Y, 1) -> X and Y are likely
1710e8d8bef9SDimitry Andric         // __builtin_expect(X && Y, 0) -> only Y is unlikely
1711e8d8bef9SDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1712e8d8bef9SDimitry Andric                              LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
17130b57cec5SDimitry Andric         EmitBlock(LHSTrue);
17140b57cec5SDimitry Andric       }
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric       incrementProfileCounter(CondBOp);
17170b57cec5SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric       // Any temporaries created here are conditional.
17200b57cec5SDimitry Andric       eval.begin(*this);
1721e8d8bef9SDimitry Andric       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1722e8d8bef9SDimitry Andric                                FalseBlock, TrueCount, LH);
17230b57cec5SDimitry Andric       eval.end(*this);
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric       return;
17260b57cec5SDimitry Andric     }
17270b57cec5SDimitry Andric 
17280b57cec5SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
17290b57cec5SDimitry Andric       // If we have "0 || X", simplify the code.  "1 || X" would have constant
17300b57cec5SDimitry Andric       // folded if the case was simple enough.
17310b57cec5SDimitry Andric       bool ConstantBool = false;
17320b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
17330b57cec5SDimitry Andric           !ConstantBool) {
17340b57cec5SDimitry Andric         // br(0 || X) -> br(X).
17350b57cec5SDimitry Andric         incrementProfileCounter(CondBOp);
1736e8d8bef9SDimitry Andric         return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1737e8d8bef9SDimitry Andric                                         FalseBlock, TrueCount, LH);
17380b57cec5SDimitry Andric       }
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric       // If we have "X || 0", simplify the code to use an uncond branch.
17410b57cec5SDimitry Andric       // "X || 1" would have been constant folded to 1.
17420b57cec5SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
17430b57cec5SDimitry Andric           !ConstantBool) {
17440b57cec5SDimitry Andric         // br(X || 0) -> br(X).
1745e8d8bef9SDimitry Andric         return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1746e8d8bef9SDimitry Andric                                         FalseBlock, TrueCount, LH, CondBOp);
17470b57cec5SDimitry Andric       }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric       // Emit the LHS as a conditional.  If the LHS conditional is true, we
17500b57cec5SDimitry Andric       // want to jump to the TrueBlock.
17510b57cec5SDimitry Andric       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
17520b57cec5SDimitry Andric       // We have the count for entry to the RHS and for the whole expression
17530b57cec5SDimitry Andric       // being true, so we can divy up True count between the short circuit and
17540b57cec5SDimitry Andric       // the RHS.
17550b57cec5SDimitry Andric       uint64_t LHSCount =
17560b57cec5SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
17570b57cec5SDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric       ConditionalEvaluation eval(*this);
17600b57cec5SDimitry Andric       {
1761e8d8bef9SDimitry Andric         // Propagate the likelihood attribute like __builtin_expect
1762e8d8bef9SDimitry Andric         // __builtin_expect(X || Y, 1) -> only Y is likely
1763e8d8bef9SDimitry Andric         // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
17640b57cec5SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
1765e8d8bef9SDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1766e8d8bef9SDimitry Andric                              LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
17670b57cec5SDimitry Andric         EmitBlock(LHSFalse);
17680b57cec5SDimitry Andric       }
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric       incrementProfileCounter(CondBOp);
17710b57cec5SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric       // Any temporaries created here are conditional.
17740b57cec5SDimitry Andric       eval.begin(*this);
1775e8d8bef9SDimitry Andric       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1776e8d8bef9SDimitry Andric                                RHSCount, LH);
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric       eval.end(*this);
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric       return;
17810b57cec5SDimitry Andric     }
17820b57cec5SDimitry Andric   }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
17850b57cec5SDimitry Andric     // br(!x, t, f) -> br(x, f, t)
17860b57cec5SDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
17870b57cec5SDimitry Andric       // Negate the count.
17880b57cec5SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1789e8d8bef9SDimitry Andric       // The values of the enum are chosen to make this negation possible.
1790e8d8bef9SDimitry Andric       LH = static_cast<Stmt::Likelihood>(-LH);
17910b57cec5SDimitry Andric       // Negate the condition and swap the destination blocks.
17920b57cec5SDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1793e8d8bef9SDimitry Andric                                   FalseCount, LH);
17940b57cec5SDimitry Andric     }
17950b57cec5SDimitry Andric   }
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
17980b57cec5SDimitry Andric     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
17990b57cec5SDimitry Andric     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
18000b57cec5SDimitry Andric     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
18010b57cec5SDimitry Andric 
1802e8d8bef9SDimitry Andric     // The ConditionalOperator itself has no likelihood information for its
1803e8d8bef9SDimitry Andric     // true and false branches. This matches the behavior of __builtin_expect.
18040b57cec5SDimitry Andric     ConditionalEvaluation cond(*this);
18050b57cec5SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1806e8d8bef9SDimitry Andric                          getProfileCount(CondOp), Stmt::LH_None);
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric     // When computing PGO branch weights, we only know the overall count for
18090b57cec5SDimitry Andric     // the true block. This code is essentially doing tail duplication of the
18100b57cec5SDimitry Andric     // naive code-gen, introducing new edges for which counts are not
18110b57cec5SDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
18120b57cec5SDimitry Andric     // the conditional operator.
18130b57cec5SDimitry Andric     uint64_t LHSScaledTrueCount = 0;
18140b57cec5SDimitry Andric     if (TrueCount) {
18150b57cec5SDimitry Andric       double LHSRatio =
18160b57cec5SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
18170b57cec5SDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
18180b57cec5SDimitry Andric     }
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric     cond.begin(*this);
18210b57cec5SDimitry Andric     EmitBlock(LHSBlock);
18220b57cec5SDimitry Andric     incrementProfileCounter(CondOp);
18230b57cec5SDimitry Andric     {
18240b57cec5SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
18250b57cec5SDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1826e8d8bef9SDimitry Andric                            LHSScaledTrueCount, LH);
18270b57cec5SDimitry Andric     }
18280b57cec5SDimitry Andric     cond.end(*this);
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric     cond.begin(*this);
18310b57cec5SDimitry Andric     EmitBlock(RHSBlock);
18320b57cec5SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1833e8d8bef9SDimitry Andric                          TrueCount - LHSScaledTrueCount, LH);
18340b57cec5SDimitry Andric     cond.end(*this);
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric     return;
18370b57cec5SDimitry Andric   }
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
18400b57cec5SDimitry Andric     // Conditional operator handling can give us a throw expression as a
18410b57cec5SDimitry Andric     // condition for a case like:
18420b57cec5SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
18430b57cec5SDimitry Andric     // Fold this to:
18440b57cec5SDimitry Andric     //   br(c, throw x, br(y, t, f))
18450b57cec5SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
18460b57cec5SDimitry Andric     return;
18470b57cec5SDimitry Andric   }
18480b57cec5SDimitry Andric 
1849fe6060f1SDimitry Andric   // Emit the code with the fully general case.
1850fe6060f1SDimitry Andric   llvm::Value *CondV;
1851fe6060f1SDimitry Andric   {
1852fe6060f1SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
1853fe6060f1SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
1854fe6060f1SDimitry Andric   }
1855fe6060f1SDimitry Andric 
1856fe6060f1SDimitry Andric   llvm::MDNode *Weights = nullptr;
1857fe6060f1SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
1858fe6060f1SDimitry Andric 
18590b57cec5SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
18600b57cec5SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
18610b57cec5SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
18620b57cec5SDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
18630b57cec5SDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
18640b57cec5SDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
18650b57cec5SDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
18660b57cec5SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
18670b57cec5SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
18680b57cec5SDimitry Andric     }
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
1871fe6060f1SDimitry Andric   // If there is a Likelihood knowledge for the cond, lower it.
1872fe6060f1SDimitry Andric   // Note that if not optimizing this won't emit anything.
1873fe6060f1SDimitry Andric   llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
1874fe6060f1SDimitry Andric   if (CondV != NewCondV)
1875fe6060f1SDimitry Andric     CondV = NewCondV;
1876fe6060f1SDimitry Andric   else {
1877fe6060f1SDimitry Andric     // Otherwise, lower profile counts. Note that we do this even at -O0.
18780b57cec5SDimitry Andric     uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1879e8d8bef9SDimitry Andric     Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
1880e8d8bef9SDimitry Andric   }
18810b57cec5SDimitry Andric 
18820b57cec5SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
18830b57cec5SDimitry Andric }
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
18860b57cec5SDimitry Andric /// specified stmt yet.
18870b57cec5SDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
18880b57cec5SDimitry Andric   CGM.ErrorUnsupported(S, Type);
18890b57cec5SDimitry Andric }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
18920b57cec5SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
18930b57cec5SDimitry Andric ///
18940b57cec5SDimitry Andric /// \param baseType the inner-most element type of the array
18950b57cec5SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
18960b57cec5SDimitry Andric /// base element of the array
18970b57cec5SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
18980b57cec5SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
18990b57cec5SDimitry Andric                                Address dest, Address src,
19000b57cec5SDimitry Andric                                llvm::Value *sizeInChars) {
19010b57cec5SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
19040b57cec5SDimitry Andric   llvm::Value *baseSizeInChars
19050b57cec5SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric   Address begin =
19080b57cec5SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1909fe6060f1SDimitry Andric   llvm::Value *end = Builder.CreateInBoundsGEP(
1910fe6060f1SDimitry Andric       begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
19130b57cec5SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
19140b57cec5SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
19170b57cec5SDimitry Andric   // count must be nonzero.
19180b57cec5SDimitry Andric   CGF.EmitBlock(loopBB);
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
19210b57cec5SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric   CharUnits curAlign =
19240b57cec5SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric   // memcpy the individual element bit-pattern.
19270b57cec5SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
19280b57cec5SDimitry Andric                        /*volatile*/ false);
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric   // Go to the next element.
19310b57cec5SDimitry Andric   llvm::Value *next =
19320b57cec5SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric   // Leave if that's the end of the VLA.
19350b57cec5SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
19360b57cec5SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
19370b57cec5SDimitry Andric   cur->addIncoming(next, loopBB);
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   CGF.EmitBlock(contBB);
19400b57cec5SDimitry Andric }
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric void
19430b57cec5SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
19440b57cec5SDimitry Andric   // Ignore empty classes in C++.
19450b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus) {
19460b57cec5SDimitry Andric     if (const RecordType *RT = Ty->getAs<RecordType>()) {
19470b57cec5SDimitry Andric       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
19480b57cec5SDimitry Andric         return;
19490b57cec5SDimitry Andric     }
19500b57cec5SDimitry Andric   }
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
19530b57cec5SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
19540b57cec5SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric   // Get size and alignment info for this aggregate.
19570b57cec5SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric   llvm::Value *SizeVal;
19600b57cec5SDimitry Andric   const VariableArrayType *vla;
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric   // Don't bother emitting a zero-byte memset.
19630b57cec5SDimitry Andric   if (size.isZero()) {
19640b57cec5SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
19650b57cec5SDimitry Andric     if (const VariableArrayType *vlaType =
19660b57cec5SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
19670b57cec5SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
19680b57cec5SDimitry Andric       auto VlaSize = getVLASize(vlaType);
19690b57cec5SDimitry Andric       SizeVal = VlaSize.NumElts;
19700b57cec5SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
19710b57cec5SDimitry Andric       if (!eltSize.isOne())
19720b57cec5SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
19730b57cec5SDimitry Andric       vla = vlaType;
19740b57cec5SDimitry Andric     } else {
19750b57cec5SDimitry Andric       return;
19760b57cec5SDimitry Andric     }
19770b57cec5SDimitry Andric   } else {
19780b57cec5SDimitry Andric     SizeVal = CGM.getSize(size);
19790b57cec5SDimitry Andric     vla = nullptr;
19800b57cec5SDimitry Andric   }
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
19830b57cec5SDimitry Andric   // Instead, create a null constant and copy it to the destination.
19840b57cec5SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
19850b57cec5SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
19860b57cec5SDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
19870b57cec5SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
19880b57cec5SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
19910b57cec5SDimitry Andric 
19920b57cec5SDimitry Andric     llvm::GlobalVariable *NullVariable =
19930b57cec5SDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
19940b57cec5SDimitry Andric                                /*isConstant=*/true,
19950b57cec5SDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
19960b57cec5SDimitry Andric                                NullConstant, Twine());
19970b57cec5SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
1998a7dea167SDimitry Andric     NullVariable->setAlignment(NullAlign.getAsAlign());
19990b57cec5SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
20000b57cec5SDimitry Andric                    NullAlign);
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
20050b57cec5SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
20060b57cec5SDimitry Andric     return;
20070b57cec5SDimitry Andric   }
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
20100b57cec5SDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
20110b57cec5SDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
20120b57cec5SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
20160b57cec5SDimitry Andric   // Make sure that there is a block for the indirect goto.
20170b57cec5SDimitry Andric   if (!IndirectBranch)
20180b57cec5SDimitry Andric     GetIndirectGotoBlock();
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric   // Make sure the indirect branch includes all of the address-taken blocks.
20230b57cec5SDimitry Andric   IndirectBranch->addDestination(BB);
20240b57cec5SDimitry Andric   return llvm::BlockAddress::get(CurFn, BB);
20250b57cec5SDimitry Andric }
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
20280b57cec5SDimitry Andric   // If we already made the indirect branch for indirect goto, return its block.
20290b57cec5SDimitry Andric   if (IndirectBranch) return IndirectBranch->getParent();
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   // Create the PHI node that indirect gotos will add entries to.
20340b57cec5SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
20350b57cec5SDimitry Andric                                               "indirect.goto.dest");
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric   // Create the indirect branch instruction.
20380b57cec5SDimitry Andric   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
20390b57cec5SDimitry Andric   return IndirectBranch->getParent();
20400b57cec5SDimitry Andric }
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric /// Computes the length of an array in elements, as well as the base
20430b57cec5SDimitry Andric /// element type and a properly-typed first element pointer.
20440b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
20450b57cec5SDimitry Andric                                               QualType &baseType,
20460b57cec5SDimitry Andric                                               Address &addr) {
20470b57cec5SDimitry Andric   const ArrayType *arrayType = origArrayType;
20480b57cec5SDimitry Andric 
20490b57cec5SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
20500b57cec5SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
20510b57cec5SDimitry Andric   llvm::Value *numVLAElements = nullptr;
20520b57cec5SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
20530b57cec5SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
20560b57cec5SDimitry Andric     // which has type T* where T is the first non-VLA element type.
20570b57cec5SDimitry Andric     do {
20580b57cec5SDimitry Andric       QualType elementType = arrayType->getElementType();
20590b57cec5SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
20620b57cec5SDimitry Andric       if (!arrayType) {
20630b57cec5SDimitry Andric         baseType = elementType;
20640b57cec5SDimitry Andric         return numVLAElements;
20650b57cec5SDimitry Andric       }
20660b57cec5SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric     // We get out here only if we find a constant array type
20690b57cec5SDimitry Andric     // inside the VLA.
20700b57cec5SDimitry Andric   }
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric   // We have some number of constant-length arrays, so addr should
20730b57cec5SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
20740b57cec5SDimitry Andric   // down to the first element of addr.
20750b57cec5SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric   // GEP down to the array type.
20780b57cec5SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
20790b57cec5SDimitry Andric   gepIndices.push_back(zero);
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric   uint64_t countFromCLAs = 1;
20820b57cec5SDimitry Andric   QualType eltType;
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric   llvm::ArrayType *llvmArrayType =
20850b57cec5SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
20860b57cec5SDimitry Andric   while (llvmArrayType) {
20870b57cec5SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
20880b57cec5SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
20890b57cec5SDimitry Andric              == llvmArrayType->getNumElements());
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric     gepIndices.push_back(zero);
20920b57cec5SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
20930b57cec5SDimitry Andric     eltType = arrayType->getElementType();
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     llvmArrayType =
20960b57cec5SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
20970b57cec5SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
20980b57cec5SDimitry Andric     assert((!llvmArrayType || arrayType) &&
20990b57cec5SDimitry Andric            "LLVM and Clang types are out-of-synch");
21000b57cec5SDimitry Andric   }
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   if (arrayType) {
21030b57cec5SDimitry Andric     // From this point onwards, the Clang array type has been emitted
21040b57cec5SDimitry Andric     // as some other type (probably a packed struct). Compute the array
21050b57cec5SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
21060b57cec5SDimitry Andric     while (arrayType) {
21070b57cec5SDimitry Andric       countFromCLAs *=
21080b57cec5SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
21090b57cec5SDimitry Andric       eltType = arrayType->getElementType();
21100b57cec5SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
21110b57cec5SDimitry Andric     }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
21140b57cec5SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
21150b57cec5SDimitry Andric   } else {
21160b57cec5SDimitry Andric     // Create the actual GEP.
2117fe6060f1SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(
2118fe6060f1SDimitry Andric         addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
211904eeddc0SDimitry Andric         ConvertTypeForMem(eltType),
21200b57cec5SDimitry Andric         addr.getAlignment());
21210b57cec5SDimitry Andric   }
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric   baseType = eltType;
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric   llvm::Value *numElements
21260b57cec5SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
21270b57cec5SDimitry Andric 
21280b57cec5SDimitry Andric   // If we had any VLA dimensions, factor them in.
21290b57cec5SDimitry Andric   if (numVLAElements)
21300b57cec5SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
21310b57cec5SDimitry Andric 
21320b57cec5SDimitry Andric   return numElements;
21330b57cec5SDimitry Andric }
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
21360b57cec5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
21370b57cec5SDimitry Andric   assert(vla && "type was not a variable array type!");
21380b57cec5SDimitry Andric   return getVLASize(vla);
21390b57cec5SDimitry Andric }
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
21420b57cec5SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
21430b57cec5SDimitry Andric   // The number of elements so far; always size_t.
21440b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   QualType elementType;
21470b57cec5SDimitry Andric   do {
21480b57cec5SDimitry Andric     elementType = type->getElementType();
21490b57cec5SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
21500b57cec5SDimitry Andric     assert(vlaSize && "no size for VLA!");
21510b57cec5SDimitry Andric     assert(vlaSize->getType() == SizeTy);
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric     if (!numElements) {
21540b57cec5SDimitry Andric       numElements = vlaSize;
21550b57cec5SDimitry Andric     } else {
21560b57cec5SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
21570b57cec5SDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
21580b57cec5SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
21590b57cec5SDimitry Andric     }
21600b57cec5SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric   return { numElements, elementType };
21630b57cec5SDimitry Andric }
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
21660b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(QualType type) {
21670b57cec5SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
21680b57cec5SDimitry Andric   assert(vla && "type was not a variable array type!");
21690b57cec5SDimitry Andric   return getVLAElements1D(vla);
21700b57cec5SDimitry Andric }
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric CodeGenFunction::VlaSizePair
21730b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
21740b57cec5SDimitry Andric   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
21750b57cec5SDimitry Andric   assert(VlaSize && "no size for VLA!");
21760b57cec5SDimitry Andric   assert(VlaSize->getType() == SizeTy);
21770b57cec5SDimitry Andric   return { VlaSize, Vla->getElementType() };
21780b57cec5SDimitry Andric }
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
21810b57cec5SDimitry Andric   assert(type->isVariablyModifiedType() &&
21820b57cec5SDimitry Andric          "Must pass variably modified type to EmitVLASizes!");
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   EnsureInsertPoint();
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric   // We're going to walk down into the type and look for VLA
21870b57cec5SDimitry Andric   // expressions.
21880b57cec5SDimitry Andric   do {
21890b57cec5SDimitry Andric     assert(type->isVariablyModifiedType());
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric     const Type *ty = type.getTypePtr();
21920b57cec5SDimitry Andric     switch (ty->getTypeClass()) {
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric #define TYPE(Class, Base)
21950b57cec5SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
21960b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
21970b57cec5SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
21980b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2199a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
22000b57cec5SDimitry Andric       llvm_unreachable("unexpected dependent type!");
22010b57cec5SDimitry Andric 
22020b57cec5SDimitry Andric     // These types are never variably-modified.
22030b57cec5SDimitry Andric     case Type::Builtin:
22040b57cec5SDimitry Andric     case Type::Complex:
22050b57cec5SDimitry Andric     case Type::Vector:
22060b57cec5SDimitry Andric     case Type::ExtVector:
22075ffd83dbSDimitry Andric     case Type::ConstantMatrix:
22080b57cec5SDimitry Andric     case Type::Record:
22090b57cec5SDimitry Andric     case Type::Enum:
22100b57cec5SDimitry Andric     case Type::Elaborated:
22110eae32dcSDimitry Andric     case Type::Using:
22120b57cec5SDimitry Andric     case Type::TemplateSpecialization:
22130b57cec5SDimitry Andric     case Type::ObjCTypeParam:
22140b57cec5SDimitry Andric     case Type::ObjCObject:
22150b57cec5SDimitry Andric     case Type::ObjCInterface:
22160b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
22170eae32dcSDimitry Andric     case Type::BitInt:
22180b57cec5SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric     case Type::Adjusted:
22210b57cec5SDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
22220b57cec5SDimitry Andric       break;
22230b57cec5SDimitry Andric 
22240b57cec5SDimitry Andric     case Type::Decayed:
22250b57cec5SDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
22260b57cec5SDimitry Andric       break;
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric     case Type::Pointer:
22290b57cec5SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
22300b57cec5SDimitry Andric       break;
22310b57cec5SDimitry Andric 
22320b57cec5SDimitry Andric     case Type::BlockPointer:
22330b57cec5SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
22340b57cec5SDimitry Andric       break;
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric     case Type::LValueReference:
22370b57cec5SDimitry Andric     case Type::RValueReference:
22380b57cec5SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
22390b57cec5SDimitry Andric       break;
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric     case Type::MemberPointer:
22420b57cec5SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
22430b57cec5SDimitry Andric       break;
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric     case Type::ConstantArray:
22460b57cec5SDimitry Andric     case Type::IncompleteArray:
22470b57cec5SDimitry Andric       // Losing element qualification here is fine.
22480b57cec5SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
22490b57cec5SDimitry Andric       break;
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric     case Type::VariableArray: {
22520b57cec5SDimitry Andric       // Losing element qualification here is fine.
22530b57cec5SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric       // Unknown size indication requires no size computation.
22560b57cec5SDimitry Andric       // Otherwise, evaluate and record it.
225704eeddc0SDimitry Andric       if (const Expr *sizeExpr = vat->getSizeExpr()) {
22580b57cec5SDimitry Andric         // It's possible that we might have emitted this already,
22590b57cec5SDimitry Andric         // e.g. with a typedef and a pointer to it.
226004eeddc0SDimitry Andric         llvm::Value *&entry = VLASizeMap[sizeExpr];
22610b57cec5SDimitry Andric         if (!entry) {
226204eeddc0SDimitry Andric           llvm::Value *size = EmitScalarExpr(sizeExpr);
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric           // C11 6.7.6.2p5:
22650b57cec5SDimitry Andric           //   If the size is an expression that is not an integer constant
22660b57cec5SDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
22670b57cec5SDimitry Andric           //   greater than zero.
226804eeddc0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound)) {
22690b57cec5SDimitry Andric             SanitizerScope SanScope(this);
227004eeddc0SDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
227104eeddc0SDimitry Andric             clang::QualType SEType = sizeExpr->getType();
227204eeddc0SDimitry Andric             llvm::Value *CheckCondition =
227304eeddc0SDimitry Andric                 SEType->isSignedIntegerType()
227404eeddc0SDimitry Andric                     ? Builder.CreateICmpSGT(size, Zero)
227504eeddc0SDimitry Andric                     : Builder.CreateICmpUGT(size, Zero);
22760b57cec5SDimitry Andric             llvm::Constant *StaticArgs[] = {
227704eeddc0SDimitry Andric                 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
227804eeddc0SDimitry Andric                 EmitCheckTypeDescriptor(SEType)};
227904eeddc0SDimitry Andric             EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
228004eeddc0SDimitry Andric                       SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
22810b57cec5SDimitry Andric           }
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric           // Always zexting here would be wrong if it weren't
22840b57cec5SDimitry Andric           // undefined behavior to have a negative bound.
228504eeddc0SDimitry Andric           // FIXME: What about when size's type is larger than size_t?
228604eeddc0SDimitry Andric           entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
22870b57cec5SDimitry Andric         }
22880b57cec5SDimitry Andric       }
22890b57cec5SDimitry Andric       type = vat->getElementType();
22900b57cec5SDimitry Andric       break;
22910b57cec5SDimitry Andric     }
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric     case Type::FunctionProto:
22940b57cec5SDimitry Andric     case Type::FunctionNoProto:
22950b57cec5SDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
22960b57cec5SDimitry Andric       break;
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric     case Type::Paren:
22990b57cec5SDimitry Andric     case Type::TypeOf:
23000b57cec5SDimitry Andric     case Type::UnaryTransform:
23010b57cec5SDimitry Andric     case Type::Attributed:
23020b57cec5SDimitry Andric     case Type::SubstTemplateTypeParm:
23030b57cec5SDimitry Andric     case Type::MacroQualified:
23040b57cec5SDimitry Andric       // Keep walking after single level desugaring.
23050b57cec5SDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
23060b57cec5SDimitry Andric       break;
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric     case Type::Typedef:
23090b57cec5SDimitry Andric     case Type::Decltype:
23100b57cec5SDimitry Andric     case Type::Auto:
23110b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
23120b57cec5SDimitry Andric       // Stop walking: nothing to do.
23130b57cec5SDimitry Andric       return;
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric     case Type::TypeOfExpr:
23160b57cec5SDimitry Andric       // Stop walking: emit typeof expression.
23170b57cec5SDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
23180b57cec5SDimitry Andric       return;
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric     case Type::Atomic:
23210b57cec5SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
23220b57cec5SDimitry Andric       break;
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric     case Type::Pipe:
23250b57cec5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
23260b57cec5SDimitry Andric       break;
23270b57cec5SDimitry Andric     }
23280b57cec5SDimitry Andric   } while (type->isVariablyModifiedType());
23290b57cec5SDimitry Andric }
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
23320b57cec5SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
23330b57cec5SDimitry Andric     return EmitPointerWithAlignment(E);
2334480093f4SDimitry Andric   return EmitLValue(E).getAddress(*this);
23350b57cec5SDimitry Andric }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2338480093f4SDimitry Andric   return EmitLValue(E).getAddress(*this);
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
23420b57cec5SDimitry Andric                                               const APValue &Init) {
23430b57cec5SDimitry Andric   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
23440b57cec5SDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
2345480093f4SDimitry Andric     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
23460b57cec5SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
23470b57cec5SDimitry Andric }
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric CodeGenFunction::PeepholeProtection
23500b57cec5SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
23510b57cec5SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
23520b57cec5SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
23530b57cec5SDimitry Andric   // extend this protection.
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
23560b57cec5SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
23570b57cec5SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   // Just make an extra bitcast.
23600b57cec5SDimitry Andric   assert(HaveInsertPoint());
23610b57cec5SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
23620b57cec5SDimitry Andric                                                   Builder.GetInsertBlock());
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   PeepholeProtection protection;
23650b57cec5SDimitry Andric   protection.Inst = inst;
23660b57cec5SDimitry Andric   return protection;
23670b57cec5SDimitry Andric }
23680b57cec5SDimitry Andric 
23690b57cec5SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
23700b57cec5SDimitry Andric   if (!protection.Inst) return;
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
23730b57cec5SDimitry Andric   protection.Inst->eraseFromParent();
23740b57cec5SDimitry Andric }
23750b57cec5SDimitry Andric 
23765ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
23770b57cec5SDimitry Andric                                               QualType Ty, SourceLocation Loc,
23780b57cec5SDimitry Andric                                               SourceLocation AssumptionLoc,
23790b57cec5SDimitry Andric                                               llvm::Value *Alignment,
23800b57cec5SDimitry Andric                                               llvm::Value *OffsetValue) {
2381e8d8bef9SDimitry Andric   if (Alignment->getType() != IntPtrTy)
2382e8d8bef9SDimitry Andric     Alignment =
2383e8d8bef9SDimitry Andric         Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2384e8d8bef9SDimitry Andric   if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2385e8d8bef9SDimitry Andric     OffsetValue =
2386e8d8bef9SDimitry Andric         Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2387e8d8bef9SDimitry Andric   llvm::Value *TheCheck = nullptr;
2388590d96feSDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment)) {
2389e8d8bef9SDimitry Andric     llvm::Value *PtrIntValue =
2390e8d8bef9SDimitry Andric         Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2391e8d8bef9SDimitry Andric 
2392e8d8bef9SDimitry Andric     if (OffsetValue) {
2393e8d8bef9SDimitry Andric       bool IsOffsetZero = false;
2394e8d8bef9SDimitry Andric       if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2395e8d8bef9SDimitry Andric         IsOffsetZero = CI->isZero();
2396e8d8bef9SDimitry Andric 
2397e8d8bef9SDimitry Andric       if (!IsOffsetZero)
2398e8d8bef9SDimitry Andric         PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2399e8d8bef9SDimitry Andric     }
2400e8d8bef9SDimitry Andric 
2401e8d8bef9SDimitry Andric     llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2402e8d8bef9SDimitry Andric     llvm::Value *Mask =
2403e8d8bef9SDimitry Andric         Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2404e8d8bef9SDimitry Andric     llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2405e8d8bef9SDimitry Andric     TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2406e8d8bef9SDimitry Andric   }
2407e8d8bef9SDimitry Andric   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2408e8d8bef9SDimitry Andric       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2409e8d8bef9SDimitry Andric 
2410e8d8bef9SDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
2411e8d8bef9SDimitry Andric     return;
24125ffd83dbSDimitry Andric   emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
24135ffd83dbSDimitry Andric                                OffsetValue, TheCheck, Assumption);
24145ffd83dbSDimitry Andric }
24155ffd83dbSDimitry Andric 
24165ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
24170b57cec5SDimitry Andric                                               const Expr *E,
24180b57cec5SDimitry Andric                                               SourceLocation AssumptionLoc,
2419a7dea167SDimitry Andric                                               llvm::Value *Alignment,
24200b57cec5SDimitry Andric                                               llvm::Value *OffsetValue) {
24210b57cec5SDimitry Andric   if (auto *CE = dyn_cast<CastExpr>(E))
24220b57cec5SDimitry Andric     E = CE->getSubExprAsWritten();
24230b57cec5SDimitry Andric   QualType Ty = E->getType();
24240b57cec5SDimitry Andric   SourceLocation Loc = E->getExprLoc();
24250b57cec5SDimitry Andric 
24265ffd83dbSDimitry Andric   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
24270b57cec5SDimitry Andric                           OffsetValue);
24280b57cec5SDimitry Andric }
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
24310b57cec5SDimitry Andric                                                  llvm::Value *AnnotatedVal,
24320b57cec5SDimitry Andric                                                  StringRef AnnotationStr,
2433e8d8bef9SDimitry Andric                                                  SourceLocation Location,
2434e8d8bef9SDimitry Andric                                                  const AnnotateAttr *Attr) {
2435e8d8bef9SDimitry Andric   SmallVector<llvm::Value *, 5> Args = {
24360b57cec5SDimitry Andric       AnnotatedVal,
24370b57cec5SDimitry Andric       Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
24380b57cec5SDimitry Andric       Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2439e8d8bef9SDimitry Andric       CGM.EmitAnnotationLineNo(Location),
24400b57cec5SDimitry Andric   };
2441e8d8bef9SDimitry Andric   if (Attr)
2442e8d8bef9SDimitry Andric     Args.push_back(CGM.EmitAnnotationArgs(Attr));
24430b57cec5SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
24440b57cec5SDimitry Andric }
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
24470b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
24480b57cec5SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
24490b57cec5SDimitry Andric   // llvm-gcc was doing.
24500b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
24510b57cec5SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
24520b57cec5SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2453e8d8bef9SDimitry Andric                        I->getAnnotation(), D->getLocation(), I);
24540b57cec5SDimitry Andric }
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
24570b57cec5SDimitry Andric                                               Address Addr) {
24580b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
24590b57cec5SDimitry Andric   llvm::Value *V = Addr.getPointer();
24600b57cec5SDimitry Andric   llvm::Type *VTy = V->getType();
2461349cc55cSDimitry Andric   auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2462349cc55cSDimitry Andric   unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2463349cc55cSDimitry Andric   llvm::PointerType *IntrinTy =
2464349cc55cSDimitry Andric       llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
2465349cc55cSDimitry Andric   llvm::Function *F =
2466349cc55cSDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
24690b57cec5SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
24700b57cec5SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
24710b57cec5SDimitry Andric     // itself.
2472349cc55cSDimitry Andric     if (VTy != IntrinTy)
2473349cc55cSDimitry Andric       V = Builder.CreateBitCast(V, IntrinTy);
2474e8d8bef9SDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
24750b57cec5SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
24760b57cec5SDimitry Andric   }
24770b57cec5SDimitry Andric 
24780b57cec5SDimitry Andric   return Address(V, Addr.getAlignment());
24790b57cec5SDimitry Andric }
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
24840b57cec5SDimitry Andric     : CGF(CGF) {
24850b57cec5SDimitry Andric   assert(!CGF->IsSanitizerScope);
24860b57cec5SDimitry Andric   CGF->IsSanitizerScope = true;
24870b57cec5SDimitry Andric }
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
24900b57cec5SDimitry Andric   CGF->IsSanitizerScope = false;
24910b57cec5SDimitry Andric }
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
24940b57cec5SDimitry Andric                                    const llvm::Twine &Name,
24950b57cec5SDimitry Andric                                    llvm::BasicBlock *BB,
24960b57cec5SDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
24970b57cec5SDimitry Andric   LoopStack.InsertHelper(I);
24980b57cec5SDimitry Andric   if (IsSanitizerScope)
24990b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
25000b57cec5SDimitry Andric }
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric void CGBuilderInserter::InsertHelper(
25030b57cec5SDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
25040b57cec5SDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
25050b57cec5SDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
25060b57cec5SDimitry Andric   if (CGF)
25070b57cec5SDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
25080b57cec5SDimitry Andric }
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the
25110b57cec5SDimitry Andric // called function.
25120b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
25130b57cec5SDimitry Andric                                           const FunctionDecl *TargetDecl) {
25140b57cec5SDimitry Andric   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
25150b57cec5SDimitry Andric }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the
25180b57cec5SDimitry Andric // called function.
25190b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
25200b57cec5SDimitry Andric                                           const FunctionDecl *TargetDecl) {
25210b57cec5SDimitry Andric   // Early exit if this is an indirect call.
25220b57cec5SDimitry Andric   if (!TargetDecl)
25230b57cec5SDimitry Andric     return;
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
25260b57cec5SDimitry Andric   // we can't check the target features anyhow.
2527a7dea167SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
25280b57cec5SDimitry Andric   if (!FD)
25290b57cec5SDimitry Andric     return;
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
25320b57cec5SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
25330b57cec5SDimitry Andric   // listed cpu and any listed features.
25340b57cec5SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
25350b57cec5SDimitry Andric   std::string MissingFeature;
2536e8d8bef9SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
2537e8d8bef9SDimitry Andric   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
25380b57cec5SDimitry Andric   if (BuiltinID) {
2539e8d8bef9SDimitry Andric     StringRef FeatureList(
2540e8d8bef9SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
25410b57cec5SDimitry Andric     // Return if the builtin doesn't have any required features.
2542e8d8bef9SDimitry Andric     if (FeatureList.empty())
25430b57cec5SDimitry Andric       return;
2544349cc55cSDimitry Andric     assert(!FeatureList.contains(' ') && "Space in feature list");
2545e8d8bef9SDimitry Andric     TargetFeatures TF(CallerFeatureMap);
2546e8d8bef9SDimitry Andric     if (!TF.hasRequiredFeatures(FeatureList))
25470b57cec5SDimitry Andric       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2548e8d8bef9SDimitry Andric           << TargetDecl->getDeclName() << FeatureList;
2549480093f4SDimitry Andric   } else if (!TargetDecl->isMultiVersion() &&
2550480093f4SDimitry Andric              TargetDecl->hasAttr<TargetAttr>()) {
25510b57cec5SDimitry Andric     // Get the required features for the callee.
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2554480093f4SDimitry Andric     ParsedTargetAttr ParsedAttr =
2555480093f4SDimitry Andric         CGM.getContext().filterFunctionTargetAttrs(TD);
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
25580b57cec5SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
2559*c3ca3130SDimitry Andric     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric     for (const auto &F : ParsedAttr.Features) {
25620b57cec5SDimitry Andric       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
25630b57cec5SDimitry Andric         ReqFeatures.push_back(StringRef(F).substr(1));
25640b57cec5SDimitry Andric     }
25650b57cec5SDimitry Andric 
25660b57cec5SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
25670b57cec5SDimitry Andric       // Only positive features are "required".
25680b57cec5SDimitry Andric       if (F.getValue())
25690b57cec5SDimitry Andric         ReqFeatures.push_back(F.getKey());
25700b57cec5SDimitry Andric     }
2571e8d8bef9SDimitry Andric     if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2572e8d8bef9SDimitry Andric       if (!CallerFeatureMap.lookup(Feature)) {
2573e8d8bef9SDimitry Andric         MissingFeature = Feature.str();
2574e8d8bef9SDimitry Andric         return false;
2575e8d8bef9SDimitry Andric       }
2576e8d8bef9SDimitry Andric       return true;
2577e8d8bef9SDimitry Andric     }))
25780b57cec5SDimitry Andric       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
25790b57cec5SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
25800b57cec5SDimitry Andric   }
25810b57cec5SDimitry Andric }
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
25840b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
25850b57cec5SDimitry Andric     return;
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
25880b57cec5SDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
25890b57cec5SDimitry Andric   CGM.getSanStats().create(IRB, SSK);
25900b57cec5SDimitry Andric }
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric llvm::Value *
25930b57cec5SDimitry Andric CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
25940b57cec5SDimitry Andric   llvm::Value *Condition = nullptr;
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
25970b57cec5SDimitry Andric     Condition = EmitX86CpuIs(RO.Conditions.Architecture);
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   if (!RO.Conditions.Features.empty()) {
26000b57cec5SDimitry Andric     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
26010b57cec5SDimitry Andric     Condition =
26020b57cec5SDimitry Andric         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
26030b57cec5SDimitry Andric   }
26040b57cec5SDimitry Andric   return Condition;
26050b57cec5SDimitry Andric }
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
26080b57cec5SDimitry Andric                                              llvm::Function *Resolver,
26090b57cec5SDimitry Andric                                              CGBuilderTy &Builder,
26100b57cec5SDimitry Andric                                              llvm::Function *FuncToReturn,
26110b57cec5SDimitry Andric                                              bool SupportsIFunc) {
26120b57cec5SDimitry Andric   if (SupportsIFunc) {
26130b57cec5SDimitry Andric     Builder.CreateRet(FuncToReturn);
26140b57cec5SDimitry Andric     return;
26150b57cec5SDimitry Andric   }
26160b57cec5SDimitry Andric 
26170b57cec5SDimitry Andric   llvm::SmallVector<llvm::Value *, 10> Args;
26180b57cec5SDimitry Andric   llvm::for_each(Resolver->args(),
26190b57cec5SDimitry Andric                  [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
26220b57cec5SDimitry Andric   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric   if (Resolver->getReturnType()->isVoidTy())
26250b57cec5SDimitry Andric     Builder.CreateRetVoid();
26260b57cec5SDimitry Andric   else
26270b57cec5SDimitry Andric     Builder.CreateRet(Result);
26280b57cec5SDimitry Andric }
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric void CodeGenFunction::EmitMultiVersionResolver(
26310b57cec5SDimitry Andric     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2632480093f4SDimitry Andric   assert(getContext().getTargetInfo().getTriple().isX86() &&
26330b57cec5SDimitry Andric          "Only implemented for x86 targets");
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   // Main function's basic block.
26380b57cec5SDimitry Andric   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
26390b57cec5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
26400b57cec5SDimitry Andric   EmitX86CpuInit();
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   for (const MultiVersionResolverOption &RO : Options) {
26430b57cec5SDimitry Andric     Builder.SetInsertPoint(CurBlock);
26440b57cec5SDimitry Andric     llvm::Value *Condition = FormResolverCondition(RO);
26450b57cec5SDimitry Andric 
26460b57cec5SDimitry Andric     // The 'default' or 'generic' case.
26470b57cec5SDimitry Andric     if (!Condition) {
26480b57cec5SDimitry Andric       assert(&RO == Options.end() - 1 &&
26490b57cec5SDimitry Andric              "Default or Generic case must be last");
26500b57cec5SDimitry Andric       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
26510b57cec5SDimitry Andric                                        SupportsIFunc);
26520b57cec5SDimitry Andric       return;
26530b57cec5SDimitry Andric     }
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
26560b57cec5SDimitry Andric     CGBuilderTy RetBuilder(*this, RetBlock);
26570b57cec5SDimitry Andric     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
26580b57cec5SDimitry Andric                                      SupportsIFunc);
26590b57cec5SDimitry Andric     CurBlock = createBasicBlock("resolver_else", Resolver);
26600b57cec5SDimitry Andric     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
26610b57cec5SDimitry Andric   }
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric   // If no generic/default, emit an unreachable.
26640b57cec5SDimitry Andric   Builder.SetInsertPoint(CurBlock);
26650b57cec5SDimitry Andric   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
26660b57cec5SDimitry Andric   TrapCall->setDoesNotReturn();
26670b57cec5SDimitry Andric   TrapCall->setDoesNotThrow();
26680b57cec5SDimitry Andric   Builder.CreateUnreachable();
26690b57cec5SDimitry Andric   Builder.ClearInsertionPoint();
26700b57cec5SDimitry Andric }
26710b57cec5SDimitry Andric 
26720b57cec5SDimitry Andric // Loc - where the diagnostic will point, where in the source code this
26730b57cec5SDimitry Andric //  alignment has failed.
26740b57cec5SDimitry Andric // SecondaryLoc - if present (will be present if sufficiently different from
26750b57cec5SDimitry Andric //  Loc), the diagnostic will additionally point a "Note:" to this location.
26760b57cec5SDimitry Andric //  It should be the location where the __attribute__((assume_aligned))
26770b57cec5SDimitry Andric //  was written e.g.
26785ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumptionCheck(
26790b57cec5SDimitry Andric     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
26800b57cec5SDimitry Andric     SourceLocation SecondaryLoc, llvm::Value *Alignment,
26810b57cec5SDimitry Andric     llvm::Value *OffsetValue, llvm::Value *TheCheck,
26820b57cec5SDimitry Andric     llvm::Instruction *Assumption) {
26830b57cec5SDimitry Andric   assert(Assumption && isa<llvm::CallInst>(Assumption) &&
26845ffd83dbSDimitry Andric          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
26850b57cec5SDimitry Andric              llvm::Intrinsic::getDeclaration(
26860b57cec5SDimitry Andric                  Builder.GetInsertBlock()->getParent()->getParent(),
26870b57cec5SDimitry Andric                  llvm::Intrinsic::assume) &&
26880b57cec5SDimitry Andric          "Assumption should be a call to llvm.assume().");
26890b57cec5SDimitry Andric   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
26900b57cec5SDimitry Andric          "Assumption should be the last instruction of the basic block, "
26910b57cec5SDimitry Andric          "since the basic block is still being generated.");
26920b57cec5SDimitry Andric 
26930b57cec5SDimitry Andric   if (!SanOpts.has(SanitizerKind::Alignment))
26940b57cec5SDimitry Andric     return;
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
26970b57cec5SDimitry Andric   // defined.
26980b57cec5SDimitry Andric   if (Ty->getPointeeType().isVolatileQualified())
26990b57cec5SDimitry Andric     return;
27000b57cec5SDimitry Andric 
27010b57cec5SDimitry Andric   // We need to temorairly remove the assumption so we can insert the
27020b57cec5SDimitry Andric   // sanitizer check before it, else the check will be dropped by optimizations.
27030b57cec5SDimitry Andric   Assumption->removeFromParent();
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric   {
27060b57cec5SDimitry Andric     SanitizerScope SanScope(this);
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric     if (!OffsetValue)
270904eeddc0SDimitry Andric       OffsetValue = Builder.getInt1(false); // no offset.
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
27120b57cec5SDimitry Andric                                     EmitCheckSourceLocation(SecondaryLoc),
27130b57cec5SDimitry Andric                                     EmitCheckTypeDescriptor(Ty)};
27140b57cec5SDimitry Andric     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
27150b57cec5SDimitry Andric                                   EmitCheckValue(Alignment),
27160b57cec5SDimitry Andric                                   EmitCheckValue(OffsetValue)};
27170b57cec5SDimitry Andric     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
27180b57cec5SDimitry Andric               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
27190b57cec5SDimitry Andric   }
27200b57cec5SDimitry Andric 
27210b57cec5SDimitry Andric   // We are now in the (new, empty) "cont" basic block.
27220b57cec5SDimitry Andric   // Reintroduce the assumption.
27230b57cec5SDimitry Andric   Builder.Insert(Assumption);
27240b57cec5SDimitry Andric   // FIXME: Assumption still has it's original basic block as it's Parent.
27250b57cec5SDimitry Andric }
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
27280b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
27290b57cec5SDimitry Andric     return DI->SourceLocToDebugLoc(Location);
27300b57cec5SDimitry Andric 
27310b57cec5SDimitry Andric   return llvm::DebugLoc();
27320b57cec5SDimitry Andric }
2733e8d8bef9SDimitry Andric 
2734fe6060f1SDimitry Andric llvm::Value *
2735fe6060f1SDimitry Andric CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
2736fe6060f1SDimitry Andric                                                       Stmt::Likelihood LH) {
2737e8d8bef9SDimitry Andric   switch (LH) {
2738e8d8bef9SDimitry Andric   case Stmt::LH_None:
2739fe6060f1SDimitry Andric     return Cond;
2740e8d8bef9SDimitry Andric   case Stmt::LH_Likely:
2741fe6060f1SDimitry Andric   case Stmt::LH_Unlikely:
2742fe6060f1SDimitry Andric     // Don't generate llvm.expect on -O0 as the backend won't use it for
2743fe6060f1SDimitry Andric     // anything.
2744fe6060f1SDimitry Andric     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2745fe6060f1SDimitry Andric       return Cond;
2746fe6060f1SDimitry Andric     llvm::Type *CondTy = Cond->getType();
2747fe6060f1SDimitry Andric     assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
2748fe6060f1SDimitry Andric     llvm::Function *FnExpect =
2749fe6060f1SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
2750fe6060f1SDimitry Andric     llvm::Value *ExpectedValueOfCond =
2751fe6060f1SDimitry Andric         llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
2752fe6060f1SDimitry Andric     return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
2753fe6060f1SDimitry Andric                               Cond->getName() + ".expval");
2754e8d8bef9SDimitry Andric   }
2755e8d8bef9SDimitry Andric   llvm_unreachable("Unknown Likelihood");
2756e8d8bef9SDimitry Andric }
2757