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"
280623d748SDimitry Andric #include "clang/Basic/Builtins.h"
29139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h"
30f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
31ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
320623d748SDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
33139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
35139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
36139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
37f22ef01cSRoman Divacky using namespace clang;
38f22ef01cSRoman Divacky using namespace CodeGen;
39f22ef01cSRoman Divacky 
407ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
41284c1978SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
420623d748SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
4359d1ed5bSDimitry Andric               CGBuilderInserterTy(this)),
440623d748SDimitry Andric       CurFn(nullptr), ReturnValue(Address::invalid()),
450623d748SDimitry Andric       CapturedStmtInfo(nullptr),
4639d628a0SDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
4739d628a0SDimitry Andric       CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
480623d748SDimitry Andric       IsOutlinedSEHHelper(false),
490623d748SDimitry Andric       BlockInfo(nullptr), BlockPointer(nullptr),
5039d628a0SDimitry Andric       LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
5139d628a0SDimitry Andric       NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
5239d628a0SDimitry Andric       ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
53875ed548SDimitry Andric       DebugInfo(CGM.getModuleDebugInfo()),
54875ed548SDimitry Andric       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
55875ed548SDimitry Andric       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
56875ed548SDimitry Andric       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
57875ed548SDimitry Andric       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
58875ed548SDimitry Andric       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
590623d748SDimitry Andric       CXXStructorImplicitParamDecl(nullptr),
6059d1ed5bSDimitry Andric       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
6159d1ed5bSDimitry Andric       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
6259d1ed5bSDimitry Andric       TerminateHandler(nullptr), TrapBB(nullptr) {
637ae0e2c9SDimitry Andric   if (!suppressNewContext)
64e580952dSDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
65139f7f9bSDimitry Andric 
66139f7f9bSDimitry Andric   llvm::FastMathFlags FMF;
67139f7f9bSDimitry Andric   if (CGM.getLangOpts().FastMath)
68139f7f9bSDimitry Andric     FMF.setUnsafeAlgebra();
69139f7f9bSDimitry Andric   if (CGM.getLangOpts().FiniteMathOnly) {
70139f7f9bSDimitry Andric     FMF.setNoNaNs();
71139f7f9bSDimitry Andric     FMF.setNoInfs();
72139f7f9bSDimitry Andric   }
7339d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
7439d628a0SDimitry Andric     FMF.setNoNaNs();
7539d628a0SDimitry Andric   }
7639d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoSignedZeros) {
7739d628a0SDimitry Andric     FMF.setNoSignedZeros();
7839d628a0SDimitry Andric   }
7933956c43SDimitry Andric   if (CGM.getCodeGenOpts().ReciprocalMath) {
8033956c43SDimitry Andric     FMF.setAllowReciprocal();
8133956c43SDimitry Andric   }
82444ed5c5SDimitry Andric   Builder.setFastMathFlags(FMF);
83f22ef01cSRoman Divacky }
84f22ef01cSRoman Divacky 
85dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() {
86f785676fSDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
87f785676fSDimitry Andric 
88dff0c46cSDimitry Andric   // If there are any unclaimed block infos, go ahead and destroy them
89dff0c46cSDimitry Andric   // now.  This can happen if IR-gen gets clever and skips evaluating
90dff0c46cSDimitry Andric   // something.
91dff0c46cSDimitry Andric   if (FirstBlockInfo)
92dff0c46cSDimitry Andric     destroyBlockInfos(FirstBlockInfo);
9359d1ed5bSDimitry Andric 
9459d1ed5bSDimitry Andric   if (getLangOpts().OpenMP) {
9533956c43SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
9659d1ed5bSDimitry Andric   }
97dff0c46cSDimitry Andric }
98dff0c46cSDimitry Andric 
990623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
1000623d748SDimitry Andric                                                      AlignmentSource *Source) {
1010623d748SDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), Source,
1020623d748SDimitry Andric                                  /*forPointee*/ true);
1030623d748SDimitry Andric }
1040623d748SDimitry Andric 
1050623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
1060623d748SDimitry Andric                                                    AlignmentSource *Source,
1070623d748SDimitry Andric                                                    bool forPointeeType) {
1080623d748SDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
1090623d748SDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
1100623d748SDimitry Andric   // there's an expressivity gap here.
1110623d748SDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
1120623d748SDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
1130623d748SDimitry Andric       if (Source) *Source = AlignmentSource::AttributedType;
1140623d748SDimitry Andric       return getContext().toCharUnitsFromBits(Align);
1150623d748SDimitry Andric     }
1160623d748SDimitry Andric   }
1170623d748SDimitry Andric 
1180623d748SDimitry Andric   if (Source) *Source = AlignmentSource::Type;
1190623d748SDimitry Andric 
12039d628a0SDimitry Andric   CharUnits Alignment;
1210623d748SDimitry Andric   if (T->isIncompleteType()) {
1220623d748SDimitry Andric     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
1230623d748SDimitry Andric   } else {
1240623d748SDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
1250623d748SDimitry Andric     // base or a complete object, so we generally need to use the
1260623d748SDimitry Andric     // non-virtual alignment.
1270623d748SDimitry Andric     const CXXRecordDecl *RD;
1280623d748SDimitry Andric     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
1290623d748SDimitry Andric       Alignment = CGM.getClassPointerAlignment(RD);
1300623d748SDimitry Andric     } else {
13139d628a0SDimitry Andric       Alignment = getContext().getTypeAlignInChars(T);
1320623d748SDimitry Andric     }
1330623d748SDimitry Andric 
1340623d748SDimitry Andric     // Cap to the global maximum type alignment unless the alignment
1350623d748SDimitry Andric     // was somehow explicit on the type.
1360623d748SDimitry Andric     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
1370623d748SDimitry Andric       if (Alignment.getQuantity() > MaxAlign &&
13839d628a0SDimitry Andric           !getContext().isAlignmentRequired(T))
13939d628a0SDimitry Andric         Alignment = CharUnits::fromQuantity(MaxAlign);
14039d628a0SDimitry Andric     }
14139d628a0SDimitry Andric   }
1420623d748SDimitry Andric   return Alignment;
1430623d748SDimitry Andric }
1440623d748SDimitry Andric 
1450623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1460623d748SDimitry Andric   AlignmentSource AlignSource;
1470623d748SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
1480623d748SDimitry Andric   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
1490623d748SDimitry Andric                           CGM.getTBAAInfo(T));
1500623d748SDimitry Andric }
1510623d748SDimitry Andric 
1520623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1530623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1540623d748SDimitry Andric LValue
1550623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
1560623d748SDimitry Andric   AlignmentSource AlignSource;
1570623d748SDimitry Andric   CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
1580623d748SDimitry Andric   return MakeAddrLValue(Address(V, Align), T, AlignSource);
1590623d748SDimitry Andric }
1600623d748SDimitry Andric 
161f22ef01cSRoman Divacky 
16217a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
163f22ef01cSRoman Divacky   return CGM.getTypes().ConvertTypeForMem(T);
164f22ef01cSRoman Divacky }
165f22ef01cSRoman Divacky 
16617a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
167f22ef01cSRoman Divacky   return CGM.getTypes().ConvertType(T);
168f22ef01cSRoman Divacky }
169f22ef01cSRoman Divacky 
170139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
171139f7f9bSDimitry Andric   type = type.getCanonicalType();
172139f7f9bSDimitry Andric   while (true) {
173139f7f9bSDimitry Andric     switch (type->getTypeClass()) {
174bd5abe19SDimitry Andric #define TYPE(name, parent)
175bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent)
176bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
177bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
178bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
179bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def"
180bd5abe19SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
181bd5abe19SDimitry Andric 
182284c1978SDimitry Andric     case Type::Auto:
183284c1978SDimitry Andric       llvm_unreachable("undeduced auto type in IR-generation");
184284c1978SDimitry Andric 
185139f7f9bSDimitry Andric     // Various scalar types.
186bd5abe19SDimitry Andric     case Type::Builtin:
187bd5abe19SDimitry Andric     case Type::Pointer:
188bd5abe19SDimitry Andric     case Type::BlockPointer:
189bd5abe19SDimitry Andric     case Type::LValueReference:
190bd5abe19SDimitry Andric     case Type::RValueReference:
191bd5abe19SDimitry Andric     case Type::MemberPointer:
192bd5abe19SDimitry Andric     case Type::Vector:
193bd5abe19SDimitry Andric     case Type::ExtVector:
194bd5abe19SDimitry Andric     case Type::FunctionProto:
195bd5abe19SDimitry Andric     case Type::FunctionNoProto:
196bd5abe19SDimitry Andric     case Type::Enum:
197bd5abe19SDimitry Andric     case Type::ObjCObjectPointer:
198444ed5c5SDimitry Andric     case Type::Pipe:
199139f7f9bSDimitry Andric       return TEK_Scalar;
200bd5abe19SDimitry Andric 
201139f7f9bSDimitry Andric     // Complexes.
202bd5abe19SDimitry Andric     case Type::Complex:
203139f7f9bSDimitry Andric       return TEK_Complex;
204139f7f9bSDimitry Andric 
205139f7f9bSDimitry Andric     // Arrays, records, and Objective-C objects.
206bd5abe19SDimitry Andric     case Type::ConstantArray:
207bd5abe19SDimitry Andric     case Type::IncompleteArray:
208bd5abe19SDimitry Andric     case Type::VariableArray:
209bd5abe19SDimitry Andric     case Type::Record:
210bd5abe19SDimitry Andric     case Type::ObjCObject:
211bd5abe19SDimitry Andric     case Type::ObjCInterface:
212139f7f9bSDimitry Andric       return TEK_Aggregate;
2136122f3e6SDimitry Andric 
214139f7f9bSDimitry Andric     // We operate on atomic values according to their underlying type.
2156122f3e6SDimitry Andric     case Type::Atomic:
216139f7f9bSDimitry Andric       type = cast<AtomicType>(type)->getValueType();
217139f7f9bSDimitry Andric       continue;
218bd5abe19SDimitry Andric     }
219bd5abe19SDimitry Andric     llvm_unreachable("unknown type kind!");
220f22ef01cSRoman Divacky   }
221139f7f9bSDimitry Andric }
222f22ef01cSRoman Divacky 
22339d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
224f22ef01cSRoman Divacky   // For cleanliness, we try to avoid emitting the return block for
225f22ef01cSRoman Divacky   // simple cases.
226f22ef01cSRoman Divacky   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
227f22ef01cSRoman Divacky 
228f22ef01cSRoman Divacky   if (CurBB) {
229f22ef01cSRoman Divacky     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
230f22ef01cSRoman Divacky 
231f22ef01cSRoman Divacky     // We have a valid insert point, reuse it if it is empty or there are no
232f22ef01cSRoman Divacky     // explicit jumps to the return block.
233e580952dSDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
234e580952dSDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
235e580952dSDimitry Andric       delete ReturnBlock.getBlock();
236f22ef01cSRoman Divacky     } else
237e580952dSDimitry Andric       EmitBlock(ReturnBlock.getBlock());
23839d628a0SDimitry Andric     return llvm::DebugLoc();
239f22ef01cSRoman Divacky   }
240f22ef01cSRoman Divacky 
241f22ef01cSRoman Divacky   // Otherwise, if the return block is the target of a single direct
242f22ef01cSRoman Divacky   // branch then we can just put the code in that block instead. This
243f22ef01cSRoman Divacky   // cleans up functions which started with a unified return block.
244e580952dSDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
245f22ef01cSRoman Divacky     llvm::BranchInst *BI =
24659d1ed5bSDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
247ffd1746dSEd Schouten     if (BI && BI->isUnconditional() &&
248e580952dSDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
24939d628a0SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
25039d628a0SDimitry Andric       // later by the actual 'ret' instruction.
25139d628a0SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
252f22ef01cSRoman Divacky       Builder.SetInsertPoint(BI->getParent());
253f22ef01cSRoman Divacky       BI->eraseFromParent();
254e580952dSDimitry Andric       delete ReturnBlock.getBlock();
25539d628a0SDimitry Andric       return Loc;
256f22ef01cSRoman Divacky     }
257f22ef01cSRoman Divacky   }
258f22ef01cSRoman Divacky 
259f22ef01cSRoman Divacky   // FIXME: We are at an unreachable point, there is no reason to emit the block
260f22ef01cSRoman Divacky   // unless it has uses. However, we still need a place to put the debug
261f22ef01cSRoman Divacky   // region.end for now.
262f22ef01cSRoman Divacky 
263e580952dSDimitry Andric   EmitBlock(ReturnBlock.getBlock());
26439d628a0SDimitry Andric   return llvm::DebugLoc();
265ffd1746dSEd Schouten }
266ffd1746dSEd Schouten 
267ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
268ffd1746dSEd Schouten   if (!BB) return;
269ffd1746dSEd Schouten   if (!BB->use_empty())
270ffd1746dSEd Schouten     return CGF.CurFn->getBasicBlockList().push_back(BB);
271ffd1746dSEd Schouten   delete BB;
272f22ef01cSRoman Divacky }
273f22ef01cSRoman Divacky 
274f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
275f22ef01cSRoman Divacky   assert(BreakContinueStack.empty() &&
276f22ef01cSRoman Divacky          "mismatched push/pop in break/continue stack!");
277f22ef01cSRoman Divacky 
278284c1978SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
279f785676fSDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
280f785676fSDimitry Andric     && ReturnBlock.getBlock()->use_empty();
281f785676fSDimitry Andric   // Usually the return expression is evaluated before the cleanup
282f785676fSDimitry Andric   // code.  If the function contains only a simple return statement,
283f785676fSDimitry Andric   // such as a constant, the location before the cleanup code becomes
284f785676fSDimitry Andric   // the last useful breakpoint in the function, because the simple
285f785676fSDimitry Andric   // return expression will be evaluated after the cleanup code. To be
286f785676fSDimitry Andric   // safe, set the debug location for cleanup code to the location of
287f785676fSDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
288f785676fSDimitry Andric   // end of the function's lexical scope.
289f785676fSDimitry Andric   //
290f785676fSDimitry Andric   // If there are multiple branches to the return block, the branch
291f785676fSDimitry Andric   // instructions will get the location of the return statements and
292f785676fSDimitry Andric   // all will be fine.
293284c1978SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
294284c1978SDimitry Andric     if (OnlySimpleReturnStmts)
295284c1978SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
296284c1978SDimitry Andric     else
297139f7f9bSDimitry Andric       DI->EmitLocation(Builder, EndLoc);
298284c1978SDimitry Andric   }
299139f7f9bSDimitry Andric 
30017a519f9SDimitry Andric   // Pop any cleanups that might have been associated with the
30117a519f9SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
30217a519f9SDimitry Andric   // important to do this before we enter the return block or return
30317a519f9SDimitry Andric   // edges will be *really* confused.
30433956c43SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
30533956c43SDimitry Andric   bool HasOnlyLifetimeMarkers =
30633956c43SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
30733956c43SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
30833956c43SDimitry Andric   if (HasCleanups) {
309284c1978SDimitry Andric     // Make sure the line table doesn't jump back into the body for
310284c1978SDimitry Andric     // the ret after it's been at EndLoc.
311284c1978SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
312284c1978SDimitry Andric       if (OnlySimpleReturnStmts)
313284c1978SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
31433956c43SDimitry Andric 
31533956c43SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
316284c1978SDimitry Andric   }
31717a519f9SDimitry Andric 
318f22ef01cSRoman Divacky   // Emit function epilog (to return).
31939d628a0SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
320f22ef01cSRoman Divacky 
3212754fe60SDimitry Andric   if (ShouldInstrumentFunction())
322ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_exit");
323ffd1746dSEd Schouten 
324f22ef01cSRoman Divacky   // Emit debug descriptor for function end.
32539d628a0SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
326e580952dSDimitry Andric     DI->EmitFunctionEnd(Builder);
327f22ef01cSRoman Divacky 
32839d628a0SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
32939d628a0SDimitry Andric   // rather than that of the end of the function's scope '}'.
33039d628a0SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
331f785676fSDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
332f22ef01cSRoman Divacky   EmitEndEHSpec(CurCodeDecl);
333f22ef01cSRoman Divacky 
334ffd1746dSEd Schouten   assert(EHStack.empty() &&
335ffd1746dSEd Schouten          "did not remove all scopes from cleanup stack!");
336ffd1746dSEd Schouten 
337f22ef01cSRoman Divacky   // If someone did an indirect goto, emit the indirect goto block at the end of
338f22ef01cSRoman Divacky   // the function.
339f22ef01cSRoman Divacky   if (IndirectBranch) {
340f22ef01cSRoman Divacky     EmitBlock(IndirectBranch->getParent());
341f22ef01cSRoman Divacky     Builder.ClearInsertionPoint();
342f22ef01cSRoman Divacky   }
343f22ef01cSRoman Divacky 
344875ed548SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
34533956c43SDimitry Andric   // entry block.
34633956c43SDimitry Andric   if (!EscapedLocals.empty()) {
34733956c43SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
34833956c43SDimitry Andric     // no holes.
34933956c43SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
35033956c43SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
35133956c43SDimitry Andric     for (auto &Pair : EscapedLocals)
35233956c43SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
35333956c43SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
354875ed548SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
3550623d748SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
35633956c43SDimitry Andric   }
35733956c43SDimitry Andric 
358f22ef01cSRoman Divacky   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
359f22ef01cSRoman Divacky   llvm::Instruction *Ptr = AllocaInsertPt;
36059d1ed5bSDimitry Andric   AllocaInsertPt = nullptr;
361f22ef01cSRoman Divacky   Ptr->eraseFromParent();
362f22ef01cSRoman Divacky 
363f22ef01cSRoman Divacky   // If someone took the address of a label but never did an indirect goto, we
364f22ef01cSRoman Divacky   // made a zero entry PHI node, which is illegal, zap it now.
365f22ef01cSRoman Divacky   if (IndirectBranch) {
366f22ef01cSRoman Divacky     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
367f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
368f22ef01cSRoman Divacky       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
369f22ef01cSRoman Divacky       PN->eraseFromParent();
370f22ef01cSRoman Divacky     }
371f22ef01cSRoman Divacky   }
372ffd1746dSEd Schouten 
3736122f3e6SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
374ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateLandingPad);
375ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateHandler);
376ffd1746dSEd Schouten   EmitIfUsed(*this, UnreachableBlock);
377ffd1746dSEd Schouten 
378ffd1746dSEd Schouten   if (CGM.getCodeGenOpts().EmitDeclMetadata)
379ffd1746dSEd Schouten     EmitDeclMetadata();
38059d1ed5bSDimitry Andric 
38159d1ed5bSDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
38259d1ed5bSDimitry Andric            I = DeferredReplacements.begin(),
38359d1ed5bSDimitry Andric            E = DeferredReplacements.end();
38459d1ed5bSDimitry Andric        I != E; ++I) {
38559d1ed5bSDimitry Andric     I->first->replaceAllUsesWith(I->second);
38659d1ed5bSDimitry Andric     I->first->eraseFromParent();
38759d1ed5bSDimitry Andric   }
388ffd1746dSEd Schouten }
389ffd1746dSEd Schouten 
390ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be
391ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls
392ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() {
393ffd1746dSEd Schouten   if (!CGM.getCodeGenOpts().InstrumentFunctions)
394ffd1746dSEd Schouten     return false;
395bd5abe19SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
396ffd1746dSEd Schouten     return false;
397ffd1746dSEd Schouten   return true;
398ffd1746dSEd Schouten }
399ffd1746dSEd Schouten 
400e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
401e7145dcbSDimitry Andric /// instrumented with XRay nop sleds.
402e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
403e7145dcbSDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
404e7145dcbSDimitry Andric }
405e7145dcbSDimitry Andric 
406ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
407ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if
408ffd1746dSEd Schouten /// function instrumentation is enabled.
409ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
410e7145dcbSDimitry Andric   auto NL = ApplyDebugLocation::CreateArtificial(*this);
411ffd1746dSEd Schouten   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
41217a519f9SDimitry Andric   llvm::PointerType *PointerTy = Int8PtrTy;
41317a519f9SDimitry Andric   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
4146122f3e6SDimitry Andric   llvm::FunctionType *FunctionTy =
415dff0c46cSDimitry Andric     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
416ffd1746dSEd Schouten 
417ffd1746dSEd Schouten   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
418ffd1746dSEd Schouten   llvm::CallInst *CallSite = Builder.CreateCall(
41917a519f9SDimitry Andric     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
420ffd1746dSEd Schouten     llvm::ConstantInt::get(Int32Ty, 0),
421ffd1746dSEd Schouten     "callsite");
422ffd1746dSEd Schouten 
423139f7f9bSDimitry Andric   llvm::Value *args[] = {
424ffd1746dSEd Schouten     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
425139f7f9bSDimitry Andric     CallSite
426139f7f9bSDimitry Andric   };
427139f7f9bSDimitry Andric 
428139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(F, args);
429f22ef01cSRoman Divacky }
430f22ef01cSRoman Divacky 
4312754fe60SDimitry Andric void CodeGenFunction::EmitMCountInstrumentation() {
432dff0c46cSDimitry Andric   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
4332754fe60SDimitry Andric 
434284c1978SDimitry Andric   llvm::Constant *MCountFn =
435284c1978SDimitry Andric     CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
436139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(MCountFn);
4372754fe60SDimitry Andric }
4382754fe60SDimitry Andric 
4397ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
4407ae0e2c9SDimitry Andric // information in the program executable. The argument information stored
4417ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used.
4427ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
4437ae0e2c9SDimitry Andric                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
444139f7f9bSDimitry Andric                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
445139f7f9bSDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
4467ae0e2c9SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
4477ae0e2c9SDimitry Andric   // the same number of values as their are kernel arguments.
4487ae0e2c9SDimitry Andric 
44959d1ed5bSDimitry Andric   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
45059d1ed5bSDimitry Andric 
451139f7f9bSDimitry Andric   // MDNode for the kernel argument address space qualifiers.
45239d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
453139f7f9bSDimitry Andric 
454139f7f9bSDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
45539d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
456139f7f9bSDimitry Andric 
457139f7f9bSDimitry Andric   // MDNode for the kernel argument type names.
45839d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
459139f7f9bSDimitry Andric 
46039d628a0SDimitry Andric   // MDNode for the kernel argument base type names.
46139d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
46239d628a0SDimitry Andric 
463139f7f9bSDimitry Andric   // MDNode for the kernel argument type qualifiers.
46439d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
465139f7f9bSDimitry Andric 
4667ae0e2c9SDimitry Andric   // MDNode for the kernel argument names.
46739d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
4687ae0e2c9SDimitry Andric 
4697ae0e2c9SDimitry Andric   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
4707ae0e2c9SDimitry Andric     const ParmVarDecl *parm = FD->getParamDecl(i);
471139f7f9bSDimitry Andric     QualType ty = parm->getType();
472139f7f9bSDimitry Andric     std::string typeQuals;
473139f7f9bSDimitry Andric 
474139f7f9bSDimitry Andric     if (ty->isPointerType()) {
475139f7f9bSDimitry Andric       QualType pointeeTy = ty->getPointeeType();
476139f7f9bSDimitry Andric 
477139f7f9bSDimitry Andric       // Get address qualifier.
47839d628a0SDimitry Andric       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
47939d628a0SDimitry Andric           ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
480139f7f9bSDimitry Andric 
481139f7f9bSDimitry Andric       // Get argument type name.
48259d1ed5bSDimitry Andric       std::string typeName =
48359d1ed5bSDimitry Andric           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
484139f7f9bSDimitry Andric 
485139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
486139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
48739d628a0SDimitry Andric       if (pointeeTy.isCanonical() && pos != std::string::npos)
488139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
489139f7f9bSDimitry Andric 
490139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
491139f7f9bSDimitry Andric 
49239d628a0SDimitry Andric       std::string baseTypeName =
49339d628a0SDimitry Andric           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
49439d628a0SDimitry Andric               Policy) +
49539d628a0SDimitry Andric           "*";
49639d628a0SDimitry Andric 
49739d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
49839d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
49939d628a0SDimitry Andric       if (pos != std::string::npos)
50039d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
50139d628a0SDimitry Andric 
50239d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
50339d628a0SDimitry Andric 
504139f7f9bSDimitry Andric       // Get argument type qualifiers:
505139f7f9bSDimitry Andric       if (ty.isRestrictQualified())
506139f7f9bSDimitry Andric         typeQuals = "restrict";
507139f7f9bSDimitry Andric       if (pointeeTy.isConstQualified() ||
508139f7f9bSDimitry Andric           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
509139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "const" : " const";
510139f7f9bSDimitry Andric       if (pointeeTy.isVolatileQualified())
511139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
512139f7f9bSDimitry Andric     } else {
51359d1ed5bSDimitry Andric       uint32_t AddrSpc = 0;
514444ed5c5SDimitry Andric       bool isPipe = ty->isPipeType();
515444ed5c5SDimitry Andric       if (ty->isImageType() || isPipe)
51659d1ed5bSDimitry Andric         AddrSpc =
51759d1ed5bSDimitry Andric           CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
51859d1ed5bSDimitry Andric 
51939d628a0SDimitry Andric       addressQuals.push_back(
52039d628a0SDimitry Andric           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
521139f7f9bSDimitry Andric 
522139f7f9bSDimitry Andric       // Get argument type name.
523444ed5c5SDimitry Andric       std::string typeName;
524444ed5c5SDimitry Andric       if (isPipe)
525e7145dcbSDimitry Andric         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
526e7145dcbSDimitry Andric                      .getAsString(Policy);
527444ed5c5SDimitry Andric       else
528444ed5c5SDimitry Andric         typeName = ty.getUnqualifiedType().getAsString(Policy);
529139f7f9bSDimitry Andric 
530139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
531139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
53239d628a0SDimitry Andric       if (ty.isCanonical() && pos != std::string::npos)
533139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
534139f7f9bSDimitry Andric 
535139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
536139f7f9bSDimitry Andric 
537444ed5c5SDimitry Andric       std::string baseTypeName;
538444ed5c5SDimitry Andric       if (isPipe)
539e7145dcbSDimitry Andric         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
540e7145dcbSDimitry Andric                           ->getElementType().getCanonicalType()
541e7145dcbSDimitry Andric                           .getAsString(Policy);
542444ed5c5SDimitry Andric       else
543444ed5c5SDimitry Andric         baseTypeName =
54439d628a0SDimitry Andric           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
54539d628a0SDimitry Andric 
54639d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
54739d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
54839d628a0SDimitry Andric       if (pos != std::string::npos)
54939d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
55039d628a0SDimitry Andric 
55139d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
55239d628a0SDimitry Andric 
553139f7f9bSDimitry Andric       // Get argument type qualifiers:
554139f7f9bSDimitry Andric       if (ty.isConstQualified())
555139f7f9bSDimitry Andric         typeQuals = "const";
556139f7f9bSDimitry Andric       if (ty.isVolatileQualified())
557139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
558444ed5c5SDimitry Andric       if (isPipe)
559444ed5c5SDimitry Andric         typeQuals = "pipe";
560139f7f9bSDimitry Andric     }
561139f7f9bSDimitry Andric 
562139f7f9bSDimitry Andric     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
563139f7f9bSDimitry Andric 
564444ed5c5SDimitry Andric     // Get image and pipe access qualifier:
565444ed5c5SDimitry Andric     if (ty->isImageType()|| ty->isPipeType()) {
566e7145dcbSDimitry Andric       const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
56759d1ed5bSDimitry Andric       if (A && A->isWriteOnly())
568139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
569e7145dcbSDimitry Andric       else if (A && A->isReadWrite())
570e7145dcbSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
571139f7f9bSDimitry Andric       else
572139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
573139f7f9bSDimitry Andric     } else
574139f7f9bSDimitry Andric       accessQuals.push_back(llvm::MDString::get(Context, "none"));
5757ae0e2c9SDimitry Andric 
5767ae0e2c9SDimitry Andric     // Get argument name.
5777ae0e2c9SDimitry Andric     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
5787ae0e2c9SDimitry Andric   }
579139f7f9bSDimitry Andric 
580e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
581e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, addressQuals));
582e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
583e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, accessQuals));
584e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type",
585e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeNames));
586e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
587e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argBaseTypeNames));
588e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
589e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeQuals));
59039d628a0SDimitry Andric   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
591e7145dcbSDimitry Andric     Fn->setMetadata("kernel_arg_name",
592e7145dcbSDimitry Andric                     llvm::MDNode::get(Context, argNames));
5937ae0e2c9SDimitry Andric }
5947ae0e2c9SDimitry Andric 
5957ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
5967ae0e2c9SDimitry Andric                                                llvm::Function *Fn)
5977ae0e2c9SDimitry Andric {
5987ae0e2c9SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
5997ae0e2c9SDimitry Andric     return;
6007ae0e2c9SDimitry Andric 
6017ae0e2c9SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
6027ae0e2c9SDimitry Andric 
603e7145dcbSDimitry Andric   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
604139f7f9bSDimitry Andric 
60559d1ed5bSDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
60659d1ed5bSDimitry Andric     QualType hintQTy = A->getTypeHint();
607139f7f9bSDimitry Andric     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
608139f7f9bSDimitry Andric     bool isSignedInteger =
609139f7f9bSDimitry Andric         hintQTy->isSignedIntegerType() ||
610139f7f9bSDimitry Andric         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
61139d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
61239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
61339d628a0SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
61439d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
615139f7f9bSDimitry Andric             llvm::IntegerType::get(Context, 32),
61639d628a0SDimitry Andric             llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
617e7145dcbSDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
618139f7f9bSDimitry Andric   }
6197ae0e2c9SDimitry Andric 
62059d1ed5bSDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
62139d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
62239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
62339d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
62439d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
625e7145dcbSDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
6267ae0e2c9SDimitry Andric   }
6277ae0e2c9SDimitry Andric 
62859d1ed5bSDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
62939d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
63039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
63139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
63239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
633e7145dcbSDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
6347ae0e2c9SDimitry Andric   }
6357ae0e2c9SDimitry Andric }
6367ae0e2c9SDimitry Andric 
63759d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt.
63859d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) {
63959d1ed5bSDimitry Andric   const Stmt *Body = nullptr;
64059d1ed5bSDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
64159d1ed5bSDimitry Andric     Body = FD->getBody();
64259d1ed5bSDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
64359d1ed5bSDimitry Andric     Body = OMD->getBody();
64459d1ed5bSDimitry Andric 
64559d1ed5bSDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
64659d1ed5bSDimitry Andric     auto LastStmt = CS->body_rbegin();
64759d1ed5bSDimitry Andric     if (LastStmt != CS->body_rend())
64859d1ed5bSDimitry Andric       return isa<ReturnStmt>(*LastStmt);
64959d1ed5bSDimitry Andric   }
65059d1ed5bSDimitry Andric   return false;
65159d1ed5bSDimitry Andric }
65259d1ed5bSDimitry Andric 
653284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD,
654284c1978SDimitry Andric                                     QualType RetTy,
655f22ef01cSRoman Divacky                                     llvm::Function *Fn,
6563b0f4066SDimitry Andric                                     const CGFunctionInfo &FnInfo,
657f22ef01cSRoman Divacky                                     const FunctionArgList &Args,
65859d1ed5bSDimitry Andric                                     SourceLocation Loc,
659f22ef01cSRoman Divacky                                     SourceLocation StartLoc) {
66039d628a0SDimitry Andric   assert(!CurFn &&
66139d628a0SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
66239d628a0SDimitry Andric 
663f22ef01cSRoman Divacky   const Decl *D = GD.getDecl();
664f22ef01cSRoman Divacky 
665f22ef01cSRoman Divacky   DidCallStackSave = false;
666284c1978SDimitry Andric   CurCodeDecl = D;
667e7145dcbSDimitry Andric   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
668e7145dcbSDimitry Andric     if (FD->usesSEHTry())
669e7145dcbSDimitry Andric       CurSEHParent = FD;
67059d1ed5bSDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
671f22ef01cSRoman Divacky   FnRetTy = RetTy;
672f22ef01cSRoman Divacky   CurFn = Fn;
6733b0f4066SDimitry Andric   CurFnInfo = &FnInfo;
674f22ef01cSRoman Divacky   assert(CurFn->isDeclaration() && "Function already has body?");
675f22ef01cSRoman Divacky 
67639d628a0SDimitry Andric   if (CGM.isInSanitizerBlacklist(Fn, Loc))
67739d628a0SDimitry Andric     SanOpts.clear();
678139f7f9bSDimitry Andric 
67933956c43SDimitry Andric   if (D) {
68033956c43SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
68133956c43SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
68233956c43SDimitry Andric       SanOpts.Mask &= ~Attr->getMask();
68333956c43SDimitry Andric   }
68433956c43SDimitry Andric 
68533956c43SDimitry Andric   // Apply sanitizer attributes to the function.
6868f0fd8f6SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
68733956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
68833956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
68933956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
69033956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Memory))
69133956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
6928f0fd8f6SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
6938f0fd8f6SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
69433956c43SDimitry Andric 
695e7145dcbSDimitry Andric   // Apply xray attributes to the function (as a string, for now)
696e7145dcbSDimitry Andric   if (D && ShouldXRayInstrumentFunction()) {
697e7145dcbSDimitry Andric     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
698e7145dcbSDimitry Andric       if (XRayAttr->alwaysXRayInstrument())
699e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
700e7145dcbSDimitry Andric       if (XRayAttr->neverXRayInstrument())
701e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
702e7145dcbSDimitry Andric     } else {
703e7145dcbSDimitry Andric       Fn->addFnAttr(
704e7145dcbSDimitry Andric           "xray-instruction-threshold",
705e7145dcbSDimitry Andric           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
706e7145dcbSDimitry Andric     }
707e7145dcbSDimitry Andric   }
708e7145dcbSDimitry Andric 
709f22ef01cSRoman Divacky   // Pass inline keyword to optimizer if it appears explicitly on any
71059d1ed5bSDimitry Andric   // declaration. Also, in the case of -fno-inline attach NoInline
711e7145dcbSDimitry Andric   // attribute to all functions that are not marked AlwaysInline, or
712e7145dcbSDimitry Andric   // to all functions that are not marked inline or implicitly inline
713e7145dcbSDimitry Andric   // in the case of -finline-hint-functions.
71459d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
715e7145dcbSDimitry Andric     const CodeGenOptions& CodeGenOpts = CGM.getCodeGenOpts();
716e7145dcbSDimitry Andric     if (!CodeGenOpts.NoInline) {
71759d1ed5bSDimitry Andric       for (auto RI : FD->redecls())
718f22ef01cSRoman Divacky         if (RI->isInlineSpecified()) {
719139f7f9bSDimitry Andric           Fn->addFnAttr(llvm::Attribute::InlineHint);
720f22ef01cSRoman Divacky           break;
721f22ef01cSRoman Divacky         }
722e7145dcbSDimitry Andric       if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyHintInlining &&
723e7145dcbSDimitry Andric           !FD->isInlined() && !Fn->hasFnAttribute(llvm::Attribute::InlineHint))
724e7145dcbSDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoInline);
72559d1ed5bSDimitry Andric     } else if (!FD->hasAttr<AlwaysInlineAttr>())
72659d1ed5bSDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoInline);
727e7145dcbSDimitry Andric     if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
728e7145dcbSDimitry Andric       CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
72959d1ed5bSDimitry Andric   }
730f22ef01cSRoman Divacky 
731e7145dcbSDimitry Andric   // Add no-jump-tables value.
732e7145dcbSDimitry Andric   Fn->addFnAttr("no-jump-tables",
733e7145dcbSDimitry Andric                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
734e7145dcbSDimitry Andric 
7353861d79fSDimitry Andric   if (getLangOpts().OpenCL) {
7362754fe60SDimitry Andric     // Add metadata for a kernel function.
7372754fe60SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
7387ae0e2c9SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
7392754fe60SDimitry Andric   }
7402754fe60SDimitry Andric 
741f785676fSDimitry Andric   // If we are checking function types, emit a function type signature as
74239d628a0SDimitry Andric   // prologue data.
74339d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
744f785676fSDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
74539d628a0SDimitry Andric       if (llvm::Constant *PrologueSig =
746f785676fSDimitry Andric               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
747f785676fSDimitry Andric         llvm::Constant *FTRTTIConst =
748f785676fSDimitry Andric             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
74939d628a0SDimitry Andric         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
75039d628a0SDimitry Andric         llvm::Constant *PrologueStructConst =
75139d628a0SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
75239d628a0SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
753f785676fSDimitry Andric       }
754f785676fSDimitry Andric     }
755f785676fSDimitry Andric   }
756f785676fSDimitry Andric 
7570623d748SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
7580623d748SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
7590623d748SDimitry Andric   // used within a program").
7600623d748SDimitry Andric   if (getLangOpts().CPlusPlus)
7610623d748SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
7620623d748SDimitry Andric       if (FD->isMain())
7630623d748SDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoRecurse);
7640623d748SDimitry Andric 
765f22ef01cSRoman Divacky   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
766f22ef01cSRoman Divacky 
767f22ef01cSRoman Divacky   // Create a marker to make it easy to insert allocas into the entryblock
768f22ef01cSRoman Divacky   // later.  Don't create this with the builder, because we don't want it
769f22ef01cSRoman Divacky   // folded.
770ffd1746dSEd Schouten   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
771e7145dcbSDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
772f22ef01cSRoman Divacky 
773ffd1746dSEd Schouten   ReturnBlock = getJumpDestInCurrentScope("return");
774f22ef01cSRoman Divacky 
775f22ef01cSRoman Divacky   Builder.SetInsertPoint(EntryBB);
776f22ef01cSRoman Divacky 
777f22ef01cSRoman Divacky   // Emit subprogram debug descriptor.
778f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
779e7145dcbSDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
780e7145dcbSDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
781e7145dcbSDimitry Andric     // convention.
782e7145dcbSDimitry Andric     CallingConv CC = CallingConv::CC_C;
783e7145dcbSDimitry Andric     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
784e7145dcbSDimitry Andric       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
785e7145dcbSDimitry Andric         CC = SrcFnTy->getCallConv();
786139f7f9bSDimitry Andric     SmallVector<QualType, 16> ArgTypes;
787e7145dcbSDimitry Andric     for (const VarDecl *VD : Args)
788e7145dcbSDimitry Andric       ArgTypes.push_back(VD->getType());
789e7145dcbSDimitry Andric     QualType FnType = getContext().getFunctionType(
790e7145dcbSDimitry Andric         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
79159d1ed5bSDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
792f22ef01cSRoman Divacky   }
793f22ef01cSRoman Divacky 
7942754fe60SDimitry Andric   if (ShouldInstrumentFunction())
795ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_enter");
796ffd1746dSEd Schouten 
7972754fe60SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling)
7982754fe60SDimitry Andric     EmitMCountInstrumentation();
7992754fe60SDimitry Andric 
800f22ef01cSRoman Divacky   if (RetTy->isVoidType()) {
801f22ef01cSRoman Divacky     // Void type; nothing to return.
8020623d748SDimitry Andric     ReturnValue = Address::invalid();
80359d1ed5bSDimitry Andric 
80459d1ed5bSDimitry Andric     // Count the implicit return.
80559d1ed5bSDimitry Andric     if (!endsWithReturn(D))
80659d1ed5bSDimitry Andric       ++NumReturnExprs;
807f22ef01cSRoman Divacky   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
808139f7f9bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
809f22ef01cSRoman Divacky     // Indirect aggregate return; emit returned value directly into sret slot.
810f22ef01cSRoman Divacky     // This reduces code size, and affects correctness in C++.
81159d1ed5bSDimitry Andric     auto AI = CurFn->arg_begin();
81259d1ed5bSDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
81359d1ed5bSDimitry Andric       ++AI;
8140623d748SDimitry Andric     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
81559d1ed5bSDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
81659d1ed5bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
81759d1ed5bSDimitry Andric     // Load the sret pointer from the argument struct and return into that.
81859d1ed5bSDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
81959d1ed5bSDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
82059d1ed5bSDimitry Andric     --EI;
8210623d748SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
8220623d748SDimitry Andric     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
8230623d748SDimitry Andric     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
824f22ef01cSRoman Divacky   } else {
825f22ef01cSRoman Divacky     ReturnValue = CreateIRTemp(RetTy, "retval");
82617a519f9SDimitry Andric 
82717a519f9SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
82817a519f9SDimitry Andric     // now so that various specialized functions can suppress it
82917a519f9SDimitry Andric     // during their IR-generation.
830dff0c46cSDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
83117a519f9SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
83217a519f9SDimitry Andric         RetTy->isObjCRetainableType())
83317a519f9SDimitry Andric       AutoreleaseResult = true;
834f22ef01cSRoman Divacky   }
835f22ef01cSRoman Divacky 
836f22ef01cSRoman Divacky   EmitStartEHSpec(CurCodeDecl);
83717a519f9SDimitry Andric 
83817a519f9SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
839f22ef01cSRoman Divacky   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
840f22ef01cSRoman Divacky 
841dff0c46cSDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
842e580952dSDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
843dff0c46cSDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
844dff0c46cSDimitry Andric     if (MD->getParent()->isLambda() &&
845dff0c46cSDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
846dff0c46cSDimitry Andric       // We're in a lambda; figure out the captures.
847dff0c46cSDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
848dff0c46cSDimitry Andric                                         LambdaThisCaptureField);
849dff0c46cSDimitry Andric       if (LambdaThisCaptureField) {
850e7145dcbSDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
851e7145dcbSDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
852e7145dcbSDimitry Andric         // object.
853e7145dcbSDimitry Andric 
854e7145dcbSDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
855e7145dcbSDimitry Andric         // or contains the address of the enclosing object).
856e7145dcbSDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
857e7145dcbSDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
858e7145dcbSDimitry Andric           // If the enclosing object was captured by value, just use its address.
859e7145dcbSDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
860e7145dcbSDimitry Andric         } else {
861e7145dcbSDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
862e7145dcbSDimitry Andric           // by reference.
863e7145dcbSDimitry Andric           CXXThisValue =
864e7145dcbSDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
865e7145dcbSDimitry Andric         }
866dff0c46cSDimitry Andric       }
86739d628a0SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
86839d628a0SDimitry Andric         if (FD->hasCapturedVLAType()) {
86939d628a0SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
87039d628a0SDimitry Andric                                            SourceLocation()).getScalarVal();
87139d628a0SDimitry Andric           auto VAT = FD->getCapturedVLAType();
87239d628a0SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
87339d628a0SDimitry Andric         }
87439d628a0SDimitry Andric       }
875dff0c46cSDimitry Andric     } else {
876dff0c46cSDimitry Andric       // Not in a lambda; just use 'this' from the method.
877dff0c46cSDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
878dff0c46cSDimitry Andric       // fast register allocator would be happier...
879dff0c46cSDimitry Andric       CXXThisValue = CXXABIThisValue;
880dff0c46cSDimitry Andric     }
881dff0c46cSDimitry Andric   }
882f22ef01cSRoman Divacky 
883f22ef01cSRoman Divacky   // If any of the arguments have a variably modified type, make sure to
884f22ef01cSRoman Divacky   // emit the type size.
885f22ef01cSRoman Divacky   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
886f22ef01cSRoman Divacky        i != e; ++i) {
887139f7f9bSDimitry Andric     const VarDecl *VD = *i;
888139f7f9bSDimitry Andric 
889139f7f9bSDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
890139f7f9bSDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
891139f7f9bSDimitry Andric     // precedent set by gcc.
892139f7f9bSDimitry Andric     QualType Ty;
893139f7f9bSDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
894139f7f9bSDimitry Andric       Ty = PVD->getOriginalType();
895139f7f9bSDimitry Andric     else
896139f7f9bSDimitry Andric       Ty = VD->getType();
897f22ef01cSRoman Divacky 
898f22ef01cSRoman Divacky     if (Ty->isVariablyModifiedType())
89917a519f9SDimitry Andric       EmitVariablyModifiedType(Ty);
900f22ef01cSRoman Divacky   }
9016122f3e6SDimitry Andric   // Emit a location at the end of the prologue.
9026122f3e6SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
9036122f3e6SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
904f22ef01cSRoman Divacky }
905f22ef01cSRoman Divacky 
906f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
907f785676fSDimitry Andric                                        const Stmt *Body) {
90833956c43SDimitry Andric   incrementProfileCounter(Body);
909f785676fSDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
910139f7f9bSDimitry Andric     EmitCompoundStmtWithoutScope(*S);
911139f7f9bSDimitry Andric   else
912f785676fSDimitry Andric     EmitStmt(Body);
913f22ef01cSRoman Divacky }
914f22ef01cSRoman Divacky 
91559d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
91659d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so
91759d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
91859d1ed5bSDimitry Andric /// this just calls EmitBlock().
91959d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
92033956c43SDimitry Andric                                                const Stmt *S) {
92159d1ed5bSDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
922e7145dcbSDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
92359d1ed5bSDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
92459d1ed5bSDimitry Andric     // statements needs to skip over the instrumentation code so that we
92559d1ed5bSDimitry Andric     // get an accurate count.
92659d1ed5bSDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
92759d1ed5bSDimitry Andric     EmitBranch(SkipCountBB);
92859d1ed5bSDimitry Andric   }
92959d1ed5bSDimitry Andric   EmitBlock(BB);
93033956c43SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
93133956c43SDimitry Andric   incrementProfileCounter(S);
93233956c43SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
93359d1ed5bSDimitry Andric   if (SkipCountBB)
93459d1ed5bSDimitry Andric     EmitBlock(SkipCountBB);
93559d1ed5bSDimitry Andric }
93659d1ed5bSDimitry Andric 
937e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the
938e580952dSDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
939e580952dSDimitry Andric /// lightweight enough to do at -O0.
940e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
941e580952dSDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
942e580952dSDimitry Andric   // can't do this on functions that can be overwritten.
943e7145dcbSDimitry Andric   if (F->isInterposable()) return;
944e580952dSDimitry Andric 
9450623d748SDimitry Andric   for (llvm::BasicBlock &BB : *F)
9460623d748SDimitry Andric     for (llvm::Instruction &I : BB)
9470623d748SDimitry Andric       if (I.mayThrow())
948e580952dSDimitry Andric         return;
9490623d748SDimitry Andric 
9503861d79fSDimitry Andric   F->setDoesNotThrow();
951e580952dSDimitry Andric }
952e580952dSDimitry Andric 
953e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
954e7145dcbSDimitry Andric                                                FunctionArgList &Args) {
955f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
95659d1ed5bSDimitry Andric   QualType ResTy = FD->getReturnType();
957f22ef01cSRoman Divacky 
95859d1ed5bSDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
95959d1ed5bSDimitry Andric   if (MD && MD->isInstance()) {
960f785676fSDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
961f785676fSDimitry Andric       ResTy = MD->getThisType(getContext());
96239d628a0SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
96339d628a0SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
96459d1ed5bSDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
965f785676fSDimitry Andric   }
966f22ef01cSRoman Divacky 
967e7145dcbSDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
968e7145dcbSDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
969e7145dcbSDimitry Andric   // the inherited constructor).
970e7145dcbSDimitry Andric   bool PassedParams = true;
971e7145dcbSDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
972e7145dcbSDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
973e7145dcbSDimitry Andric       PassedParams =
974e7145dcbSDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
975e7145dcbSDimitry Andric 
976e7145dcbSDimitry Andric   if (PassedParams) {
977e7145dcbSDimitry Andric     for (auto *Param : FD->parameters()) {
9780623d748SDimitry Andric       Args.push_back(Param);
9790623d748SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
9800623d748SDimitry Andric         continue;
9810623d748SDimitry Andric 
9820623d748SDimitry Andric       IdentifierInfo *NoID = nullptr;
9830623d748SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
9840623d748SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
9850623d748SDimitry Andric           getContext().getSizeType());
9860623d748SDimitry Andric       SizeArguments[Param] = Implicit;
9870623d748SDimitry Andric       Args.push_back(Implicit);
9880623d748SDimitry Andric     }
989e7145dcbSDimitry Andric   }
990f22ef01cSRoman Divacky 
99159d1ed5bSDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
99259d1ed5bSDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
99359d1ed5bSDimitry Andric 
994e7145dcbSDimitry Andric   return ResTy;
995e7145dcbSDimitry Andric }
996e7145dcbSDimitry Andric 
997e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
998e7145dcbSDimitry Andric                                    const CGFunctionInfo &FnInfo) {
999e7145dcbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1000e7145dcbSDimitry Andric   CurGD = GD;
1001e7145dcbSDimitry Andric 
1002e7145dcbSDimitry Andric   FunctionArgList Args;
1003e7145dcbSDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
1004e7145dcbSDimitry Andric 
1005e7145dcbSDimitry Andric   // Check if we should generate debug info for this function.
1006e7145dcbSDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
1007e7145dcbSDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
1008e7145dcbSDimitry Andric 
1009f22ef01cSRoman Divacky   SourceRange BodyRange;
1010f22ef01cSRoman Divacky   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1011f785676fSDimitry Andric   CurEHLocation = BodyRange.getEnd();
1012139f7f9bSDimitry Andric 
101359d1ed5bSDimitry Andric   // Use the location of the start of the function to determine where
101459d1ed5bSDimitry Andric   // the function definition is located. By default use the location
101559d1ed5bSDimitry Andric   // of the declaration as the location for the subprogram. A function
101659d1ed5bSDimitry Andric   // may lack a declaration in the source code if it is created by code
101759d1ed5bSDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
101859d1ed5bSDimitry Andric   SourceLocation Loc = FD->getLocation();
101959d1ed5bSDimitry Andric 
102059d1ed5bSDimitry Andric   // If this is a function specialization then use the pattern body
102159d1ed5bSDimitry Andric   // as the location for the function.
102259d1ed5bSDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
102359d1ed5bSDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
102459d1ed5bSDimitry Andric       Loc = SpecDecl->getLocation();
102559d1ed5bSDimitry Andric 
1026f22ef01cSRoman Divacky   // Emit the standard function prologue.
102759d1ed5bSDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1028f22ef01cSRoman Divacky 
1029f22ef01cSRoman Divacky   // Generate the body of the function.
10300623d748SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
1031f22ef01cSRoman Divacky   if (isa<CXXDestructorDecl>(FD))
1032f22ef01cSRoman Divacky     EmitDestructorBody(Args);
1033f22ef01cSRoman Divacky   else if (isa<CXXConstructorDecl>(FD))
1034f22ef01cSRoman Divacky     EmitConstructorBody(Args);
10353861d79fSDimitry Andric   else if (getLangOpts().CUDA &&
103633956c43SDimitry Andric            !getLangOpts().CUDAIsDevice &&
10376122f3e6SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
103833956c43SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1039dff0c46cSDimitry Andric   else if (isa<CXXConversionDecl>(FD) &&
1040dff0c46cSDimitry Andric            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1041dff0c46cSDimitry Andric     // The lambda conversion to block pointer is special; the semantics can't be
1042dff0c46cSDimitry Andric     // expressed in the AST, so IRGen needs to special-case it.
1043dff0c46cSDimitry Andric     EmitLambdaToBlockPointerBody(Args);
1044dff0c46cSDimitry Andric   } else if (isa<CXXMethodDecl>(FD) &&
1045dff0c46cSDimitry Andric              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1046f785676fSDimitry Andric     // The lambda static invoker function is special, because it forwards or
1047dff0c46cSDimitry Andric     // clones the body of the function call operator (but is actually static).
1048dff0c46cSDimitry Andric     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1049139f7f9bSDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1050f785676fSDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1051f785676fSDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1052139f7f9bSDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
1053139f7f9bSDimitry Andric     // copy-constructors.
1054139f7f9bSDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
1055f785676fSDimitry Andric   } else if (Stmt *Body = FD->getBody()) {
1056f785676fSDimitry Andric     EmitFunctionBody(Args, Body);
1057f785676fSDimitry Andric   } else
1058f785676fSDimitry Andric     llvm_unreachable("no definition for emitted function");
1059f22ef01cSRoman Divacky 
10603861d79fSDimitry Andric   // C++11 [stmt.return]p2:
10613861d79fSDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
10623861d79fSDimitry Andric   //   a value-returning function.
10633861d79fSDimitry Andric   // C11 6.9.1p12:
10643861d79fSDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
10653861d79fSDimitry Andric   //   function call is used by the caller, the behavior is undefined.
106639d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
106759d1ed5bSDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
106839d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
106959d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
107039d628a0SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
107139d628a0SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
107239d628a0SDimitry Andric                 "missing_return", EmitCheckSourceLocation(FD->getLocation()),
107339d628a0SDimitry Andric                 None);
10743dac3a9bSDimitry Andric     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
10753dac3a9bSDimitry Andric       EmitTrapCall(llvm::Intrinsic::trap);
10763dac3a9bSDimitry Andric     }
10773861d79fSDimitry Andric     Builder.CreateUnreachable();
10783861d79fSDimitry Andric     Builder.ClearInsertionPoint();
10793861d79fSDimitry Andric   }
10803861d79fSDimitry Andric 
1081f22ef01cSRoman Divacky   // Emit the standard function epilogue.
1082f22ef01cSRoman Divacky   FinishFunction(BodyRange.getEnd());
1083f22ef01cSRoman Divacky 
1084e580952dSDimitry Andric   // If we haven't marked the function nothrow through other means, do
1085e580952dSDimitry Andric   // a quick pass now to see if we can.
1086e580952dSDimitry Andric   if (!CurFn->doesNotThrow())
1087e580952dSDimitry Andric     TryMarkNoThrow(CurFn);
1088f22ef01cSRoman Divacky }
1089f22ef01cSRoman Divacky 
1090f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it.  If
1091f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means
1092f22ef01cSRoman Divacky /// that we can just remove the code.
1093f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1094f22ef01cSRoman Divacky   // Null statement, not a label!
109559d1ed5bSDimitry Andric   if (!S) return false;
1096f22ef01cSRoman Divacky 
1097f22ef01cSRoman Divacky   // If this is a label, we have to emit the code, consider something like:
1098f22ef01cSRoman Divacky   // if (0) {  ...  foo:  bar(); }  goto foo;
10993b0f4066SDimitry Andric   //
11003b0f4066SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
11013b0f4066SDimitry Andric   // can't jump to one from outside their declared region.
1102f22ef01cSRoman Divacky   if (isa<LabelStmt>(S))
1103f22ef01cSRoman Divacky     return true;
1104f22ef01cSRoman Divacky 
1105f22ef01cSRoman Divacky   // If this is a case/default statement, and we haven't seen a switch, we have
1106f22ef01cSRoman Divacky   // to emit the code.
1107f22ef01cSRoman Divacky   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1108f22ef01cSRoman Divacky     return true;
1109f22ef01cSRoman Divacky 
1110f22ef01cSRoman Divacky   // If this is a switch statement, we want to ignore cases below it.
1111f22ef01cSRoman Divacky   if (isa<SwitchStmt>(S))
1112f22ef01cSRoman Divacky     IgnoreCaseStmts = true;
1113f22ef01cSRoman Divacky 
1114f22ef01cSRoman Divacky   // Scan subexpressions for verboten labels.
11153dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
11163dac3a9bSDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1117f22ef01cSRoman Divacky       return true;
1118f22ef01cSRoman Divacky 
1119f22ef01cSRoman Divacky   return false;
1120f22ef01cSRoman Divacky }
1121f22ef01cSRoman Divacky 
11223b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
11233b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
11243b0f4066SDimitry Andric /// inside of it, this is fine.
11253b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
11263b0f4066SDimitry Andric   // Null statement, not a label!
112759d1ed5bSDimitry Andric   if (!S) return false;
1128f22ef01cSRoman Divacky 
11293b0f4066SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
11303b0f4066SDimitry Andric   // include it and anything inside of it.
11313b0f4066SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
11323b0f4066SDimitry Andric       isa<ForStmt>(S))
11333b0f4066SDimitry Andric     return false;
11343b0f4066SDimitry Andric 
11353b0f4066SDimitry Andric   if (isa<BreakStmt>(S))
11363b0f4066SDimitry Andric     return true;
11373b0f4066SDimitry Andric 
11383b0f4066SDimitry Andric   // Scan subexpressions for verboten breaks.
11393dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
11403dac3a9bSDimitry Andric     if (containsBreak(SubStmt))
11413b0f4066SDimitry Andric       return true;
11423b0f4066SDimitry Andric 
11433b0f4066SDimitry Andric   return false;
11443b0f4066SDimitry Andric }
11453b0f4066SDimitry Andric 
11463b0f4066SDimitry Andric 
11473b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
11483b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
11493b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result.
11503b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1151e7145dcbSDimitry Andric                                                    bool &ResultBool,
1152e7145dcbSDimitry Andric                                                    bool AllowLabels) {
11537ae0e2c9SDimitry Andric   llvm::APSInt ResultInt;
1154e7145dcbSDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
11553b0f4066SDimitry Andric     return false;
11563b0f4066SDimitry Andric 
11573b0f4066SDimitry Andric   ResultBool = ResultInt.getBoolValue();
11583b0f4066SDimitry Andric   return true;
11593b0f4066SDimitry Andric }
11603b0f4066SDimitry Andric 
11613b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
11623b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
11633b0f4066SDimitry Andric /// constant folds return true and set the folded value.
1164e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1165e7145dcbSDimitry Andric                                                    llvm::APSInt &ResultInt,
1166e7145dcbSDimitry Andric                                                    bool AllowLabels) {
1167f22ef01cSRoman Divacky   // FIXME: Rename and handle conversion of other evaluatable things
1168f22ef01cSRoman Divacky   // to bool.
1169dff0c46cSDimitry Andric   llvm::APSInt Int;
1170dff0c46cSDimitry Andric   if (!Cond->EvaluateAsInt(Int, getContext()))
11713b0f4066SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
1172f22ef01cSRoman Divacky 
1173e7145dcbSDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
11743b0f4066SDimitry Andric     return false;  // Contains a label.
1175f22ef01cSRoman Divacky 
1176dff0c46cSDimitry Andric   ResultInt = Int;
11773b0f4066SDimitry Andric   return true;
1178f22ef01cSRoman Divacky }
1179f22ef01cSRoman Divacky 
1180f22ef01cSRoman Divacky 
11813b0f4066SDimitry Andric 
1182f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1183f22ef01cSRoman Divacky /// statement) to the specified blocks.  Based on the condition, this might try
1184f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch.
1185f22ef01cSRoman Divacky ///
1186f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1187f22ef01cSRoman Divacky                                            llvm::BasicBlock *TrueBlock,
118859d1ed5bSDimitry Andric                                            llvm::BasicBlock *FalseBlock,
118959d1ed5bSDimitry Andric                                            uint64_t TrueCount) {
11903b0f4066SDimitry Andric   Cond = Cond->IgnoreParens();
1191f22ef01cSRoman Divacky 
1192f22ef01cSRoman Divacky   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
119359d1ed5bSDimitry Andric 
1194f22ef01cSRoman Divacky     // Handle X && Y in a condition.
1195e580952dSDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
1196f22ef01cSRoman Divacky       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1197f22ef01cSRoman Divacky       // folded if the case was simple enough.
11983b0f4066SDimitry Andric       bool ConstantBool = false;
11993b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
12003b0f4066SDimitry Andric           ConstantBool) {
1201f22ef01cSRoman Divacky         // br(1 && X) -> br(X).
120233956c43SDimitry Andric         incrementProfileCounter(CondBOp);
120359d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
120459d1ed5bSDimitry Andric                                     TrueCount);
1205f22ef01cSRoman Divacky       }
1206f22ef01cSRoman Divacky 
1207f22ef01cSRoman Divacky       // If we have "X && 1", simplify the code to use an uncond branch.
1208f22ef01cSRoman Divacky       // "X && 0" would have been constant folded to 0.
12093b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
12103b0f4066SDimitry Andric           ConstantBool) {
1211f22ef01cSRoman Divacky         // br(X && 1) -> br(X).
121259d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
121359d1ed5bSDimitry Andric                                     TrueCount);
1214f22ef01cSRoman Divacky       }
1215f22ef01cSRoman Divacky 
1216f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1217f22ef01cSRoman Divacky       // want to jump to the FalseBlock.
1218f22ef01cSRoman Divacky       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
121959d1ed5bSDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
122059d1ed5bSDimitry Andric       // can be propagated to that branch.
122133956c43SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
12222754fe60SDimitry Andric 
12232754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
122433956c43SDimitry Andric       {
122533956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
122659d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1227f22ef01cSRoman Divacky         EmitBlock(LHSTrue);
122833956c43SDimitry Andric       }
122933956c43SDimitry Andric 
123033956c43SDimitry Andric       incrementProfileCounter(CondBOp);
123133956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1232f22ef01cSRoman Divacky 
1233f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
12342754fe60SDimitry Andric       eval.begin(*this);
123559d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
12362754fe60SDimitry Andric       eval.end(*this);
1237f22ef01cSRoman Divacky 
1238f22ef01cSRoman Divacky       return;
12393b0f4066SDimitry Andric     }
12403b0f4066SDimitry Andric 
12413b0f4066SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
1242f22ef01cSRoman Divacky       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1243f22ef01cSRoman Divacky       // folded if the case was simple enough.
12443b0f4066SDimitry Andric       bool ConstantBool = false;
12453b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
12463b0f4066SDimitry Andric           !ConstantBool) {
1247f22ef01cSRoman Divacky         // br(0 || X) -> br(X).
124833956c43SDimitry Andric         incrementProfileCounter(CondBOp);
124959d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
125059d1ed5bSDimitry Andric                                     TrueCount);
1251f22ef01cSRoman Divacky       }
1252f22ef01cSRoman Divacky 
1253f22ef01cSRoman Divacky       // If we have "X || 0", simplify the code to use an uncond branch.
1254f22ef01cSRoman Divacky       // "X || 1" would have been constant folded to 1.
12553b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
12563b0f4066SDimitry Andric           !ConstantBool) {
1257f22ef01cSRoman Divacky         // br(X || 0) -> br(X).
125859d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
125959d1ed5bSDimitry Andric                                     TrueCount);
1260f22ef01cSRoman Divacky       }
1261f22ef01cSRoman Divacky 
1262f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1263f22ef01cSRoman Divacky       // want to jump to the TrueBlock.
1264f22ef01cSRoman Divacky       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
126559d1ed5bSDimitry Andric       // We have the count for entry to the RHS and for the whole expression
126659d1ed5bSDimitry Andric       // being true, so we can divy up True count between the short circuit and
126759d1ed5bSDimitry Andric       // the RHS.
126833956c43SDimitry Andric       uint64_t LHSCount =
126933956c43SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
127059d1ed5bSDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
12712754fe60SDimitry Andric 
12722754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
127333956c43SDimitry Andric       {
127433956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
127559d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1276f22ef01cSRoman Divacky         EmitBlock(LHSFalse);
127733956c43SDimitry Andric       }
127833956c43SDimitry Andric 
127933956c43SDimitry Andric       incrementProfileCounter(CondBOp);
128033956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1281f22ef01cSRoman Divacky 
1282f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
12832754fe60SDimitry Andric       eval.begin(*this);
128459d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
128559d1ed5bSDimitry Andric 
12862754fe60SDimitry Andric       eval.end(*this);
1287f22ef01cSRoman Divacky 
1288f22ef01cSRoman Divacky       return;
1289f22ef01cSRoman Divacky     }
1290f22ef01cSRoman Divacky   }
1291f22ef01cSRoman Divacky 
1292f22ef01cSRoman Divacky   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1293f22ef01cSRoman Divacky     // br(!x, t, f) -> br(x, f, t)
129459d1ed5bSDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
129559d1ed5bSDimitry Andric       // Negate the count.
129633956c43SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
129759d1ed5bSDimitry Andric       // Negate the condition and swap the destination blocks.
129859d1ed5bSDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
129959d1ed5bSDimitry Andric                                   FalseCount);
130059d1ed5bSDimitry Andric     }
1301f22ef01cSRoman Divacky   }
1302f22ef01cSRoman Divacky 
1303f22ef01cSRoman Divacky   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1304f22ef01cSRoman Divacky     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1305f22ef01cSRoman Divacky     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1306f22ef01cSRoman Divacky     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
13072754fe60SDimitry Andric 
13082754fe60SDimitry Andric     ConditionalEvaluation cond(*this);
130933956c43SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
131033956c43SDimitry Andric                          getProfileCount(CondOp));
131159d1ed5bSDimitry Andric 
131259d1ed5bSDimitry Andric     // When computing PGO branch weights, we only know the overall count for
131359d1ed5bSDimitry Andric     // the true block. This code is essentially doing tail duplication of the
131459d1ed5bSDimitry Andric     // naive code-gen, introducing new edges for which counts are not
131559d1ed5bSDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
131659d1ed5bSDimitry Andric     // the conditional operator.
131759d1ed5bSDimitry Andric     uint64_t LHSScaledTrueCount = 0;
131859d1ed5bSDimitry Andric     if (TrueCount) {
131933956c43SDimitry Andric       double LHSRatio =
132033956c43SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
132159d1ed5bSDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
132259d1ed5bSDimitry Andric     }
13232754fe60SDimitry Andric 
13242754fe60SDimitry Andric     cond.begin(*this);
1325f22ef01cSRoman Divacky     EmitBlock(LHSBlock);
132633956c43SDimitry Andric     incrementProfileCounter(CondOp);
132733956c43SDimitry Andric     {
132833956c43SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
132959d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
133059d1ed5bSDimitry Andric                            LHSScaledTrueCount);
133133956c43SDimitry Andric     }
13322754fe60SDimitry Andric     cond.end(*this);
13332754fe60SDimitry Andric 
13342754fe60SDimitry Andric     cond.begin(*this);
1335f22ef01cSRoman Divacky     EmitBlock(RHSBlock);
133659d1ed5bSDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
133759d1ed5bSDimitry Andric                          TrueCount - LHSScaledTrueCount);
13382754fe60SDimitry Andric     cond.end(*this);
13392754fe60SDimitry Andric 
1340f22ef01cSRoman Divacky     return;
1341f22ef01cSRoman Divacky   }
1342f22ef01cSRoman Divacky 
1343284c1978SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1344284c1978SDimitry Andric     // Conditional operator handling can give us a throw expression as a
1345284c1978SDimitry Andric     // condition for a case like:
1346284c1978SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1347284c1978SDimitry Andric     // Fold this to:
1348284c1978SDimitry Andric     //   br(c, throw x, br(y, t, f))
1349284c1978SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1350284c1978SDimitry Andric     return;
1351284c1978SDimitry Andric   }
1352284c1978SDimitry Andric 
13530623d748SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
13540623d748SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
13550623d748SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
13560623d748SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
1357e7145dcbSDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond);
1358e7145dcbSDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1359e7145dcbSDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1360e7145dcbSDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
13610623d748SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
13620623d748SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
13630623d748SDimitry Andric     }
13640623d748SDimitry Andric   }
13650623d748SDimitry Andric 
136659d1ed5bSDimitry Andric   // Create branch weights based on the number of times we get here and the
136759d1ed5bSDimitry Andric   // number of times the condition should be true.
136833956c43SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
136933956c43SDimitry Andric   llvm::MDNode *Weights =
137033956c43SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
137159d1ed5bSDimitry Andric 
1372f22ef01cSRoman Divacky   // Emit the code with the fully general case.
137333956c43SDimitry Andric   llvm::Value *CondV;
137433956c43SDimitry Andric   {
137533956c43SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
137633956c43SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
137733956c43SDimitry Andric   }
13780623d748SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1379f22ef01cSRoman Divacky }
1380f22ef01cSRoman Divacky 
1381f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
1382f22ef01cSRoman Divacky /// specified stmt yet.
1383f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1384f785676fSDimitry Andric   CGM.ErrorUnsupported(S, Type);
1385f22ef01cSRoman Divacky }
1386f22ef01cSRoman Divacky 
13872754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
13882754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
13892754fe60SDimitry Andric ///
13907ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array
13912754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
13922754fe60SDimitry Andric /// base element of the array
13932754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
13942754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
13950623d748SDimitry Andric                                Address dest, Address src,
13962754fe60SDimitry Andric                                llvm::Value *sizeInChars) {
13972754fe60SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
13982754fe60SDimitry Andric 
13990623d748SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
14002754fe60SDimitry Andric   llvm::Value *baseSizeInChars
14010623d748SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
14022754fe60SDimitry Andric 
14030623d748SDimitry Andric   Address begin =
14040623d748SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
14050623d748SDimitry Andric   llvm::Value *end =
14060623d748SDimitry Andric     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
14072754fe60SDimitry Andric 
14082754fe60SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
14092754fe60SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
14102754fe60SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
14112754fe60SDimitry Andric 
14122754fe60SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
14132754fe60SDimitry Andric   // count must be nonzero.
14142754fe60SDimitry Andric   CGF.EmitBlock(loopBB);
14152754fe60SDimitry Andric 
14160623d748SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
14170623d748SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
14180623d748SDimitry Andric 
14190623d748SDimitry Andric   CharUnits curAlign =
14200623d748SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
14212754fe60SDimitry Andric 
14222754fe60SDimitry Andric   // memcpy the individual element bit-pattern.
14230623d748SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
14242754fe60SDimitry Andric                        /*volatile*/ false);
14252754fe60SDimitry Andric 
14262754fe60SDimitry Andric   // Go to the next element.
14270623d748SDimitry Andric   llvm::Value *next =
14280623d748SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
14292754fe60SDimitry Andric 
14302754fe60SDimitry Andric   // Leave if that's the end of the VLA.
14312754fe60SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
14322754fe60SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
14332754fe60SDimitry Andric   cur->addIncoming(next, loopBB);
14342754fe60SDimitry Andric 
14352754fe60SDimitry Andric   CGF.EmitBlock(contBB);
14362754fe60SDimitry Andric }
14372754fe60SDimitry Andric 
1438f22ef01cSRoman Divacky void
14390623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1440f22ef01cSRoman Divacky   // Ignore empty classes in C++.
14413861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1442f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1443f22ef01cSRoman Divacky       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1444f22ef01cSRoman Divacky         return;
1445f22ef01cSRoman Divacky     }
1446f22ef01cSRoman Divacky   }
1447f22ef01cSRoman Divacky 
1448e580952dSDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
14490623d748SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
14500623d748SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1451f22ef01cSRoman Divacky 
1452f22ef01cSRoman Divacky   // Get size and alignment info for this aggregate.
14530623d748SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
14542754fe60SDimitry Andric 
14552754fe60SDimitry Andric   llvm::Value *SizeVal;
14562754fe60SDimitry Andric   const VariableArrayType *vla;
1457f22ef01cSRoman Divacky 
1458f22ef01cSRoman Divacky   // Don't bother emitting a zero-byte memset.
14590623d748SDimitry Andric   if (size.isZero()) {
14602754fe60SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
14612754fe60SDimitry Andric     if (const VariableArrayType *vlaType =
14622754fe60SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
14632754fe60SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
146417a519f9SDimitry Andric       QualType eltType;
146517a519f9SDimitry Andric       llvm::Value *numElts;
146659d1ed5bSDimitry Andric       std::tie(numElts, eltType) = getVLASize(vlaType);
146717a519f9SDimitry Andric 
146817a519f9SDimitry Andric       SizeVal = numElts;
146917a519f9SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
147017a519f9SDimitry Andric       if (!eltSize.isOne())
147117a519f9SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
14722754fe60SDimitry Andric       vla = vlaType;
14732754fe60SDimitry Andric     } else {
1474f22ef01cSRoman Divacky       return;
14752754fe60SDimitry Andric     }
14762754fe60SDimitry Andric   } else {
14770623d748SDimitry Andric     SizeVal = CGM.getSize(size);
147859d1ed5bSDimitry Andric     vla = nullptr;
14792754fe60SDimitry Andric   }
1480e580952dSDimitry Andric 
1481e580952dSDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
1482e580952dSDimitry Andric   // Instead, create a null constant and copy it to the destination.
14832754fe60SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
14842754fe60SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
1485e580952dSDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
14862754fe60SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
14872754fe60SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
14882754fe60SDimitry Andric 
1489e580952dSDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1490e580952dSDimitry Andric 
1491e580952dSDimitry Andric     llvm::GlobalVariable *NullVariable =
1492e580952dSDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1493e580952dSDimitry Andric                                /*isConstant=*/true,
1494e580952dSDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
14956122f3e6SDimitry Andric                                NullConstant, Twine());
14960623d748SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
14970623d748SDimitry Andric     NullVariable->setAlignment(NullAlign.getQuantity());
14980623d748SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
14990623d748SDimitry Andric                    NullAlign);
1500e580952dSDimitry Andric 
15012754fe60SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1502e580952dSDimitry Andric 
1503e580952dSDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
15040623d748SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1505e580952dSDimitry Andric     return;
1506e580952dSDimitry Andric   }
1507e580952dSDimitry Andric 
1508e580952dSDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
1509e580952dSDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
1510e580952dSDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
15110623d748SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1512f22ef01cSRoman Divacky }
1513f22ef01cSRoman Divacky 
15142754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1515f22ef01cSRoman Divacky   // Make sure that there is a block for the indirect goto.
151659d1ed5bSDimitry Andric   if (!IndirectBranch)
1517f22ef01cSRoman Divacky     GetIndirectGotoBlock();
1518f22ef01cSRoman Divacky 
1519e580952dSDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1520f22ef01cSRoman Divacky 
1521f22ef01cSRoman Divacky   // Make sure the indirect branch includes all of the address-taken blocks.
1522f22ef01cSRoman Divacky   IndirectBranch->addDestination(BB);
1523f22ef01cSRoman Divacky   return llvm::BlockAddress::get(CurFn, BB);
1524f22ef01cSRoman Divacky }
1525f22ef01cSRoman Divacky 
1526f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1527f22ef01cSRoman Divacky   // If we already made the indirect branch for indirect goto, return its block.
1528f22ef01cSRoman Divacky   if (IndirectBranch) return IndirectBranch->getParent();
1529f22ef01cSRoman Divacky 
15300623d748SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1531f22ef01cSRoman Divacky 
1532f22ef01cSRoman Divacky   // Create the PHI node that indirect gotos will add entries to.
15333b0f4066SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
15343b0f4066SDimitry Andric                                               "indirect.goto.dest");
1535f22ef01cSRoman Divacky 
1536f22ef01cSRoman Divacky   // Create the indirect branch instruction.
1537f22ef01cSRoman Divacky   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1538f22ef01cSRoman Divacky   return IndirectBranch->getParent();
1539f22ef01cSRoman Divacky }
1540f22ef01cSRoman Divacky 
154117a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base
154217a519f9SDimitry Andric /// element type and a properly-typed first element pointer.
154317a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
154417a519f9SDimitry Andric                                               QualType &baseType,
15450623d748SDimitry Andric                                               Address &addr) {
154617a519f9SDimitry Andric   const ArrayType *arrayType = origArrayType;
1547f22ef01cSRoman Divacky 
154817a519f9SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
154917a519f9SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
155059d1ed5bSDimitry Andric   llvm::Value *numVLAElements = nullptr;
155117a519f9SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
155217a519f9SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
155317a519f9SDimitry Andric 
155417a519f9SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
155517a519f9SDimitry Andric     // which has type T* where T is the first non-VLA element type.
155617a519f9SDimitry Andric     do {
155717a519f9SDimitry Andric       QualType elementType = arrayType->getElementType();
155817a519f9SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
155917a519f9SDimitry Andric 
156017a519f9SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
156117a519f9SDimitry Andric       if (!arrayType) {
156217a519f9SDimitry Andric         baseType = elementType;
156317a519f9SDimitry Andric         return numVLAElements;
156417a519f9SDimitry Andric       }
156517a519f9SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
156617a519f9SDimitry Andric 
156717a519f9SDimitry Andric     // We get out here only if we find a constant array type
156817a519f9SDimitry Andric     // inside the VLA.
1569f22ef01cSRoman Divacky   }
1570f22ef01cSRoman Divacky 
157117a519f9SDimitry Andric   // We have some number of constant-length arrays, so addr should
157217a519f9SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
157317a519f9SDimitry Andric   // down to the first element of addr.
15746122f3e6SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
157517a519f9SDimitry Andric 
157617a519f9SDimitry Andric   // GEP down to the array type.
157717a519f9SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
157817a519f9SDimitry Andric   gepIndices.push_back(zero);
157917a519f9SDimitry Andric 
158017a519f9SDimitry Andric   uint64_t countFromCLAs = 1;
15817ae0e2c9SDimitry Andric   QualType eltType;
158217a519f9SDimitry Andric 
15836122f3e6SDimitry Andric   llvm::ArrayType *llvmArrayType =
15840623d748SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
15857ae0e2c9SDimitry Andric   while (llvmArrayType) {
158617a519f9SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
158717a519f9SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
158817a519f9SDimitry Andric              == llvmArrayType->getNumElements());
158917a519f9SDimitry Andric 
159017a519f9SDimitry Andric     gepIndices.push_back(zero);
159117a519f9SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
15927ae0e2c9SDimitry Andric     eltType = arrayType->getElementType();
159317a519f9SDimitry Andric 
159417a519f9SDimitry Andric     llvmArrayType =
159517a519f9SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
159617a519f9SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
15977ae0e2c9SDimitry Andric     assert((!llvmArrayType || arrayType) &&
15987ae0e2c9SDimitry Andric            "LLVM and Clang types are out-of-synch");
159917a519f9SDimitry Andric   }
160017a519f9SDimitry Andric 
16017ae0e2c9SDimitry Andric   if (arrayType) {
16027ae0e2c9SDimitry Andric     // From this point onwards, the Clang array type has been emitted
16037ae0e2c9SDimitry Andric     // as some other type (probably a packed struct). Compute the array
16047ae0e2c9SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
16057ae0e2c9SDimitry Andric     while (arrayType) {
16067ae0e2c9SDimitry Andric       countFromCLAs *=
16077ae0e2c9SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
16087ae0e2c9SDimitry Andric       eltType = arrayType->getElementType();
16097ae0e2c9SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
16107ae0e2c9SDimitry Andric     }
161117a519f9SDimitry Andric 
16120623d748SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
16130623d748SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
16147ae0e2c9SDimitry Andric   } else {
161517a519f9SDimitry Andric     // Create the actual GEP.
16160623d748SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
16170623d748SDimitry Andric                                              gepIndices, "array.begin"),
16180623d748SDimitry Andric                    addr.getAlignment());
16197ae0e2c9SDimitry Andric   }
16207ae0e2c9SDimitry Andric 
16217ae0e2c9SDimitry Andric   baseType = eltType;
162217a519f9SDimitry Andric 
162317a519f9SDimitry Andric   llvm::Value *numElements
162417a519f9SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
162517a519f9SDimitry Andric 
162617a519f9SDimitry Andric   // If we had any VLA dimensions, factor them in.
162717a519f9SDimitry Andric   if (numVLAElements)
162817a519f9SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
162917a519f9SDimitry Andric 
163017a519f9SDimitry Andric   return numElements;
163117a519f9SDimitry Andric }
163217a519f9SDimitry Andric 
163317a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
163417a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) {
163517a519f9SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
163617a519f9SDimitry Andric   assert(vla && "type was not a variable array type!");
163717a519f9SDimitry Andric   return getVLASize(vla);
163817a519f9SDimitry Andric }
163917a519f9SDimitry Andric 
164017a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
164117a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
164217a519f9SDimitry Andric   // The number of elements so far; always size_t.
164359d1ed5bSDimitry Andric   llvm::Value *numElements = nullptr;
164417a519f9SDimitry Andric 
164517a519f9SDimitry Andric   QualType elementType;
164617a519f9SDimitry Andric   do {
164717a519f9SDimitry Andric     elementType = type->getElementType();
164817a519f9SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
164917a519f9SDimitry Andric     assert(vlaSize && "no size for VLA!");
165017a519f9SDimitry Andric     assert(vlaSize->getType() == SizeTy);
165117a519f9SDimitry Andric 
165217a519f9SDimitry Andric     if (!numElements) {
165317a519f9SDimitry Andric       numElements = vlaSize;
165417a519f9SDimitry Andric     } else {
165517a519f9SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
165659d1ed5bSDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
165717a519f9SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
165817a519f9SDimitry Andric     }
165917a519f9SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
166017a519f9SDimitry Andric 
166117a519f9SDimitry Andric   return std::pair<llvm::Value*,QualType>(numElements, elementType);
166217a519f9SDimitry Andric }
166317a519f9SDimitry Andric 
166417a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
166517a519f9SDimitry Andric   assert(type->isVariablyModifiedType() &&
1666f22ef01cSRoman Divacky          "Must pass variably modified type to EmitVLASizes!");
1667f22ef01cSRoman Divacky 
1668f22ef01cSRoman Divacky   EnsureInsertPoint();
1669f22ef01cSRoman Divacky 
167017a519f9SDimitry Andric   // We're going to walk down into the type and look for VLA
167117a519f9SDimitry Andric   // expressions.
167217a519f9SDimitry Andric   do {
167317a519f9SDimitry Andric     assert(type->isVariablyModifiedType());
1674f22ef01cSRoman Divacky 
167517a519f9SDimitry Andric     const Type *ty = type.getTypePtr();
167617a519f9SDimitry Andric     switch (ty->getTypeClass()) {
1677dff0c46cSDimitry Andric 
167817a519f9SDimitry Andric #define TYPE(Class, Base)
167917a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
1680dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
168117a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1682dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
168317a519f9SDimitry Andric #include "clang/AST/TypeNodes.def"
1684dff0c46cSDimitry Andric       llvm_unreachable("unexpected dependent type!");
1685f22ef01cSRoman Divacky 
168617a519f9SDimitry Andric     // These types are never variably-modified.
168717a519f9SDimitry Andric     case Type::Builtin:
168817a519f9SDimitry Andric     case Type::Complex:
168917a519f9SDimitry Andric     case Type::Vector:
169017a519f9SDimitry Andric     case Type::ExtVector:
169117a519f9SDimitry Andric     case Type::Record:
169217a519f9SDimitry Andric     case Type::Enum:
1693dff0c46cSDimitry Andric     case Type::Elaborated:
1694dff0c46cSDimitry Andric     case Type::TemplateSpecialization:
169517a519f9SDimitry Andric     case Type::ObjCObject:
169617a519f9SDimitry Andric     case Type::ObjCInterface:
169717a519f9SDimitry Andric     case Type::ObjCObjectPointer:
169817a519f9SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
1699f22ef01cSRoman Divacky 
170059d1ed5bSDimitry Andric     case Type::Adjusted:
170159d1ed5bSDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
170259d1ed5bSDimitry Andric       break;
170359d1ed5bSDimitry Andric 
1704f785676fSDimitry Andric     case Type::Decayed:
1705f785676fSDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
1706f785676fSDimitry Andric       break;
1707f785676fSDimitry Andric 
170817a519f9SDimitry Andric     case Type::Pointer:
170917a519f9SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
171017a519f9SDimitry Andric       break;
1711f22ef01cSRoman Divacky 
171217a519f9SDimitry Andric     case Type::BlockPointer:
171317a519f9SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
171417a519f9SDimitry Andric       break;
171517a519f9SDimitry Andric 
171617a519f9SDimitry Andric     case Type::LValueReference:
171717a519f9SDimitry Andric     case Type::RValueReference:
171817a519f9SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
171917a519f9SDimitry Andric       break;
172017a519f9SDimitry Andric 
172117a519f9SDimitry Andric     case Type::MemberPointer:
172217a519f9SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
172317a519f9SDimitry Andric       break;
172417a519f9SDimitry Andric 
172517a519f9SDimitry Andric     case Type::ConstantArray:
172617a519f9SDimitry Andric     case Type::IncompleteArray:
172717a519f9SDimitry Andric       // Losing element qualification here is fine.
172817a519f9SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
172917a519f9SDimitry Andric       break;
173017a519f9SDimitry Andric 
173117a519f9SDimitry Andric     case Type::VariableArray: {
173217a519f9SDimitry Andric       // Losing element qualification here is fine.
173317a519f9SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
173417a519f9SDimitry Andric 
173517a519f9SDimitry Andric       // Unknown size indication requires no size computation.
173617a519f9SDimitry Andric       // Otherwise, evaluate and record it.
173717a519f9SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
173817a519f9SDimitry Andric         // It's possible that we might have emitted this already,
173917a519f9SDimitry Andric         // e.g. with a typedef and a pointer to it.
174017a519f9SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
174117a519f9SDimitry Andric         if (!entry) {
17423861d79fSDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
17433861d79fSDimitry Andric 
17443861d79fSDimitry Andric           // C11 6.7.6.2p5:
17453861d79fSDimitry Andric           //   If the size is an expression that is not an integer constant
17463861d79fSDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
17473861d79fSDimitry Andric           //   greater than zero.
174839d628a0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
17493861d79fSDimitry Andric               size->getType()->isSignedIntegerType()) {
175059d1ed5bSDimitry Andric             SanitizerScope SanScope(this);
17513861d79fSDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
17523861d79fSDimitry Andric             llvm::Constant *StaticArgs[] = {
17533861d79fSDimitry Andric               EmitCheckSourceLocation(size->getLocStart()),
17543861d79fSDimitry Andric               EmitCheckTypeDescriptor(size->getType())
17553861d79fSDimitry Andric             };
175639d628a0SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
175739d628a0SDimitry Andric                                      SanitizerKind::VLABound),
175839d628a0SDimitry Andric                       "vla_bound_not_positive", StaticArgs, Size);
17593861d79fSDimitry Andric           }
17603861d79fSDimitry Andric 
176117a519f9SDimitry Andric           // Always zexting here would be wrong if it weren't
176217a519f9SDimitry Andric           // undefined behavior to have a negative bound.
17633861d79fSDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
176417a519f9SDimitry Andric         }
176517a519f9SDimitry Andric       }
176617a519f9SDimitry Andric       type = vat->getElementType();
176717a519f9SDimitry Andric       break;
1768f22ef01cSRoman Divacky     }
1769f22ef01cSRoman Divacky 
177017a519f9SDimitry Andric     case Type::FunctionProto:
177117a519f9SDimitry Andric     case Type::FunctionNoProto:
177259d1ed5bSDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
177317a519f9SDimitry Andric       break;
17746122f3e6SDimitry Andric 
1775dff0c46cSDimitry Andric     case Type::Paren:
1776dff0c46cSDimitry Andric     case Type::TypeOf:
1777dff0c46cSDimitry Andric     case Type::UnaryTransform:
1778dff0c46cSDimitry Andric     case Type::Attributed:
1779dff0c46cSDimitry Andric     case Type::SubstTemplateTypeParm:
1780f785676fSDimitry Andric     case Type::PackExpansion:
1781dff0c46cSDimitry Andric       // Keep walking after single level desugaring.
1782dff0c46cSDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
1783dff0c46cSDimitry Andric       break;
1784dff0c46cSDimitry Andric 
1785dff0c46cSDimitry Andric     case Type::Typedef:
1786dff0c46cSDimitry Andric     case Type::Decltype:
1787dff0c46cSDimitry Andric     case Type::Auto:
1788dff0c46cSDimitry Andric       // Stop walking: nothing to do.
1789dff0c46cSDimitry Andric       return;
1790dff0c46cSDimitry Andric 
1791dff0c46cSDimitry Andric     case Type::TypeOfExpr:
1792dff0c46cSDimitry Andric       // Stop walking: emit typeof expression.
1793dff0c46cSDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1794dff0c46cSDimitry Andric       return;
1795dff0c46cSDimitry Andric 
17966122f3e6SDimitry Andric     case Type::Atomic:
17976122f3e6SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
17986122f3e6SDimitry Andric       break;
1799444ed5c5SDimitry Andric 
1800444ed5c5SDimitry Andric     case Type::Pipe:
1801444ed5c5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
1802444ed5c5SDimitry Andric       break;
1803f22ef01cSRoman Divacky     }
180417a519f9SDimitry Andric   } while (type->isVariablyModifiedType());
1805f22ef01cSRoman Divacky }
1806f22ef01cSRoman Divacky 
18070623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
18082754fe60SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
18090623d748SDimitry Andric     return EmitPointerWithAlignment(E);
18100623d748SDimitry Andric   return EmitLValue(E).getAddress();
18110623d748SDimitry Andric }
18120623d748SDimitry Andric 
18130623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1814f22ef01cSRoman Divacky   return EmitLValue(E).getAddress();
1815f22ef01cSRoman Divacky }
1816f22ef01cSRoman Divacky 
1817e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
18182754fe60SDimitry Andric                                               llvm::Constant *Init) {
1819e580952dSDimitry Andric   assert (Init && "Invalid DeclRefExpr initializer!");
1820e580952dSDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
1821e7145dcbSDimitry Andric     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
18222754fe60SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
18232754fe60SDimitry Andric }
18242754fe60SDimitry Andric 
18252754fe60SDimitry Andric CodeGenFunction::PeepholeProtection
18262754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
18272754fe60SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
18282754fe60SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
18292754fe60SDimitry Andric   // extend this protection.
18302754fe60SDimitry Andric 
18312754fe60SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
18322754fe60SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
18332754fe60SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
18342754fe60SDimitry Andric 
18352754fe60SDimitry Andric   // Just make an extra bitcast.
18362754fe60SDimitry Andric   assert(HaveInsertPoint());
18372754fe60SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
18382754fe60SDimitry Andric                                                   Builder.GetInsertBlock());
18392754fe60SDimitry Andric 
18402754fe60SDimitry Andric   PeepholeProtection protection;
18412754fe60SDimitry Andric   protection.Inst = inst;
18422754fe60SDimitry Andric   return protection;
18432754fe60SDimitry Andric }
18442754fe60SDimitry Andric 
18452754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
18462754fe60SDimitry Andric   if (!protection.Inst) return;
18472754fe60SDimitry Andric 
18482754fe60SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
18492754fe60SDimitry Andric   protection.Inst->eraseFromParent();
1850e580952dSDimitry Andric }
18516122f3e6SDimitry Andric 
18526122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
18536122f3e6SDimitry Andric                                                  llvm::Value *AnnotatedVal,
1854139f7f9bSDimitry Andric                                                  StringRef AnnotationStr,
18556122f3e6SDimitry Andric                                                  SourceLocation Location) {
18566122f3e6SDimitry Andric   llvm::Value *Args[4] = {
18576122f3e6SDimitry Andric     AnnotatedVal,
18586122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
18596122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
18606122f3e6SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
18616122f3e6SDimitry Andric   };
18626122f3e6SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
18636122f3e6SDimitry Andric }
18646122f3e6SDimitry Andric 
18656122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
18666122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
18676122f3e6SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
18686122f3e6SDimitry Andric   // llvm-gcc was doing.
186959d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
18706122f3e6SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
18716122f3e6SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
187259d1ed5bSDimitry Andric                        I->getAnnotation(), D->getLocation());
18736122f3e6SDimitry Andric }
18746122f3e6SDimitry Andric 
18750623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
18760623d748SDimitry Andric                                               Address Addr) {
18776122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
18780623d748SDimitry Andric   llvm::Value *V = Addr.getPointer();
18796122f3e6SDimitry Andric   llvm::Type *VTy = V->getType();
18806122f3e6SDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
18816122f3e6SDimitry Andric                                     CGM.Int8PtrTy);
18826122f3e6SDimitry Andric 
188359d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
18846122f3e6SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
18856122f3e6SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
18866122f3e6SDimitry Andric     // itself.
18876122f3e6SDimitry Andric     if (VTy != CGM.Int8PtrTy)
18886122f3e6SDimitry Andric       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
188959d1ed5bSDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
18906122f3e6SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
18916122f3e6SDimitry Andric   }
18926122f3e6SDimitry Andric 
18930623d748SDimitry Andric   return Address(V, Addr.getAlignment());
18946122f3e6SDimitry Andric }
1895f785676fSDimitry Andric 
1896f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
189759d1ed5bSDimitry Andric 
189859d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
189959d1ed5bSDimitry Andric     : CGF(CGF) {
190059d1ed5bSDimitry Andric   assert(!CGF->IsSanitizerScope);
190159d1ed5bSDimitry Andric   CGF->IsSanitizerScope = true;
190259d1ed5bSDimitry Andric }
190359d1ed5bSDimitry Andric 
190459d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
190559d1ed5bSDimitry Andric   CGF->IsSanitizerScope = false;
190659d1ed5bSDimitry Andric }
190759d1ed5bSDimitry Andric 
190859d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
190959d1ed5bSDimitry Andric                                    const llvm::Twine &Name,
191059d1ed5bSDimitry Andric                                    llvm::BasicBlock *BB,
191159d1ed5bSDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
191259d1ed5bSDimitry Andric   LoopStack.InsertHelper(I);
191339d628a0SDimitry Andric   if (IsSanitizerScope)
191439d628a0SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
191559d1ed5bSDimitry Andric }
191659d1ed5bSDimitry Andric 
1917e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper(
191859d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
191959d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
1920e7145dcbSDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
192159d1ed5bSDimitry Andric   if (CGF)
192259d1ed5bSDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
192359d1ed5bSDimitry Andric }
192459d1ed5bSDimitry Andric 
19250623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
19260623d748SDimitry Andric                                 CodeGenModule &CGM, const FunctionDecl *FD,
19270623d748SDimitry Andric                                 std::string &FirstMissing) {
19280623d748SDimitry Andric   // If there aren't any required features listed then go ahead and return.
19290623d748SDimitry Andric   if (ReqFeatures.empty())
19300623d748SDimitry Andric     return false;
19310623d748SDimitry Andric 
19320623d748SDimitry Andric   // Now build up the set of caller features and verify that all the required
19330623d748SDimitry Andric   // features are there.
19340623d748SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
19350623d748SDimitry Andric   CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
19360623d748SDimitry Andric 
19370623d748SDimitry Andric   // If we have at least one of the features in the feature list return
19380623d748SDimitry Andric   // true, otherwise return false.
19390623d748SDimitry Andric   return std::all_of(
19400623d748SDimitry Andric       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
19410623d748SDimitry Andric         SmallVector<StringRef, 1> OrFeatures;
19420623d748SDimitry Andric         Feature.split(OrFeatures, "|");
19430623d748SDimitry Andric         return std::any_of(OrFeatures.begin(), OrFeatures.end(),
19440623d748SDimitry Andric                            [&](StringRef Feature) {
19450623d748SDimitry Andric                              if (!CallerFeatureMap.lookup(Feature)) {
19460623d748SDimitry Andric                                FirstMissing = Feature.str();
19470623d748SDimitry Andric                                return false;
19480623d748SDimitry Andric                              }
19490623d748SDimitry Andric                              return true;
19500623d748SDimitry Andric                            });
19510623d748SDimitry Andric       });
19520623d748SDimitry Andric }
19530623d748SDimitry Andric 
19540623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the
19550623d748SDimitry Andric // called function.
19560623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
19570623d748SDimitry Andric                                           const FunctionDecl *TargetDecl) {
19580623d748SDimitry Andric   // Early exit if this is an indirect call.
19590623d748SDimitry Andric   if (!TargetDecl)
19600623d748SDimitry Andric     return;
19610623d748SDimitry Andric 
19620623d748SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
19630623d748SDimitry Andric   // we can't check the target features anyhow.
19640623d748SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
19650623d748SDimitry Andric   if (!FD)
19660623d748SDimitry Andric     return;
19670623d748SDimitry Andric 
19680623d748SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
19690623d748SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
19700623d748SDimitry Andric   // listed cpu and any listed features.
19710623d748SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
19720623d748SDimitry Andric   std::string MissingFeature;
19730623d748SDimitry Andric   if (BuiltinID) {
19740623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
19750623d748SDimitry Andric     const char *FeatureList =
19760623d748SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
19770623d748SDimitry Andric     // Return if the builtin doesn't have any required features.
19780623d748SDimitry Andric     if (!FeatureList || StringRef(FeatureList) == "")
19790623d748SDimitry Andric       return;
19800623d748SDimitry Andric     StringRef(FeatureList).split(ReqFeatures, ",");
19810623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
19820623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
19830623d748SDimitry Andric           << TargetDecl->getDeclName()
19840623d748SDimitry Andric           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
19850623d748SDimitry Andric 
19860623d748SDimitry Andric   } else if (TargetDecl->hasAttr<TargetAttr>()) {
19870623d748SDimitry Andric     // Get the required features for the callee.
19880623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
19890623d748SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
19900623d748SDimitry Andric     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
19910623d748SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
19920623d748SDimitry Andric       // Only positive features are "required".
19930623d748SDimitry Andric       if (F.getValue())
19940623d748SDimitry Andric         ReqFeatures.push_back(F.getKey());
19950623d748SDimitry Andric     }
19960623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
19970623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
19980623d748SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
19990623d748SDimitry Andric   }
20000623d748SDimitry Andric }
2001e7145dcbSDimitry Andric 
2002e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2003e7145dcbSDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
2004e7145dcbSDimitry Andric     return;
2005e7145dcbSDimitry Andric 
2006e7145dcbSDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2007e7145dcbSDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2008e7145dcbSDimitry Andric   CGM.getSanStats().create(IRB, SSK);
2009e7145dcbSDimitry Andric }
2010