1f22ef01cSRoman Divacky //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-function state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenFunction.h"
150623d748SDimitry Andric #include "CGBlocks.h"
1633956c43SDimitry Andric #include "CGCleanup.h"
176122f3e6SDimitry Andric #include "CGCUDARuntime.h"
18e580952dSDimitry Andric #include "CGCXXABI.h"
19f22ef01cSRoman Divacky #include "CGDebugInfo.h"
2059d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
21139f7f9bSDimitry Andric #include "CodeGenModule.h"
2259d1ed5bSDimitry Andric #include "CodeGenPGO.h"
23f785676fSDimitry Andric #include "TargetInfo.h"
24f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
25f22ef01cSRoman Divacky #include "clang/AST/Decl.h"
26f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
27f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h"
28f41fbc90SDimitry Andric #include "clang/AST/StmtObjC.h"
290623d748SDimitry Andric #include "clang/Basic/Builtins.h"
30139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h"
31f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
32ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
330623d748SDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
34139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
36139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
38f22ef01cSRoman Divacky using namespace clang;
39f22ef01cSRoman Divacky using namespace CodeGen;
40f22ef01cSRoman Divacky 
4144290647SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
4244290647SDimitry Andric /// markers.
4344290647SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
4444290647SDimitry Andric                                       const LangOptions &LangOpts) {
4524e2fe98SDimitry Andric   if (CGOpts.DisableLifetimeMarkers)
4624e2fe98SDimitry Andric     return false;
4724e2fe98SDimitry Andric 
4844290647SDimitry Andric   // Disable lifetime markers in msan builds.
4944290647SDimitry Andric   // FIXME: Remove this when msan works with lifetime markers.
5044290647SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Memory))
5144290647SDimitry Andric     return false;
5244290647SDimitry Andric 
5320e90f04SDimitry Andric   // Asan uses markers for use-after-scope checks.
5420e90f04SDimitry Andric   if (CGOpts.SanitizeAddressUseAfterScope)
5520e90f04SDimitry Andric     return true;
5620e90f04SDimitry Andric 
5744290647SDimitry Andric   // For now, only in optimized builds.
5844290647SDimitry Andric   return CGOpts.OptimizationLevel != 0;
5944290647SDimitry Andric }
6044290647SDimitry Andric 
617ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
62284c1978SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
630623d748SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
6459d1ed5bSDimitry Andric               CGBuilderInserterTy(this)),
650623d748SDimitry Andric       CurFn(nullptr), ReturnValue(Address::invalid()),
6644290647SDimitry Andric       CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
6744290647SDimitry Andric       IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
6844290647SDimitry Andric       SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr),
6944290647SDimitry Andric       BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
7044290647SDimitry Andric       NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
7144290647SDimitry Andric       FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
7244290647SDimitry Andric       EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
73875ed548SDimitry Andric       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
74875ed548SDimitry Andric       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
75875ed548SDimitry Andric       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
76875ed548SDimitry Andric       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
77875ed548SDimitry Andric       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
780623d748SDimitry Andric       CXXStructorImplicitParamDecl(nullptr),
7959d1ed5bSDimitry Andric       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
8059d1ed5bSDimitry Andric       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
8144290647SDimitry Andric       TerminateHandler(nullptr), TrapBB(nullptr),
8244290647SDimitry Andric       ShouldEmitLifetimeMarkers(
8344290647SDimitry Andric           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
847ae0e2c9SDimitry Andric   if (!suppressNewContext)
85e580952dSDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
86139f7f9bSDimitry Andric 
87139f7f9bSDimitry Andric   llvm::FastMathFlags FMF;
88139f7f9bSDimitry Andric   if (CGM.getLangOpts().FastMath)
89139f7f9bSDimitry Andric     FMF.setUnsafeAlgebra();
90139f7f9bSDimitry Andric   if (CGM.getLangOpts().FiniteMathOnly) {
91139f7f9bSDimitry Andric     FMF.setNoNaNs();
92139f7f9bSDimitry Andric     FMF.setNoInfs();
93139f7f9bSDimitry Andric   }
9439d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
9539d628a0SDimitry Andric     FMF.setNoNaNs();
9639d628a0SDimitry Andric   }
9739d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoSignedZeros) {
9839d628a0SDimitry Andric     FMF.setNoSignedZeros();
9939d628a0SDimitry Andric   }
10033956c43SDimitry Andric   if (CGM.getCodeGenOpts().ReciprocalMath) {
10133956c43SDimitry Andric     FMF.setAllowReciprocal();
10233956c43SDimitry Andric   }
103444ed5c5SDimitry Andric   Builder.setFastMathFlags(FMF);
104f22ef01cSRoman Divacky }
105f22ef01cSRoman Divacky 
106dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() {
107f785676fSDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
108f785676fSDimitry Andric 
109dff0c46cSDimitry Andric   // If there are any unclaimed block infos, go ahead and destroy them
110dff0c46cSDimitry Andric   // now.  This can happen if IR-gen gets clever and skips evaluating
111dff0c46cSDimitry Andric   // something.
112dff0c46cSDimitry Andric   if (FirstBlockInfo)
113dff0c46cSDimitry Andric     destroyBlockInfos(FirstBlockInfo);
11459d1ed5bSDimitry Andric 
11598221d2eSDimitry Andric   if (getLangOpts().OpenMP && CurFn)
11633956c43SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
11759d1ed5bSDimitry Andric }
118dff0c46cSDimitry Andric 
1190623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
120d8866befSDimitry Andric                                                     LValueBaseInfo *BaseInfo) {
121d8866befSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo,
1220623d748SDimitry Andric                                  /*forPointee*/ true);
1230623d748SDimitry Andric }
1240623d748SDimitry Andric 
1250623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
126d8866befSDimitry Andric                                                    LValueBaseInfo *BaseInfo,
1270623d748SDimitry Andric                                                    bool forPointeeType) {
1280623d748SDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
1290623d748SDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
1300623d748SDimitry Andric   // there's an expressivity gap here.
1310623d748SDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
1320623d748SDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
133d8866befSDimitry Andric       if (BaseInfo)
134d8866befSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType, false);
1350623d748SDimitry Andric       return getContext().toCharUnitsFromBits(Align);
1360623d748SDimitry Andric     }
1370623d748SDimitry Andric   }
1380623d748SDimitry Andric 
139d8866befSDimitry Andric   if (BaseInfo)
140d8866befSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type, false);
1410623d748SDimitry Andric 
14239d628a0SDimitry Andric   CharUnits Alignment;
1430623d748SDimitry Andric   if (T->isIncompleteType()) {
1440623d748SDimitry Andric     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
1450623d748SDimitry Andric   } else {
1460623d748SDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
1470623d748SDimitry Andric     // base or a complete object, so we generally need to use the
1480623d748SDimitry Andric     // non-virtual alignment.
1490623d748SDimitry Andric     const CXXRecordDecl *RD;
1500623d748SDimitry Andric     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
1510623d748SDimitry Andric       Alignment = CGM.getClassPointerAlignment(RD);
1520623d748SDimitry Andric     } else {
15339d628a0SDimitry Andric       Alignment = getContext().getTypeAlignInChars(T);
15420e90f04SDimitry Andric       if (T.getQualifiers().hasUnaligned())
15520e90f04SDimitry Andric         Alignment = CharUnits::One();
1560623d748SDimitry Andric     }
1570623d748SDimitry Andric 
1580623d748SDimitry Andric     // Cap to the global maximum type alignment unless the alignment
1590623d748SDimitry Andric     // was somehow explicit on the type.
1600623d748SDimitry Andric     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
1610623d748SDimitry Andric       if (Alignment.getQuantity() > MaxAlign &&
16239d628a0SDimitry Andric           !getContext().isAlignmentRequired(T))
16339d628a0SDimitry Andric         Alignment = CharUnits::fromQuantity(MaxAlign);
16439d628a0SDimitry Andric     }
16539d628a0SDimitry Andric   }
1660623d748SDimitry Andric   return Alignment;
1670623d748SDimitry Andric }
1680623d748SDimitry Andric 
1690623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
170d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
171d8866befSDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo);
172d8866befSDimitry Andric   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
1730623d748SDimitry Andric                           CGM.getTBAAInfo(T));
1740623d748SDimitry Andric }
1750623d748SDimitry Andric 
1760623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1770623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1780623d748SDimitry Andric LValue
1790623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
180d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
181d8866befSDimitry Andric   CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, /*pointee*/ true);
182d8866befSDimitry Andric   return MakeAddrLValue(Address(V, Align), T, BaseInfo);
1830623d748SDimitry Andric }
1840623d748SDimitry Andric 
185f22ef01cSRoman Divacky 
18617a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
187f22ef01cSRoman Divacky   return CGM.getTypes().ConvertTypeForMem(T);
188f22ef01cSRoman Divacky }
189f22ef01cSRoman Divacky 
19017a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
191f22ef01cSRoman Divacky   return CGM.getTypes().ConvertType(T);
192f22ef01cSRoman Divacky }
193f22ef01cSRoman Divacky 
194139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
195139f7f9bSDimitry Andric   type = type.getCanonicalType();
196139f7f9bSDimitry Andric   while (true) {
197139f7f9bSDimitry Andric     switch (type->getTypeClass()) {
198bd5abe19SDimitry Andric #define TYPE(name, parent)
199bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent)
200bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
201bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
202bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
203bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def"
204bd5abe19SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
205bd5abe19SDimitry Andric 
206284c1978SDimitry Andric     case Type::Auto:
20720e90f04SDimitry Andric     case Type::DeducedTemplateSpecialization:
20820e90f04SDimitry Andric       llvm_unreachable("undeduced type in IR-generation");
209284c1978SDimitry Andric 
210139f7f9bSDimitry Andric     // Various scalar types.
211bd5abe19SDimitry Andric     case Type::Builtin:
212bd5abe19SDimitry Andric     case Type::Pointer:
213bd5abe19SDimitry Andric     case Type::BlockPointer:
214bd5abe19SDimitry Andric     case Type::LValueReference:
215bd5abe19SDimitry Andric     case Type::RValueReference:
216bd5abe19SDimitry Andric     case Type::MemberPointer:
217bd5abe19SDimitry Andric     case Type::Vector:
218bd5abe19SDimitry Andric     case Type::ExtVector:
219bd5abe19SDimitry Andric     case Type::FunctionProto:
220bd5abe19SDimitry Andric     case Type::FunctionNoProto:
221bd5abe19SDimitry Andric     case Type::Enum:
222bd5abe19SDimitry Andric     case Type::ObjCObjectPointer:
223444ed5c5SDimitry Andric     case Type::Pipe:
224139f7f9bSDimitry Andric       return TEK_Scalar;
225bd5abe19SDimitry Andric 
226139f7f9bSDimitry Andric     // Complexes.
227bd5abe19SDimitry Andric     case Type::Complex:
228139f7f9bSDimitry Andric       return TEK_Complex;
229139f7f9bSDimitry Andric 
230139f7f9bSDimitry Andric     // Arrays, records, and Objective-C objects.
231bd5abe19SDimitry Andric     case Type::ConstantArray:
232bd5abe19SDimitry Andric     case Type::IncompleteArray:
233bd5abe19SDimitry Andric     case Type::VariableArray:
234bd5abe19SDimitry Andric     case Type::Record:
235bd5abe19SDimitry Andric     case Type::ObjCObject:
236bd5abe19SDimitry Andric     case Type::ObjCInterface:
237139f7f9bSDimitry Andric       return TEK_Aggregate;
2386122f3e6SDimitry Andric 
239139f7f9bSDimitry Andric     // We operate on atomic values according to their underlying type.
2406122f3e6SDimitry Andric     case Type::Atomic:
241139f7f9bSDimitry Andric       type = cast<AtomicType>(type)->getValueType();
242139f7f9bSDimitry Andric       continue;
243bd5abe19SDimitry Andric     }
244bd5abe19SDimitry Andric     llvm_unreachable("unknown type kind!");
245f22ef01cSRoman Divacky   }
246139f7f9bSDimitry Andric }
247f22ef01cSRoman Divacky 
24839d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
249f22ef01cSRoman Divacky   // For cleanliness, we try to avoid emitting the return block for
250f22ef01cSRoman Divacky   // simple cases.
251f22ef01cSRoman Divacky   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
252f22ef01cSRoman Divacky 
253f22ef01cSRoman Divacky   if (CurBB) {
254f22ef01cSRoman Divacky     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
255f22ef01cSRoman Divacky 
256f22ef01cSRoman Divacky     // We have a valid insert point, reuse it if it is empty or there are no
257f22ef01cSRoman Divacky     // explicit jumps to the return block.
258e580952dSDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
259e580952dSDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
260e580952dSDimitry Andric       delete ReturnBlock.getBlock();
261f22ef01cSRoman Divacky     } else
262e580952dSDimitry Andric       EmitBlock(ReturnBlock.getBlock());
26339d628a0SDimitry Andric     return llvm::DebugLoc();
264f22ef01cSRoman Divacky   }
265f22ef01cSRoman Divacky 
266f22ef01cSRoman Divacky   // Otherwise, if the return block is the target of a single direct
267f22ef01cSRoman Divacky   // branch then we can just put the code in that block instead. This
268f22ef01cSRoman Divacky   // cleans up functions which started with a unified return block.
269e580952dSDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
270f22ef01cSRoman Divacky     llvm::BranchInst *BI =
27159d1ed5bSDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
272ffd1746dSEd Schouten     if (BI && BI->isUnconditional() &&
273e580952dSDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
27439d628a0SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
27539d628a0SDimitry Andric       // later by the actual 'ret' instruction.
27639d628a0SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
277f22ef01cSRoman Divacky       Builder.SetInsertPoint(BI->getParent());
278f22ef01cSRoman Divacky       BI->eraseFromParent();
279e580952dSDimitry Andric       delete ReturnBlock.getBlock();
28039d628a0SDimitry Andric       return Loc;
281f22ef01cSRoman Divacky     }
282f22ef01cSRoman Divacky   }
283f22ef01cSRoman Divacky 
284f22ef01cSRoman Divacky   // FIXME: We are at an unreachable point, there is no reason to emit the block
285f22ef01cSRoman Divacky   // unless it has uses. However, we still need a place to put the debug
286f22ef01cSRoman Divacky   // region.end for now.
287f22ef01cSRoman Divacky 
288e580952dSDimitry Andric   EmitBlock(ReturnBlock.getBlock());
28939d628a0SDimitry Andric   return llvm::DebugLoc();
290ffd1746dSEd Schouten }
291ffd1746dSEd Schouten 
292ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
293ffd1746dSEd Schouten   if (!BB) return;
294ffd1746dSEd Schouten   if (!BB->use_empty())
295ffd1746dSEd Schouten     return CGF.CurFn->getBasicBlockList().push_back(BB);
296ffd1746dSEd Schouten   delete BB;
297f22ef01cSRoman Divacky }
298f22ef01cSRoman Divacky 
299f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
300f22ef01cSRoman Divacky   assert(BreakContinueStack.empty() &&
301f22ef01cSRoman Divacky          "mismatched push/pop in break/continue stack!");
302f22ef01cSRoman Divacky 
303284c1978SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
304f785676fSDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
305f785676fSDimitry Andric     && ReturnBlock.getBlock()->use_empty();
306f785676fSDimitry Andric   // Usually the return expression is evaluated before the cleanup
307f785676fSDimitry Andric   // code.  If the function contains only a simple return statement,
308f785676fSDimitry Andric   // such as a constant, the location before the cleanup code becomes
309f785676fSDimitry Andric   // the last useful breakpoint in the function, because the simple
310f785676fSDimitry Andric   // return expression will be evaluated after the cleanup code. To be
311f785676fSDimitry Andric   // safe, set the debug location for cleanup code to the location of
312f785676fSDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
313f785676fSDimitry Andric   // end of the function's lexical scope.
314f785676fSDimitry Andric   //
315f785676fSDimitry Andric   // If there are multiple branches to the return block, the branch
316f785676fSDimitry Andric   // instructions will get the location of the return statements and
317f785676fSDimitry Andric   // all will be fine.
318284c1978SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
319284c1978SDimitry Andric     if (OnlySimpleReturnStmts)
320284c1978SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
321284c1978SDimitry Andric     else
322139f7f9bSDimitry Andric       DI->EmitLocation(Builder, EndLoc);
323284c1978SDimitry Andric   }
324139f7f9bSDimitry Andric 
32517a519f9SDimitry Andric   // Pop any cleanups that might have been associated with the
32617a519f9SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
32717a519f9SDimitry Andric   // important to do this before we enter the return block or return
32817a519f9SDimitry Andric   // edges will be *really* confused.
32933956c43SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
33033956c43SDimitry Andric   bool HasOnlyLifetimeMarkers =
33133956c43SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
33233956c43SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
33333956c43SDimitry Andric   if (HasCleanups) {
334284c1978SDimitry Andric     // Make sure the line table doesn't jump back into the body for
335284c1978SDimitry Andric     // the ret after it's been at EndLoc.
336284c1978SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
337284c1978SDimitry Andric       if (OnlySimpleReturnStmts)
338284c1978SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
33933956c43SDimitry Andric 
34033956c43SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
341284c1978SDimitry Andric   }
34217a519f9SDimitry Andric 
343f22ef01cSRoman Divacky   // Emit function epilog (to return).
34439d628a0SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
345f22ef01cSRoman Divacky 
3462754fe60SDimitry Andric   if (ShouldInstrumentFunction())
347ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_exit");
348ffd1746dSEd Schouten 
349f22ef01cSRoman Divacky   // Emit debug descriptor for function end.
35039d628a0SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
3516d97bb29SDimitry Andric     DI->EmitFunctionEnd(Builder, CurFn);
352f22ef01cSRoman Divacky 
35339d628a0SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
35439d628a0SDimitry Andric   // rather than that of the end of the function's scope '}'.
35539d628a0SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
356f785676fSDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
357f22ef01cSRoman Divacky   EmitEndEHSpec(CurCodeDecl);
358f22ef01cSRoman Divacky 
359ffd1746dSEd Schouten   assert(EHStack.empty() &&
360ffd1746dSEd Schouten          "did not remove all scopes from cleanup stack!");
361ffd1746dSEd Schouten 
362f22ef01cSRoman Divacky   // If someone did an indirect goto, emit the indirect goto block at the end of
363f22ef01cSRoman Divacky   // the function.
364f22ef01cSRoman Divacky   if (IndirectBranch) {
365f22ef01cSRoman Divacky     EmitBlock(IndirectBranch->getParent());
366f22ef01cSRoman Divacky     Builder.ClearInsertionPoint();
367f22ef01cSRoman Divacky   }
368f22ef01cSRoman Divacky 
369875ed548SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
37033956c43SDimitry Andric   // entry block.
37133956c43SDimitry Andric   if (!EscapedLocals.empty()) {
37233956c43SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
37333956c43SDimitry Andric     // no holes.
37433956c43SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
37533956c43SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
37633956c43SDimitry Andric     for (auto &Pair : EscapedLocals)
37733956c43SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
37833956c43SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
379875ed548SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
3800623d748SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
38133956c43SDimitry Andric   }
38233956c43SDimitry Andric 
383f22ef01cSRoman Divacky   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
384f22ef01cSRoman Divacky   llvm::Instruction *Ptr = AllocaInsertPt;
38559d1ed5bSDimitry Andric   AllocaInsertPt = nullptr;
386f22ef01cSRoman Divacky   Ptr->eraseFromParent();
387f22ef01cSRoman Divacky 
388f22ef01cSRoman Divacky   // If someone took the address of a label but never did an indirect goto, we
389f22ef01cSRoman Divacky   // made a zero entry PHI node, which is illegal, zap it now.
390f22ef01cSRoman Divacky   if (IndirectBranch) {
391f22ef01cSRoman Divacky     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
392f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
393f22ef01cSRoman Divacky       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
394f22ef01cSRoman Divacky       PN->eraseFromParent();
395f22ef01cSRoman Divacky     }
396f22ef01cSRoman Divacky   }
397ffd1746dSEd Schouten 
3986122f3e6SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
399ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateLandingPad);
400ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateHandler);
401ffd1746dSEd Schouten   EmitIfUsed(*this, UnreachableBlock);
402ffd1746dSEd Schouten 
403ffd1746dSEd Schouten   if (CGM.getCodeGenOpts().EmitDeclMetadata)
404ffd1746dSEd Schouten     EmitDeclMetadata();
40559d1ed5bSDimitry Andric 
40659d1ed5bSDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
40759d1ed5bSDimitry Andric            I = DeferredReplacements.begin(),
40859d1ed5bSDimitry Andric            E = DeferredReplacements.end();
40959d1ed5bSDimitry Andric        I != E; ++I) {
41059d1ed5bSDimitry Andric     I->first->replaceAllUsesWith(I->second);
41159d1ed5bSDimitry Andric     I->first->eraseFromParent();
41259d1ed5bSDimitry Andric   }
413ffd1746dSEd Schouten }
414ffd1746dSEd Schouten 
415ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be
416ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls
417ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() {
418ffd1746dSEd Schouten   if (!CGM.getCodeGenOpts().InstrumentFunctions)
419ffd1746dSEd Schouten     return false;
420bd5abe19SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
421ffd1746dSEd Schouten     return false;
422ffd1746dSEd Schouten   return true;
423ffd1746dSEd Schouten }
424ffd1746dSEd Schouten 
425e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
426e7145dcbSDimitry Andric /// instrumented with XRay nop sleds.
427e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
428e7145dcbSDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
429e7145dcbSDimitry Andric }
430e7145dcbSDimitry Andric 
431ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
432ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if
433ffd1746dSEd Schouten /// function instrumentation is enabled.
434ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
435e7145dcbSDimitry Andric   auto NL = ApplyDebugLocation::CreateArtificial(*this);
436ffd1746dSEd Schouten   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
43717a519f9SDimitry Andric   llvm::PointerType *PointerTy = Int8PtrTy;
43817a519f9SDimitry Andric   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
4396122f3e6SDimitry Andric   llvm::FunctionType *FunctionTy =
440dff0c46cSDimitry Andric     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
441ffd1746dSEd Schouten 
442ffd1746dSEd Schouten   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
443ffd1746dSEd Schouten   llvm::CallInst *CallSite = Builder.CreateCall(
44417a519f9SDimitry Andric     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
445ffd1746dSEd Schouten     llvm::ConstantInt::get(Int32Ty, 0),
446ffd1746dSEd Schouten     "callsite");
447ffd1746dSEd Schouten 
448139f7f9bSDimitry Andric   llvm::Value *args[] = {
449ffd1746dSEd Schouten     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
450139f7f9bSDimitry Andric     CallSite
451139f7f9bSDimitry Andric   };
452139f7f9bSDimitry Andric 
453139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(F, args);
454f22ef01cSRoman Divacky }
455f22ef01cSRoman Divacky 
45644290647SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
45744290647SDimitry Andric   std::string ReadOnlyQual("__read_only");
45844290647SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
45944290647SDimitry Andric   if (ReadOnlyPos != std::string::npos)
46044290647SDimitry Andric     // "+ 1" for the space after access qualifier.
46144290647SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
46244290647SDimitry Andric   else {
46344290647SDimitry Andric     std::string WriteOnlyQual("__write_only");
46444290647SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
46544290647SDimitry Andric     if (WriteOnlyPos != std::string::npos)
46644290647SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
46744290647SDimitry Andric     else {
46844290647SDimitry Andric       std::string ReadWriteQual("__read_write");
46944290647SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
47044290647SDimitry Andric       if (ReadWritePos != std::string::npos)
47144290647SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
47244290647SDimitry Andric     }
47344290647SDimitry Andric   }
4742754fe60SDimitry Andric }
4752754fe60SDimitry Andric 
476f41fbc90SDimitry Andric // Returns the address space id that should be produced to the
477f41fbc90SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
478f41fbc90SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
479f41fbc90SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
480f41fbc90SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
481f41fbc90SDimitry Andric // (basically all single AS CPUs).
482f41fbc90SDimitry Andric static unsigned ArgInfoAddressSpace(unsigned LangAS) {
483f41fbc90SDimitry Andric   switch (LangAS) {
484f41fbc90SDimitry Andric   case LangAS::opencl_global:   return 1;
485f41fbc90SDimitry Andric   case LangAS::opencl_constant: return 2;
486f41fbc90SDimitry Andric   case LangAS::opencl_local:    return 3;
487f41fbc90SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
488f41fbc90SDimitry Andric   default:
489f41fbc90SDimitry Andric     return 0; // Assume private.
490f41fbc90SDimitry Andric   }
491f41fbc90SDimitry Andric }
492f41fbc90SDimitry Andric 
4937ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
4947ae0e2c9SDimitry Andric // information in the program executable. The argument information stored
4957ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used.
4967ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
4977ae0e2c9SDimitry Andric                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
498139f7f9bSDimitry Andric                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
499139f7f9bSDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
5007ae0e2c9SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
5017ae0e2c9SDimitry Andric   // the same number of values as their are kernel arguments.
5027ae0e2c9SDimitry Andric 
50359d1ed5bSDimitry Andric   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
50459d1ed5bSDimitry Andric 
505139f7f9bSDimitry Andric   // MDNode for the kernel argument address space qualifiers.
50639d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
507139f7f9bSDimitry Andric 
508139f7f9bSDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
50939d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
510139f7f9bSDimitry Andric 
511139f7f9bSDimitry Andric   // MDNode for the kernel argument type names.
51239d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
513139f7f9bSDimitry Andric 
51439d628a0SDimitry Andric   // MDNode for the kernel argument base type names.
51539d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
51639d628a0SDimitry Andric 
517139f7f9bSDimitry Andric   // MDNode for the kernel argument type qualifiers.
51839d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
519139f7f9bSDimitry Andric 
5207ae0e2c9SDimitry Andric   // MDNode for the kernel argument names.
52139d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
5227ae0e2c9SDimitry Andric 
5237ae0e2c9SDimitry Andric   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
5247ae0e2c9SDimitry Andric     const ParmVarDecl *parm = FD->getParamDecl(i);
525139f7f9bSDimitry Andric     QualType ty = parm->getType();
526139f7f9bSDimitry Andric     std::string typeQuals;
527139f7f9bSDimitry Andric 
528139f7f9bSDimitry Andric     if (ty->isPointerType()) {
529139f7f9bSDimitry Andric       QualType pointeeTy = ty->getPointeeType();
530139f7f9bSDimitry Andric 
531139f7f9bSDimitry Andric       // Get address qualifier.
53239d628a0SDimitry Andric       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
533f41fbc90SDimitry Andric         ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
534139f7f9bSDimitry Andric 
535139f7f9bSDimitry Andric       // Get argument type name.
53659d1ed5bSDimitry Andric       std::string typeName =
53759d1ed5bSDimitry Andric           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
538139f7f9bSDimitry Andric 
539139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
540139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
54139d628a0SDimitry Andric       if (pointeeTy.isCanonical() && pos != std::string::npos)
542139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
543139f7f9bSDimitry Andric 
544139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
545139f7f9bSDimitry Andric 
54639d628a0SDimitry Andric       std::string baseTypeName =
54739d628a0SDimitry Andric           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
54839d628a0SDimitry Andric               Policy) +
54939d628a0SDimitry Andric           "*";
55039d628a0SDimitry Andric 
55139d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
55239d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
55339d628a0SDimitry Andric       if (pos != std::string::npos)
55439d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
55539d628a0SDimitry Andric 
55639d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
55739d628a0SDimitry Andric 
558139f7f9bSDimitry Andric       // Get argument type qualifiers:
559139f7f9bSDimitry Andric       if (ty.isRestrictQualified())
560139f7f9bSDimitry Andric         typeQuals = "restrict";
561139f7f9bSDimitry Andric       if (pointeeTy.isConstQualified() ||
562139f7f9bSDimitry Andric           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
563139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "const" : " const";
564139f7f9bSDimitry Andric       if (pointeeTy.isVolatileQualified())
565139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
566139f7f9bSDimitry Andric     } else {
56759d1ed5bSDimitry Andric       uint32_t AddrSpc = 0;
568444ed5c5SDimitry Andric       bool isPipe = ty->isPipeType();
569444ed5c5SDimitry Andric       if (ty->isImageType() || isPipe)
570f41fbc90SDimitry Andric         AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
57159d1ed5bSDimitry Andric 
57239d628a0SDimitry Andric       addressQuals.push_back(
57339d628a0SDimitry Andric           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
574139f7f9bSDimitry Andric 
575139f7f9bSDimitry Andric       // Get argument type name.
576444ed5c5SDimitry Andric       std::string typeName;
577444ed5c5SDimitry Andric       if (isPipe)
578e7145dcbSDimitry Andric         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
579e7145dcbSDimitry Andric                      .getAsString(Policy);
580444ed5c5SDimitry Andric       else
581444ed5c5SDimitry Andric         typeName = ty.getUnqualifiedType().getAsString(Policy);
582139f7f9bSDimitry Andric 
583139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
584139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
58539d628a0SDimitry Andric       if (ty.isCanonical() && pos != std::string::npos)
586139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
587139f7f9bSDimitry Andric 
588444ed5c5SDimitry Andric       std::string baseTypeName;
589444ed5c5SDimitry Andric       if (isPipe)
590e7145dcbSDimitry Andric         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
591e7145dcbSDimitry Andric                           ->getElementType().getCanonicalType()
592e7145dcbSDimitry Andric                           .getAsString(Policy);
593444ed5c5SDimitry Andric       else
594444ed5c5SDimitry Andric         baseTypeName =
59539d628a0SDimitry Andric           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
59639d628a0SDimitry Andric 
59744290647SDimitry Andric       // Remove access qualifiers on images
59844290647SDimitry Andric       // (as they are inseparable from type in clang implementation,
59944290647SDimitry Andric       // but OpenCL spec provides a special query to get access qualifier
60044290647SDimitry Andric       // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
60144290647SDimitry Andric       if (ty->isImageType()) {
60244290647SDimitry Andric         removeImageAccessQualifier(typeName);
60344290647SDimitry Andric         removeImageAccessQualifier(baseTypeName);
60444290647SDimitry Andric       }
60544290647SDimitry Andric 
60644290647SDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
60744290647SDimitry Andric 
60839d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
60939d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
61039d628a0SDimitry Andric       if (pos != std::string::npos)
61139d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
61239d628a0SDimitry Andric 
61339d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
61439d628a0SDimitry Andric 
615444ed5c5SDimitry Andric       if (isPipe)
616444ed5c5SDimitry Andric         typeQuals = "pipe";
617139f7f9bSDimitry Andric     }
618139f7f9bSDimitry Andric 
619139f7f9bSDimitry Andric     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
620139f7f9bSDimitry Andric 
621444ed5c5SDimitry Andric     // Get image and pipe access qualifier:
622444ed5c5SDimitry Andric     if (ty->isImageType()|| ty->isPipeType()) {
623e7145dcbSDimitry Andric       const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
62459d1ed5bSDimitry Andric       if (A && A->isWriteOnly())
625139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
626e7145dcbSDimitry Andric       else if (A && A->isReadWrite())
627e7145dcbSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
628139f7f9bSDimitry Andric       else
629139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
630139f7f9bSDimitry Andric     } else
631139f7f9bSDimitry Andric       accessQuals.push_back(llvm::MDString::get(Context, "none"));
6327ae0e2c9SDimitry Andric 
6337ae0e2c9SDimitry Andric     // Get argument name.
6347ae0e2c9SDimitry Andric     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
6357ae0e2c9SDimitry Andric   }
636139f7f9bSDimitry Andric 
637e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
638e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, addressQuals));
639e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
640e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, accessQuals));
641e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type",
642e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeNames));
643e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
644e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argBaseTypeNames));
645e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
646e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeQuals));
64739d628a0SDimitry Andric   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
648e7145dcbSDimitry Andric     Fn->setMetadata("kernel_arg_name",
649e7145dcbSDimitry Andric                     llvm::MDNode::get(Context, argNames));
6507ae0e2c9SDimitry Andric }
6517ae0e2c9SDimitry Andric 
6527ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
6537ae0e2c9SDimitry Andric                                                llvm::Function *Fn)
6547ae0e2c9SDimitry Andric {
6557ae0e2c9SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
6567ae0e2c9SDimitry Andric     return;
6577ae0e2c9SDimitry Andric 
6587ae0e2c9SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
6597ae0e2c9SDimitry Andric 
660e7145dcbSDimitry Andric   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
661139f7f9bSDimitry Andric 
66259d1ed5bSDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
6630f5676f4SDimitry Andric     QualType HintQTy = A->getTypeHint();
6640f5676f4SDimitry Andric     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
6650f5676f4SDimitry Andric     bool IsSignedInteger =
6660f5676f4SDimitry Andric         HintQTy->isSignedIntegerType() ||
6670f5676f4SDimitry Andric         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
6680f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
66939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
67039d628a0SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
67139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
672139f7f9bSDimitry Andric             llvm::IntegerType::get(Context, 32),
6730f5676f4SDimitry Andric             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
6740f5676f4SDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
675139f7f9bSDimitry Andric   }
6767ae0e2c9SDimitry Andric 
67759d1ed5bSDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
6780f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
67939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
68039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
68139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6820f5676f4SDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
6837ae0e2c9SDimitry Andric   }
6847ae0e2c9SDimitry Andric 
68559d1ed5bSDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
6860f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
68739d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
68839d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
68939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
6900f5676f4SDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
6910f5676f4SDimitry Andric   }
6920f5676f4SDimitry Andric 
6930f5676f4SDimitry Andric   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
6940f5676f4SDimitry Andric           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6950f5676f4SDimitry Andric     llvm::Metadata *AttrMDArgs[] = {
6960f5676f4SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
6970f5676f4SDimitry Andric     Fn->setMetadata("intel_reqd_sub_group_size",
6980f5676f4SDimitry Andric                     llvm::MDNode::get(Context, AttrMDArgs));
6997ae0e2c9SDimitry Andric   }
7007ae0e2c9SDimitry Andric }
7017ae0e2c9SDimitry Andric 
70259d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt.
70359d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) {
70459d1ed5bSDimitry Andric   const Stmt *Body = nullptr;
70559d1ed5bSDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
70659d1ed5bSDimitry Andric     Body = FD->getBody();
70759d1ed5bSDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
70859d1ed5bSDimitry Andric     Body = OMD->getBody();
70959d1ed5bSDimitry Andric 
71059d1ed5bSDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
71159d1ed5bSDimitry Andric     auto LastStmt = CS->body_rbegin();
71259d1ed5bSDimitry Andric     if (LastStmt != CS->body_rend())
71359d1ed5bSDimitry Andric       return isa<ReturnStmt>(*LastStmt);
71459d1ed5bSDimitry Andric   }
71559d1ed5bSDimitry Andric   return false;
71659d1ed5bSDimitry Andric }
71759d1ed5bSDimitry Andric 
71820e90f04SDimitry Andric static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
71920e90f04SDimitry Andric   Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
72020e90f04SDimitry Andric   Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
72120e90f04SDimitry Andric }
72220e90f04SDimitry Andric 
723284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD,
724284c1978SDimitry Andric                                     QualType RetTy,
725f22ef01cSRoman Divacky                                     llvm::Function *Fn,
7263b0f4066SDimitry Andric                                     const CGFunctionInfo &FnInfo,
727f22ef01cSRoman Divacky                                     const FunctionArgList &Args,
72859d1ed5bSDimitry Andric                                     SourceLocation Loc,
729f22ef01cSRoman Divacky                                     SourceLocation StartLoc) {
73039d628a0SDimitry Andric   assert(!CurFn &&
73139d628a0SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
73239d628a0SDimitry Andric 
733f22ef01cSRoman Divacky   const Decl *D = GD.getDecl();
734f22ef01cSRoman Divacky 
735f22ef01cSRoman Divacky   DidCallStackSave = false;
736284c1978SDimitry Andric   CurCodeDecl = D;
737e7145dcbSDimitry Andric   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
738e7145dcbSDimitry Andric     if (FD->usesSEHTry())
739e7145dcbSDimitry Andric       CurSEHParent = FD;
74059d1ed5bSDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
741f22ef01cSRoman Divacky   FnRetTy = RetTy;
742f22ef01cSRoman Divacky   CurFn = Fn;
7433b0f4066SDimitry Andric   CurFnInfo = &FnInfo;
744f22ef01cSRoman Divacky   assert(CurFn->isDeclaration() && "Function already has body?");
745f22ef01cSRoman Divacky 
74639d628a0SDimitry Andric   if (CGM.isInSanitizerBlacklist(Fn, Loc))
74739d628a0SDimitry Andric     SanOpts.clear();
748139f7f9bSDimitry Andric 
74933956c43SDimitry Andric   if (D) {
75033956c43SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
75133956c43SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
75233956c43SDimitry Andric       SanOpts.Mask &= ~Attr->getMask();
75333956c43SDimitry Andric   }
75433956c43SDimitry Andric 
75533956c43SDimitry Andric   // Apply sanitizer attributes to the function.
7568f0fd8f6SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
75733956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
75833956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
75933956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
76033956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Memory))
76133956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
7628f0fd8f6SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
7638f0fd8f6SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
76433956c43SDimitry Andric 
76544290647SDimitry Andric   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
76620e90f04SDimitry Andric   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
76744290647SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread)) {
76844290647SDimitry Andric     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
76944290647SDimitry Andric       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
77044290647SDimitry Andric       if (OMD->getMethodFamily() == OMF_dealloc ||
77144290647SDimitry Andric           OMD->getMethodFamily() == OMF_initialize ||
77244290647SDimitry Andric           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
77320e90f04SDimitry Andric         markAsIgnoreThreadCheckingAtRuntime(Fn);
77444290647SDimitry Andric       }
77520e90f04SDimitry Andric     } else if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
77620e90f04SDimitry Andric       IdentifierInfo *II = FD->getIdentifier();
77720e90f04SDimitry Andric       if (II && II->isStr("__destroy_helper_block_"))
77820e90f04SDimitry Andric         markAsIgnoreThreadCheckingAtRuntime(Fn);
77944290647SDimitry Andric     }
78044290647SDimitry Andric   }
78144290647SDimitry Andric 
782e7145dcbSDimitry Andric   // Apply xray attributes to the function (as a string, for now)
783e7145dcbSDimitry Andric   if (D && ShouldXRayInstrumentFunction()) {
784e7145dcbSDimitry Andric     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
785e7145dcbSDimitry Andric       if (XRayAttr->alwaysXRayInstrument())
786e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
787e7145dcbSDimitry Andric       if (XRayAttr->neverXRayInstrument())
788e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
78920e90f04SDimitry Andric       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) {
79020e90f04SDimitry Andric         Fn->addFnAttr("xray-log-args",
79120e90f04SDimitry Andric                       llvm::utostr(LogArgs->getArgumentCount()));
79220e90f04SDimitry Andric       }
793e7145dcbSDimitry Andric     } else {
79420e90f04SDimitry Andric       if (!CGM.imbueXRayAttrs(Fn, Loc))
795e7145dcbSDimitry Andric         Fn->addFnAttr(
796e7145dcbSDimitry Andric             "xray-instruction-threshold",
797e7145dcbSDimitry Andric             llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
798e7145dcbSDimitry Andric     }
799e7145dcbSDimitry Andric   }
800e7145dcbSDimitry Andric 
80144290647SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
802e7145dcbSDimitry Andric     if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
803e7145dcbSDimitry Andric       CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
804f22ef01cSRoman Divacky 
805e7145dcbSDimitry Andric   // Add no-jump-tables value.
806e7145dcbSDimitry Andric   Fn->addFnAttr("no-jump-tables",
807e7145dcbSDimitry Andric                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
808e7145dcbSDimitry Andric 
8093861d79fSDimitry Andric   if (getLangOpts().OpenCL) {
8102754fe60SDimitry Andric     // Add metadata for a kernel function.
8112754fe60SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
8127ae0e2c9SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
8132754fe60SDimitry Andric   }
8142754fe60SDimitry Andric 
815f785676fSDimitry Andric   // If we are checking function types, emit a function type signature as
81639d628a0SDimitry Andric   // prologue data.
81739d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
818f785676fSDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
81939d628a0SDimitry Andric       if (llvm::Constant *PrologueSig =
820f785676fSDimitry Andric               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
821f785676fSDimitry Andric         llvm::Constant *FTRTTIConst =
822f785676fSDimitry Andric             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
82339d628a0SDimitry Andric         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
82439d628a0SDimitry Andric         llvm::Constant *PrologueStructConst =
82539d628a0SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
82639d628a0SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
827f785676fSDimitry Andric       }
828f785676fSDimitry Andric     }
829f785676fSDimitry Andric   }
830f785676fSDimitry Andric 
83120e90f04SDimitry Andric   // If we're checking nullability, we need to know whether we can check the
83220e90f04SDimitry Andric   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
83320e90f04SDimitry Andric   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
83420e90f04SDimitry Andric     auto Nullability = FnRetTy->getNullability(getContext());
83520e90f04SDimitry Andric     if (Nullability && *Nullability == NullabilityKind::NonNull) {
83620e90f04SDimitry Andric       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
83720e90f04SDimitry Andric             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
83820e90f04SDimitry Andric         RetValNullabilityPrecondition =
83920e90f04SDimitry Andric             llvm::ConstantInt::getTrue(getLLVMContext());
84020e90f04SDimitry Andric     }
84120e90f04SDimitry Andric   }
84220e90f04SDimitry Andric 
8430623d748SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
8440623d748SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
8450623d748SDimitry Andric   // used within a program").
8460623d748SDimitry Andric   if (getLangOpts().CPlusPlus)
8470623d748SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
8480623d748SDimitry Andric       if (FD->isMain())
8490623d748SDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoRecurse);
8500623d748SDimitry Andric 
851f22ef01cSRoman Divacky   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
852f22ef01cSRoman Divacky 
853f22ef01cSRoman Divacky   // Create a marker to make it easy to insert allocas into the entryblock
854f22ef01cSRoman Divacky   // later.  Don't create this with the builder, because we don't want it
855f22ef01cSRoman Divacky   // folded.
856ffd1746dSEd Schouten   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
857e7145dcbSDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
858f22ef01cSRoman Divacky 
859ffd1746dSEd Schouten   ReturnBlock = getJumpDestInCurrentScope("return");
860f22ef01cSRoman Divacky 
861f22ef01cSRoman Divacky   Builder.SetInsertPoint(EntryBB);
862f22ef01cSRoman Divacky 
863f22ef01cSRoman Divacky   // Emit subprogram debug descriptor.
864f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
865e7145dcbSDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
866e7145dcbSDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
867e7145dcbSDimitry Andric     // convention.
868e7145dcbSDimitry Andric     CallingConv CC = CallingConv::CC_C;
869e7145dcbSDimitry Andric     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
870e7145dcbSDimitry Andric       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
871e7145dcbSDimitry Andric         CC = SrcFnTy->getCallConv();
872139f7f9bSDimitry Andric     SmallVector<QualType, 16> ArgTypes;
873e7145dcbSDimitry Andric     for (const VarDecl *VD : Args)
874e7145dcbSDimitry Andric       ArgTypes.push_back(VD->getType());
875e7145dcbSDimitry Andric     QualType FnType = getContext().getFunctionType(
876e7145dcbSDimitry Andric         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
87759d1ed5bSDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
878f22ef01cSRoman Divacky   }
879f22ef01cSRoman Divacky 
8802754fe60SDimitry Andric   if (ShouldInstrumentFunction())
881ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_enter");
882ffd1746dSEd Schouten 
88344290647SDimitry Andric   // Since emitting the mcount call here impacts optimizations such as function
88444290647SDimitry Andric   // inlining, we just add an attribute to insert a mcount call in backend.
88544290647SDimitry Andric   // The attribute "counting-function" is set to mcount function name which is
88644290647SDimitry Andric   // architecture dependent.
88720e90f04SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
88820e90f04SDimitry Andric     if (CGM.getCodeGenOpts().CallFEntry)
88920e90f04SDimitry Andric       Fn->addFnAttr("fentry-call", "true");
89020e90f04SDimitry Andric     else
89144290647SDimitry Andric       Fn->addFnAttr("counting-function", getTarget().getMCountName());
89220e90f04SDimitry Andric   }
8932754fe60SDimitry Andric 
894f22ef01cSRoman Divacky   if (RetTy->isVoidType()) {
895f22ef01cSRoman Divacky     // Void type; nothing to return.
8960623d748SDimitry Andric     ReturnValue = Address::invalid();
89759d1ed5bSDimitry Andric 
89859d1ed5bSDimitry Andric     // Count the implicit return.
89959d1ed5bSDimitry Andric     if (!endsWithReturn(D))
90059d1ed5bSDimitry Andric       ++NumReturnExprs;
901f22ef01cSRoman Divacky   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
902139f7f9bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
903f22ef01cSRoman Divacky     // Indirect aggregate return; emit returned value directly into sret slot.
904f22ef01cSRoman Divacky     // This reduces code size, and affects correctness in C++.
90559d1ed5bSDimitry Andric     auto AI = CurFn->arg_begin();
90659d1ed5bSDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
90759d1ed5bSDimitry Andric       ++AI;
9080623d748SDimitry Andric     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
90959d1ed5bSDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
91059d1ed5bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
91159d1ed5bSDimitry Andric     // Load the sret pointer from the argument struct and return into that.
91259d1ed5bSDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
91359d1ed5bSDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
91459d1ed5bSDimitry Andric     --EI;
9150623d748SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
9160623d748SDimitry Andric     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
9170623d748SDimitry Andric     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
918f22ef01cSRoman Divacky   } else {
919f22ef01cSRoman Divacky     ReturnValue = CreateIRTemp(RetTy, "retval");
92017a519f9SDimitry Andric 
92117a519f9SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
92217a519f9SDimitry Andric     // now so that various specialized functions can suppress it
92317a519f9SDimitry Andric     // during their IR-generation.
924dff0c46cSDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
92517a519f9SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
92617a519f9SDimitry Andric         RetTy->isObjCRetainableType())
92717a519f9SDimitry Andric       AutoreleaseResult = true;
928f22ef01cSRoman Divacky   }
929f22ef01cSRoman Divacky 
930f22ef01cSRoman Divacky   EmitStartEHSpec(CurCodeDecl);
93117a519f9SDimitry Andric 
93217a519f9SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
933f22ef01cSRoman Divacky   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
934f22ef01cSRoman Divacky 
935dff0c46cSDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
936e580952dSDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
937dff0c46cSDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
938dff0c46cSDimitry Andric     if (MD->getParent()->isLambda() &&
939dff0c46cSDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
940dff0c46cSDimitry Andric       // We're in a lambda; figure out the captures.
941dff0c46cSDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
942dff0c46cSDimitry Andric                                         LambdaThisCaptureField);
943dff0c46cSDimitry Andric       if (LambdaThisCaptureField) {
944e7145dcbSDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
945e7145dcbSDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
946e7145dcbSDimitry Andric         // object.
947e7145dcbSDimitry Andric 
948e7145dcbSDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
949e7145dcbSDimitry Andric         // or contains the address of the enclosing object).
950e7145dcbSDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
951e7145dcbSDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
952e7145dcbSDimitry Andric           // If the enclosing object was captured by value, just use its address.
953e7145dcbSDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
954e7145dcbSDimitry Andric         } else {
955e7145dcbSDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
956e7145dcbSDimitry Andric           // by reference.
957e7145dcbSDimitry Andric           CXXThisValue =
958e7145dcbSDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
959e7145dcbSDimitry Andric         }
960dff0c46cSDimitry Andric       }
96139d628a0SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
96239d628a0SDimitry Andric         if (FD->hasCapturedVLAType()) {
96339d628a0SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
96439d628a0SDimitry Andric                                            SourceLocation()).getScalarVal();
96539d628a0SDimitry Andric           auto VAT = FD->getCapturedVLAType();
96639d628a0SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
96739d628a0SDimitry Andric         }
96839d628a0SDimitry Andric       }
969dff0c46cSDimitry Andric     } else {
970dff0c46cSDimitry Andric       // Not in a lambda; just use 'this' from the method.
971dff0c46cSDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
972dff0c46cSDimitry Andric       // fast register allocator would be happier...
973dff0c46cSDimitry Andric       CXXThisValue = CXXABIThisValue;
974dff0c46cSDimitry Andric     }
97520e90f04SDimitry Andric 
97620e90f04SDimitry Andric     // Check the 'this' pointer once per function, if it's available.
97720e90f04SDimitry Andric     if (CXXThisValue) {
97820e90f04SDimitry Andric       SanitizerSet SkippedChecks;
97920e90f04SDimitry Andric       SkippedChecks.set(SanitizerKind::ObjectSize, true);
98020e90f04SDimitry Andric       QualType ThisTy = MD->getThisType(getContext());
98120e90f04SDimitry Andric       EmitTypeCheck(TCK_Load, Loc, CXXThisValue, ThisTy,
98220e90f04SDimitry Andric                     getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
98320e90f04SDimitry Andric                     SkippedChecks);
98420e90f04SDimitry Andric     }
985dff0c46cSDimitry Andric   }
986f22ef01cSRoman Divacky 
987f22ef01cSRoman Divacky   // If any of the arguments have a variably modified type, make sure to
988f22ef01cSRoman Divacky   // emit the type size.
989f22ef01cSRoman Divacky   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
990f22ef01cSRoman Divacky        i != e; ++i) {
991139f7f9bSDimitry Andric     const VarDecl *VD = *i;
992139f7f9bSDimitry Andric 
993139f7f9bSDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
994139f7f9bSDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
995139f7f9bSDimitry Andric     // precedent set by gcc.
996139f7f9bSDimitry Andric     QualType Ty;
997139f7f9bSDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
998139f7f9bSDimitry Andric       Ty = PVD->getOriginalType();
999139f7f9bSDimitry Andric     else
1000139f7f9bSDimitry Andric       Ty = VD->getType();
1001f22ef01cSRoman Divacky 
1002f22ef01cSRoman Divacky     if (Ty->isVariablyModifiedType())
100317a519f9SDimitry Andric       EmitVariablyModifiedType(Ty);
1004f22ef01cSRoman Divacky   }
10056122f3e6SDimitry Andric   // Emit a location at the end of the prologue.
10066122f3e6SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
10076122f3e6SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
1008f22ef01cSRoman Divacky }
1009f22ef01cSRoman Divacky 
1010f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
1011f785676fSDimitry Andric                                        const Stmt *Body) {
101233956c43SDimitry Andric   incrementProfileCounter(Body);
1013f785676fSDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1014139f7f9bSDimitry Andric     EmitCompoundStmtWithoutScope(*S);
1015139f7f9bSDimitry Andric   else
1016f785676fSDimitry Andric     EmitStmt(Body);
1017f22ef01cSRoman Divacky }
1018f22ef01cSRoman Divacky 
101959d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
102059d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so
102159d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
102259d1ed5bSDimitry Andric /// this just calls EmitBlock().
102359d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
102433956c43SDimitry Andric                                                const Stmt *S) {
102559d1ed5bSDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
1026e7145dcbSDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
102759d1ed5bSDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
102859d1ed5bSDimitry Andric     // statements needs to skip over the instrumentation code so that we
102959d1ed5bSDimitry Andric     // get an accurate count.
103059d1ed5bSDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
103159d1ed5bSDimitry Andric     EmitBranch(SkipCountBB);
103259d1ed5bSDimitry Andric   }
103359d1ed5bSDimitry Andric   EmitBlock(BB);
103433956c43SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
103533956c43SDimitry Andric   incrementProfileCounter(S);
103633956c43SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
103759d1ed5bSDimitry Andric   if (SkipCountBB)
103859d1ed5bSDimitry Andric     EmitBlock(SkipCountBB);
103959d1ed5bSDimitry Andric }
104059d1ed5bSDimitry Andric 
1041e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the
1042e580952dSDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
1043e580952dSDimitry Andric /// lightweight enough to do at -O0.
1044e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
1045e580952dSDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
1046e580952dSDimitry Andric   // can't do this on functions that can be overwritten.
1047e7145dcbSDimitry Andric   if (F->isInterposable()) return;
1048e580952dSDimitry Andric 
10490623d748SDimitry Andric   for (llvm::BasicBlock &BB : *F)
10500623d748SDimitry Andric     for (llvm::Instruction &I : BB)
10510623d748SDimitry Andric       if (I.mayThrow())
1052e580952dSDimitry Andric         return;
10530623d748SDimitry Andric 
10543861d79fSDimitry Andric   F->setDoesNotThrow();
1055e580952dSDimitry Andric }
1056e580952dSDimitry Andric 
1057e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1058e7145dcbSDimitry Andric                                                FunctionArgList &Args) {
1059f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
106059d1ed5bSDimitry Andric   QualType ResTy = FD->getReturnType();
1061f22ef01cSRoman Divacky 
106259d1ed5bSDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
106359d1ed5bSDimitry Andric   if (MD && MD->isInstance()) {
1064f785676fSDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
1065f785676fSDimitry Andric       ResTy = MD->getThisType(getContext());
106639d628a0SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
106739d628a0SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
106859d1ed5bSDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
1069f785676fSDimitry Andric   }
1070f22ef01cSRoman Divacky 
1071e7145dcbSDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
1072e7145dcbSDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
1073e7145dcbSDimitry Andric   // the inherited constructor).
1074e7145dcbSDimitry Andric   bool PassedParams = true;
1075e7145dcbSDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1076e7145dcbSDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
1077e7145dcbSDimitry Andric       PassedParams =
1078e7145dcbSDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1079e7145dcbSDimitry Andric 
1080e7145dcbSDimitry Andric   if (PassedParams) {
1081e7145dcbSDimitry Andric     for (auto *Param : FD->parameters()) {
10820623d748SDimitry Andric       Args.push_back(Param);
10830623d748SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
10840623d748SDimitry Andric         continue;
10850623d748SDimitry Andric 
10860623d748SDimitry Andric       IdentifierInfo *NoID = nullptr;
10870623d748SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
10880623d748SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
10890623d748SDimitry Andric           getContext().getSizeType());
10900623d748SDimitry Andric       SizeArguments[Param] = Implicit;
10910623d748SDimitry Andric       Args.push_back(Implicit);
10920623d748SDimitry Andric     }
1093e7145dcbSDimitry Andric   }
1094f22ef01cSRoman Divacky 
109559d1ed5bSDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
109659d1ed5bSDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
109759d1ed5bSDimitry Andric 
1098e7145dcbSDimitry Andric   return ResTy;
1099e7145dcbSDimitry Andric }
1100e7145dcbSDimitry Andric 
11018e0f8b8cSDimitry Andric static bool
11028e0f8b8cSDimitry Andric shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
11038e0f8b8cSDimitry Andric                                              const ASTContext &Context) {
11048e0f8b8cSDimitry Andric   QualType T = FD->getReturnType();
11058e0f8b8cSDimitry Andric   // Avoid the optimization for functions that return a record type with a
11068e0f8b8cSDimitry Andric   // trivial destructor or another trivially copyable type.
11078e0f8b8cSDimitry Andric   if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
11088e0f8b8cSDimitry Andric     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
11098e0f8b8cSDimitry Andric       return !ClassDecl->hasTrivialDestructor();
11108e0f8b8cSDimitry Andric   }
11118e0f8b8cSDimitry Andric   return !T.isTriviallyCopyableType(Context);
11128e0f8b8cSDimitry Andric }
11138e0f8b8cSDimitry Andric 
1114e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1115e7145dcbSDimitry Andric                                    const CGFunctionInfo &FnInfo) {
1116e7145dcbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1117e7145dcbSDimitry Andric   CurGD = GD;
1118e7145dcbSDimitry Andric 
1119e7145dcbSDimitry Andric   FunctionArgList Args;
1120e7145dcbSDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
1121e7145dcbSDimitry Andric 
1122e7145dcbSDimitry Andric   // Check if we should generate debug info for this function.
1123e7145dcbSDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
1124e7145dcbSDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
1125e7145dcbSDimitry Andric 
112620e90f04SDimitry Andric   // The function might not have a body if we're generating thunks for a
112720e90f04SDimitry Andric   // function declaration.
1128f22ef01cSRoman Divacky   SourceRange BodyRange;
112920e90f04SDimitry Andric   if (Stmt *Body = FD->getBody())
113020e90f04SDimitry Andric     BodyRange = Body->getSourceRange();
113120e90f04SDimitry Andric   else
113220e90f04SDimitry Andric     BodyRange = FD->getLocation();
1133f785676fSDimitry Andric   CurEHLocation = BodyRange.getEnd();
1134139f7f9bSDimitry Andric 
113559d1ed5bSDimitry Andric   // Use the location of the start of the function to determine where
113659d1ed5bSDimitry Andric   // the function definition is located. By default use the location
113759d1ed5bSDimitry Andric   // of the declaration as the location for the subprogram. A function
113859d1ed5bSDimitry Andric   // may lack a declaration in the source code if it is created by code
113959d1ed5bSDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
114059d1ed5bSDimitry Andric   SourceLocation Loc = FD->getLocation();
114159d1ed5bSDimitry Andric 
114259d1ed5bSDimitry Andric   // If this is a function specialization then use the pattern body
114359d1ed5bSDimitry Andric   // as the location for the function.
114459d1ed5bSDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
114559d1ed5bSDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
114659d1ed5bSDimitry Andric       Loc = SpecDecl->getLocation();
114759d1ed5bSDimitry Andric 
114844290647SDimitry Andric   Stmt *Body = FD->getBody();
114944290647SDimitry Andric 
115044290647SDimitry Andric   // Initialize helper which will detect jumps which can cause invalid lifetime
115144290647SDimitry Andric   // markers.
115244290647SDimitry Andric   if (Body && ShouldEmitLifetimeMarkers)
115344290647SDimitry Andric     Bypasses.Init(Body);
115444290647SDimitry Andric 
1155f22ef01cSRoman Divacky   // Emit the standard function prologue.
115659d1ed5bSDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1157f22ef01cSRoman Divacky 
1158f22ef01cSRoman Divacky   // Generate the body of the function.
11590623d748SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
1160f22ef01cSRoman Divacky   if (isa<CXXDestructorDecl>(FD))
1161f22ef01cSRoman Divacky     EmitDestructorBody(Args);
1162f22ef01cSRoman Divacky   else if (isa<CXXConstructorDecl>(FD))
1163f22ef01cSRoman Divacky     EmitConstructorBody(Args);
11643861d79fSDimitry Andric   else if (getLangOpts().CUDA &&
116533956c43SDimitry Andric            !getLangOpts().CUDAIsDevice &&
11666122f3e6SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
116733956c43SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1168dff0c46cSDimitry Andric   else if (isa<CXXConversionDecl>(FD) &&
1169dff0c46cSDimitry Andric            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1170dff0c46cSDimitry Andric     // The lambda conversion to block pointer is special; the semantics can't be
1171dff0c46cSDimitry Andric     // expressed in the AST, so IRGen needs to special-case it.
1172dff0c46cSDimitry Andric     EmitLambdaToBlockPointerBody(Args);
1173dff0c46cSDimitry Andric   } else if (isa<CXXMethodDecl>(FD) &&
1174dff0c46cSDimitry Andric              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1175f785676fSDimitry Andric     // The lambda static invoker function is special, because it forwards or
1176dff0c46cSDimitry Andric     // clones the body of the function call operator (but is actually static).
1177dff0c46cSDimitry Andric     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1178139f7f9bSDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1179f785676fSDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1180f785676fSDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1181139f7f9bSDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
1182139f7f9bSDimitry Andric     // copy-constructors.
1183139f7f9bSDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
118444290647SDimitry Andric   } else if (Body) {
1185f785676fSDimitry Andric     EmitFunctionBody(Args, Body);
1186f785676fSDimitry Andric   } else
1187f785676fSDimitry Andric     llvm_unreachable("no definition for emitted function");
1188f22ef01cSRoman Divacky 
11893861d79fSDimitry Andric   // C++11 [stmt.return]p2:
11903861d79fSDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
11913861d79fSDimitry Andric   //   a value-returning function.
11923861d79fSDimitry Andric   // C11 6.9.1p12:
11933861d79fSDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
11943861d79fSDimitry Andric   //   function call is used by the caller, the behavior is undefined.
119539d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
119659d1ed5bSDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
11978e0f8b8cSDimitry Andric     bool ShouldEmitUnreachable =
11988e0f8b8cSDimitry Andric         CGM.getCodeGenOpts().StrictReturn ||
11998e0f8b8cSDimitry Andric         shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
120039d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
120159d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
120239d628a0SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
120339d628a0SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
120444290647SDimitry Andric                 SanitizerHandler::MissingReturn,
120544290647SDimitry Andric                 EmitCheckSourceLocation(FD->getLocation()), None);
12068e0f8b8cSDimitry Andric     } else if (ShouldEmitUnreachable) {
12078e0f8b8cSDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
12083dac3a9bSDimitry Andric         EmitTrapCall(llvm::Intrinsic::trap);
12093dac3a9bSDimitry Andric     }
12108e0f8b8cSDimitry Andric     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
12113861d79fSDimitry Andric       Builder.CreateUnreachable();
12123861d79fSDimitry Andric       Builder.ClearInsertionPoint();
12133861d79fSDimitry Andric     }
12148e0f8b8cSDimitry Andric   }
12153861d79fSDimitry Andric 
1216f22ef01cSRoman Divacky   // Emit the standard function epilogue.
1217f22ef01cSRoman Divacky   FinishFunction(BodyRange.getEnd());
1218f22ef01cSRoman Divacky 
1219e580952dSDimitry Andric   // If we haven't marked the function nothrow through other means, do
1220e580952dSDimitry Andric   // a quick pass now to see if we can.
1221e580952dSDimitry Andric   if (!CurFn->doesNotThrow())
1222e580952dSDimitry Andric     TryMarkNoThrow(CurFn);
1223f22ef01cSRoman Divacky }
1224f22ef01cSRoman Divacky 
1225f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it.  If
1226f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means
1227f22ef01cSRoman Divacky /// that we can just remove the code.
1228f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1229f22ef01cSRoman Divacky   // Null statement, not a label!
123059d1ed5bSDimitry Andric   if (!S) return false;
1231f22ef01cSRoman Divacky 
1232f22ef01cSRoman Divacky   // If this is a label, we have to emit the code, consider something like:
1233f22ef01cSRoman Divacky   // if (0) {  ...  foo:  bar(); }  goto foo;
12343b0f4066SDimitry Andric   //
12353b0f4066SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
12363b0f4066SDimitry Andric   // can't jump to one from outside their declared region.
1237f22ef01cSRoman Divacky   if (isa<LabelStmt>(S))
1238f22ef01cSRoman Divacky     return true;
1239f22ef01cSRoman Divacky 
1240f22ef01cSRoman Divacky   // If this is a case/default statement, and we haven't seen a switch, we have
1241f22ef01cSRoman Divacky   // to emit the code.
1242f22ef01cSRoman Divacky   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1243f22ef01cSRoman Divacky     return true;
1244f22ef01cSRoman Divacky 
1245f22ef01cSRoman Divacky   // If this is a switch statement, we want to ignore cases below it.
1246f22ef01cSRoman Divacky   if (isa<SwitchStmt>(S))
1247f22ef01cSRoman Divacky     IgnoreCaseStmts = true;
1248f22ef01cSRoman Divacky 
1249f22ef01cSRoman Divacky   // Scan subexpressions for verboten labels.
12503dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
12513dac3a9bSDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1252f22ef01cSRoman Divacky       return true;
1253f22ef01cSRoman Divacky 
1254f22ef01cSRoman Divacky   return false;
1255f22ef01cSRoman Divacky }
1256f22ef01cSRoman Divacky 
12573b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
12583b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
12593b0f4066SDimitry Andric /// inside of it, this is fine.
12603b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
12613b0f4066SDimitry Andric   // Null statement, not a label!
126259d1ed5bSDimitry Andric   if (!S) return false;
1263f22ef01cSRoman Divacky 
12643b0f4066SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
12653b0f4066SDimitry Andric   // include it and anything inside of it.
12663b0f4066SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
12673b0f4066SDimitry Andric       isa<ForStmt>(S))
12683b0f4066SDimitry Andric     return false;
12693b0f4066SDimitry Andric 
12703b0f4066SDimitry Andric   if (isa<BreakStmt>(S))
12713b0f4066SDimitry Andric     return true;
12723b0f4066SDimitry Andric 
12733b0f4066SDimitry Andric   // Scan subexpressions for verboten breaks.
12743dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
12753dac3a9bSDimitry Andric     if (containsBreak(SubStmt))
12763b0f4066SDimitry Andric       return true;
12773b0f4066SDimitry Andric 
12783b0f4066SDimitry Andric   return false;
12793b0f4066SDimitry Andric }
12803b0f4066SDimitry Andric 
1281f41fbc90SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1282f41fbc90SDimitry Andric   if (!S) return false;
1283f41fbc90SDimitry Andric 
1284f41fbc90SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
1285f41fbc90SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
1286f41fbc90SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
1287f41fbc90SDimitry Andric   // correct even if more statement kinds are added.
1288f41fbc90SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1289f41fbc90SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1290f41fbc90SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1291f41fbc90SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1292f41fbc90SDimitry Andric     return false;
1293f41fbc90SDimitry Andric 
1294f41fbc90SDimitry Andric   if (isa<DeclStmt>(S))
1295f41fbc90SDimitry Andric     return true;
1296f41fbc90SDimitry Andric 
1297f41fbc90SDimitry Andric   for (const Stmt *SubStmt : S->children())
1298f41fbc90SDimitry Andric     if (mightAddDeclToScope(SubStmt))
1299f41fbc90SDimitry Andric       return true;
1300f41fbc90SDimitry Andric 
1301f41fbc90SDimitry Andric   return false;
1302f41fbc90SDimitry Andric }
13033b0f4066SDimitry Andric 
13043b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
13053b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
13063b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result.
13073b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1308e7145dcbSDimitry Andric                                                    bool &ResultBool,
1309e7145dcbSDimitry Andric                                                    bool AllowLabels) {
13107ae0e2c9SDimitry Andric   llvm::APSInt ResultInt;
1311e7145dcbSDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
13123b0f4066SDimitry Andric     return false;
13133b0f4066SDimitry Andric 
13143b0f4066SDimitry Andric   ResultBool = ResultInt.getBoolValue();
13153b0f4066SDimitry Andric   return true;
13163b0f4066SDimitry Andric }
13173b0f4066SDimitry Andric 
13183b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
13193b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
13203b0f4066SDimitry Andric /// constant folds return true and set the folded value.
1321e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1322e7145dcbSDimitry Andric                                                    llvm::APSInt &ResultInt,
1323e7145dcbSDimitry Andric                                                    bool AllowLabels) {
1324f22ef01cSRoman Divacky   // FIXME: Rename and handle conversion of other evaluatable things
1325f22ef01cSRoman Divacky   // to bool.
1326dff0c46cSDimitry Andric   llvm::APSInt Int;
1327dff0c46cSDimitry Andric   if (!Cond->EvaluateAsInt(Int, getContext()))
13283b0f4066SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
1329f22ef01cSRoman Divacky 
1330e7145dcbSDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
13313b0f4066SDimitry Andric     return false;  // Contains a label.
1332f22ef01cSRoman Divacky 
1333dff0c46cSDimitry Andric   ResultInt = Int;
13343b0f4066SDimitry Andric   return true;
1335f22ef01cSRoman Divacky }
1336f22ef01cSRoman Divacky 
1337f22ef01cSRoman Divacky 
13383b0f4066SDimitry Andric 
1339f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1340f22ef01cSRoman Divacky /// statement) to the specified blocks.  Based on the condition, this might try
1341f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch.
1342f22ef01cSRoman Divacky ///
1343f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1344f22ef01cSRoman Divacky                                            llvm::BasicBlock *TrueBlock,
134559d1ed5bSDimitry Andric                                            llvm::BasicBlock *FalseBlock,
134659d1ed5bSDimitry Andric                                            uint64_t TrueCount) {
13473b0f4066SDimitry Andric   Cond = Cond->IgnoreParens();
1348f22ef01cSRoman Divacky 
1349f22ef01cSRoman Divacky   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
135059d1ed5bSDimitry Andric 
1351f22ef01cSRoman Divacky     // Handle X && Y in a condition.
1352e580952dSDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
1353f22ef01cSRoman Divacky       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1354f22ef01cSRoman Divacky       // folded if the case was simple enough.
13553b0f4066SDimitry Andric       bool ConstantBool = false;
13563b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
13573b0f4066SDimitry Andric           ConstantBool) {
1358f22ef01cSRoman Divacky         // br(1 && X) -> br(X).
135933956c43SDimitry Andric         incrementProfileCounter(CondBOp);
136059d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
136159d1ed5bSDimitry Andric                                     TrueCount);
1362f22ef01cSRoman Divacky       }
1363f22ef01cSRoman Divacky 
1364f22ef01cSRoman Divacky       // If we have "X && 1", simplify the code to use an uncond branch.
1365f22ef01cSRoman Divacky       // "X && 0" would have been constant folded to 0.
13663b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
13673b0f4066SDimitry Andric           ConstantBool) {
1368f22ef01cSRoman Divacky         // br(X && 1) -> br(X).
136959d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
137059d1ed5bSDimitry Andric                                     TrueCount);
1371f22ef01cSRoman Divacky       }
1372f22ef01cSRoman Divacky 
1373f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1374f22ef01cSRoman Divacky       // want to jump to the FalseBlock.
1375f22ef01cSRoman Divacky       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
137659d1ed5bSDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
137759d1ed5bSDimitry Andric       // can be propagated to that branch.
137833956c43SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
13792754fe60SDimitry Andric 
13802754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
138133956c43SDimitry Andric       {
138233956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
138359d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1384f22ef01cSRoman Divacky         EmitBlock(LHSTrue);
138533956c43SDimitry Andric       }
138633956c43SDimitry Andric 
138733956c43SDimitry Andric       incrementProfileCounter(CondBOp);
138833956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1389f22ef01cSRoman Divacky 
1390f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
13912754fe60SDimitry Andric       eval.begin(*this);
139259d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
13932754fe60SDimitry Andric       eval.end(*this);
1394f22ef01cSRoman Divacky 
1395f22ef01cSRoman Divacky       return;
13963b0f4066SDimitry Andric     }
13973b0f4066SDimitry Andric 
13983b0f4066SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
1399f22ef01cSRoman Divacky       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1400f22ef01cSRoman Divacky       // folded if the case was simple enough.
14013b0f4066SDimitry Andric       bool ConstantBool = false;
14023b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
14033b0f4066SDimitry Andric           !ConstantBool) {
1404f22ef01cSRoman Divacky         // br(0 || X) -> br(X).
140533956c43SDimitry Andric         incrementProfileCounter(CondBOp);
140659d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
140759d1ed5bSDimitry Andric                                     TrueCount);
1408f22ef01cSRoman Divacky       }
1409f22ef01cSRoman Divacky 
1410f22ef01cSRoman Divacky       // If we have "X || 0", simplify the code to use an uncond branch.
1411f22ef01cSRoman Divacky       // "X || 1" would have been constant folded to 1.
14123b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
14133b0f4066SDimitry Andric           !ConstantBool) {
1414f22ef01cSRoman Divacky         // br(X || 0) -> br(X).
141559d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
141659d1ed5bSDimitry Andric                                     TrueCount);
1417f22ef01cSRoman Divacky       }
1418f22ef01cSRoman Divacky 
1419f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1420f22ef01cSRoman Divacky       // want to jump to the TrueBlock.
1421f22ef01cSRoman Divacky       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
142259d1ed5bSDimitry Andric       // We have the count for entry to the RHS and for the whole expression
142359d1ed5bSDimitry Andric       // being true, so we can divy up True count between the short circuit and
142459d1ed5bSDimitry Andric       // the RHS.
142533956c43SDimitry Andric       uint64_t LHSCount =
142633956c43SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
142759d1ed5bSDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
14282754fe60SDimitry Andric 
14292754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
143033956c43SDimitry Andric       {
143133956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
143259d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1433f22ef01cSRoman Divacky         EmitBlock(LHSFalse);
143433956c43SDimitry Andric       }
143533956c43SDimitry Andric 
143633956c43SDimitry Andric       incrementProfileCounter(CondBOp);
143733956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1438f22ef01cSRoman Divacky 
1439f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
14402754fe60SDimitry Andric       eval.begin(*this);
144159d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
144259d1ed5bSDimitry Andric 
14432754fe60SDimitry Andric       eval.end(*this);
1444f22ef01cSRoman Divacky 
1445f22ef01cSRoman Divacky       return;
1446f22ef01cSRoman Divacky     }
1447f22ef01cSRoman Divacky   }
1448f22ef01cSRoman Divacky 
1449f22ef01cSRoman Divacky   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1450f22ef01cSRoman Divacky     // br(!x, t, f) -> br(x, f, t)
145159d1ed5bSDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
145259d1ed5bSDimitry Andric       // Negate the count.
145333956c43SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
145459d1ed5bSDimitry Andric       // Negate the condition and swap the destination blocks.
145559d1ed5bSDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
145659d1ed5bSDimitry Andric                                   FalseCount);
145759d1ed5bSDimitry Andric     }
1458f22ef01cSRoman Divacky   }
1459f22ef01cSRoman Divacky 
1460f22ef01cSRoman Divacky   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1461f22ef01cSRoman Divacky     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1462f22ef01cSRoman Divacky     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1463f22ef01cSRoman Divacky     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
14642754fe60SDimitry Andric 
14652754fe60SDimitry Andric     ConditionalEvaluation cond(*this);
146633956c43SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
146733956c43SDimitry Andric                          getProfileCount(CondOp));
146859d1ed5bSDimitry Andric 
146959d1ed5bSDimitry Andric     // When computing PGO branch weights, we only know the overall count for
147059d1ed5bSDimitry Andric     // the true block. This code is essentially doing tail duplication of the
147159d1ed5bSDimitry Andric     // naive code-gen, introducing new edges for which counts are not
147259d1ed5bSDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
147359d1ed5bSDimitry Andric     // the conditional operator.
147459d1ed5bSDimitry Andric     uint64_t LHSScaledTrueCount = 0;
147559d1ed5bSDimitry Andric     if (TrueCount) {
147633956c43SDimitry Andric       double LHSRatio =
147733956c43SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
147859d1ed5bSDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
147959d1ed5bSDimitry Andric     }
14802754fe60SDimitry Andric 
14812754fe60SDimitry Andric     cond.begin(*this);
1482f22ef01cSRoman Divacky     EmitBlock(LHSBlock);
148333956c43SDimitry Andric     incrementProfileCounter(CondOp);
148433956c43SDimitry Andric     {
148533956c43SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
148659d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
148759d1ed5bSDimitry Andric                            LHSScaledTrueCount);
148833956c43SDimitry Andric     }
14892754fe60SDimitry Andric     cond.end(*this);
14902754fe60SDimitry Andric 
14912754fe60SDimitry Andric     cond.begin(*this);
1492f22ef01cSRoman Divacky     EmitBlock(RHSBlock);
149359d1ed5bSDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
149459d1ed5bSDimitry Andric                          TrueCount - LHSScaledTrueCount);
14952754fe60SDimitry Andric     cond.end(*this);
14962754fe60SDimitry Andric 
1497f22ef01cSRoman Divacky     return;
1498f22ef01cSRoman Divacky   }
1499f22ef01cSRoman Divacky 
1500284c1978SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1501284c1978SDimitry Andric     // Conditional operator handling can give us a throw expression as a
1502284c1978SDimitry Andric     // condition for a case like:
1503284c1978SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1504284c1978SDimitry Andric     // Fold this to:
1505284c1978SDimitry Andric     //   br(c, throw x, br(y, t, f))
1506284c1978SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1507284c1978SDimitry Andric     return;
1508284c1978SDimitry Andric   }
1509284c1978SDimitry Andric 
15100623d748SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
15110623d748SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
15120623d748SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
15130623d748SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
1514e7145dcbSDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond);
1515e7145dcbSDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1516e7145dcbSDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1517e7145dcbSDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
15180623d748SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
15190623d748SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
15200623d748SDimitry Andric     }
15210623d748SDimitry Andric   }
15220623d748SDimitry Andric 
152359d1ed5bSDimitry Andric   // Create branch weights based on the number of times we get here and the
152459d1ed5bSDimitry Andric   // number of times the condition should be true.
152533956c43SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
152633956c43SDimitry Andric   llvm::MDNode *Weights =
152733956c43SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
152859d1ed5bSDimitry Andric 
1529f22ef01cSRoman Divacky   // Emit the code with the fully general case.
153033956c43SDimitry Andric   llvm::Value *CondV;
153133956c43SDimitry Andric   {
153233956c43SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
153333956c43SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
153433956c43SDimitry Andric   }
15350623d748SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1536f22ef01cSRoman Divacky }
1537f22ef01cSRoman Divacky 
1538f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
1539f22ef01cSRoman Divacky /// specified stmt yet.
1540f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1541f785676fSDimitry Andric   CGM.ErrorUnsupported(S, Type);
1542f22ef01cSRoman Divacky }
1543f22ef01cSRoman Divacky 
15442754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
15452754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
15462754fe60SDimitry Andric ///
15477ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array
15482754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
15492754fe60SDimitry Andric /// base element of the array
15502754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
15512754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
15520623d748SDimitry Andric                                Address dest, Address src,
15532754fe60SDimitry Andric                                llvm::Value *sizeInChars) {
15542754fe60SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
15552754fe60SDimitry Andric 
15560623d748SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
15572754fe60SDimitry Andric   llvm::Value *baseSizeInChars
15580623d748SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
15592754fe60SDimitry Andric 
15600623d748SDimitry Andric   Address begin =
15610623d748SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
15620623d748SDimitry Andric   llvm::Value *end =
15630623d748SDimitry Andric     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
15642754fe60SDimitry Andric 
15652754fe60SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
15662754fe60SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
15672754fe60SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
15682754fe60SDimitry Andric 
15692754fe60SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
15702754fe60SDimitry Andric   // count must be nonzero.
15712754fe60SDimitry Andric   CGF.EmitBlock(loopBB);
15722754fe60SDimitry Andric 
15730623d748SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
15740623d748SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
15750623d748SDimitry Andric 
15760623d748SDimitry Andric   CharUnits curAlign =
15770623d748SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
15782754fe60SDimitry Andric 
15792754fe60SDimitry Andric   // memcpy the individual element bit-pattern.
15800623d748SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
15812754fe60SDimitry Andric                        /*volatile*/ false);
15822754fe60SDimitry Andric 
15832754fe60SDimitry Andric   // Go to the next element.
15840623d748SDimitry Andric   llvm::Value *next =
15850623d748SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
15862754fe60SDimitry Andric 
15872754fe60SDimitry Andric   // Leave if that's the end of the VLA.
15882754fe60SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
15892754fe60SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
15902754fe60SDimitry Andric   cur->addIncoming(next, loopBB);
15912754fe60SDimitry Andric 
15922754fe60SDimitry Andric   CGF.EmitBlock(contBB);
15932754fe60SDimitry Andric }
15942754fe60SDimitry Andric 
1595f22ef01cSRoman Divacky void
15960623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1597f22ef01cSRoman Divacky   // Ignore empty classes in C++.
15983861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1599f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1600f22ef01cSRoman Divacky       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1601f22ef01cSRoman Divacky         return;
1602f22ef01cSRoman Divacky     }
1603f22ef01cSRoman Divacky   }
1604f22ef01cSRoman Divacky 
1605e580952dSDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
16060623d748SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
16070623d748SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1608f22ef01cSRoman Divacky 
1609f22ef01cSRoman Divacky   // Get size and alignment info for this aggregate.
16100623d748SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
16112754fe60SDimitry Andric 
16122754fe60SDimitry Andric   llvm::Value *SizeVal;
16132754fe60SDimitry Andric   const VariableArrayType *vla;
1614f22ef01cSRoman Divacky 
1615f22ef01cSRoman Divacky   // Don't bother emitting a zero-byte memset.
16160623d748SDimitry Andric   if (size.isZero()) {
16172754fe60SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
16182754fe60SDimitry Andric     if (const VariableArrayType *vlaType =
16192754fe60SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
16202754fe60SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
162117a519f9SDimitry Andric       QualType eltType;
162217a519f9SDimitry Andric       llvm::Value *numElts;
162359d1ed5bSDimitry Andric       std::tie(numElts, eltType) = getVLASize(vlaType);
162417a519f9SDimitry Andric 
162517a519f9SDimitry Andric       SizeVal = numElts;
162617a519f9SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
162717a519f9SDimitry Andric       if (!eltSize.isOne())
162817a519f9SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
16292754fe60SDimitry Andric       vla = vlaType;
16302754fe60SDimitry Andric     } else {
1631f22ef01cSRoman Divacky       return;
16322754fe60SDimitry Andric     }
16332754fe60SDimitry Andric   } else {
16340623d748SDimitry Andric     SizeVal = CGM.getSize(size);
163559d1ed5bSDimitry Andric     vla = nullptr;
16362754fe60SDimitry Andric   }
1637e580952dSDimitry Andric 
1638e580952dSDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
1639e580952dSDimitry Andric   // Instead, create a null constant and copy it to the destination.
16402754fe60SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
16412754fe60SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
1642e580952dSDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
16432754fe60SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
16442754fe60SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
16452754fe60SDimitry Andric 
1646e580952dSDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1647e580952dSDimitry Andric 
1648e580952dSDimitry Andric     llvm::GlobalVariable *NullVariable =
1649e580952dSDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1650e580952dSDimitry Andric                                /*isConstant=*/true,
1651e580952dSDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
16526122f3e6SDimitry Andric                                NullConstant, Twine());
16530623d748SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
16540623d748SDimitry Andric     NullVariable->setAlignment(NullAlign.getQuantity());
16550623d748SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
16560623d748SDimitry Andric                    NullAlign);
1657e580952dSDimitry Andric 
16582754fe60SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1659e580952dSDimitry Andric 
1660e580952dSDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
16610623d748SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1662e580952dSDimitry Andric     return;
1663e580952dSDimitry Andric   }
1664e580952dSDimitry Andric 
1665e580952dSDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
1666e580952dSDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
1667e580952dSDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
16680623d748SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1669f22ef01cSRoman Divacky }
1670f22ef01cSRoman Divacky 
16712754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1672f22ef01cSRoman Divacky   // Make sure that there is a block for the indirect goto.
167359d1ed5bSDimitry Andric   if (!IndirectBranch)
1674f22ef01cSRoman Divacky     GetIndirectGotoBlock();
1675f22ef01cSRoman Divacky 
1676e580952dSDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1677f22ef01cSRoman Divacky 
1678f22ef01cSRoman Divacky   // Make sure the indirect branch includes all of the address-taken blocks.
1679f22ef01cSRoman Divacky   IndirectBranch->addDestination(BB);
1680f22ef01cSRoman Divacky   return llvm::BlockAddress::get(CurFn, BB);
1681f22ef01cSRoman Divacky }
1682f22ef01cSRoman Divacky 
1683f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1684f22ef01cSRoman Divacky   // If we already made the indirect branch for indirect goto, return its block.
1685f22ef01cSRoman Divacky   if (IndirectBranch) return IndirectBranch->getParent();
1686f22ef01cSRoman Divacky 
16870623d748SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1688f22ef01cSRoman Divacky 
1689f22ef01cSRoman Divacky   // Create the PHI node that indirect gotos will add entries to.
16903b0f4066SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
16913b0f4066SDimitry Andric                                               "indirect.goto.dest");
1692f22ef01cSRoman Divacky 
1693f22ef01cSRoman Divacky   // Create the indirect branch instruction.
1694f22ef01cSRoman Divacky   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1695f22ef01cSRoman Divacky   return IndirectBranch->getParent();
1696f22ef01cSRoman Divacky }
1697f22ef01cSRoman Divacky 
169817a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base
169917a519f9SDimitry Andric /// element type and a properly-typed first element pointer.
170017a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
170117a519f9SDimitry Andric                                               QualType &baseType,
17020623d748SDimitry Andric                                               Address &addr) {
170317a519f9SDimitry Andric   const ArrayType *arrayType = origArrayType;
1704f22ef01cSRoman Divacky 
170517a519f9SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
170617a519f9SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
170759d1ed5bSDimitry Andric   llvm::Value *numVLAElements = nullptr;
170817a519f9SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
170917a519f9SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
171017a519f9SDimitry Andric 
171117a519f9SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
171217a519f9SDimitry Andric     // which has type T* where T is the first non-VLA element type.
171317a519f9SDimitry Andric     do {
171417a519f9SDimitry Andric       QualType elementType = arrayType->getElementType();
171517a519f9SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
171617a519f9SDimitry Andric 
171717a519f9SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
171817a519f9SDimitry Andric       if (!arrayType) {
171917a519f9SDimitry Andric         baseType = elementType;
172017a519f9SDimitry Andric         return numVLAElements;
172117a519f9SDimitry Andric       }
172217a519f9SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
172317a519f9SDimitry Andric 
172417a519f9SDimitry Andric     // We get out here only if we find a constant array type
172517a519f9SDimitry Andric     // inside the VLA.
1726f22ef01cSRoman Divacky   }
1727f22ef01cSRoman Divacky 
172817a519f9SDimitry Andric   // We have some number of constant-length arrays, so addr should
172917a519f9SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
173017a519f9SDimitry Andric   // down to the first element of addr.
17316122f3e6SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
173217a519f9SDimitry Andric 
173317a519f9SDimitry Andric   // GEP down to the array type.
173417a519f9SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
173517a519f9SDimitry Andric   gepIndices.push_back(zero);
173617a519f9SDimitry Andric 
173717a519f9SDimitry Andric   uint64_t countFromCLAs = 1;
17387ae0e2c9SDimitry Andric   QualType eltType;
173917a519f9SDimitry Andric 
17406122f3e6SDimitry Andric   llvm::ArrayType *llvmArrayType =
17410623d748SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
17427ae0e2c9SDimitry Andric   while (llvmArrayType) {
174317a519f9SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
174417a519f9SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
174517a519f9SDimitry Andric              == llvmArrayType->getNumElements());
174617a519f9SDimitry Andric 
174717a519f9SDimitry Andric     gepIndices.push_back(zero);
174817a519f9SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
17497ae0e2c9SDimitry Andric     eltType = arrayType->getElementType();
175017a519f9SDimitry Andric 
175117a519f9SDimitry Andric     llvmArrayType =
175217a519f9SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
175317a519f9SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
17547ae0e2c9SDimitry Andric     assert((!llvmArrayType || arrayType) &&
17557ae0e2c9SDimitry Andric            "LLVM and Clang types are out-of-synch");
175617a519f9SDimitry Andric   }
175717a519f9SDimitry Andric 
17587ae0e2c9SDimitry Andric   if (arrayType) {
17597ae0e2c9SDimitry Andric     // From this point onwards, the Clang array type has been emitted
17607ae0e2c9SDimitry Andric     // as some other type (probably a packed struct). Compute the array
17617ae0e2c9SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
17627ae0e2c9SDimitry Andric     while (arrayType) {
17637ae0e2c9SDimitry Andric       countFromCLAs *=
17647ae0e2c9SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
17657ae0e2c9SDimitry Andric       eltType = arrayType->getElementType();
17667ae0e2c9SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
17677ae0e2c9SDimitry Andric     }
176817a519f9SDimitry Andric 
17690623d748SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
17700623d748SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
17717ae0e2c9SDimitry Andric   } else {
177217a519f9SDimitry Andric     // Create the actual GEP.
17730623d748SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
17740623d748SDimitry Andric                                              gepIndices, "array.begin"),
17750623d748SDimitry Andric                    addr.getAlignment());
17767ae0e2c9SDimitry Andric   }
17777ae0e2c9SDimitry Andric 
17787ae0e2c9SDimitry Andric   baseType = eltType;
177917a519f9SDimitry Andric 
178017a519f9SDimitry Andric   llvm::Value *numElements
178117a519f9SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
178217a519f9SDimitry Andric 
178317a519f9SDimitry Andric   // If we had any VLA dimensions, factor them in.
178417a519f9SDimitry Andric   if (numVLAElements)
178517a519f9SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
178617a519f9SDimitry Andric 
178717a519f9SDimitry Andric   return numElements;
178817a519f9SDimitry Andric }
178917a519f9SDimitry Andric 
179017a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
179117a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) {
179217a519f9SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
179317a519f9SDimitry Andric   assert(vla && "type was not a variable array type!");
179417a519f9SDimitry Andric   return getVLASize(vla);
179517a519f9SDimitry Andric }
179617a519f9SDimitry Andric 
179717a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
179817a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
179917a519f9SDimitry Andric   // The number of elements so far; always size_t.
180059d1ed5bSDimitry Andric   llvm::Value *numElements = nullptr;
180117a519f9SDimitry Andric 
180217a519f9SDimitry Andric   QualType elementType;
180317a519f9SDimitry Andric   do {
180417a519f9SDimitry Andric     elementType = type->getElementType();
180517a519f9SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
180617a519f9SDimitry Andric     assert(vlaSize && "no size for VLA!");
180717a519f9SDimitry Andric     assert(vlaSize->getType() == SizeTy);
180817a519f9SDimitry Andric 
180917a519f9SDimitry Andric     if (!numElements) {
181017a519f9SDimitry Andric       numElements = vlaSize;
181117a519f9SDimitry Andric     } else {
181217a519f9SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
181359d1ed5bSDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
181417a519f9SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
181517a519f9SDimitry Andric     }
181617a519f9SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
181717a519f9SDimitry Andric 
181817a519f9SDimitry Andric   return std::pair<llvm::Value*,QualType>(numElements, elementType);
181917a519f9SDimitry Andric }
182017a519f9SDimitry Andric 
182117a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
182217a519f9SDimitry Andric   assert(type->isVariablyModifiedType() &&
1823f22ef01cSRoman Divacky          "Must pass variably modified type to EmitVLASizes!");
1824f22ef01cSRoman Divacky 
1825f22ef01cSRoman Divacky   EnsureInsertPoint();
1826f22ef01cSRoman Divacky 
182717a519f9SDimitry Andric   // We're going to walk down into the type and look for VLA
182817a519f9SDimitry Andric   // expressions.
182917a519f9SDimitry Andric   do {
183017a519f9SDimitry Andric     assert(type->isVariablyModifiedType());
1831f22ef01cSRoman Divacky 
183217a519f9SDimitry Andric     const Type *ty = type.getTypePtr();
183317a519f9SDimitry Andric     switch (ty->getTypeClass()) {
1834dff0c46cSDimitry Andric 
183517a519f9SDimitry Andric #define TYPE(Class, Base)
183617a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
1837dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
183817a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1839dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
184017a519f9SDimitry Andric #include "clang/AST/TypeNodes.def"
1841dff0c46cSDimitry Andric       llvm_unreachable("unexpected dependent type!");
1842f22ef01cSRoman Divacky 
184317a519f9SDimitry Andric     // These types are never variably-modified.
184417a519f9SDimitry Andric     case Type::Builtin:
184517a519f9SDimitry Andric     case Type::Complex:
184617a519f9SDimitry Andric     case Type::Vector:
184717a519f9SDimitry Andric     case Type::ExtVector:
184817a519f9SDimitry Andric     case Type::Record:
184917a519f9SDimitry Andric     case Type::Enum:
1850dff0c46cSDimitry Andric     case Type::Elaborated:
1851dff0c46cSDimitry Andric     case Type::TemplateSpecialization:
185244290647SDimitry Andric     case Type::ObjCTypeParam:
185317a519f9SDimitry Andric     case Type::ObjCObject:
185417a519f9SDimitry Andric     case Type::ObjCInterface:
185517a519f9SDimitry Andric     case Type::ObjCObjectPointer:
185617a519f9SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
1857f22ef01cSRoman Divacky 
185859d1ed5bSDimitry Andric     case Type::Adjusted:
185959d1ed5bSDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
186059d1ed5bSDimitry Andric       break;
186159d1ed5bSDimitry Andric 
1862f785676fSDimitry Andric     case Type::Decayed:
1863f785676fSDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
1864f785676fSDimitry Andric       break;
1865f785676fSDimitry Andric 
186617a519f9SDimitry Andric     case Type::Pointer:
186717a519f9SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
186817a519f9SDimitry Andric       break;
1869f22ef01cSRoman Divacky 
187017a519f9SDimitry Andric     case Type::BlockPointer:
187117a519f9SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
187217a519f9SDimitry Andric       break;
187317a519f9SDimitry Andric 
187417a519f9SDimitry Andric     case Type::LValueReference:
187517a519f9SDimitry Andric     case Type::RValueReference:
187617a519f9SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
187717a519f9SDimitry Andric       break;
187817a519f9SDimitry Andric 
187917a519f9SDimitry Andric     case Type::MemberPointer:
188017a519f9SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
188117a519f9SDimitry Andric       break;
188217a519f9SDimitry Andric 
188317a519f9SDimitry Andric     case Type::ConstantArray:
188417a519f9SDimitry Andric     case Type::IncompleteArray:
188517a519f9SDimitry Andric       // Losing element qualification here is fine.
188617a519f9SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
188717a519f9SDimitry Andric       break;
188817a519f9SDimitry Andric 
188917a519f9SDimitry Andric     case Type::VariableArray: {
189017a519f9SDimitry Andric       // Losing element qualification here is fine.
189117a519f9SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
189217a519f9SDimitry Andric 
189317a519f9SDimitry Andric       // Unknown size indication requires no size computation.
189417a519f9SDimitry Andric       // Otherwise, evaluate and record it.
189517a519f9SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
189617a519f9SDimitry Andric         // It's possible that we might have emitted this already,
189717a519f9SDimitry Andric         // e.g. with a typedef and a pointer to it.
189817a519f9SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
189917a519f9SDimitry Andric         if (!entry) {
19003861d79fSDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
19013861d79fSDimitry Andric 
19023861d79fSDimitry Andric           // C11 6.7.6.2p5:
19033861d79fSDimitry Andric           //   If the size is an expression that is not an integer constant
19043861d79fSDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
19053861d79fSDimitry Andric           //   greater than zero.
190639d628a0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
19073861d79fSDimitry Andric               size->getType()->isSignedIntegerType()) {
190859d1ed5bSDimitry Andric             SanitizerScope SanScope(this);
19093861d79fSDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
19103861d79fSDimitry Andric             llvm::Constant *StaticArgs[] = {
19113861d79fSDimitry Andric               EmitCheckSourceLocation(size->getLocStart()),
19123861d79fSDimitry Andric               EmitCheckTypeDescriptor(size->getType())
19133861d79fSDimitry Andric             };
191439d628a0SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
191539d628a0SDimitry Andric                                      SanitizerKind::VLABound),
191644290647SDimitry Andric                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
19173861d79fSDimitry Andric           }
19183861d79fSDimitry Andric 
191917a519f9SDimitry Andric           // Always zexting here would be wrong if it weren't
192017a519f9SDimitry Andric           // undefined behavior to have a negative bound.
19213861d79fSDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
192217a519f9SDimitry Andric         }
192317a519f9SDimitry Andric       }
192417a519f9SDimitry Andric       type = vat->getElementType();
192517a519f9SDimitry Andric       break;
1926f22ef01cSRoman Divacky     }
1927f22ef01cSRoman Divacky 
192817a519f9SDimitry Andric     case Type::FunctionProto:
192917a519f9SDimitry Andric     case Type::FunctionNoProto:
193059d1ed5bSDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
193117a519f9SDimitry Andric       break;
19326122f3e6SDimitry Andric 
1933dff0c46cSDimitry Andric     case Type::Paren:
1934dff0c46cSDimitry Andric     case Type::TypeOf:
1935dff0c46cSDimitry Andric     case Type::UnaryTransform:
1936dff0c46cSDimitry Andric     case Type::Attributed:
1937dff0c46cSDimitry Andric     case Type::SubstTemplateTypeParm:
1938f785676fSDimitry Andric     case Type::PackExpansion:
1939dff0c46cSDimitry Andric       // Keep walking after single level desugaring.
1940dff0c46cSDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
1941dff0c46cSDimitry Andric       break;
1942dff0c46cSDimitry Andric 
1943dff0c46cSDimitry Andric     case Type::Typedef:
1944dff0c46cSDimitry Andric     case Type::Decltype:
1945dff0c46cSDimitry Andric     case Type::Auto:
194620e90f04SDimitry Andric     case Type::DeducedTemplateSpecialization:
1947dff0c46cSDimitry Andric       // Stop walking: nothing to do.
1948dff0c46cSDimitry Andric       return;
1949dff0c46cSDimitry Andric 
1950dff0c46cSDimitry Andric     case Type::TypeOfExpr:
1951dff0c46cSDimitry Andric       // Stop walking: emit typeof expression.
1952dff0c46cSDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1953dff0c46cSDimitry Andric       return;
1954dff0c46cSDimitry Andric 
19556122f3e6SDimitry Andric     case Type::Atomic:
19566122f3e6SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
19576122f3e6SDimitry Andric       break;
1958444ed5c5SDimitry Andric 
1959444ed5c5SDimitry Andric     case Type::Pipe:
1960444ed5c5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
1961444ed5c5SDimitry Andric       break;
1962f22ef01cSRoman Divacky     }
196317a519f9SDimitry Andric   } while (type->isVariablyModifiedType());
1964f22ef01cSRoman Divacky }
1965f22ef01cSRoman Divacky 
19660623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
19672754fe60SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
19680623d748SDimitry Andric     return EmitPointerWithAlignment(E);
19690623d748SDimitry Andric   return EmitLValue(E).getAddress();
19700623d748SDimitry Andric }
19710623d748SDimitry Andric 
19720623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1973f22ef01cSRoman Divacky   return EmitLValue(E).getAddress();
1974f22ef01cSRoman Divacky }
1975f22ef01cSRoman Divacky 
1976e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
197744290647SDimitry Andric                                               const APValue &Init) {
197844290647SDimitry Andric   assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
1979e580952dSDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
1980e7145dcbSDimitry Andric     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
19812754fe60SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
19822754fe60SDimitry Andric }
19832754fe60SDimitry Andric 
19842754fe60SDimitry Andric CodeGenFunction::PeepholeProtection
19852754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
19862754fe60SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
19872754fe60SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
19882754fe60SDimitry Andric   // extend this protection.
19892754fe60SDimitry Andric 
19902754fe60SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
19912754fe60SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
19922754fe60SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
19932754fe60SDimitry Andric 
19942754fe60SDimitry Andric   // Just make an extra bitcast.
19952754fe60SDimitry Andric   assert(HaveInsertPoint());
19962754fe60SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
19972754fe60SDimitry Andric                                                   Builder.GetInsertBlock());
19982754fe60SDimitry Andric 
19992754fe60SDimitry Andric   PeepholeProtection protection;
20002754fe60SDimitry Andric   protection.Inst = inst;
20012754fe60SDimitry Andric   return protection;
20022754fe60SDimitry Andric }
20032754fe60SDimitry Andric 
20042754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
20052754fe60SDimitry Andric   if (!protection.Inst) return;
20062754fe60SDimitry Andric 
20072754fe60SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
20082754fe60SDimitry Andric   protection.Inst->eraseFromParent();
2009e580952dSDimitry Andric }
20106122f3e6SDimitry Andric 
20116122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
20126122f3e6SDimitry Andric                                                  llvm::Value *AnnotatedVal,
2013139f7f9bSDimitry Andric                                                  StringRef AnnotationStr,
20146122f3e6SDimitry Andric                                                  SourceLocation Location) {
20156122f3e6SDimitry Andric   llvm::Value *Args[4] = {
20166122f3e6SDimitry Andric     AnnotatedVal,
20176122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
20186122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
20196122f3e6SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
20206122f3e6SDimitry Andric   };
20216122f3e6SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
20226122f3e6SDimitry Andric }
20236122f3e6SDimitry Andric 
20246122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
20256122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
20266122f3e6SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
20276122f3e6SDimitry Andric   // llvm-gcc was doing.
202859d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
20296122f3e6SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
20306122f3e6SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
203159d1ed5bSDimitry Andric                        I->getAnnotation(), D->getLocation());
20326122f3e6SDimitry Andric }
20336122f3e6SDimitry Andric 
20340623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
20350623d748SDimitry Andric                                               Address Addr) {
20366122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
20370623d748SDimitry Andric   llvm::Value *V = Addr.getPointer();
20386122f3e6SDimitry Andric   llvm::Type *VTy = V->getType();
20396122f3e6SDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
20406122f3e6SDimitry Andric                                     CGM.Int8PtrTy);
20416122f3e6SDimitry Andric 
204259d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
20436122f3e6SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
20446122f3e6SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
20456122f3e6SDimitry Andric     // itself.
20466122f3e6SDimitry Andric     if (VTy != CGM.Int8PtrTy)
20476122f3e6SDimitry Andric       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
204859d1ed5bSDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
20496122f3e6SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
20506122f3e6SDimitry Andric   }
20516122f3e6SDimitry Andric 
20520623d748SDimitry Andric   return Address(V, Addr.getAlignment());
20536122f3e6SDimitry Andric }
2054f785676fSDimitry Andric 
2055f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
205659d1ed5bSDimitry Andric 
205759d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
205859d1ed5bSDimitry Andric     : CGF(CGF) {
205959d1ed5bSDimitry Andric   assert(!CGF->IsSanitizerScope);
206059d1ed5bSDimitry Andric   CGF->IsSanitizerScope = true;
206159d1ed5bSDimitry Andric }
206259d1ed5bSDimitry Andric 
206359d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
206459d1ed5bSDimitry Andric   CGF->IsSanitizerScope = false;
206559d1ed5bSDimitry Andric }
206659d1ed5bSDimitry Andric 
206759d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
206859d1ed5bSDimitry Andric                                    const llvm::Twine &Name,
206959d1ed5bSDimitry Andric                                    llvm::BasicBlock *BB,
207059d1ed5bSDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
207159d1ed5bSDimitry Andric   LoopStack.InsertHelper(I);
207239d628a0SDimitry Andric   if (IsSanitizerScope)
207339d628a0SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
207459d1ed5bSDimitry Andric }
207559d1ed5bSDimitry Andric 
2076e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper(
207759d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
207859d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
2079e7145dcbSDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
208059d1ed5bSDimitry Andric   if (CGF)
208159d1ed5bSDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
208259d1ed5bSDimitry Andric }
208359d1ed5bSDimitry Andric 
20840623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
20850623d748SDimitry Andric                                 CodeGenModule &CGM, const FunctionDecl *FD,
20860623d748SDimitry Andric                                 std::string &FirstMissing) {
20870623d748SDimitry Andric   // If there aren't any required features listed then go ahead and return.
20880623d748SDimitry Andric   if (ReqFeatures.empty())
20890623d748SDimitry Andric     return false;
20900623d748SDimitry Andric 
20910623d748SDimitry Andric   // Now build up the set of caller features and verify that all the required
20920623d748SDimitry Andric   // features are there.
20930623d748SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
20940623d748SDimitry Andric   CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
20950623d748SDimitry Andric 
20960623d748SDimitry Andric   // If we have at least one of the features in the feature list return
20970623d748SDimitry Andric   // true, otherwise return false.
20980623d748SDimitry Andric   return std::all_of(
20990623d748SDimitry Andric       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
21000623d748SDimitry Andric         SmallVector<StringRef, 1> OrFeatures;
21010623d748SDimitry Andric         Feature.split(OrFeatures, "|");
21020623d748SDimitry Andric         return std::any_of(OrFeatures.begin(), OrFeatures.end(),
21030623d748SDimitry Andric                            [&](StringRef Feature) {
21040623d748SDimitry Andric                              if (!CallerFeatureMap.lookup(Feature)) {
21050623d748SDimitry Andric                                FirstMissing = Feature.str();
21060623d748SDimitry Andric                                return false;
21070623d748SDimitry Andric                              }
21080623d748SDimitry Andric                              return true;
21090623d748SDimitry Andric                            });
21100623d748SDimitry Andric       });
21110623d748SDimitry Andric }
21120623d748SDimitry Andric 
21130623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the
21140623d748SDimitry Andric // called function.
21150623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
21160623d748SDimitry Andric                                           const FunctionDecl *TargetDecl) {
21170623d748SDimitry Andric   // Early exit if this is an indirect call.
21180623d748SDimitry Andric   if (!TargetDecl)
21190623d748SDimitry Andric     return;
21200623d748SDimitry Andric 
21210623d748SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
21220623d748SDimitry Andric   // we can't check the target features anyhow.
21230623d748SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
21240623d748SDimitry Andric   if (!FD)
21250623d748SDimitry Andric     return;
21260623d748SDimitry Andric 
21270623d748SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
21280623d748SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
21290623d748SDimitry Andric   // listed cpu and any listed features.
21300623d748SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
21310623d748SDimitry Andric   std::string MissingFeature;
21320623d748SDimitry Andric   if (BuiltinID) {
21330623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
21340623d748SDimitry Andric     const char *FeatureList =
21350623d748SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
21360623d748SDimitry Andric     // Return if the builtin doesn't have any required features.
21370623d748SDimitry Andric     if (!FeatureList || StringRef(FeatureList) == "")
21380623d748SDimitry Andric       return;
21390623d748SDimitry Andric     StringRef(FeatureList).split(ReqFeatures, ",");
21400623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
21410623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
21420623d748SDimitry Andric           << TargetDecl->getDeclName()
21430623d748SDimitry Andric           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
21440623d748SDimitry Andric 
21450623d748SDimitry Andric   } else if (TargetDecl->hasAttr<TargetAttr>()) {
21460623d748SDimitry Andric     // Get the required features for the callee.
21470623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
21480623d748SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
21490623d748SDimitry Andric     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
21500623d748SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
21510623d748SDimitry Andric       // Only positive features are "required".
21520623d748SDimitry Andric       if (F.getValue())
21530623d748SDimitry Andric         ReqFeatures.push_back(F.getKey());
21540623d748SDimitry Andric     }
21550623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
21560623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
21570623d748SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
21580623d748SDimitry Andric   }
21590623d748SDimitry Andric }
2160e7145dcbSDimitry Andric 
2161e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2162e7145dcbSDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
2163e7145dcbSDimitry Andric     return;
2164e7145dcbSDimitry Andric 
2165e7145dcbSDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2166e7145dcbSDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2167e7145dcbSDimitry Andric   CGM.getSanStats().create(IRB, SSK);
2168e7145dcbSDimitry Andric }
216944290647SDimitry Andric 
217044290647SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
217144290647SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
217244290647SDimitry Andric     return DI->SourceLocToDebugLoc(Location);
217344290647SDimitry Andric 
217444290647SDimitry Andric   return llvm::DebugLoc();
217544290647SDimitry Andric }
2176