1f22ef01cSRoman Divacky //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-function state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenFunction.h"
150623d748SDimitry Andric #include "CGBlocks.h"
1633956c43SDimitry Andric #include "CGCleanup.h"
176122f3e6SDimitry Andric #include "CGCUDARuntime.h"
18e580952dSDimitry Andric #include "CGCXXABI.h"
19f22ef01cSRoman Divacky #include "CGDebugInfo.h"
2059d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
21139f7f9bSDimitry Andric #include "CodeGenModule.h"
2259d1ed5bSDimitry Andric #include "CodeGenPGO.h"
23f785676fSDimitry Andric #include "TargetInfo.h"
24f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
25f22ef01cSRoman Divacky #include "clang/AST/Decl.h"
26f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
27f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h"
28f41fbc90SDimitry Andric #include "clang/AST/StmtObjC.h"
290623d748SDimitry Andric #include "clang/Basic/Builtins.h"
30139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h"
31f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
32ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
330623d748SDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
34139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
36139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
38f22ef01cSRoman Divacky using namespace clang;
39f22ef01cSRoman Divacky using namespace CodeGen;
40f22ef01cSRoman Divacky 
417ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
42284c1978SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
430623d748SDimitry Andric       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
4459d1ed5bSDimitry Andric               CGBuilderInserterTy(this)),
450623d748SDimitry Andric       CurFn(nullptr), ReturnValue(Address::invalid()),
460623d748SDimitry Andric       CapturedStmtInfo(nullptr),
4739d628a0SDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
4839d628a0SDimitry Andric       CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
490623d748SDimitry Andric       IsOutlinedSEHHelper(false),
500623d748SDimitry Andric       BlockInfo(nullptr), BlockPointer(nullptr),
5139d628a0SDimitry Andric       LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
5239d628a0SDimitry Andric       NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
5339d628a0SDimitry Andric       ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
54875ed548SDimitry Andric       DebugInfo(CGM.getModuleDebugInfo()),
55875ed548SDimitry Andric       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
56875ed548SDimitry Andric       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
57875ed548SDimitry Andric       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
58875ed548SDimitry Andric       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
59875ed548SDimitry Andric       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
600623d748SDimitry Andric       CXXStructorImplicitParamDecl(nullptr),
6159d1ed5bSDimitry Andric       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
6259d1ed5bSDimitry Andric       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
6359d1ed5bSDimitry Andric       TerminateHandler(nullptr), TrapBB(nullptr) {
647ae0e2c9SDimitry Andric   if (!suppressNewContext)
65e580952dSDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
66139f7f9bSDimitry Andric 
67139f7f9bSDimitry Andric   llvm::FastMathFlags FMF;
68139f7f9bSDimitry Andric   if (CGM.getLangOpts().FastMath)
69139f7f9bSDimitry Andric     FMF.setUnsafeAlgebra();
70139f7f9bSDimitry Andric   if (CGM.getLangOpts().FiniteMathOnly) {
71139f7f9bSDimitry Andric     FMF.setNoNaNs();
72139f7f9bSDimitry Andric     FMF.setNoInfs();
73139f7f9bSDimitry Andric   }
7439d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
7539d628a0SDimitry Andric     FMF.setNoNaNs();
7639d628a0SDimitry Andric   }
7739d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoSignedZeros) {
7839d628a0SDimitry Andric     FMF.setNoSignedZeros();
7939d628a0SDimitry Andric   }
8033956c43SDimitry Andric   if (CGM.getCodeGenOpts().ReciprocalMath) {
8133956c43SDimitry Andric     FMF.setAllowReciprocal();
8233956c43SDimitry Andric   }
83444ed5c5SDimitry Andric   Builder.setFastMathFlags(FMF);
84f22ef01cSRoman Divacky }
85f22ef01cSRoman Divacky 
86dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() {
87f785676fSDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
88f785676fSDimitry Andric 
89dff0c46cSDimitry Andric   // If there are any unclaimed block infos, go ahead and destroy them
90dff0c46cSDimitry Andric   // now.  This can happen if IR-gen gets clever and skips evaluating
91dff0c46cSDimitry Andric   // something.
92dff0c46cSDimitry Andric   if (FirstBlockInfo)
93dff0c46cSDimitry Andric     destroyBlockInfos(FirstBlockInfo);
9459d1ed5bSDimitry Andric 
9559d1ed5bSDimitry Andric   if (getLangOpts().OpenMP) {
9633956c43SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
9759d1ed5bSDimitry Andric   }
98dff0c46cSDimitry Andric }
99dff0c46cSDimitry Andric 
1000623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
1010623d748SDimitry Andric                                                      AlignmentSource *Source) {
1020623d748SDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), Source,
1030623d748SDimitry Andric                                  /*forPointee*/ true);
1040623d748SDimitry Andric }
1050623d748SDimitry Andric 
1060623d748SDimitry Andric CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
1070623d748SDimitry Andric                                                    AlignmentSource *Source,
1080623d748SDimitry Andric                                                    bool forPointeeType) {
1090623d748SDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
1100623d748SDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
1110623d748SDimitry Andric   // there's an expressivity gap here.
1120623d748SDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
1130623d748SDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
1140623d748SDimitry Andric       if (Source) *Source = AlignmentSource::AttributedType;
1150623d748SDimitry Andric       return getContext().toCharUnitsFromBits(Align);
1160623d748SDimitry Andric     }
1170623d748SDimitry Andric   }
1180623d748SDimitry Andric 
1190623d748SDimitry Andric   if (Source) *Source = AlignmentSource::Type;
1200623d748SDimitry Andric 
12139d628a0SDimitry Andric   CharUnits Alignment;
1220623d748SDimitry Andric   if (T->isIncompleteType()) {
1230623d748SDimitry Andric     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
1240623d748SDimitry Andric   } else {
1250623d748SDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
1260623d748SDimitry Andric     // base or a complete object, so we generally need to use the
1270623d748SDimitry Andric     // non-virtual alignment.
1280623d748SDimitry Andric     const CXXRecordDecl *RD;
1290623d748SDimitry Andric     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
1300623d748SDimitry Andric       Alignment = CGM.getClassPointerAlignment(RD);
1310623d748SDimitry Andric     } else {
13239d628a0SDimitry Andric       Alignment = getContext().getTypeAlignInChars(T);
1330623d748SDimitry Andric     }
1340623d748SDimitry Andric 
1350623d748SDimitry Andric     // Cap to the global maximum type alignment unless the alignment
1360623d748SDimitry Andric     // was somehow explicit on the type.
1370623d748SDimitry Andric     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
1380623d748SDimitry Andric       if (Alignment.getQuantity() > MaxAlign &&
13939d628a0SDimitry Andric           !getContext().isAlignmentRequired(T))
14039d628a0SDimitry Andric         Alignment = CharUnits::fromQuantity(MaxAlign);
14139d628a0SDimitry Andric     }
14239d628a0SDimitry Andric   }
1430623d748SDimitry Andric   return Alignment;
1440623d748SDimitry Andric }
1450623d748SDimitry Andric 
1460623d748SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1470623d748SDimitry Andric   AlignmentSource AlignSource;
1480623d748SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
1490623d748SDimitry Andric   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
1500623d748SDimitry Andric                           CGM.getTBAAInfo(T));
1510623d748SDimitry Andric }
1520623d748SDimitry Andric 
1530623d748SDimitry Andric /// Given a value of type T* that may not be to a complete object,
1540623d748SDimitry Andric /// construct an l-value with the natural pointee alignment of T.
1550623d748SDimitry Andric LValue
1560623d748SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
1570623d748SDimitry Andric   AlignmentSource AlignSource;
1580623d748SDimitry Andric   CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
1590623d748SDimitry Andric   return MakeAddrLValue(Address(V, Align), T, AlignSource);
1600623d748SDimitry Andric }
1610623d748SDimitry Andric 
162f22ef01cSRoman Divacky 
16317a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
164f22ef01cSRoman Divacky   return CGM.getTypes().ConvertTypeForMem(T);
165f22ef01cSRoman Divacky }
166f22ef01cSRoman Divacky 
16717a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
168f22ef01cSRoman Divacky   return CGM.getTypes().ConvertType(T);
169f22ef01cSRoman Divacky }
170f22ef01cSRoman Divacky 
171139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
172139f7f9bSDimitry Andric   type = type.getCanonicalType();
173139f7f9bSDimitry Andric   while (true) {
174139f7f9bSDimitry Andric     switch (type->getTypeClass()) {
175bd5abe19SDimitry Andric #define TYPE(name, parent)
176bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent)
177bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
178bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
179bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
180bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def"
181bd5abe19SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
182bd5abe19SDimitry Andric 
183284c1978SDimitry Andric     case Type::Auto:
184284c1978SDimitry Andric       llvm_unreachable("undeduced auto type in IR-generation");
185284c1978SDimitry Andric 
186139f7f9bSDimitry Andric     // Various scalar types.
187bd5abe19SDimitry Andric     case Type::Builtin:
188bd5abe19SDimitry Andric     case Type::Pointer:
189bd5abe19SDimitry Andric     case Type::BlockPointer:
190bd5abe19SDimitry Andric     case Type::LValueReference:
191bd5abe19SDimitry Andric     case Type::RValueReference:
192bd5abe19SDimitry Andric     case Type::MemberPointer:
193bd5abe19SDimitry Andric     case Type::Vector:
194bd5abe19SDimitry Andric     case Type::ExtVector:
195bd5abe19SDimitry Andric     case Type::FunctionProto:
196bd5abe19SDimitry Andric     case Type::FunctionNoProto:
197bd5abe19SDimitry Andric     case Type::Enum:
198bd5abe19SDimitry Andric     case Type::ObjCObjectPointer:
199444ed5c5SDimitry Andric     case Type::Pipe:
200139f7f9bSDimitry Andric       return TEK_Scalar;
201bd5abe19SDimitry Andric 
202139f7f9bSDimitry Andric     // Complexes.
203bd5abe19SDimitry Andric     case Type::Complex:
204139f7f9bSDimitry Andric       return TEK_Complex;
205139f7f9bSDimitry Andric 
206139f7f9bSDimitry Andric     // Arrays, records, and Objective-C objects.
207bd5abe19SDimitry Andric     case Type::ConstantArray:
208bd5abe19SDimitry Andric     case Type::IncompleteArray:
209bd5abe19SDimitry Andric     case Type::VariableArray:
210bd5abe19SDimitry Andric     case Type::Record:
211bd5abe19SDimitry Andric     case Type::ObjCObject:
212bd5abe19SDimitry Andric     case Type::ObjCInterface:
213139f7f9bSDimitry Andric       return TEK_Aggregate;
2146122f3e6SDimitry Andric 
215139f7f9bSDimitry Andric     // We operate on atomic values according to their underlying type.
2166122f3e6SDimitry Andric     case Type::Atomic:
217139f7f9bSDimitry Andric       type = cast<AtomicType>(type)->getValueType();
218139f7f9bSDimitry Andric       continue;
219bd5abe19SDimitry Andric     }
220bd5abe19SDimitry Andric     llvm_unreachable("unknown type kind!");
221f22ef01cSRoman Divacky   }
222139f7f9bSDimitry Andric }
223f22ef01cSRoman Divacky 
22439d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
225f22ef01cSRoman Divacky   // For cleanliness, we try to avoid emitting the return block for
226f22ef01cSRoman Divacky   // simple cases.
227f22ef01cSRoman Divacky   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
228f22ef01cSRoman Divacky 
229f22ef01cSRoman Divacky   if (CurBB) {
230f22ef01cSRoman Divacky     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
231f22ef01cSRoman Divacky 
232f22ef01cSRoman Divacky     // We have a valid insert point, reuse it if it is empty or there are no
233f22ef01cSRoman Divacky     // explicit jumps to the return block.
234e580952dSDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
235e580952dSDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
236e580952dSDimitry Andric       delete ReturnBlock.getBlock();
237f22ef01cSRoman Divacky     } else
238e580952dSDimitry Andric       EmitBlock(ReturnBlock.getBlock());
23939d628a0SDimitry Andric     return llvm::DebugLoc();
240f22ef01cSRoman Divacky   }
241f22ef01cSRoman Divacky 
242f22ef01cSRoman Divacky   // Otherwise, if the return block is the target of a single direct
243f22ef01cSRoman Divacky   // branch then we can just put the code in that block instead. This
244f22ef01cSRoman Divacky   // cleans up functions which started with a unified return block.
245e580952dSDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
246f22ef01cSRoman Divacky     llvm::BranchInst *BI =
24759d1ed5bSDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
248ffd1746dSEd Schouten     if (BI && BI->isUnconditional() &&
249e580952dSDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
25039d628a0SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
25139d628a0SDimitry Andric       // later by the actual 'ret' instruction.
25239d628a0SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
253f22ef01cSRoman Divacky       Builder.SetInsertPoint(BI->getParent());
254f22ef01cSRoman Divacky       BI->eraseFromParent();
255e580952dSDimitry Andric       delete ReturnBlock.getBlock();
25639d628a0SDimitry Andric       return Loc;
257f22ef01cSRoman Divacky     }
258f22ef01cSRoman Divacky   }
259f22ef01cSRoman Divacky 
260f22ef01cSRoman Divacky   // FIXME: We are at an unreachable point, there is no reason to emit the block
261f22ef01cSRoman Divacky   // unless it has uses. However, we still need a place to put the debug
262f22ef01cSRoman Divacky   // region.end for now.
263f22ef01cSRoman Divacky 
264e580952dSDimitry Andric   EmitBlock(ReturnBlock.getBlock());
26539d628a0SDimitry Andric   return llvm::DebugLoc();
266ffd1746dSEd Schouten }
267ffd1746dSEd Schouten 
268ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
269ffd1746dSEd Schouten   if (!BB) return;
270ffd1746dSEd Schouten   if (!BB->use_empty())
271ffd1746dSEd Schouten     return CGF.CurFn->getBasicBlockList().push_back(BB);
272ffd1746dSEd Schouten   delete BB;
273f22ef01cSRoman Divacky }
274f22ef01cSRoman Divacky 
275f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
276f22ef01cSRoman Divacky   assert(BreakContinueStack.empty() &&
277f22ef01cSRoman Divacky          "mismatched push/pop in break/continue stack!");
278f22ef01cSRoman Divacky 
279284c1978SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
280f785676fSDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
281f785676fSDimitry Andric     && ReturnBlock.getBlock()->use_empty();
282f785676fSDimitry Andric   // Usually the return expression is evaluated before the cleanup
283f785676fSDimitry Andric   // code.  If the function contains only a simple return statement,
284f785676fSDimitry Andric   // such as a constant, the location before the cleanup code becomes
285f785676fSDimitry Andric   // the last useful breakpoint in the function, because the simple
286f785676fSDimitry Andric   // return expression will be evaluated after the cleanup code. To be
287f785676fSDimitry Andric   // safe, set the debug location for cleanup code to the location of
288f785676fSDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
289f785676fSDimitry Andric   // end of the function's lexical scope.
290f785676fSDimitry Andric   //
291f785676fSDimitry Andric   // If there are multiple branches to the return block, the branch
292f785676fSDimitry Andric   // instructions will get the location of the return statements and
293f785676fSDimitry Andric   // all will be fine.
294284c1978SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
295284c1978SDimitry Andric     if (OnlySimpleReturnStmts)
296284c1978SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
297284c1978SDimitry Andric     else
298139f7f9bSDimitry Andric       DI->EmitLocation(Builder, EndLoc);
299284c1978SDimitry Andric   }
300139f7f9bSDimitry Andric 
30117a519f9SDimitry Andric   // Pop any cleanups that might have been associated with the
30217a519f9SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
30317a519f9SDimitry Andric   // important to do this before we enter the return block or return
30417a519f9SDimitry Andric   // edges will be *really* confused.
30533956c43SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
30633956c43SDimitry Andric   bool HasOnlyLifetimeMarkers =
30733956c43SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
30833956c43SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
30933956c43SDimitry Andric   if (HasCleanups) {
310284c1978SDimitry Andric     // Make sure the line table doesn't jump back into the body for
311284c1978SDimitry Andric     // the ret after it's been at EndLoc.
312284c1978SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
313284c1978SDimitry Andric       if (OnlySimpleReturnStmts)
314284c1978SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
31533956c43SDimitry Andric 
31633956c43SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
317284c1978SDimitry Andric   }
31817a519f9SDimitry Andric 
319f22ef01cSRoman Divacky   // Emit function epilog (to return).
32039d628a0SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
321f22ef01cSRoman Divacky 
3222754fe60SDimitry Andric   if (ShouldInstrumentFunction())
323ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_exit");
324ffd1746dSEd Schouten 
325f22ef01cSRoman Divacky   // Emit debug descriptor for function end.
32639d628a0SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
327e580952dSDimitry Andric     DI->EmitFunctionEnd(Builder);
328f22ef01cSRoman Divacky 
32939d628a0SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
33039d628a0SDimitry Andric   // rather than that of the end of the function's scope '}'.
33139d628a0SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
332f785676fSDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
333f22ef01cSRoman Divacky   EmitEndEHSpec(CurCodeDecl);
334f22ef01cSRoman Divacky 
335ffd1746dSEd Schouten   assert(EHStack.empty() &&
336ffd1746dSEd Schouten          "did not remove all scopes from cleanup stack!");
337ffd1746dSEd Schouten 
338f22ef01cSRoman Divacky   // If someone did an indirect goto, emit the indirect goto block at the end of
339f22ef01cSRoman Divacky   // the function.
340f22ef01cSRoman Divacky   if (IndirectBranch) {
341f22ef01cSRoman Divacky     EmitBlock(IndirectBranch->getParent());
342f22ef01cSRoman Divacky     Builder.ClearInsertionPoint();
343f22ef01cSRoman Divacky   }
344f22ef01cSRoman Divacky 
345875ed548SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
34633956c43SDimitry Andric   // entry block.
34733956c43SDimitry Andric   if (!EscapedLocals.empty()) {
34833956c43SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
34933956c43SDimitry Andric     // no holes.
35033956c43SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
35133956c43SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
35233956c43SDimitry Andric     for (auto &Pair : EscapedLocals)
35333956c43SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
35433956c43SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
355875ed548SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
3560623d748SDimitry Andric     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
35733956c43SDimitry Andric   }
35833956c43SDimitry Andric 
359f22ef01cSRoman Divacky   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
360f22ef01cSRoman Divacky   llvm::Instruction *Ptr = AllocaInsertPt;
36159d1ed5bSDimitry Andric   AllocaInsertPt = nullptr;
362f22ef01cSRoman Divacky   Ptr->eraseFromParent();
363f22ef01cSRoman Divacky 
364f22ef01cSRoman Divacky   // If someone took the address of a label but never did an indirect goto, we
365f22ef01cSRoman Divacky   // made a zero entry PHI node, which is illegal, zap it now.
366f22ef01cSRoman Divacky   if (IndirectBranch) {
367f22ef01cSRoman Divacky     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
368f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
369f22ef01cSRoman Divacky       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
370f22ef01cSRoman Divacky       PN->eraseFromParent();
371f22ef01cSRoman Divacky     }
372f22ef01cSRoman Divacky   }
373ffd1746dSEd Schouten 
3746122f3e6SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
375ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateLandingPad);
376ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateHandler);
377ffd1746dSEd Schouten   EmitIfUsed(*this, UnreachableBlock);
378ffd1746dSEd Schouten 
379ffd1746dSEd Schouten   if (CGM.getCodeGenOpts().EmitDeclMetadata)
380ffd1746dSEd Schouten     EmitDeclMetadata();
38159d1ed5bSDimitry Andric 
38259d1ed5bSDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
38359d1ed5bSDimitry Andric            I = DeferredReplacements.begin(),
38459d1ed5bSDimitry Andric            E = DeferredReplacements.end();
38559d1ed5bSDimitry Andric        I != E; ++I) {
38659d1ed5bSDimitry Andric     I->first->replaceAllUsesWith(I->second);
38759d1ed5bSDimitry Andric     I->first->eraseFromParent();
38859d1ed5bSDimitry Andric   }
389ffd1746dSEd Schouten }
390ffd1746dSEd Schouten 
391ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be
392ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls
393ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() {
394ffd1746dSEd Schouten   if (!CGM.getCodeGenOpts().InstrumentFunctions)
395ffd1746dSEd Schouten     return false;
396bd5abe19SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
397ffd1746dSEd Schouten     return false;
398ffd1746dSEd Schouten   return true;
399ffd1746dSEd Schouten }
400ffd1746dSEd Schouten 
401e7145dcbSDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be
402e7145dcbSDimitry Andric /// instrumented with XRay nop sleds.
403e7145dcbSDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
404e7145dcbSDimitry Andric   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
405e7145dcbSDimitry Andric }
406e7145dcbSDimitry Andric 
407ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
408ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if
409ffd1746dSEd Schouten /// function instrumentation is enabled.
410ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
411e7145dcbSDimitry Andric   auto NL = ApplyDebugLocation::CreateArtificial(*this);
412ffd1746dSEd Schouten   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
41317a519f9SDimitry Andric   llvm::PointerType *PointerTy = Int8PtrTy;
41417a519f9SDimitry Andric   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
4156122f3e6SDimitry Andric   llvm::FunctionType *FunctionTy =
416dff0c46cSDimitry Andric     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
417ffd1746dSEd Schouten 
418ffd1746dSEd Schouten   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
419ffd1746dSEd Schouten   llvm::CallInst *CallSite = Builder.CreateCall(
42017a519f9SDimitry Andric     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
421ffd1746dSEd Schouten     llvm::ConstantInt::get(Int32Ty, 0),
422ffd1746dSEd Schouten     "callsite");
423ffd1746dSEd Schouten 
424139f7f9bSDimitry Andric   llvm::Value *args[] = {
425ffd1746dSEd Schouten     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
426139f7f9bSDimitry Andric     CallSite
427139f7f9bSDimitry Andric   };
428139f7f9bSDimitry Andric 
429139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(F, args);
430f22ef01cSRoman Divacky }
431f22ef01cSRoman Divacky 
4322754fe60SDimitry Andric void CodeGenFunction::EmitMCountInstrumentation() {
433dff0c46cSDimitry Andric   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
4342754fe60SDimitry Andric 
435284c1978SDimitry Andric   llvm::Constant *MCountFn =
436284c1978SDimitry Andric     CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
437139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(MCountFn);
4382754fe60SDimitry Andric }
4392754fe60SDimitry Andric 
440f41fbc90SDimitry Andric // Returns the address space id that should be produced to the
441f41fbc90SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
442f41fbc90SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
443f41fbc90SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
444f41fbc90SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
445f41fbc90SDimitry Andric // (basically all single AS CPUs).
446f41fbc90SDimitry Andric static unsigned ArgInfoAddressSpace(unsigned LangAS) {
447f41fbc90SDimitry Andric   switch (LangAS) {
448f41fbc90SDimitry Andric   case LangAS::opencl_global:   return 1;
449f41fbc90SDimitry Andric   case LangAS::opencl_constant: return 2;
450f41fbc90SDimitry Andric   case LangAS::opencl_local:    return 3;
451f41fbc90SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
452f41fbc90SDimitry Andric   default:
453f41fbc90SDimitry Andric     return 0; // Assume private.
454f41fbc90SDimitry Andric   }
455f41fbc90SDimitry Andric }
456f41fbc90SDimitry Andric 
4577ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
4587ae0e2c9SDimitry Andric // information in the program executable. The argument information stored
4597ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used.
4607ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
4617ae0e2c9SDimitry Andric                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
462139f7f9bSDimitry Andric                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
463139f7f9bSDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
4647ae0e2c9SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
4657ae0e2c9SDimitry Andric   // the same number of values as their are kernel arguments.
4667ae0e2c9SDimitry Andric 
46759d1ed5bSDimitry Andric   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
46859d1ed5bSDimitry Andric 
469139f7f9bSDimitry Andric   // MDNode for the kernel argument address space qualifiers.
47039d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
471139f7f9bSDimitry Andric 
472139f7f9bSDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
47339d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
474139f7f9bSDimitry Andric 
475139f7f9bSDimitry Andric   // MDNode for the kernel argument type names.
47639d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
477139f7f9bSDimitry Andric 
47839d628a0SDimitry Andric   // MDNode for the kernel argument base type names.
47939d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
48039d628a0SDimitry Andric 
481139f7f9bSDimitry Andric   // MDNode for the kernel argument type qualifiers.
48239d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
483139f7f9bSDimitry Andric 
4847ae0e2c9SDimitry Andric   // MDNode for the kernel argument names.
48539d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
4867ae0e2c9SDimitry Andric 
4877ae0e2c9SDimitry Andric   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
4887ae0e2c9SDimitry Andric     const ParmVarDecl *parm = FD->getParamDecl(i);
489139f7f9bSDimitry Andric     QualType ty = parm->getType();
490139f7f9bSDimitry Andric     std::string typeQuals;
491139f7f9bSDimitry Andric 
492139f7f9bSDimitry Andric     if (ty->isPointerType()) {
493139f7f9bSDimitry Andric       QualType pointeeTy = ty->getPointeeType();
494139f7f9bSDimitry Andric 
495139f7f9bSDimitry Andric       // Get address qualifier.
49639d628a0SDimitry Andric       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
497f41fbc90SDimitry Andric         ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
498139f7f9bSDimitry Andric 
499139f7f9bSDimitry Andric       // Get argument type name.
50059d1ed5bSDimitry Andric       std::string typeName =
50159d1ed5bSDimitry Andric           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
502139f7f9bSDimitry Andric 
503139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
504139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
50539d628a0SDimitry Andric       if (pointeeTy.isCanonical() && pos != std::string::npos)
506139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
507139f7f9bSDimitry Andric 
508139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
509139f7f9bSDimitry Andric 
51039d628a0SDimitry Andric       std::string baseTypeName =
51139d628a0SDimitry Andric           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
51239d628a0SDimitry Andric               Policy) +
51339d628a0SDimitry Andric           "*";
51439d628a0SDimitry Andric 
51539d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
51639d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
51739d628a0SDimitry Andric       if (pos != std::string::npos)
51839d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
51939d628a0SDimitry Andric 
52039d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
52139d628a0SDimitry Andric 
522139f7f9bSDimitry Andric       // Get argument type qualifiers:
523139f7f9bSDimitry Andric       if (ty.isRestrictQualified())
524139f7f9bSDimitry Andric         typeQuals = "restrict";
525139f7f9bSDimitry Andric       if (pointeeTy.isConstQualified() ||
526139f7f9bSDimitry Andric           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
527139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "const" : " const";
528139f7f9bSDimitry Andric       if (pointeeTy.isVolatileQualified())
529139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
530139f7f9bSDimitry Andric     } else {
53159d1ed5bSDimitry Andric       uint32_t AddrSpc = 0;
532444ed5c5SDimitry Andric       bool isPipe = ty->isPipeType();
533444ed5c5SDimitry Andric       if (ty->isImageType() || isPipe)
534f41fbc90SDimitry Andric         AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
53559d1ed5bSDimitry Andric 
53639d628a0SDimitry Andric       addressQuals.push_back(
53739d628a0SDimitry Andric           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
538139f7f9bSDimitry Andric 
539139f7f9bSDimitry Andric       // Get argument type name.
540444ed5c5SDimitry Andric       std::string typeName;
541444ed5c5SDimitry Andric       if (isPipe)
542e7145dcbSDimitry Andric         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
543e7145dcbSDimitry Andric                      .getAsString(Policy);
544444ed5c5SDimitry Andric       else
545444ed5c5SDimitry Andric         typeName = ty.getUnqualifiedType().getAsString(Policy);
546139f7f9bSDimitry Andric 
547139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
548139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
54939d628a0SDimitry Andric       if (ty.isCanonical() && pos != std::string::npos)
550139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
551139f7f9bSDimitry Andric 
552139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
553139f7f9bSDimitry Andric 
554444ed5c5SDimitry Andric       std::string baseTypeName;
555444ed5c5SDimitry Andric       if (isPipe)
556e7145dcbSDimitry Andric         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
557e7145dcbSDimitry Andric                           ->getElementType().getCanonicalType()
558e7145dcbSDimitry Andric                           .getAsString(Policy);
559444ed5c5SDimitry Andric       else
560444ed5c5SDimitry Andric         baseTypeName =
56139d628a0SDimitry Andric           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
56239d628a0SDimitry Andric 
56339d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
56439d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
56539d628a0SDimitry Andric       if (pos != std::string::npos)
56639d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
56739d628a0SDimitry Andric 
56839d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
56939d628a0SDimitry Andric 
570139f7f9bSDimitry Andric       // Get argument type qualifiers:
571139f7f9bSDimitry Andric       if (ty.isConstQualified())
572139f7f9bSDimitry Andric         typeQuals = "const";
573139f7f9bSDimitry Andric       if (ty.isVolatileQualified())
574139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
575444ed5c5SDimitry Andric       if (isPipe)
576444ed5c5SDimitry Andric         typeQuals = "pipe";
577139f7f9bSDimitry Andric     }
578139f7f9bSDimitry Andric 
579139f7f9bSDimitry Andric     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
580139f7f9bSDimitry Andric 
581444ed5c5SDimitry Andric     // Get image and pipe access qualifier:
582444ed5c5SDimitry Andric     if (ty->isImageType()|| ty->isPipeType()) {
583e7145dcbSDimitry Andric       const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
58459d1ed5bSDimitry Andric       if (A && A->isWriteOnly())
585139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
586e7145dcbSDimitry Andric       else if (A && A->isReadWrite())
587e7145dcbSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
588139f7f9bSDimitry Andric       else
589139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
590139f7f9bSDimitry Andric     } else
591139f7f9bSDimitry Andric       accessQuals.push_back(llvm::MDString::get(Context, "none"));
5927ae0e2c9SDimitry Andric 
5937ae0e2c9SDimitry Andric     // Get argument name.
5947ae0e2c9SDimitry Andric     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
5957ae0e2c9SDimitry Andric   }
596139f7f9bSDimitry Andric 
597e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
598e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, addressQuals));
599e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
600e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, accessQuals));
601e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type",
602e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeNames));
603e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
604e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argBaseTypeNames));
605e7145dcbSDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
606e7145dcbSDimitry Andric                   llvm::MDNode::get(Context, argTypeQuals));
60739d628a0SDimitry Andric   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
608e7145dcbSDimitry Andric     Fn->setMetadata("kernel_arg_name",
609e7145dcbSDimitry Andric                     llvm::MDNode::get(Context, argNames));
6107ae0e2c9SDimitry Andric }
6117ae0e2c9SDimitry Andric 
6127ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
6137ae0e2c9SDimitry Andric                                                llvm::Function *Fn)
6147ae0e2c9SDimitry Andric {
6157ae0e2c9SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
6167ae0e2c9SDimitry Andric     return;
6177ae0e2c9SDimitry Andric 
6187ae0e2c9SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
6197ae0e2c9SDimitry Andric 
620e7145dcbSDimitry Andric   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
621139f7f9bSDimitry Andric 
62259d1ed5bSDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
62359d1ed5bSDimitry Andric     QualType hintQTy = A->getTypeHint();
624139f7f9bSDimitry Andric     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
625139f7f9bSDimitry Andric     bool isSignedInteger =
626139f7f9bSDimitry Andric         hintQTy->isSignedIntegerType() ||
627139f7f9bSDimitry Andric         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
62839d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
62939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
63039d628a0SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
63139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
632139f7f9bSDimitry Andric             llvm::IntegerType::get(Context, 32),
63339d628a0SDimitry Andric             llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
634e7145dcbSDimitry Andric     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
635139f7f9bSDimitry Andric   }
6367ae0e2c9SDimitry Andric 
63759d1ed5bSDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
63839d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
63939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
64039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
64139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
642e7145dcbSDimitry Andric     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
6437ae0e2c9SDimitry Andric   }
6447ae0e2c9SDimitry Andric 
64559d1ed5bSDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
64639d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
64739d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
64839d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
64939d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
650e7145dcbSDimitry Andric     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
6517ae0e2c9SDimitry Andric   }
6527ae0e2c9SDimitry Andric }
6537ae0e2c9SDimitry Andric 
65459d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt.
65559d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) {
65659d1ed5bSDimitry Andric   const Stmt *Body = nullptr;
65759d1ed5bSDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
65859d1ed5bSDimitry Andric     Body = FD->getBody();
65959d1ed5bSDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
66059d1ed5bSDimitry Andric     Body = OMD->getBody();
66159d1ed5bSDimitry Andric 
66259d1ed5bSDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
66359d1ed5bSDimitry Andric     auto LastStmt = CS->body_rbegin();
66459d1ed5bSDimitry Andric     if (LastStmt != CS->body_rend())
66559d1ed5bSDimitry Andric       return isa<ReturnStmt>(*LastStmt);
66659d1ed5bSDimitry Andric   }
66759d1ed5bSDimitry Andric   return false;
66859d1ed5bSDimitry Andric }
66959d1ed5bSDimitry Andric 
670284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD,
671284c1978SDimitry Andric                                     QualType RetTy,
672f22ef01cSRoman Divacky                                     llvm::Function *Fn,
6733b0f4066SDimitry Andric                                     const CGFunctionInfo &FnInfo,
674f22ef01cSRoman Divacky                                     const FunctionArgList &Args,
67559d1ed5bSDimitry Andric                                     SourceLocation Loc,
676f22ef01cSRoman Divacky                                     SourceLocation StartLoc) {
67739d628a0SDimitry Andric   assert(!CurFn &&
67839d628a0SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
67939d628a0SDimitry Andric 
680f22ef01cSRoman Divacky   const Decl *D = GD.getDecl();
681f22ef01cSRoman Divacky 
682f22ef01cSRoman Divacky   DidCallStackSave = false;
683284c1978SDimitry Andric   CurCodeDecl = D;
684e7145dcbSDimitry Andric   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
685e7145dcbSDimitry Andric     if (FD->usesSEHTry())
686e7145dcbSDimitry Andric       CurSEHParent = FD;
68759d1ed5bSDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
688f22ef01cSRoman Divacky   FnRetTy = RetTy;
689f22ef01cSRoman Divacky   CurFn = Fn;
6903b0f4066SDimitry Andric   CurFnInfo = &FnInfo;
691f22ef01cSRoman Divacky   assert(CurFn->isDeclaration() && "Function already has body?");
692f22ef01cSRoman Divacky 
69339d628a0SDimitry Andric   if (CGM.isInSanitizerBlacklist(Fn, Loc))
69439d628a0SDimitry Andric     SanOpts.clear();
695139f7f9bSDimitry Andric 
69633956c43SDimitry Andric   if (D) {
69733956c43SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
69833956c43SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
69933956c43SDimitry Andric       SanOpts.Mask &= ~Attr->getMask();
70033956c43SDimitry Andric   }
70133956c43SDimitry Andric 
70233956c43SDimitry Andric   // Apply sanitizer attributes to the function.
7038f0fd8f6SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
70433956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
70533956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
70633956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
70733956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Memory))
70833956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
7098f0fd8f6SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
7108f0fd8f6SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
71133956c43SDimitry Andric 
712e7145dcbSDimitry Andric   // Apply xray attributes to the function (as a string, for now)
713e7145dcbSDimitry Andric   if (D && ShouldXRayInstrumentFunction()) {
714e7145dcbSDimitry Andric     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
715e7145dcbSDimitry Andric       if (XRayAttr->alwaysXRayInstrument())
716e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-always");
717e7145dcbSDimitry Andric       if (XRayAttr->neverXRayInstrument())
718e7145dcbSDimitry Andric         Fn->addFnAttr("function-instrument", "xray-never");
719e7145dcbSDimitry Andric     } else {
720e7145dcbSDimitry Andric       Fn->addFnAttr(
721e7145dcbSDimitry Andric           "xray-instruction-threshold",
722e7145dcbSDimitry Andric           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
723e7145dcbSDimitry Andric     }
724e7145dcbSDimitry Andric   }
725e7145dcbSDimitry Andric 
726f22ef01cSRoman Divacky   // Pass inline keyword to optimizer if it appears explicitly on any
72759d1ed5bSDimitry Andric   // declaration. Also, in the case of -fno-inline attach NoInline
728e7145dcbSDimitry Andric   // attribute to all functions that are not marked AlwaysInline, or
729e7145dcbSDimitry Andric   // to all functions that are not marked inline or implicitly inline
730e7145dcbSDimitry Andric   // in the case of -finline-hint-functions.
73159d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
732e7145dcbSDimitry Andric     const CodeGenOptions& CodeGenOpts = CGM.getCodeGenOpts();
733e7145dcbSDimitry Andric     if (!CodeGenOpts.NoInline) {
73459d1ed5bSDimitry Andric       for (auto RI : FD->redecls())
735f22ef01cSRoman Divacky         if (RI->isInlineSpecified()) {
736139f7f9bSDimitry Andric           Fn->addFnAttr(llvm::Attribute::InlineHint);
737f22ef01cSRoman Divacky           break;
738f22ef01cSRoman Divacky         }
739e7145dcbSDimitry Andric       if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyHintInlining &&
740e7145dcbSDimitry Andric           !FD->isInlined() && !Fn->hasFnAttribute(llvm::Attribute::InlineHint))
741e7145dcbSDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoInline);
74259d1ed5bSDimitry Andric     } else if (!FD->hasAttr<AlwaysInlineAttr>())
74359d1ed5bSDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoInline);
744e7145dcbSDimitry Andric     if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
745e7145dcbSDimitry Andric       CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
74659d1ed5bSDimitry Andric   }
747f22ef01cSRoman Divacky 
748e7145dcbSDimitry Andric   // Add no-jump-tables value.
749e7145dcbSDimitry Andric   Fn->addFnAttr("no-jump-tables",
750e7145dcbSDimitry Andric                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
751e7145dcbSDimitry Andric 
7523861d79fSDimitry Andric   if (getLangOpts().OpenCL) {
7532754fe60SDimitry Andric     // Add metadata for a kernel function.
7542754fe60SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
7557ae0e2c9SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
7562754fe60SDimitry Andric   }
7572754fe60SDimitry Andric 
758f785676fSDimitry Andric   // If we are checking function types, emit a function type signature as
75939d628a0SDimitry Andric   // prologue data.
76039d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
761f785676fSDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
76239d628a0SDimitry Andric       if (llvm::Constant *PrologueSig =
763f785676fSDimitry Andric               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
764f785676fSDimitry Andric         llvm::Constant *FTRTTIConst =
765f785676fSDimitry Andric             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
76639d628a0SDimitry Andric         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
76739d628a0SDimitry Andric         llvm::Constant *PrologueStructConst =
76839d628a0SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
76939d628a0SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
770f785676fSDimitry Andric       }
771f785676fSDimitry Andric     }
772f785676fSDimitry Andric   }
773f785676fSDimitry Andric 
7740623d748SDimitry Andric   // If we're in C++ mode and the function name is "main", it is guaranteed
7750623d748SDimitry Andric   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
7760623d748SDimitry Andric   // used within a program").
7770623d748SDimitry Andric   if (getLangOpts().CPlusPlus)
7780623d748SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
7790623d748SDimitry Andric       if (FD->isMain())
7800623d748SDimitry Andric         Fn->addFnAttr(llvm::Attribute::NoRecurse);
7810623d748SDimitry Andric 
782f22ef01cSRoman Divacky   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
783f22ef01cSRoman Divacky 
784f22ef01cSRoman Divacky   // Create a marker to make it easy to insert allocas into the entryblock
785f22ef01cSRoman Divacky   // later.  Don't create this with the builder, because we don't want it
786f22ef01cSRoman Divacky   // folded.
787ffd1746dSEd Schouten   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
788e7145dcbSDimitry Andric   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
789f22ef01cSRoman Divacky 
790ffd1746dSEd Schouten   ReturnBlock = getJumpDestInCurrentScope("return");
791f22ef01cSRoman Divacky 
792f22ef01cSRoman Divacky   Builder.SetInsertPoint(EntryBB);
793f22ef01cSRoman Divacky 
794f22ef01cSRoman Divacky   // Emit subprogram debug descriptor.
795f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
796e7145dcbSDimitry Andric     // Reconstruct the type from the argument list so that implicit parameters,
797e7145dcbSDimitry Andric     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
798e7145dcbSDimitry Andric     // convention.
799e7145dcbSDimitry Andric     CallingConv CC = CallingConv::CC_C;
800e7145dcbSDimitry Andric     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
801e7145dcbSDimitry Andric       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
802e7145dcbSDimitry Andric         CC = SrcFnTy->getCallConv();
803139f7f9bSDimitry Andric     SmallVector<QualType, 16> ArgTypes;
804e7145dcbSDimitry Andric     for (const VarDecl *VD : Args)
805e7145dcbSDimitry Andric       ArgTypes.push_back(VD->getType());
806e7145dcbSDimitry Andric     QualType FnType = getContext().getFunctionType(
807e7145dcbSDimitry Andric         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
80859d1ed5bSDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
809f22ef01cSRoman Divacky   }
810f22ef01cSRoman Divacky 
8112754fe60SDimitry Andric   if (ShouldInstrumentFunction())
812ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_enter");
813ffd1746dSEd Schouten 
8142754fe60SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling)
8152754fe60SDimitry Andric     EmitMCountInstrumentation();
8162754fe60SDimitry Andric 
817f22ef01cSRoman Divacky   if (RetTy->isVoidType()) {
818f22ef01cSRoman Divacky     // Void type; nothing to return.
8190623d748SDimitry Andric     ReturnValue = Address::invalid();
82059d1ed5bSDimitry Andric 
82159d1ed5bSDimitry Andric     // Count the implicit return.
82259d1ed5bSDimitry Andric     if (!endsWithReturn(D))
82359d1ed5bSDimitry Andric       ++NumReturnExprs;
824f22ef01cSRoman Divacky   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
825139f7f9bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
826f22ef01cSRoman Divacky     // Indirect aggregate return; emit returned value directly into sret slot.
827f22ef01cSRoman Divacky     // This reduces code size, and affects correctness in C++.
82859d1ed5bSDimitry Andric     auto AI = CurFn->arg_begin();
82959d1ed5bSDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
83059d1ed5bSDimitry Andric       ++AI;
8310623d748SDimitry Andric     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
83259d1ed5bSDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
83359d1ed5bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
83459d1ed5bSDimitry Andric     // Load the sret pointer from the argument struct and return into that.
83559d1ed5bSDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
83659d1ed5bSDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
83759d1ed5bSDimitry Andric     --EI;
8380623d748SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
8390623d748SDimitry Andric     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
8400623d748SDimitry Andric     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
841f22ef01cSRoman Divacky   } else {
842f22ef01cSRoman Divacky     ReturnValue = CreateIRTemp(RetTy, "retval");
84317a519f9SDimitry Andric 
84417a519f9SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
84517a519f9SDimitry Andric     // now so that various specialized functions can suppress it
84617a519f9SDimitry Andric     // during their IR-generation.
847dff0c46cSDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
84817a519f9SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
84917a519f9SDimitry Andric         RetTy->isObjCRetainableType())
85017a519f9SDimitry Andric       AutoreleaseResult = true;
851f22ef01cSRoman Divacky   }
852f22ef01cSRoman Divacky 
853f22ef01cSRoman Divacky   EmitStartEHSpec(CurCodeDecl);
85417a519f9SDimitry Andric 
85517a519f9SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
856f22ef01cSRoman Divacky   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
857f22ef01cSRoman Divacky 
858dff0c46cSDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
859e580952dSDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
860dff0c46cSDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
861dff0c46cSDimitry Andric     if (MD->getParent()->isLambda() &&
862dff0c46cSDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
863dff0c46cSDimitry Andric       // We're in a lambda; figure out the captures.
864dff0c46cSDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
865dff0c46cSDimitry Andric                                         LambdaThisCaptureField);
866dff0c46cSDimitry Andric       if (LambdaThisCaptureField) {
867e7145dcbSDimitry Andric         // If the lambda captures the object referred to by '*this' - either by
868e7145dcbSDimitry Andric         // value or by reference, make sure CXXThisValue points to the correct
869e7145dcbSDimitry Andric         // object.
870e7145dcbSDimitry Andric 
871e7145dcbSDimitry Andric         // Get the lvalue for the field (which is a copy of the enclosing object
872e7145dcbSDimitry Andric         // or contains the address of the enclosing object).
873e7145dcbSDimitry Andric         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
874e7145dcbSDimitry Andric         if (!LambdaThisCaptureField->getType()->isPointerType()) {
875e7145dcbSDimitry Andric           // If the enclosing object was captured by value, just use its address.
876e7145dcbSDimitry Andric           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
877e7145dcbSDimitry Andric         } else {
878e7145dcbSDimitry Andric           // Load the lvalue pointed to by the field, since '*this' was captured
879e7145dcbSDimitry Andric           // by reference.
880e7145dcbSDimitry Andric           CXXThisValue =
881e7145dcbSDimitry Andric               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
882e7145dcbSDimitry Andric         }
883dff0c46cSDimitry Andric       }
88439d628a0SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
88539d628a0SDimitry Andric         if (FD->hasCapturedVLAType()) {
88639d628a0SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
88739d628a0SDimitry Andric                                            SourceLocation()).getScalarVal();
88839d628a0SDimitry Andric           auto VAT = FD->getCapturedVLAType();
88939d628a0SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
89039d628a0SDimitry Andric         }
89139d628a0SDimitry Andric       }
892dff0c46cSDimitry Andric     } else {
893dff0c46cSDimitry Andric       // Not in a lambda; just use 'this' from the method.
894dff0c46cSDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
895dff0c46cSDimitry Andric       // fast register allocator would be happier...
896dff0c46cSDimitry Andric       CXXThisValue = CXXABIThisValue;
897dff0c46cSDimitry Andric     }
898dff0c46cSDimitry Andric   }
899f22ef01cSRoman Divacky 
900f22ef01cSRoman Divacky   // If any of the arguments have a variably modified type, make sure to
901f22ef01cSRoman Divacky   // emit the type size.
902f22ef01cSRoman Divacky   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
903f22ef01cSRoman Divacky        i != e; ++i) {
904139f7f9bSDimitry Andric     const VarDecl *VD = *i;
905139f7f9bSDimitry Andric 
906139f7f9bSDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
907139f7f9bSDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
908139f7f9bSDimitry Andric     // precedent set by gcc.
909139f7f9bSDimitry Andric     QualType Ty;
910139f7f9bSDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
911139f7f9bSDimitry Andric       Ty = PVD->getOriginalType();
912139f7f9bSDimitry Andric     else
913139f7f9bSDimitry Andric       Ty = VD->getType();
914f22ef01cSRoman Divacky 
915f22ef01cSRoman Divacky     if (Ty->isVariablyModifiedType())
91617a519f9SDimitry Andric       EmitVariablyModifiedType(Ty);
917f22ef01cSRoman Divacky   }
9186122f3e6SDimitry Andric   // Emit a location at the end of the prologue.
9196122f3e6SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
9206122f3e6SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
921f22ef01cSRoman Divacky }
922f22ef01cSRoman Divacky 
923f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
924f785676fSDimitry Andric                                        const Stmt *Body) {
92533956c43SDimitry Andric   incrementProfileCounter(Body);
926f785676fSDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
927139f7f9bSDimitry Andric     EmitCompoundStmtWithoutScope(*S);
928139f7f9bSDimitry Andric   else
929f785676fSDimitry Andric     EmitStmt(Body);
930f22ef01cSRoman Divacky }
931f22ef01cSRoman Divacky 
93259d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
93359d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so
93459d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
93559d1ed5bSDimitry Andric /// this just calls EmitBlock().
93659d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
93733956c43SDimitry Andric                                                const Stmt *S) {
93859d1ed5bSDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
939e7145dcbSDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
94059d1ed5bSDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
94159d1ed5bSDimitry Andric     // statements needs to skip over the instrumentation code so that we
94259d1ed5bSDimitry Andric     // get an accurate count.
94359d1ed5bSDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
94459d1ed5bSDimitry Andric     EmitBranch(SkipCountBB);
94559d1ed5bSDimitry Andric   }
94659d1ed5bSDimitry Andric   EmitBlock(BB);
94733956c43SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
94833956c43SDimitry Andric   incrementProfileCounter(S);
94933956c43SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
95059d1ed5bSDimitry Andric   if (SkipCountBB)
95159d1ed5bSDimitry Andric     EmitBlock(SkipCountBB);
95259d1ed5bSDimitry Andric }
95359d1ed5bSDimitry Andric 
954e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the
955e580952dSDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
956e580952dSDimitry Andric /// lightweight enough to do at -O0.
957e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
958e580952dSDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
959e580952dSDimitry Andric   // can't do this on functions that can be overwritten.
960e7145dcbSDimitry Andric   if (F->isInterposable()) return;
961e580952dSDimitry Andric 
9620623d748SDimitry Andric   for (llvm::BasicBlock &BB : *F)
9630623d748SDimitry Andric     for (llvm::Instruction &I : BB)
9640623d748SDimitry Andric       if (I.mayThrow())
965e580952dSDimitry Andric         return;
9660623d748SDimitry Andric 
9673861d79fSDimitry Andric   F->setDoesNotThrow();
968e580952dSDimitry Andric }
969e580952dSDimitry Andric 
970e7145dcbSDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
971e7145dcbSDimitry Andric                                                FunctionArgList &Args) {
972f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
97359d1ed5bSDimitry Andric   QualType ResTy = FD->getReturnType();
974f22ef01cSRoman Divacky 
97559d1ed5bSDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
97659d1ed5bSDimitry Andric   if (MD && MD->isInstance()) {
977f785676fSDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
978f785676fSDimitry Andric       ResTy = MD->getThisType(getContext());
97939d628a0SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
98039d628a0SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
98159d1ed5bSDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
982f785676fSDimitry Andric   }
983f22ef01cSRoman Divacky 
984e7145dcbSDimitry Andric   // The base version of an inheriting constructor whose constructed base is a
985e7145dcbSDimitry Andric   // virtual base is not passed any arguments (because it doesn't actually call
986e7145dcbSDimitry Andric   // the inherited constructor).
987e7145dcbSDimitry Andric   bool PassedParams = true;
988e7145dcbSDimitry Andric   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
989e7145dcbSDimitry Andric     if (auto Inherited = CD->getInheritedConstructor())
990e7145dcbSDimitry Andric       PassedParams =
991e7145dcbSDimitry Andric           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
992e7145dcbSDimitry Andric 
993e7145dcbSDimitry Andric   if (PassedParams) {
994e7145dcbSDimitry Andric     for (auto *Param : FD->parameters()) {
9950623d748SDimitry Andric       Args.push_back(Param);
9960623d748SDimitry Andric       if (!Param->hasAttr<PassObjectSizeAttr>())
9970623d748SDimitry Andric         continue;
9980623d748SDimitry Andric 
9990623d748SDimitry Andric       IdentifierInfo *NoID = nullptr;
10000623d748SDimitry Andric       auto *Implicit = ImplicitParamDecl::Create(
10010623d748SDimitry Andric           getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
10020623d748SDimitry Andric           getContext().getSizeType());
10030623d748SDimitry Andric       SizeArguments[Param] = Implicit;
10040623d748SDimitry Andric       Args.push_back(Implicit);
10050623d748SDimitry Andric     }
1006e7145dcbSDimitry Andric   }
1007f22ef01cSRoman Divacky 
100859d1ed5bSDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
100959d1ed5bSDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
101059d1ed5bSDimitry Andric 
1011e7145dcbSDimitry Andric   return ResTy;
1012e7145dcbSDimitry Andric }
1013e7145dcbSDimitry Andric 
1014e7145dcbSDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1015e7145dcbSDimitry Andric                                    const CGFunctionInfo &FnInfo) {
1016e7145dcbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1017e7145dcbSDimitry Andric   CurGD = GD;
1018e7145dcbSDimitry Andric 
1019e7145dcbSDimitry Andric   FunctionArgList Args;
1020e7145dcbSDimitry Andric   QualType ResTy = BuildFunctionArgList(GD, Args);
1021e7145dcbSDimitry Andric 
1022e7145dcbSDimitry Andric   // Check if we should generate debug info for this function.
1023e7145dcbSDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
1024e7145dcbSDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
1025e7145dcbSDimitry Andric 
1026f22ef01cSRoman Divacky   SourceRange BodyRange;
1027f22ef01cSRoman Divacky   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1028f785676fSDimitry Andric   CurEHLocation = BodyRange.getEnd();
1029139f7f9bSDimitry Andric 
103059d1ed5bSDimitry Andric   // Use the location of the start of the function to determine where
103159d1ed5bSDimitry Andric   // the function definition is located. By default use the location
103259d1ed5bSDimitry Andric   // of the declaration as the location for the subprogram. A function
103359d1ed5bSDimitry Andric   // may lack a declaration in the source code if it is created by code
103459d1ed5bSDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
103559d1ed5bSDimitry Andric   SourceLocation Loc = FD->getLocation();
103659d1ed5bSDimitry Andric 
103759d1ed5bSDimitry Andric   // If this is a function specialization then use the pattern body
103859d1ed5bSDimitry Andric   // as the location for the function.
103959d1ed5bSDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
104059d1ed5bSDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
104159d1ed5bSDimitry Andric       Loc = SpecDecl->getLocation();
104259d1ed5bSDimitry Andric 
1043f22ef01cSRoman Divacky   // Emit the standard function prologue.
104459d1ed5bSDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1045f22ef01cSRoman Divacky 
1046f22ef01cSRoman Divacky   // Generate the body of the function.
10470623d748SDimitry Andric   PGO.assignRegionCounters(GD, CurFn);
1048f22ef01cSRoman Divacky   if (isa<CXXDestructorDecl>(FD))
1049f22ef01cSRoman Divacky     EmitDestructorBody(Args);
1050f22ef01cSRoman Divacky   else if (isa<CXXConstructorDecl>(FD))
1051f22ef01cSRoman Divacky     EmitConstructorBody(Args);
10523861d79fSDimitry Andric   else if (getLangOpts().CUDA &&
105333956c43SDimitry Andric            !getLangOpts().CUDAIsDevice &&
10546122f3e6SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
105533956c43SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1056dff0c46cSDimitry Andric   else if (isa<CXXConversionDecl>(FD) &&
1057dff0c46cSDimitry Andric            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1058dff0c46cSDimitry Andric     // The lambda conversion to block pointer is special; the semantics can't be
1059dff0c46cSDimitry Andric     // expressed in the AST, so IRGen needs to special-case it.
1060dff0c46cSDimitry Andric     EmitLambdaToBlockPointerBody(Args);
1061dff0c46cSDimitry Andric   } else if (isa<CXXMethodDecl>(FD) &&
1062dff0c46cSDimitry Andric              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1063f785676fSDimitry Andric     // The lambda static invoker function is special, because it forwards or
1064dff0c46cSDimitry Andric     // clones the body of the function call operator (but is actually static).
1065dff0c46cSDimitry Andric     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1066139f7f9bSDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1067f785676fSDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1068f785676fSDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1069139f7f9bSDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
1070139f7f9bSDimitry Andric     // copy-constructors.
1071139f7f9bSDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
1072f785676fSDimitry Andric   } else if (Stmt *Body = FD->getBody()) {
1073f785676fSDimitry Andric     EmitFunctionBody(Args, Body);
1074f785676fSDimitry Andric   } else
1075f785676fSDimitry Andric     llvm_unreachable("no definition for emitted function");
1076f22ef01cSRoman Divacky 
10773861d79fSDimitry Andric   // C++11 [stmt.return]p2:
10783861d79fSDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
10793861d79fSDimitry Andric   //   a value-returning function.
10803861d79fSDimitry Andric   // C11 6.9.1p12:
10813861d79fSDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
10823861d79fSDimitry Andric   //   function call is used by the caller, the behavior is undefined.
108339d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
108459d1ed5bSDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
108539d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
108659d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
108739d628a0SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
108839d628a0SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
108939d628a0SDimitry Andric                 "missing_return", EmitCheckSourceLocation(FD->getLocation()),
109039d628a0SDimitry Andric                 None);
10913dac3a9bSDimitry Andric     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
10923dac3a9bSDimitry Andric       EmitTrapCall(llvm::Intrinsic::trap);
10933dac3a9bSDimitry Andric     }
10943861d79fSDimitry Andric     Builder.CreateUnreachable();
10953861d79fSDimitry Andric     Builder.ClearInsertionPoint();
10963861d79fSDimitry Andric   }
10973861d79fSDimitry Andric 
1098f22ef01cSRoman Divacky   // Emit the standard function epilogue.
1099f22ef01cSRoman Divacky   FinishFunction(BodyRange.getEnd());
1100f22ef01cSRoman Divacky 
1101e580952dSDimitry Andric   // If we haven't marked the function nothrow through other means, do
1102e580952dSDimitry Andric   // a quick pass now to see if we can.
1103e580952dSDimitry Andric   if (!CurFn->doesNotThrow())
1104e580952dSDimitry Andric     TryMarkNoThrow(CurFn);
1105f22ef01cSRoman Divacky }
1106f22ef01cSRoman Divacky 
1107f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it.  If
1108f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means
1109f22ef01cSRoman Divacky /// that we can just remove the code.
1110f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1111f22ef01cSRoman Divacky   // Null statement, not a label!
111259d1ed5bSDimitry Andric   if (!S) return false;
1113f22ef01cSRoman Divacky 
1114f22ef01cSRoman Divacky   // If this is a label, we have to emit the code, consider something like:
1115f22ef01cSRoman Divacky   // if (0) {  ...  foo:  bar(); }  goto foo;
11163b0f4066SDimitry Andric   //
11173b0f4066SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
11183b0f4066SDimitry Andric   // can't jump to one from outside their declared region.
1119f22ef01cSRoman Divacky   if (isa<LabelStmt>(S))
1120f22ef01cSRoman Divacky     return true;
1121f22ef01cSRoman Divacky 
1122f22ef01cSRoman Divacky   // If this is a case/default statement, and we haven't seen a switch, we have
1123f22ef01cSRoman Divacky   // to emit the code.
1124f22ef01cSRoman Divacky   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1125f22ef01cSRoman Divacky     return true;
1126f22ef01cSRoman Divacky 
1127f22ef01cSRoman Divacky   // If this is a switch statement, we want to ignore cases below it.
1128f22ef01cSRoman Divacky   if (isa<SwitchStmt>(S))
1129f22ef01cSRoman Divacky     IgnoreCaseStmts = true;
1130f22ef01cSRoman Divacky 
1131f22ef01cSRoman Divacky   // Scan subexpressions for verboten labels.
11323dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
11333dac3a9bSDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1134f22ef01cSRoman Divacky       return true;
1135f22ef01cSRoman Divacky 
1136f22ef01cSRoman Divacky   return false;
1137f22ef01cSRoman Divacky }
1138f22ef01cSRoman Divacky 
11393b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
11403b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
11413b0f4066SDimitry Andric /// inside of it, this is fine.
11423b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
11433b0f4066SDimitry Andric   // Null statement, not a label!
114459d1ed5bSDimitry Andric   if (!S) return false;
1145f22ef01cSRoman Divacky 
11463b0f4066SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
11473b0f4066SDimitry Andric   // include it and anything inside of it.
11483b0f4066SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
11493b0f4066SDimitry Andric       isa<ForStmt>(S))
11503b0f4066SDimitry Andric     return false;
11513b0f4066SDimitry Andric 
11523b0f4066SDimitry Andric   if (isa<BreakStmt>(S))
11533b0f4066SDimitry Andric     return true;
11543b0f4066SDimitry Andric 
11553b0f4066SDimitry Andric   // Scan subexpressions for verboten breaks.
11563dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
11573dac3a9bSDimitry Andric     if (containsBreak(SubStmt))
11583b0f4066SDimitry Andric       return true;
11593b0f4066SDimitry Andric 
11603b0f4066SDimitry Andric   return false;
11613b0f4066SDimitry Andric }
11623b0f4066SDimitry Andric 
1163f41fbc90SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1164f41fbc90SDimitry Andric   if (!S) return false;
1165f41fbc90SDimitry Andric 
1166f41fbc90SDimitry Andric   // Some statement kinds add a scope and thus never add a decl to the current
1167f41fbc90SDimitry Andric   // scope. Note, this list is longer than the list of statements that might
1168f41fbc90SDimitry Andric   // have an unscoped decl nested within them, but this way is conservatively
1169f41fbc90SDimitry Andric   // correct even if more statement kinds are added.
1170f41fbc90SDimitry Andric   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1171f41fbc90SDimitry Andric       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1172f41fbc90SDimitry Andric       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1173f41fbc90SDimitry Andric       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1174f41fbc90SDimitry Andric     return false;
1175f41fbc90SDimitry Andric 
1176f41fbc90SDimitry Andric   if (isa<DeclStmt>(S))
1177f41fbc90SDimitry Andric     return true;
1178f41fbc90SDimitry Andric 
1179f41fbc90SDimitry Andric   for (const Stmt *SubStmt : S->children())
1180f41fbc90SDimitry Andric     if (mightAddDeclToScope(SubStmt))
1181f41fbc90SDimitry Andric       return true;
1182f41fbc90SDimitry Andric 
1183f41fbc90SDimitry Andric   return false;
1184f41fbc90SDimitry Andric }
11853b0f4066SDimitry Andric 
11863b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
11873b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
11883b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result.
11893b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1190e7145dcbSDimitry Andric                                                    bool &ResultBool,
1191e7145dcbSDimitry Andric                                                    bool AllowLabels) {
11927ae0e2c9SDimitry Andric   llvm::APSInt ResultInt;
1193e7145dcbSDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
11943b0f4066SDimitry Andric     return false;
11953b0f4066SDimitry Andric 
11963b0f4066SDimitry Andric   ResultBool = ResultInt.getBoolValue();
11973b0f4066SDimitry Andric   return true;
11983b0f4066SDimitry Andric }
11993b0f4066SDimitry Andric 
12003b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
12013b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
12023b0f4066SDimitry Andric /// constant folds return true and set the folded value.
1203e7145dcbSDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1204e7145dcbSDimitry Andric                                                    llvm::APSInt &ResultInt,
1205e7145dcbSDimitry Andric                                                    bool AllowLabels) {
1206f22ef01cSRoman Divacky   // FIXME: Rename and handle conversion of other evaluatable things
1207f22ef01cSRoman Divacky   // to bool.
1208dff0c46cSDimitry Andric   llvm::APSInt Int;
1209dff0c46cSDimitry Andric   if (!Cond->EvaluateAsInt(Int, getContext()))
12103b0f4066SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
1211f22ef01cSRoman Divacky 
1212e7145dcbSDimitry Andric   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
12133b0f4066SDimitry Andric     return false;  // Contains a label.
1214f22ef01cSRoman Divacky 
1215dff0c46cSDimitry Andric   ResultInt = Int;
12163b0f4066SDimitry Andric   return true;
1217f22ef01cSRoman Divacky }
1218f22ef01cSRoman Divacky 
1219f22ef01cSRoman Divacky 
12203b0f4066SDimitry Andric 
1221f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1222f22ef01cSRoman Divacky /// statement) to the specified blocks.  Based on the condition, this might try
1223f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch.
1224f22ef01cSRoman Divacky ///
1225f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1226f22ef01cSRoman Divacky                                            llvm::BasicBlock *TrueBlock,
122759d1ed5bSDimitry Andric                                            llvm::BasicBlock *FalseBlock,
122859d1ed5bSDimitry Andric                                            uint64_t TrueCount) {
12293b0f4066SDimitry Andric   Cond = Cond->IgnoreParens();
1230f22ef01cSRoman Divacky 
1231f22ef01cSRoman Divacky   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
123259d1ed5bSDimitry Andric 
1233f22ef01cSRoman Divacky     // Handle X && Y in a condition.
1234e580952dSDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
1235f22ef01cSRoman Divacky       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1236f22ef01cSRoman Divacky       // folded if the case was simple enough.
12373b0f4066SDimitry Andric       bool ConstantBool = false;
12383b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
12393b0f4066SDimitry Andric           ConstantBool) {
1240f22ef01cSRoman Divacky         // br(1 && X) -> br(X).
124133956c43SDimitry Andric         incrementProfileCounter(CondBOp);
124259d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
124359d1ed5bSDimitry Andric                                     TrueCount);
1244f22ef01cSRoman Divacky       }
1245f22ef01cSRoman Divacky 
1246f22ef01cSRoman Divacky       // If we have "X && 1", simplify the code to use an uncond branch.
1247f22ef01cSRoman Divacky       // "X && 0" would have been constant folded to 0.
12483b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
12493b0f4066SDimitry Andric           ConstantBool) {
1250f22ef01cSRoman Divacky         // br(X && 1) -> br(X).
125159d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
125259d1ed5bSDimitry Andric                                     TrueCount);
1253f22ef01cSRoman Divacky       }
1254f22ef01cSRoman Divacky 
1255f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1256f22ef01cSRoman Divacky       // want to jump to the FalseBlock.
1257f22ef01cSRoman Divacky       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
125859d1ed5bSDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
125959d1ed5bSDimitry Andric       // can be propagated to that branch.
126033956c43SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
12612754fe60SDimitry Andric 
12622754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
126333956c43SDimitry Andric       {
126433956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
126559d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1266f22ef01cSRoman Divacky         EmitBlock(LHSTrue);
126733956c43SDimitry Andric       }
126833956c43SDimitry Andric 
126933956c43SDimitry Andric       incrementProfileCounter(CondBOp);
127033956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1271f22ef01cSRoman Divacky 
1272f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
12732754fe60SDimitry Andric       eval.begin(*this);
127459d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
12752754fe60SDimitry Andric       eval.end(*this);
1276f22ef01cSRoman Divacky 
1277f22ef01cSRoman Divacky       return;
12783b0f4066SDimitry Andric     }
12793b0f4066SDimitry Andric 
12803b0f4066SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
1281f22ef01cSRoman Divacky       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1282f22ef01cSRoman Divacky       // folded if the case was simple enough.
12833b0f4066SDimitry Andric       bool ConstantBool = false;
12843b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
12853b0f4066SDimitry Andric           !ConstantBool) {
1286f22ef01cSRoman Divacky         // br(0 || X) -> br(X).
128733956c43SDimitry Andric         incrementProfileCounter(CondBOp);
128859d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
128959d1ed5bSDimitry Andric                                     TrueCount);
1290f22ef01cSRoman Divacky       }
1291f22ef01cSRoman Divacky 
1292f22ef01cSRoman Divacky       // If we have "X || 0", simplify the code to use an uncond branch.
1293f22ef01cSRoman Divacky       // "X || 1" would have been constant folded to 1.
12943b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
12953b0f4066SDimitry Andric           !ConstantBool) {
1296f22ef01cSRoman Divacky         // br(X || 0) -> br(X).
129759d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
129859d1ed5bSDimitry Andric                                     TrueCount);
1299f22ef01cSRoman Divacky       }
1300f22ef01cSRoman Divacky 
1301f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1302f22ef01cSRoman Divacky       // want to jump to the TrueBlock.
1303f22ef01cSRoman Divacky       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
130459d1ed5bSDimitry Andric       // We have the count for entry to the RHS and for the whole expression
130559d1ed5bSDimitry Andric       // being true, so we can divy up True count between the short circuit and
130659d1ed5bSDimitry Andric       // the RHS.
130733956c43SDimitry Andric       uint64_t LHSCount =
130833956c43SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
130959d1ed5bSDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
13102754fe60SDimitry Andric 
13112754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
131233956c43SDimitry Andric       {
131333956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
131459d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1315f22ef01cSRoman Divacky         EmitBlock(LHSFalse);
131633956c43SDimitry Andric       }
131733956c43SDimitry Andric 
131833956c43SDimitry Andric       incrementProfileCounter(CondBOp);
131933956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1320f22ef01cSRoman Divacky 
1321f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
13222754fe60SDimitry Andric       eval.begin(*this);
132359d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
132459d1ed5bSDimitry Andric 
13252754fe60SDimitry Andric       eval.end(*this);
1326f22ef01cSRoman Divacky 
1327f22ef01cSRoman Divacky       return;
1328f22ef01cSRoman Divacky     }
1329f22ef01cSRoman Divacky   }
1330f22ef01cSRoman Divacky 
1331f22ef01cSRoman Divacky   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1332f22ef01cSRoman Divacky     // br(!x, t, f) -> br(x, f, t)
133359d1ed5bSDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
133459d1ed5bSDimitry Andric       // Negate the count.
133533956c43SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
133659d1ed5bSDimitry Andric       // Negate the condition and swap the destination blocks.
133759d1ed5bSDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
133859d1ed5bSDimitry Andric                                   FalseCount);
133959d1ed5bSDimitry Andric     }
1340f22ef01cSRoman Divacky   }
1341f22ef01cSRoman Divacky 
1342f22ef01cSRoman Divacky   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1343f22ef01cSRoman Divacky     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1344f22ef01cSRoman Divacky     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1345f22ef01cSRoman Divacky     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
13462754fe60SDimitry Andric 
13472754fe60SDimitry Andric     ConditionalEvaluation cond(*this);
134833956c43SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
134933956c43SDimitry Andric                          getProfileCount(CondOp));
135059d1ed5bSDimitry Andric 
135159d1ed5bSDimitry Andric     // When computing PGO branch weights, we only know the overall count for
135259d1ed5bSDimitry Andric     // the true block. This code is essentially doing tail duplication of the
135359d1ed5bSDimitry Andric     // naive code-gen, introducing new edges for which counts are not
135459d1ed5bSDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
135559d1ed5bSDimitry Andric     // the conditional operator.
135659d1ed5bSDimitry Andric     uint64_t LHSScaledTrueCount = 0;
135759d1ed5bSDimitry Andric     if (TrueCount) {
135833956c43SDimitry Andric       double LHSRatio =
135933956c43SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
136059d1ed5bSDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
136159d1ed5bSDimitry Andric     }
13622754fe60SDimitry Andric 
13632754fe60SDimitry Andric     cond.begin(*this);
1364f22ef01cSRoman Divacky     EmitBlock(LHSBlock);
136533956c43SDimitry Andric     incrementProfileCounter(CondOp);
136633956c43SDimitry Andric     {
136733956c43SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
136859d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
136959d1ed5bSDimitry Andric                            LHSScaledTrueCount);
137033956c43SDimitry Andric     }
13712754fe60SDimitry Andric     cond.end(*this);
13722754fe60SDimitry Andric 
13732754fe60SDimitry Andric     cond.begin(*this);
1374f22ef01cSRoman Divacky     EmitBlock(RHSBlock);
137559d1ed5bSDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
137659d1ed5bSDimitry Andric                          TrueCount - LHSScaledTrueCount);
13772754fe60SDimitry Andric     cond.end(*this);
13782754fe60SDimitry Andric 
1379f22ef01cSRoman Divacky     return;
1380f22ef01cSRoman Divacky   }
1381f22ef01cSRoman Divacky 
1382284c1978SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1383284c1978SDimitry Andric     // Conditional operator handling can give us a throw expression as a
1384284c1978SDimitry Andric     // condition for a case like:
1385284c1978SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1386284c1978SDimitry Andric     // Fold this to:
1387284c1978SDimitry Andric     //   br(c, throw x, br(y, t, f))
1388284c1978SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1389284c1978SDimitry Andric     return;
1390284c1978SDimitry Andric   }
1391284c1978SDimitry Andric 
13920623d748SDimitry Andric   // If the branch has a condition wrapped by __builtin_unpredictable,
13930623d748SDimitry Andric   // create metadata that specifies that the branch is unpredictable.
13940623d748SDimitry Andric   // Don't bother if not optimizing because that metadata would not be used.
13950623d748SDimitry Andric   llvm::MDNode *Unpredictable = nullptr;
1396e7145dcbSDimitry Andric   auto *Call = dyn_cast<CallExpr>(Cond);
1397e7145dcbSDimitry Andric   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1398e7145dcbSDimitry Andric     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1399e7145dcbSDimitry Andric     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
14000623d748SDimitry Andric       llvm::MDBuilder MDHelper(getLLVMContext());
14010623d748SDimitry Andric       Unpredictable = MDHelper.createUnpredictable();
14020623d748SDimitry Andric     }
14030623d748SDimitry Andric   }
14040623d748SDimitry Andric 
140559d1ed5bSDimitry Andric   // Create branch weights based on the number of times we get here and the
140659d1ed5bSDimitry Andric   // number of times the condition should be true.
140733956c43SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
140833956c43SDimitry Andric   llvm::MDNode *Weights =
140933956c43SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
141059d1ed5bSDimitry Andric 
1411f22ef01cSRoman Divacky   // Emit the code with the fully general case.
141233956c43SDimitry Andric   llvm::Value *CondV;
141333956c43SDimitry Andric   {
141433956c43SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
141533956c43SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
141633956c43SDimitry Andric   }
14170623d748SDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1418f22ef01cSRoman Divacky }
1419f22ef01cSRoman Divacky 
1420f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
1421f22ef01cSRoman Divacky /// specified stmt yet.
1422f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1423f785676fSDimitry Andric   CGM.ErrorUnsupported(S, Type);
1424f22ef01cSRoman Divacky }
1425f22ef01cSRoman Divacky 
14262754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
14272754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
14282754fe60SDimitry Andric ///
14297ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array
14302754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
14312754fe60SDimitry Andric /// base element of the array
14322754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
14332754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
14340623d748SDimitry Andric                                Address dest, Address src,
14352754fe60SDimitry Andric                                llvm::Value *sizeInChars) {
14362754fe60SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
14372754fe60SDimitry Andric 
14380623d748SDimitry Andric   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
14392754fe60SDimitry Andric   llvm::Value *baseSizeInChars
14400623d748SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
14412754fe60SDimitry Andric 
14420623d748SDimitry Andric   Address begin =
14430623d748SDimitry Andric     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
14440623d748SDimitry Andric   llvm::Value *end =
14450623d748SDimitry Andric     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
14462754fe60SDimitry Andric 
14472754fe60SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
14482754fe60SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
14492754fe60SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
14502754fe60SDimitry Andric 
14512754fe60SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
14522754fe60SDimitry Andric   // count must be nonzero.
14532754fe60SDimitry Andric   CGF.EmitBlock(loopBB);
14542754fe60SDimitry Andric 
14550623d748SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
14560623d748SDimitry Andric   cur->addIncoming(begin.getPointer(), originBB);
14570623d748SDimitry Andric 
14580623d748SDimitry Andric   CharUnits curAlign =
14590623d748SDimitry Andric     dest.getAlignment().alignmentOfArrayElement(baseSize);
14602754fe60SDimitry Andric 
14612754fe60SDimitry Andric   // memcpy the individual element bit-pattern.
14620623d748SDimitry Andric   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
14632754fe60SDimitry Andric                        /*volatile*/ false);
14642754fe60SDimitry Andric 
14652754fe60SDimitry Andric   // Go to the next element.
14660623d748SDimitry Andric   llvm::Value *next =
14670623d748SDimitry Andric     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
14682754fe60SDimitry Andric 
14692754fe60SDimitry Andric   // Leave if that's the end of the VLA.
14702754fe60SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
14712754fe60SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
14722754fe60SDimitry Andric   cur->addIncoming(next, loopBB);
14732754fe60SDimitry Andric 
14742754fe60SDimitry Andric   CGF.EmitBlock(contBB);
14752754fe60SDimitry Andric }
14762754fe60SDimitry Andric 
1477f22ef01cSRoman Divacky void
14780623d748SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1479f22ef01cSRoman Divacky   // Ignore empty classes in C++.
14803861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1481f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1482f22ef01cSRoman Divacky       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1483f22ef01cSRoman Divacky         return;
1484f22ef01cSRoman Divacky     }
1485f22ef01cSRoman Divacky   }
1486f22ef01cSRoman Divacky 
1487e580952dSDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
14880623d748SDimitry Andric   if (DestPtr.getElementType() != Int8Ty)
14890623d748SDimitry Andric     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1490f22ef01cSRoman Divacky 
1491f22ef01cSRoman Divacky   // Get size and alignment info for this aggregate.
14920623d748SDimitry Andric   CharUnits size = getContext().getTypeSizeInChars(Ty);
14932754fe60SDimitry Andric 
14942754fe60SDimitry Andric   llvm::Value *SizeVal;
14952754fe60SDimitry Andric   const VariableArrayType *vla;
1496f22ef01cSRoman Divacky 
1497f22ef01cSRoman Divacky   // Don't bother emitting a zero-byte memset.
14980623d748SDimitry Andric   if (size.isZero()) {
14992754fe60SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
15002754fe60SDimitry Andric     if (const VariableArrayType *vlaType =
15012754fe60SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
15022754fe60SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
150317a519f9SDimitry Andric       QualType eltType;
150417a519f9SDimitry Andric       llvm::Value *numElts;
150559d1ed5bSDimitry Andric       std::tie(numElts, eltType) = getVLASize(vlaType);
150617a519f9SDimitry Andric 
150717a519f9SDimitry Andric       SizeVal = numElts;
150817a519f9SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
150917a519f9SDimitry Andric       if (!eltSize.isOne())
151017a519f9SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
15112754fe60SDimitry Andric       vla = vlaType;
15122754fe60SDimitry Andric     } else {
1513f22ef01cSRoman Divacky       return;
15142754fe60SDimitry Andric     }
15152754fe60SDimitry Andric   } else {
15160623d748SDimitry Andric     SizeVal = CGM.getSize(size);
151759d1ed5bSDimitry Andric     vla = nullptr;
15182754fe60SDimitry Andric   }
1519e580952dSDimitry Andric 
1520e580952dSDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
1521e580952dSDimitry Andric   // Instead, create a null constant and copy it to the destination.
15222754fe60SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
15232754fe60SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
1524e580952dSDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
15252754fe60SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
15262754fe60SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
15272754fe60SDimitry Andric 
1528e580952dSDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1529e580952dSDimitry Andric 
1530e580952dSDimitry Andric     llvm::GlobalVariable *NullVariable =
1531e580952dSDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1532e580952dSDimitry Andric                                /*isConstant=*/true,
1533e580952dSDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
15346122f3e6SDimitry Andric                                NullConstant, Twine());
15350623d748SDimitry Andric     CharUnits NullAlign = DestPtr.getAlignment();
15360623d748SDimitry Andric     NullVariable->setAlignment(NullAlign.getQuantity());
15370623d748SDimitry Andric     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
15380623d748SDimitry Andric                    NullAlign);
1539e580952dSDimitry Andric 
15402754fe60SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1541e580952dSDimitry Andric 
1542e580952dSDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
15430623d748SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1544e580952dSDimitry Andric     return;
1545e580952dSDimitry Andric   }
1546e580952dSDimitry Andric 
1547e580952dSDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
1548e580952dSDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
1549e580952dSDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
15500623d748SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1551f22ef01cSRoman Divacky }
1552f22ef01cSRoman Divacky 
15532754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1554f22ef01cSRoman Divacky   // Make sure that there is a block for the indirect goto.
155559d1ed5bSDimitry Andric   if (!IndirectBranch)
1556f22ef01cSRoman Divacky     GetIndirectGotoBlock();
1557f22ef01cSRoman Divacky 
1558e580952dSDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1559f22ef01cSRoman Divacky 
1560f22ef01cSRoman Divacky   // Make sure the indirect branch includes all of the address-taken blocks.
1561f22ef01cSRoman Divacky   IndirectBranch->addDestination(BB);
1562f22ef01cSRoman Divacky   return llvm::BlockAddress::get(CurFn, BB);
1563f22ef01cSRoman Divacky }
1564f22ef01cSRoman Divacky 
1565f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1566f22ef01cSRoman Divacky   // If we already made the indirect branch for indirect goto, return its block.
1567f22ef01cSRoman Divacky   if (IndirectBranch) return IndirectBranch->getParent();
1568f22ef01cSRoman Divacky 
15690623d748SDimitry Andric   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1570f22ef01cSRoman Divacky 
1571f22ef01cSRoman Divacky   // Create the PHI node that indirect gotos will add entries to.
15723b0f4066SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
15733b0f4066SDimitry Andric                                               "indirect.goto.dest");
1574f22ef01cSRoman Divacky 
1575f22ef01cSRoman Divacky   // Create the indirect branch instruction.
1576f22ef01cSRoman Divacky   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1577f22ef01cSRoman Divacky   return IndirectBranch->getParent();
1578f22ef01cSRoman Divacky }
1579f22ef01cSRoman Divacky 
158017a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base
158117a519f9SDimitry Andric /// element type and a properly-typed first element pointer.
158217a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
158317a519f9SDimitry Andric                                               QualType &baseType,
15840623d748SDimitry Andric                                               Address &addr) {
158517a519f9SDimitry Andric   const ArrayType *arrayType = origArrayType;
1586f22ef01cSRoman Divacky 
158717a519f9SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
158817a519f9SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
158959d1ed5bSDimitry Andric   llvm::Value *numVLAElements = nullptr;
159017a519f9SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
159117a519f9SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
159217a519f9SDimitry Andric 
159317a519f9SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
159417a519f9SDimitry Andric     // which has type T* where T is the first non-VLA element type.
159517a519f9SDimitry Andric     do {
159617a519f9SDimitry Andric       QualType elementType = arrayType->getElementType();
159717a519f9SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
159817a519f9SDimitry Andric 
159917a519f9SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
160017a519f9SDimitry Andric       if (!arrayType) {
160117a519f9SDimitry Andric         baseType = elementType;
160217a519f9SDimitry Andric         return numVLAElements;
160317a519f9SDimitry Andric       }
160417a519f9SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
160517a519f9SDimitry Andric 
160617a519f9SDimitry Andric     // We get out here only if we find a constant array type
160717a519f9SDimitry Andric     // inside the VLA.
1608f22ef01cSRoman Divacky   }
1609f22ef01cSRoman Divacky 
161017a519f9SDimitry Andric   // We have some number of constant-length arrays, so addr should
161117a519f9SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
161217a519f9SDimitry Andric   // down to the first element of addr.
16136122f3e6SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
161417a519f9SDimitry Andric 
161517a519f9SDimitry Andric   // GEP down to the array type.
161617a519f9SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
161717a519f9SDimitry Andric   gepIndices.push_back(zero);
161817a519f9SDimitry Andric 
161917a519f9SDimitry Andric   uint64_t countFromCLAs = 1;
16207ae0e2c9SDimitry Andric   QualType eltType;
162117a519f9SDimitry Andric 
16226122f3e6SDimitry Andric   llvm::ArrayType *llvmArrayType =
16230623d748SDimitry Andric     dyn_cast<llvm::ArrayType>(addr.getElementType());
16247ae0e2c9SDimitry Andric   while (llvmArrayType) {
162517a519f9SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
162617a519f9SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
162717a519f9SDimitry Andric              == llvmArrayType->getNumElements());
162817a519f9SDimitry Andric 
162917a519f9SDimitry Andric     gepIndices.push_back(zero);
163017a519f9SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
16317ae0e2c9SDimitry Andric     eltType = arrayType->getElementType();
163217a519f9SDimitry Andric 
163317a519f9SDimitry Andric     llvmArrayType =
163417a519f9SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
163517a519f9SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
16367ae0e2c9SDimitry Andric     assert((!llvmArrayType || arrayType) &&
16377ae0e2c9SDimitry Andric            "LLVM and Clang types are out-of-synch");
163817a519f9SDimitry Andric   }
163917a519f9SDimitry Andric 
16407ae0e2c9SDimitry Andric   if (arrayType) {
16417ae0e2c9SDimitry Andric     // From this point onwards, the Clang array type has been emitted
16427ae0e2c9SDimitry Andric     // as some other type (probably a packed struct). Compute the array
16437ae0e2c9SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
16447ae0e2c9SDimitry Andric     while (arrayType) {
16457ae0e2c9SDimitry Andric       countFromCLAs *=
16467ae0e2c9SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
16477ae0e2c9SDimitry Andric       eltType = arrayType->getElementType();
16487ae0e2c9SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
16497ae0e2c9SDimitry Andric     }
165017a519f9SDimitry Andric 
16510623d748SDimitry Andric     llvm::Type *baseType = ConvertType(eltType);
16520623d748SDimitry Andric     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
16537ae0e2c9SDimitry Andric   } else {
165417a519f9SDimitry Andric     // Create the actual GEP.
16550623d748SDimitry Andric     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
16560623d748SDimitry Andric                                              gepIndices, "array.begin"),
16570623d748SDimitry Andric                    addr.getAlignment());
16587ae0e2c9SDimitry Andric   }
16597ae0e2c9SDimitry Andric 
16607ae0e2c9SDimitry Andric   baseType = eltType;
166117a519f9SDimitry Andric 
166217a519f9SDimitry Andric   llvm::Value *numElements
166317a519f9SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
166417a519f9SDimitry Andric 
166517a519f9SDimitry Andric   // If we had any VLA dimensions, factor them in.
166617a519f9SDimitry Andric   if (numVLAElements)
166717a519f9SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
166817a519f9SDimitry Andric 
166917a519f9SDimitry Andric   return numElements;
167017a519f9SDimitry Andric }
167117a519f9SDimitry Andric 
167217a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
167317a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) {
167417a519f9SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
167517a519f9SDimitry Andric   assert(vla && "type was not a variable array type!");
167617a519f9SDimitry Andric   return getVLASize(vla);
167717a519f9SDimitry Andric }
167817a519f9SDimitry Andric 
167917a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
168017a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
168117a519f9SDimitry Andric   // The number of elements so far; always size_t.
168259d1ed5bSDimitry Andric   llvm::Value *numElements = nullptr;
168317a519f9SDimitry Andric 
168417a519f9SDimitry Andric   QualType elementType;
168517a519f9SDimitry Andric   do {
168617a519f9SDimitry Andric     elementType = type->getElementType();
168717a519f9SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
168817a519f9SDimitry Andric     assert(vlaSize && "no size for VLA!");
168917a519f9SDimitry Andric     assert(vlaSize->getType() == SizeTy);
169017a519f9SDimitry Andric 
169117a519f9SDimitry Andric     if (!numElements) {
169217a519f9SDimitry Andric       numElements = vlaSize;
169317a519f9SDimitry Andric     } else {
169417a519f9SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
169559d1ed5bSDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
169617a519f9SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
169717a519f9SDimitry Andric     }
169817a519f9SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
169917a519f9SDimitry Andric 
170017a519f9SDimitry Andric   return std::pair<llvm::Value*,QualType>(numElements, elementType);
170117a519f9SDimitry Andric }
170217a519f9SDimitry Andric 
170317a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
170417a519f9SDimitry Andric   assert(type->isVariablyModifiedType() &&
1705f22ef01cSRoman Divacky          "Must pass variably modified type to EmitVLASizes!");
1706f22ef01cSRoman Divacky 
1707f22ef01cSRoman Divacky   EnsureInsertPoint();
1708f22ef01cSRoman Divacky 
170917a519f9SDimitry Andric   // We're going to walk down into the type and look for VLA
171017a519f9SDimitry Andric   // expressions.
171117a519f9SDimitry Andric   do {
171217a519f9SDimitry Andric     assert(type->isVariablyModifiedType());
1713f22ef01cSRoman Divacky 
171417a519f9SDimitry Andric     const Type *ty = type.getTypePtr();
171517a519f9SDimitry Andric     switch (ty->getTypeClass()) {
1716dff0c46cSDimitry Andric 
171717a519f9SDimitry Andric #define TYPE(Class, Base)
171817a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
1719dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
172017a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1721dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
172217a519f9SDimitry Andric #include "clang/AST/TypeNodes.def"
1723dff0c46cSDimitry Andric       llvm_unreachable("unexpected dependent type!");
1724f22ef01cSRoman Divacky 
172517a519f9SDimitry Andric     // These types are never variably-modified.
172617a519f9SDimitry Andric     case Type::Builtin:
172717a519f9SDimitry Andric     case Type::Complex:
172817a519f9SDimitry Andric     case Type::Vector:
172917a519f9SDimitry Andric     case Type::ExtVector:
173017a519f9SDimitry Andric     case Type::Record:
173117a519f9SDimitry Andric     case Type::Enum:
1732dff0c46cSDimitry Andric     case Type::Elaborated:
1733dff0c46cSDimitry Andric     case Type::TemplateSpecialization:
173417a519f9SDimitry Andric     case Type::ObjCObject:
173517a519f9SDimitry Andric     case Type::ObjCInterface:
173617a519f9SDimitry Andric     case Type::ObjCObjectPointer:
173717a519f9SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
1738f22ef01cSRoman Divacky 
173959d1ed5bSDimitry Andric     case Type::Adjusted:
174059d1ed5bSDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
174159d1ed5bSDimitry Andric       break;
174259d1ed5bSDimitry Andric 
1743f785676fSDimitry Andric     case Type::Decayed:
1744f785676fSDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
1745f785676fSDimitry Andric       break;
1746f785676fSDimitry Andric 
174717a519f9SDimitry Andric     case Type::Pointer:
174817a519f9SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
174917a519f9SDimitry Andric       break;
1750f22ef01cSRoman Divacky 
175117a519f9SDimitry Andric     case Type::BlockPointer:
175217a519f9SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
175317a519f9SDimitry Andric       break;
175417a519f9SDimitry Andric 
175517a519f9SDimitry Andric     case Type::LValueReference:
175617a519f9SDimitry Andric     case Type::RValueReference:
175717a519f9SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
175817a519f9SDimitry Andric       break;
175917a519f9SDimitry Andric 
176017a519f9SDimitry Andric     case Type::MemberPointer:
176117a519f9SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
176217a519f9SDimitry Andric       break;
176317a519f9SDimitry Andric 
176417a519f9SDimitry Andric     case Type::ConstantArray:
176517a519f9SDimitry Andric     case Type::IncompleteArray:
176617a519f9SDimitry Andric       // Losing element qualification here is fine.
176717a519f9SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
176817a519f9SDimitry Andric       break;
176917a519f9SDimitry Andric 
177017a519f9SDimitry Andric     case Type::VariableArray: {
177117a519f9SDimitry Andric       // Losing element qualification here is fine.
177217a519f9SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
177317a519f9SDimitry Andric 
177417a519f9SDimitry Andric       // Unknown size indication requires no size computation.
177517a519f9SDimitry Andric       // Otherwise, evaluate and record it.
177617a519f9SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
177717a519f9SDimitry Andric         // It's possible that we might have emitted this already,
177817a519f9SDimitry Andric         // e.g. with a typedef and a pointer to it.
177917a519f9SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
178017a519f9SDimitry Andric         if (!entry) {
17813861d79fSDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
17823861d79fSDimitry Andric 
17833861d79fSDimitry Andric           // C11 6.7.6.2p5:
17843861d79fSDimitry Andric           //   If the size is an expression that is not an integer constant
17853861d79fSDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
17863861d79fSDimitry Andric           //   greater than zero.
178739d628a0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
17883861d79fSDimitry Andric               size->getType()->isSignedIntegerType()) {
178959d1ed5bSDimitry Andric             SanitizerScope SanScope(this);
17903861d79fSDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
17913861d79fSDimitry Andric             llvm::Constant *StaticArgs[] = {
17923861d79fSDimitry Andric               EmitCheckSourceLocation(size->getLocStart()),
17933861d79fSDimitry Andric               EmitCheckTypeDescriptor(size->getType())
17943861d79fSDimitry Andric             };
179539d628a0SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
179639d628a0SDimitry Andric                                      SanitizerKind::VLABound),
179739d628a0SDimitry Andric                       "vla_bound_not_positive", StaticArgs, Size);
17983861d79fSDimitry Andric           }
17993861d79fSDimitry Andric 
180017a519f9SDimitry Andric           // Always zexting here would be wrong if it weren't
180117a519f9SDimitry Andric           // undefined behavior to have a negative bound.
18023861d79fSDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
180317a519f9SDimitry Andric         }
180417a519f9SDimitry Andric       }
180517a519f9SDimitry Andric       type = vat->getElementType();
180617a519f9SDimitry Andric       break;
1807f22ef01cSRoman Divacky     }
1808f22ef01cSRoman Divacky 
180917a519f9SDimitry Andric     case Type::FunctionProto:
181017a519f9SDimitry Andric     case Type::FunctionNoProto:
181159d1ed5bSDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
181217a519f9SDimitry Andric       break;
18136122f3e6SDimitry Andric 
1814dff0c46cSDimitry Andric     case Type::Paren:
1815dff0c46cSDimitry Andric     case Type::TypeOf:
1816dff0c46cSDimitry Andric     case Type::UnaryTransform:
1817dff0c46cSDimitry Andric     case Type::Attributed:
1818dff0c46cSDimitry Andric     case Type::SubstTemplateTypeParm:
1819f785676fSDimitry Andric     case Type::PackExpansion:
1820dff0c46cSDimitry Andric       // Keep walking after single level desugaring.
1821dff0c46cSDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
1822dff0c46cSDimitry Andric       break;
1823dff0c46cSDimitry Andric 
1824dff0c46cSDimitry Andric     case Type::Typedef:
1825dff0c46cSDimitry Andric     case Type::Decltype:
1826dff0c46cSDimitry Andric     case Type::Auto:
1827dff0c46cSDimitry Andric       // Stop walking: nothing to do.
1828dff0c46cSDimitry Andric       return;
1829dff0c46cSDimitry Andric 
1830dff0c46cSDimitry Andric     case Type::TypeOfExpr:
1831dff0c46cSDimitry Andric       // Stop walking: emit typeof expression.
1832dff0c46cSDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1833dff0c46cSDimitry Andric       return;
1834dff0c46cSDimitry Andric 
18356122f3e6SDimitry Andric     case Type::Atomic:
18366122f3e6SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
18376122f3e6SDimitry Andric       break;
1838444ed5c5SDimitry Andric 
1839444ed5c5SDimitry Andric     case Type::Pipe:
1840444ed5c5SDimitry Andric       type = cast<PipeType>(ty)->getElementType();
1841444ed5c5SDimitry Andric       break;
1842f22ef01cSRoman Divacky     }
184317a519f9SDimitry Andric   } while (type->isVariablyModifiedType());
1844f22ef01cSRoman Divacky }
1845f22ef01cSRoman Divacky 
18460623d748SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) {
18472754fe60SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
18480623d748SDimitry Andric     return EmitPointerWithAlignment(E);
18490623d748SDimitry Andric   return EmitLValue(E).getAddress();
18500623d748SDimitry Andric }
18510623d748SDimitry Andric 
18520623d748SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1853f22ef01cSRoman Divacky   return EmitLValue(E).getAddress();
1854f22ef01cSRoman Divacky }
1855f22ef01cSRoman Divacky 
1856e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
18572754fe60SDimitry Andric                                               llvm::Constant *Init) {
1858e580952dSDimitry Andric   assert (Init && "Invalid DeclRefExpr initializer!");
1859e580952dSDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
1860e7145dcbSDimitry Andric     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
18612754fe60SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
18622754fe60SDimitry Andric }
18632754fe60SDimitry Andric 
18642754fe60SDimitry Andric CodeGenFunction::PeepholeProtection
18652754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
18662754fe60SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
18672754fe60SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
18682754fe60SDimitry Andric   // extend this protection.
18692754fe60SDimitry Andric 
18702754fe60SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
18712754fe60SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
18722754fe60SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
18732754fe60SDimitry Andric 
18742754fe60SDimitry Andric   // Just make an extra bitcast.
18752754fe60SDimitry Andric   assert(HaveInsertPoint());
18762754fe60SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
18772754fe60SDimitry Andric                                                   Builder.GetInsertBlock());
18782754fe60SDimitry Andric 
18792754fe60SDimitry Andric   PeepholeProtection protection;
18802754fe60SDimitry Andric   protection.Inst = inst;
18812754fe60SDimitry Andric   return protection;
18822754fe60SDimitry Andric }
18832754fe60SDimitry Andric 
18842754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
18852754fe60SDimitry Andric   if (!protection.Inst) return;
18862754fe60SDimitry Andric 
18872754fe60SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
18882754fe60SDimitry Andric   protection.Inst->eraseFromParent();
1889e580952dSDimitry Andric }
18906122f3e6SDimitry Andric 
18916122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
18926122f3e6SDimitry Andric                                                  llvm::Value *AnnotatedVal,
1893139f7f9bSDimitry Andric                                                  StringRef AnnotationStr,
18946122f3e6SDimitry Andric                                                  SourceLocation Location) {
18956122f3e6SDimitry Andric   llvm::Value *Args[4] = {
18966122f3e6SDimitry Andric     AnnotatedVal,
18976122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
18986122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
18996122f3e6SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
19006122f3e6SDimitry Andric   };
19016122f3e6SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
19026122f3e6SDimitry Andric }
19036122f3e6SDimitry Andric 
19046122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
19056122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
19066122f3e6SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
19076122f3e6SDimitry Andric   // llvm-gcc was doing.
190859d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
19096122f3e6SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
19106122f3e6SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
191159d1ed5bSDimitry Andric                        I->getAnnotation(), D->getLocation());
19126122f3e6SDimitry Andric }
19136122f3e6SDimitry Andric 
19140623d748SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
19150623d748SDimitry Andric                                               Address Addr) {
19166122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
19170623d748SDimitry Andric   llvm::Value *V = Addr.getPointer();
19186122f3e6SDimitry Andric   llvm::Type *VTy = V->getType();
19196122f3e6SDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
19206122f3e6SDimitry Andric                                     CGM.Int8PtrTy);
19216122f3e6SDimitry Andric 
192259d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
19236122f3e6SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
19246122f3e6SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
19256122f3e6SDimitry Andric     // itself.
19266122f3e6SDimitry Andric     if (VTy != CGM.Int8PtrTy)
19276122f3e6SDimitry Andric       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
192859d1ed5bSDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
19296122f3e6SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
19306122f3e6SDimitry Andric   }
19316122f3e6SDimitry Andric 
19320623d748SDimitry Andric   return Address(V, Addr.getAlignment());
19336122f3e6SDimitry Andric }
1934f785676fSDimitry Andric 
1935f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
193659d1ed5bSDimitry Andric 
193759d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
193859d1ed5bSDimitry Andric     : CGF(CGF) {
193959d1ed5bSDimitry Andric   assert(!CGF->IsSanitizerScope);
194059d1ed5bSDimitry Andric   CGF->IsSanitizerScope = true;
194159d1ed5bSDimitry Andric }
194259d1ed5bSDimitry Andric 
194359d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
194459d1ed5bSDimitry Andric   CGF->IsSanitizerScope = false;
194559d1ed5bSDimitry Andric }
194659d1ed5bSDimitry Andric 
194759d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
194859d1ed5bSDimitry Andric                                    const llvm::Twine &Name,
194959d1ed5bSDimitry Andric                                    llvm::BasicBlock *BB,
195059d1ed5bSDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
195159d1ed5bSDimitry Andric   LoopStack.InsertHelper(I);
195239d628a0SDimitry Andric   if (IsSanitizerScope)
195339d628a0SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
195459d1ed5bSDimitry Andric }
195559d1ed5bSDimitry Andric 
1956e7145dcbSDimitry Andric void CGBuilderInserter::InsertHelper(
195759d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
195859d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
1959e7145dcbSDimitry Andric   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
196059d1ed5bSDimitry Andric   if (CGF)
196159d1ed5bSDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
196259d1ed5bSDimitry Andric }
196359d1ed5bSDimitry Andric 
19640623d748SDimitry Andric static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
19650623d748SDimitry Andric                                 CodeGenModule &CGM, const FunctionDecl *FD,
19660623d748SDimitry Andric                                 std::string &FirstMissing) {
19670623d748SDimitry Andric   // If there aren't any required features listed then go ahead and return.
19680623d748SDimitry Andric   if (ReqFeatures.empty())
19690623d748SDimitry Andric     return false;
19700623d748SDimitry Andric 
19710623d748SDimitry Andric   // Now build up the set of caller features and verify that all the required
19720623d748SDimitry Andric   // features are there.
19730623d748SDimitry Andric   llvm::StringMap<bool> CallerFeatureMap;
19740623d748SDimitry Andric   CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
19750623d748SDimitry Andric 
19760623d748SDimitry Andric   // If we have at least one of the features in the feature list return
19770623d748SDimitry Andric   // true, otherwise return false.
19780623d748SDimitry Andric   return std::all_of(
19790623d748SDimitry Andric       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
19800623d748SDimitry Andric         SmallVector<StringRef, 1> OrFeatures;
19810623d748SDimitry Andric         Feature.split(OrFeatures, "|");
19820623d748SDimitry Andric         return std::any_of(OrFeatures.begin(), OrFeatures.end(),
19830623d748SDimitry Andric                            [&](StringRef Feature) {
19840623d748SDimitry Andric                              if (!CallerFeatureMap.lookup(Feature)) {
19850623d748SDimitry Andric                                FirstMissing = Feature.str();
19860623d748SDimitry Andric                                return false;
19870623d748SDimitry Andric                              }
19880623d748SDimitry Andric                              return true;
19890623d748SDimitry Andric                            });
19900623d748SDimitry Andric       });
19910623d748SDimitry Andric }
19920623d748SDimitry Andric 
19930623d748SDimitry Andric // Emits an error if we don't have a valid set of target features for the
19940623d748SDimitry Andric // called function.
19950623d748SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
19960623d748SDimitry Andric                                           const FunctionDecl *TargetDecl) {
19970623d748SDimitry Andric   // Early exit if this is an indirect call.
19980623d748SDimitry Andric   if (!TargetDecl)
19990623d748SDimitry Andric     return;
20000623d748SDimitry Andric 
20010623d748SDimitry Andric   // Get the current enclosing function if it exists. If it doesn't
20020623d748SDimitry Andric   // we can't check the target features anyhow.
20030623d748SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
20040623d748SDimitry Andric   if (!FD)
20050623d748SDimitry Andric     return;
20060623d748SDimitry Andric 
20070623d748SDimitry Andric   // Grab the required features for the call. For a builtin this is listed in
20080623d748SDimitry Andric   // the td file with the default cpu, for an always_inline function this is any
20090623d748SDimitry Andric   // listed cpu and any listed features.
20100623d748SDimitry Andric   unsigned BuiltinID = TargetDecl->getBuiltinID();
20110623d748SDimitry Andric   std::string MissingFeature;
20120623d748SDimitry Andric   if (BuiltinID) {
20130623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
20140623d748SDimitry Andric     const char *FeatureList =
20150623d748SDimitry Andric         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
20160623d748SDimitry Andric     // Return if the builtin doesn't have any required features.
20170623d748SDimitry Andric     if (!FeatureList || StringRef(FeatureList) == "")
20180623d748SDimitry Andric       return;
20190623d748SDimitry Andric     StringRef(FeatureList).split(ReqFeatures, ",");
20200623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
20210623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
20220623d748SDimitry Andric           << TargetDecl->getDeclName()
20230623d748SDimitry Andric           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
20240623d748SDimitry Andric 
20250623d748SDimitry Andric   } else if (TargetDecl->hasAttr<TargetAttr>()) {
20260623d748SDimitry Andric     // Get the required features for the callee.
20270623d748SDimitry Andric     SmallVector<StringRef, 1> ReqFeatures;
20280623d748SDimitry Andric     llvm::StringMap<bool> CalleeFeatureMap;
20290623d748SDimitry Andric     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
20300623d748SDimitry Andric     for (const auto &F : CalleeFeatureMap) {
20310623d748SDimitry Andric       // Only positive features are "required".
20320623d748SDimitry Andric       if (F.getValue())
20330623d748SDimitry Andric         ReqFeatures.push_back(F.getKey());
20340623d748SDimitry Andric     }
20350623d748SDimitry Andric     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
20360623d748SDimitry Andric       CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
20370623d748SDimitry Andric           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
20380623d748SDimitry Andric   }
20390623d748SDimitry Andric }
2040e7145dcbSDimitry Andric 
2041e7145dcbSDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2042e7145dcbSDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeStats)
2043e7145dcbSDimitry Andric     return;
2044e7145dcbSDimitry Andric 
2045e7145dcbSDimitry Andric   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2046e7145dcbSDimitry Andric   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2047e7145dcbSDimitry Andric   CGM.getSanStats().create(IRB, SSK);
2048e7145dcbSDimitry Andric }
2049