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"
1533956c43SDimitry Andric #include "CGCleanup.h"
166122f3e6SDimitry Andric #include "CGCUDARuntime.h"
17e580952dSDimitry Andric #include "CGCXXABI.h"
18f22ef01cSRoman Divacky #include "CGDebugInfo.h"
1959d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
20139f7f9bSDimitry Andric #include "CodeGenModule.h"
2159d1ed5bSDimitry Andric #include "CodeGenPGO.h"
22f785676fSDimitry Andric #include "TargetInfo.h"
23f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
24f22ef01cSRoman Divacky #include "clang/AST/Decl.h"
25f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
26f22ef01cSRoman Divacky #include "clang/AST/StmtCXX.h"
27139f7f9bSDimitry Andric #include "clang/Basic/TargetInfo.h"
28f785676fSDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
29ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
30139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
32139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
33139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
34f22ef01cSRoman Divacky using namespace clang;
35f22ef01cSRoman Divacky using namespace CodeGen;
36f22ef01cSRoman Divacky 
377ae0e2c9SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
38284c1978SDimitry Andric     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
3959d1ed5bSDimitry Andric       Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
4059d1ed5bSDimitry Andric               CGBuilderInserterTy(this)),
4139d628a0SDimitry Andric       CurFn(nullptr), CapturedStmtInfo(nullptr),
4239d628a0SDimitry Andric       SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
4339d628a0SDimitry Andric       CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
4433956c43SDimitry Andric       IsOutlinedSEHHelper(false), BlockInfo(nullptr), BlockPointer(nullptr),
4539d628a0SDimitry Andric       LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
4639d628a0SDimitry Andric       NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
4739d628a0SDimitry Andric       ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
48875ed548SDimitry Andric       DebugInfo(CGM.getModuleDebugInfo()),
49875ed548SDimitry Andric       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
50875ed548SDimitry Andric       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
51875ed548SDimitry Andric       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
52875ed548SDimitry Andric       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
53875ed548SDimitry Andric       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
5459d1ed5bSDimitry Andric       CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
5559d1ed5bSDimitry Andric       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
5659d1ed5bSDimitry Andric       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
5759d1ed5bSDimitry Andric       TerminateHandler(nullptr), TrapBB(nullptr) {
587ae0e2c9SDimitry Andric   if (!suppressNewContext)
59e580952dSDimitry Andric     CGM.getCXXABI().getMangleContext().startNewFunction();
60139f7f9bSDimitry Andric 
61139f7f9bSDimitry Andric   llvm::FastMathFlags FMF;
62139f7f9bSDimitry Andric   if (CGM.getLangOpts().FastMath)
63139f7f9bSDimitry Andric     FMF.setUnsafeAlgebra();
64139f7f9bSDimitry Andric   if (CGM.getLangOpts().FiniteMathOnly) {
65139f7f9bSDimitry Andric     FMF.setNoNaNs();
66139f7f9bSDimitry Andric     FMF.setNoInfs();
67139f7f9bSDimitry Andric   }
6839d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
6939d628a0SDimitry Andric     FMF.setNoNaNs();
7039d628a0SDimitry Andric   }
7139d628a0SDimitry Andric   if (CGM.getCodeGenOpts().NoSignedZeros) {
7239d628a0SDimitry Andric     FMF.setNoSignedZeros();
7339d628a0SDimitry Andric   }
7433956c43SDimitry Andric   if (CGM.getCodeGenOpts().ReciprocalMath) {
7533956c43SDimitry Andric     FMF.setAllowReciprocal();
7633956c43SDimitry Andric   }
77139f7f9bSDimitry Andric   Builder.SetFastMathFlags(FMF);
78f22ef01cSRoman Divacky }
79f22ef01cSRoman Divacky 
80dff0c46cSDimitry Andric CodeGenFunction::~CodeGenFunction() {
81f785676fSDimitry Andric   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
82f785676fSDimitry Andric 
83dff0c46cSDimitry Andric   // If there are any unclaimed block infos, go ahead and destroy them
84dff0c46cSDimitry Andric   // now.  This can happen if IR-gen gets clever and skips evaluating
85dff0c46cSDimitry Andric   // something.
86dff0c46cSDimitry Andric   if (FirstBlockInfo)
87dff0c46cSDimitry Andric     destroyBlockInfos(FirstBlockInfo);
8859d1ed5bSDimitry Andric 
8959d1ed5bSDimitry Andric   if (getLangOpts().OpenMP) {
9033956c43SDimitry Andric     CGM.getOpenMPRuntime().functionFinished(*this);
9159d1ed5bSDimitry Andric   }
92dff0c46cSDimitry Andric }
93dff0c46cSDimitry Andric 
9439d628a0SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
9539d628a0SDimitry Andric   CharUnits Alignment;
9639d628a0SDimitry Andric   if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
9739d628a0SDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
9839d628a0SDimitry Andric     unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
9939d628a0SDimitry Andric     if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
10039d628a0SDimitry Andric         !getContext().isAlignmentRequired(T))
10139d628a0SDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
10239d628a0SDimitry Andric   }
10339d628a0SDimitry Andric   return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
10439d628a0SDimitry Andric }
105f22ef01cSRoman Divacky 
10617a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
107f22ef01cSRoman Divacky   return CGM.getTypes().ConvertTypeForMem(T);
108f22ef01cSRoman Divacky }
109f22ef01cSRoman Divacky 
11017a519f9SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) {
111f22ef01cSRoman Divacky   return CGM.getTypes().ConvertType(T);
112f22ef01cSRoman Divacky }
113f22ef01cSRoman Divacky 
114139f7f9bSDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
115139f7f9bSDimitry Andric   type = type.getCanonicalType();
116139f7f9bSDimitry Andric   while (true) {
117139f7f9bSDimitry Andric     switch (type->getTypeClass()) {
118bd5abe19SDimitry Andric #define TYPE(name, parent)
119bd5abe19SDimitry Andric #define ABSTRACT_TYPE(name, parent)
120bd5abe19SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name:
121bd5abe19SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name:
122bd5abe19SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
123bd5abe19SDimitry Andric #include "clang/AST/TypeNodes.def"
124bd5abe19SDimitry Andric       llvm_unreachable("non-canonical or dependent type in IR-generation");
125bd5abe19SDimitry Andric 
126284c1978SDimitry Andric     case Type::Auto:
127284c1978SDimitry Andric       llvm_unreachable("undeduced auto type in IR-generation");
128284c1978SDimitry Andric 
129139f7f9bSDimitry Andric     // Various scalar types.
130bd5abe19SDimitry Andric     case Type::Builtin:
131bd5abe19SDimitry Andric     case Type::Pointer:
132bd5abe19SDimitry Andric     case Type::BlockPointer:
133bd5abe19SDimitry Andric     case Type::LValueReference:
134bd5abe19SDimitry Andric     case Type::RValueReference:
135bd5abe19SDimitry Andric     case Type::MemberPointer:
136bd5abe19SDimitry Andric     case Type::Vector:
137bd5abe19SDimitry Andric     case Type::ExtVector:
138bd5abe19SDimitry Andric     case Type::FunctionProto:
139bd5abe19SDimitry Andric     case Type::FunctionNoProto:
140bd5abe19SDimitry Andric     case Type::Enum:
141bd5abe19SDimitry Andric     case Type::ObjCObjectPointer:
142139f7f9bSDimitry Andric       return TEK_Scalar;
143bd5abe19SDimitry Andric 
144139f7f9bSDimitry Andric     // Complexes.
145bd5abe19SDimitry Andric     case Type::Complex:
146139f7f9bSDimitry Andric       return TEK_Complex;
147139f7f9bSDimitry Andric 
148139f7f9bSDimitry Andric     // Arrays, records, and Objective-C objects.
149bd5abe19SDimitry Andric     case Type::ConstantArray:
150bd5abe19SDimitry Andric     case Type::IncompleteArray:
151bd5abe19SDimitry Andric     case Type::VariableArray:
152bd5abe19SDimitry Andric     case Type::Record:
153bd5abe19SDimitry Andric     case Type::ObjCObject:
154bd5abe19SDimitry Andric     case Type::ObjCInterface:
155139f7f9bSDimitry Andric       return TEK_Aggregate;
1566122f3e6SDimitry Andric 
157139f7f9bSDimitry Andric     // We operate on atomic values according to their underlying type.
1586122f3e6SDimitry Andric     case Type::Atomic:
159139f7f9bSDimitry Andric       type = cast<AtomicType>(type)->getValueType();
160139f7f9bSDimitry Andric       continue;
161bd5abe19SDimitry Andric     }
162bd5abe19SDimitry Andric     llvm_unreachable("unknown type kind!");
163f22ef01cSRoman Divacky   }
164139f7f9bSDimitry Andric }
165f22ef01cSRoman Divacky 
16639d628a0SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
167f22ef01cSRoman Divacky   // For cleanliness, we try to avoid emitting the return block for
168f22ef01cSRoman Divacky   // simple cases.
169f22ef01cSRoman Divacky   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
170f22ef01cSRoman Divacky 
171f22ef01cSRoman Divacky   if (CurBB) {
172f22ef01cSRoman Divacky     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
173f22ef01cSRoman Divacky 
174f22ef01cSRoman Divacky     // We have a valid insert point, reuse it if it is empty or there are no
175f22ef01cSRoman Divacky     // explicit jumps to the return block.
176e580952dSDimitry Andric     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
177e580952dSDimitry Andric       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
178e580952dSDimitry Andric       delete ReturnBlock.getBlock();
179f22ef01cSRoman Divacky     } else
180e580952dSDimitry Andric       EmitBlock(ReturnBlock.getBlock());
18139d628a0SDimitry Andric     return llvm::DebugLoc();
182f22ef01cSRoman Divacky   }
183f22ef01cSRoman Divacky 
184f22ef01cSRoman Divacky   // Otherwise, if the return block is the target of a single direct
185f22ef01cSRoman Divacky   // branch then we can just put the code in that block instead. This
186f22ef01cSRoman Divacky   // cleans up functions which started with a unified return block.
187e580952dSDimitry Andric   if (ReturnBlock.getBlock()->hasOneUse()) {
188f22ef01cSRoman Divacky     llvm::BranchInst *BI =
18959d1ed5bSDimitry Andric       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
190ffd1746dSEd Schouten     if (BI && BI->isUnconditional() &&
191e580952dSDimitry Andric         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
19239d628a0SDimitry Andric       // Record/return the DebugLoc of the simple 'return' expression to be used
19339d628a0SDimitry Andric       // later by the actual 'ret' instruction.
19439d628a0SDimitry Andric       llvm::DebugLoc Loc = BI->getDebugLoc();
195f22ef01cSRoman Divacky       Builder.SetInsertPoint(BI->getParent());
196f22ef01cSRoman Divacky       BI->eraseFromParent();
197e580952dSDimitry Andric       delete ReturnBlock.getBlock();
19839d628a0SDimitry Andric       return Loc;
199f22ef01cSRoman Divacky     }
200f22ef01cSRoman Divacky   }
201f22ef01cSRoman Divacky 
202f22ef01cSRoman Divacky   // FIXME: We are at an unreachable point, there is no reason to emit the block
203f22ef01cSRoman Divacky   // unless it has uses. However, we still need a place to put the debug
204f22ef01cSRoman Divacky   // region.end for now.
205f22ef01cSRoman Divacky 
206e580952dSDimitry Andric   EmitBlock(ReturnBlock.getBlock());
20739d628a0SDimitry Andric   return llvm::DebugLoc();
208ffd1746dSEd Schouten }
209ffd1746dSEd Schouten 
210ffd1746dSEd Schouten static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
211ffd1746dSEd Schouten   if (!BB) return;
212ffd1746dSEd Schouten   if (!BB->use_empty())
213ffd1746dSEd Schouten     return CGF.CurFn->getBasicBlockList().push_back(BB);
214ffd1746dSEd Schouten   delete BB;
215f22ef01cSRoman Divacky }
216f22ef01cSRoman Divacky 
217f22ef01cSRoman Divacky void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
218f22ef01cSRoman Divacky   assert(BreakContinueStack.empty() &&
219f22ef01cSRoman Divacky          "mismatched push/pop in break/continue stack!");
220f22ef01cSRoman Divacky 
221284c1978SDimitry Andric   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
222f785676fSDimitry Andric     && NumSimpleReturnExprs == NumReturnExprs
223f785676fSDimitry Andric     && ReturnBlock.getBlock()->use_empty();
224f785676fSDimitry Andric   // Usually the return expression is evaluated before the cleanup
225f785676fSDimitry Andric   // code.  If the function contains only a simple return statement,
226f785676fSDimitry Andric   // such as a constant, the location before the cleanup code becomes
227f785676fSDimitry Andric   // the last useful breakpoint in the function, because the simple
228f785676fSDimitry Andric   // return expression will be evaluated after the cleanup code. To be
229f785676fSDimitry Andric   // safe, set the debug location for cleanup code to the location of
230f785676fSDimitry Andric   // the return statement.  Otherwise the cleanup code should be at the
231f785676fSDimitry Andric   // end of the function's lexical scope.
232f785676fSDimitry Andric   //
233f785676fSDimitry Andric   // If there are multiple branches to the return block, the branch
234f785676fSDimitry Andric   // instructions will get the location of the return statements and
235f785676fSDimitry Andric   // all will be fine.
236284c1978SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
237284c1978SDimitry Andric     if (OnlySimpleReturnStmts)
238284c1978SDimitry Andric       DI->EmitLocation(Builder, LastStopPoint);
239284c1978SDimitry Andric     else
240139f7f9bSDimitry Andric       DI->EmitLocation(Builder, EndLoc);
241284c1978SDimitry Andric   }
242139f7f9bSDimitry Andric 
24317a519f9SDimitry Andric   // Pop any cleanups that might have been associated with the
24417a519f9SDimitry Andric   // parameters.  Do this in whatever block we're currently in; it's
24517a519f9SDimitry Andric   // important to do this before we enter the return block or return
24617a519f9SDimitry Andric   // edges will be *really* confused.
24733956c43SDimitry Andric   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
24833956c43SDimitry Andric   bool HasOnlyLifetimeMarkers =
24933956c43SDimitry Andric       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
25033956c43SDimitry Andric   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
25133956c43SDimitry Andric   if (HasCleanups) {
252284c1978SDimitry Andric     // Make sure the line table doesn't jump back into the body for
253284c1978SDimitry Andric     // the ret after it's been at EndLoc.
254284c1978SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
255284c1978SDimitry Andric       if (OnlySimpleReturnStmts)
256284c1978SDimitry Andric         DI->EmitLocation(Builder, EndLoc);
25733956c43SDimitry Andric 
25833956c43SDimitry Andric     PopCleanupBlocks(PrologueCleanupDepth);
259284c1978SDimitry Andric   }
26017a519f9SDimitry Andric 
261f22ef01cSRoman Divacky   // Emit function epilog (to return).
26239d628a0SDimitry Andric   llvm::DebugLoc Loc = EmitReturnBlock();
263f22ef01cSRoman Divacky 
2642754fe60SDimitry Andric   if (ShouldInstrumentFunction())
265ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_exit");
266ffd1746dSEd Schouten 
267f22ef01cSRoman Divacky   // Emit debug descriptor for function end.
26839d628a0SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
269e580952dSDimitry Andric     DI->EmitFunctionEnd(Builder);
270f22ef01cSRoman Divacky 
27139d628a0SDimitry Andric   // Reset the debug location to that of the simple 'return' expression, if any
27239d628a0SDimitry Andric   // rather than that of the end of the function's scope '}'.
27339d628a0SDimitry Andric   ApplyDebugLocation AL(*this, Loc);
274f785676fSDimitry Andric   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
275f22ef01cSRoman Divacky   EmitEndEHSpec(CurCodeDecl);
276f22ef01cSRoman Divacky 
277ffd1746dSEd Schouten   assert(EHStack.empty() &&
278ffd1746dSEd Schouten          "did not remove all scopes from cleanup stack!");
279ffd1746dSEd Schouten 
280f22ef01cSRoman Divacky   // If someone did an indirect goto, emit the indirect goto block at the end of
281f22ef01cSRoman Divacky   // the function.
282f22ef01cSRoman Divacky   if (IndirectBranch) {
283f22ef01cSRoman Divacky     EmitBlock(IndirectBranch->getParent());
284f22ef01cSRoman Divacky     Builder.ClearInsertionPoint();
285f22ef01cSRoman Divacky   }
286f22ef01cSRoman Divacky 
287875ed548SDimitry Andric   // If some of our locals escaped, insert a call to llvm.localescape in the
28833956c43SDimitry Andric   // entry block.
28933956c43SDimitry Andric   if (!EscapedLocals.empty()) {
29033956c43SDimitry Andric     // Invert the map from local to index into a simple vector. There should be
29133956c43SDimitry Andric     // no holes.
29233956c43SDimitry Andric     SmallVector<llvm::Value *, 4> EscapeArgs;
29333956c43SDimitry Andric     EscapeArgs.resize(EscapedLocals.size());
29433956c43SDimitry Andric     for (auto &Pair : EscapedLocals)
29533956c43SDimitry Andric       EscapeArgs[Pair.second] = Pair.first;
29633956c43SDimitry Andric     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
297875ed548SDimitry Andric         &CGM.getModule(), llvm::Intrinsic::localescape);
29833956c43SDimitry Andric     CGBuilderTy(AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
29933956c43SDimitry Andric   }
30033956c43SDimitry Andric 
301f22ef01cSRoman Divacky   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
302f22ef01cSRoman Divacky   llvm::Instruction *Ptr = AllocaInsertPt;
30359d1ed5bSDimitry Andric   AllocaInsertPt = nullptr;
304f22ef01cSRoman Divacky   Ptr->eraseFromParent();
305f22ef01cSRoman Divacky 
306f22ef01cSRoman Divacky   // If someone took the address of a label but never did an indirect goto, we
307f22ef01cSRoman Divacky   // made a zero entry PHI node, which is illegal, zap it now.
308f22ef01cSRoman Divacky   if (IndirectBranch) {
309f22ef01cSRoman Divacky     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
310f22ef01cSRoman Divacky     if (PN->getNumIncomingValues() == 0) {
311f22ef01cSRoman Divacky       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
312f22ef01cSRoman Divacky       PN->eraseFromParent();
313f22ef01cSRoman Divacky     }
314f22ef01cSRoman Divacky   }
315ffd1746dSEd Schouten 
3166122f3e6SDimitry Andric   EmitIfUsed(*this, EHResumeBlock);
317ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateLandingPad);
318ffd1746dSEd Schouten   EmitIfUsed(*this, TerminateHandler);
319ffd1746dSEd Schouten   EmitIfUsed(*this, UnreachableBlock);
320ffd1746dSEd Schouten 
321ffd1746dSEd Schouten   if (CGM.getCodeGenOpts().EmitDeclMetadata)
322ffd1746dSEd Schouten     EmitDeclMetadata();
32359d1ed5bSDimitry Andric 
32459d1ed5bSDimitry Andric   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
32559d1ed5bSDimitry Andric            I = DeferredReplacements.begin(),
32659d1ed5bSDimitry Andric            E = DeferredReplacements.end();
32759d1ed5bSDimitry Andric        I != E; ++I) {
32859d1ed5bSDimitry Andric     I->first->replaceAllUsesWith(I->second);
32959d1ed5bSDimitry Andric     I->first->eraseFromParent();
33059d1ed5bSDimitry Andric   }
331ffd1746dSEd Schouten }
332ffd1746dSEd Schouten 
333ffd1746dSEd Schouten /// ShouldInstrumentFunction - Return true if the current function should be
334ffd1746dSEd Schouten /// instrumented with __cyg_profile_func_* calls
335ffd1746dSEd Schouten bool CodeGenFunction::ShouldInstrumentFunction() {
336ffd1746dSEd Schouten   if (!CGM.getCodeGenOpts().InstrumentFunctions)
337ffd1746dSEd Schouten     return false;
338bd5abe19SDimitry Andric   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
339ffd1746dSEd Schouten     return false;
340ffd1746dSEd Schouten   return true;
341ffd1746dSEd Schouten }
342ffd1746dSEd Schouten 
343ffd1746dSEd Schouten /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
344ffd1746dSEd Schouten /// instrumentation function with the current function and the call site, if
345ffd1746dSEd Schouten /// function instrumentation is enabled.
346ffd1746dSEd Schouten void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
347ffd1746dSEd Schouten   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
34817a519f9SDimitry Andric   llvm::PointerType *PointerTy = Int8PtrTy;
34917a519f9SDimitry Andric   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
3506122f3e6SDimitry Andric   llvm::FunctionType *FunctionTy =
351dff0c46cSDimitry Andric     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
352ffd1746dSEd Schouten 
353ffd1746dSEd Schouten   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
354ffd1746dSEd Schouten   llvm::CallInst *CallSite = Builder.CreateCall(
35517a519f9SDimitry Andric     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
356ffd1746dSEd Schouten     llvm::ConstantInt::get(Int32Ty, 0),
357ffd1746dSEd Schouten     "callsite");
358ffd1746dSEd Schouten 
359139f7f9bSDimitry Andric   llvm::Value *args[] = {
360ffd1746dSEd Schouten     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
361139f7f9bSDimitry Andric     CallSite
362139f7f9bSDimitry Andric   };
363139f7f9bSDimitry Andric 
364139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(F, args);
365f22ef01cSRoman Divacky }
366f22ef01cSRoman Divacky 
3672754fe60SDimitry Andric void CodeGenFunction::EmitMCountInstrumentation() {
368dff0c46cSDimitry Andric   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
3692754fe60SDimitry Andric 
370284c1978SDimitry Andric   llvm::Constant *MCountFn =
371284c1978SDimitry Andric     CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
372139f7f9bSDimitry Andric   EmitNounwindRuntimeCall(MCountFn);
3732754fe60SDimitry Andric }
3742754fe60SDimitry Andric 
3757ae0e2c9SDimitry Andric // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
3767ae0e2c9SDimitry Andric // information in the program executable. The argument information stored
3777ae0e2c9SDimitry Andric // includes the argument name, its type, the address and access qualifiers used.
3787ae0e2c9SDimitry Andric static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
3797ae0e2c9SDimitry Andric                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
38039d628a0SDimitry Andric                                  SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
381139f7f9bSDimitry Andric                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
382139f7f9bSDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
3837ae0e2c9SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
3847ae0e2c9SDimitry Andric   // the same number of values as their are kernel arguments.
3857ae0e2c9SDimitry Andric 
38659d1ed5bSDimitry Andric   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
38759d1ed5bSDimitry Andric 
388139f7f9bSDimitry Andric   // MDNode for the kernel argument address space qualifiers.
38939d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
390139f7f9bSDimitry Andric   addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
391139f7f9bSDimitry Andric 
392139f7f9bSDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
39339d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
394139f7f9bSDimitry Andric   accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
395139f7f9bSDimitry Andric 
396139f7f9bSDimitry Andric   // MDNode for the kernel argument type names.
39739d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
398139f7f9bSDimitry Andric   argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
399139f7f9bSDimitry Andric 
40039d628a0SDimitry Andric   // MDNode for the kernel argument base type names.
40139d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
40239d628a0SDimitry Andric   argBaseTypeNames.push_back(
40339d628a0SDimitry Andric       llvm::MDString::get(Context, "kernel_arg_base_type"));
40439d628a0SDimitry Andric 
405139f7f9bSDimitry Andric   // MDNode for the kernel argument type qualifiers.
40639d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
407139f7f9bSDimitry Andric   argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
408139f7f9bSDimitry Andric 
4097ae0e2c9SDimitry Andric   // MDNode for the kernel argument names.
41039d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
4117ae0e2c9SDimitry Andric   argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
4127ae0e2c9SDimitry Andric 
4137ae0e2c9SDimitry Andric   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
4147ae0e2c9SDimitry Andric     const ParmVarDecl *parm = FD->getParamDecl(i);
415139f7f9bSDimitry Andric     QualType ty = parm->getType();
416139f7f9bSDimitry Andric     std::string typeQuals;
417139f7f9bSDimitry Andric 
418139f7f9bSDimitry Andric     if (ty->isPointerType()) {
419139f7f9bSDimitry Andric       QualType pointeeTy = ty->getPointeeType();
420139f7f9bSDimitry Andric 
421139f7f9bSDimitry Andric       // Get address qualifier.
42239d628a0SDimitry Andric       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
42339d628a0SDimitry Andric           ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
424139f7f9bSDimitry Andric 
425139f7f9bSDimitry Andric       // Get argument type name.
42659d1ed5bSDimitry Andric       std::string typeName =
42759d1ed5bSDimitry Andric           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
428139f7f9bSDimitry Andric 
429139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
430139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
43139d628a0SDimitry Andric       if (pointeeTy.isCanonical() && pos != std::string::npos)
432139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
433139f7f9bSDimitry Andric 
434139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
435139f7f9bSDimitry Andric 
43639d628a0SDimitry Andric       std::string baseTypeName =
43739d628a0SDimitry Andric           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
43839d628a0SDimitry Andric               Policy) +
43939d628a0SDimitry Andric           "*";
44039d628a0SDimitry Andric 
44139d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
44239d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
44339d628a0SDimitry Andric       if (pos != std::string::npos)
44439d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
44539d628a0SDimitry Andric 
44639d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
44739d628a0SDimitry Andric 
448139f7f9bSDimitry Andric       // Get argument type qualifiers:
449139f7f9bSDimitry Andric       if (ty.isRestrictQualified())
450139f7f9bSDimitry Andric         typeQuals = "restrict";
451139f7f9bSDimitry Andric       if (pointeeTy.isConstQualified() ||
452139f7f9bSDimitry Andric           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
453139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "const" : " const";
454139f7f9bSDimitry Andric       if (pointeeTy.isVolatileQualified())
455139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
456139f7f9bSDimitry Andric     } else {
45759d1ed5bSDimitry Andric       uint32_t AddrSpc = 0;
45859d1ed5bSDimitry Andric       if (ty->isImageType())
45959d1ed5bSDimitry Andric         AddrSpc =
46059d1ed5bSDimitry Andric           CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
46159d1ed5bSDimitry Andric 
46239d628a0SDimitry Andric       addressQuals.push_back(
46339d628a0SDimitry Andric           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
464139f7f9bSDimitry Andric 
465139f7f9bSDimitry Andric       // Get argument type name.
46659d1ed5bSDimitry Andric       std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
467139f7f9bSDimitry Andric 
468139f7f9bSDimitry Andric       // Turn "unsigned type" to "utype"
469139f7f9bSDimitry Andric       std::string::size_type pos = typeName.find("unsigned");
47039d628a0SDimitry Andric       if (ty.isCanonical() && pos != std::string::npos)
471139f7f9bSDimitry Andric         typeName.erase(pos+1, 8);
472139f7f9bSDimitry Andric 
473139f7f9bSDimitry Andric       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
474139f7f9bSDimitry Andric 
47539d628a0SDimitry Andric       std::string baseTypeName =
47639d628a0SDimitry Andric           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
47739d628a0SDimitry Andric 
47839d628a0SDimitry Andric       // Turn "unsigned type" to "utype"
47939d628a0SDimitry Andric       pos = baseTypeName.find("unsigned");
48039d628a0SDimitry Andric       if (pos != std::string::npos)
48139d628a0SDimitry Andric         baseTypeName.erase(pos+1, 8);
48239d628a0SDimitry Andric 
48339d628a0SDimitry Andric       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
48439d628a0SDimitry Andric 
485139f7f9bSDimitry Andric       // Get argument type qualifiers:
486139f7f9bSDimitry Andric       if (ty.isConstQualified())
487139f7f9bSDimitry Andric         typeQuals = "const";
488139f7f9bSDimitry Andric       if (ty.isVolatileQualified())
489139f7f9bSDimitry Andric         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
490139f7f9bSDimitry Andric     }
491139f7f9bSDimitry Andric 
492139f7f9bSDimitry Andric     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
493139f7f9bSDimitry Andric 
494139f7f9bSDimitry Andric     // Get image access qualifier:
495139f7f9bSDimitry Andric     if (ty->isImageType()) {
49659d1ed5bSDimitry Andric       const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
49759d1ed5bSDimitry Andric       if (A && A->isWriteOnly())
498139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
499139f7f9bSDimitry Andric       else
500139f7f9bSDimitry Andric         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
50159d1ed5bSDimitry Andric       // FIXME: what about read_write?
502139f7f9bSDimitry Andric     } else
503139f7f9bSDimitry Andric       accessQuals.push_back(llvm::MDString::get(Context, "none"));
5047ae0e2c9SDimitry Andric 
5057ae0e2c9SDimitry Andric     // Get argument name.
5067ae0e2c9SDimitry Andric     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
5077ae0e2c9SDimitry Andric   }
508139f7f9bSDimitry Andric 
509139f7f9bSDimitry Andric   kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
510139f7f9bSDimitry Andric   kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
511139f7f9bSDimitry Andric   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
51239d628a0SDimitry Andric   kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
513139f7f9bSDimitry Andric   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
51439d628a0SDimitry Andric   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
5157ae0e2c9SDimitry Andric     kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
5167ae0e2c9SDimitry Andric }
5177ae0e2c9SDimitry Andric 
5187ae0e2c9SDimitry Andric void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
5197ae0e2c9SDimitry Andric                                                llvm::Function *Fn)
5207ae0e2c9SDimitry Andric {
5217ae0e2c9SDimitry Andric   if (!FD->hasAttr<OpenCLKernelAttr>())
5227ae0e2c9SDimitry Andric     return;
5237ae0e2c9SDimitry Andric 
5247ae0e2c9SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
5257ae0e2c9SDimitry Andric 
52639d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 5> kernelMDArgs;
52739d628a0SDimitry Andric   kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
5287ae0e2c9SDimitry Andric 
52939d628a0SDimitry Andric   GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
53039d628a0SDimitry Andric                        getContext());
531139f7f9bSDimitry Andric 
53259d1ed5bSDimitry Andric   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
53359d1ed5bSDimitry Andric     QualType hintQTy = A->getTypeHint();
534139f7f9bSDimitry Andric     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
535139f7f9bSDimitry Andric     bool isSignedInteger =
536139f7f9bSDimitry Andric         hintQTy->isSignedIntegerType() ||
537139f7f9bSDimitry Andric         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
53839d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
539139f7f9bSDimitry Andric         llvm::MDString::get(Context, "vec_type_hint"),
54039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
54139d628a0SDimitry Andric             CGM.getTypes().ConvertType(A->getTypeHint()))),
54239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
543139f7f9bSDimitry Andric             llvm::IntegerType::get(Context, 32),
54439d628a0SDimitry Andric             llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
545139f7f9bSDimitry Andric     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
546139f7f9bSDimitry Andric   }
5477ae0e2c9SDimitry Andric 
54859d1ed5bSDimitry Andric   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
54939d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
550139f7f9bSDimitry Andric         llvm::MDString::get(Context, "work_group_size_hint"),
55139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
55239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
55339d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
5547ae0e2c9SDimitry Andric     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
5557ae0e2c9SDimitry Andric   }
5567ae0e2c9SDimitry Andric 
55759d1ed5bSDimitry Andric   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
55839d628a0SDimitry Andric     llvm::Metadata *attrMDArgs[] = {
559139f7f9bSDimitry Andric         llvm::MDString::get(Context, "reqd_work_group_size"),
56039d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
56139d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
56239d628a0SDimitry Andric         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
5637ae0e2c9SDimitry Andric     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
5647ae0e2c9SDimitry Andric   }
5657ae0e2c9SDimitry Andric 
5667ae0e2c9SDimitry Andric   llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
5677ae0e2c9SDimitry Andric   llvm::NamedMDNode *OpenCLKernelMetadata =
5687ae0e2c9SDimitry Andric     CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
5697ae0e2c9SDimitry Andric   OpenCLKernelMetadata->addOperand(kernelMDNode);
5707ae0e2c9SDimitry Andric }
5717ae0e2c9SDimitry Andric 
57259d1ed5bSDimitry Andric /// Determine whether the function F ends with a return stmt.
57359d1ed5bSDimitry Andric static bool endsWithReturn(const Decl* F) {
57459d1ed5bSDimitry Andric   const Stmt *Body = nullptr;
57559d1ed5bSDimitry Andric   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
57659d1ed5bSDimitry Andric     Body = FD->getBody();
57759d1ed5bSDimitry Andric   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
57859d1ed5bSDimitry Andric     Body = OMD->getBody();
57959d1ed5bSDimitry Andric 
58059d1ed5bSDimitry Andric   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
58159d1ed5bSDimitry Andric     auto LastStmt = CS->body_rbegin();
58259d1ed5bSDimitry Andric     if (LastStmt != CS->body_rend())
58359d1ed5bSDimitry Andric       return isa<ReturnStmt>(*LastStmt);
58459d1ed5bSDimitry Andric   }
58559d1ed5bSDimitry Andric   return false;
58659d1ed5bSDimitry Andric }
58759d1ed5bSDimitry Andric 
588284c1978SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD,
589284c1978SDimitry Andric                                     QualType RetTy,
590f22ef01cSRoman Divacky                                     llvm::Function *Fn,
5913b0f4066SDimitry Andric                                     const CGFunctionInfo &FnInfo,
592f22ef01cSRoman Divacky                                     const FunctionArgList &Args,
59359d1ed5bSDimitry Andric                                     SourceLocation Loc,
594f22ef01cSRoman Divacky                                     SourceLocation StartLoc) {
59539d628a0SDimitry Andric   assert(!CurFn &&
59639d628a0SDimitry Andric          "Do not use a CodeGenFunction object for more than one function");
59739d628a0SDimitry Andric 
598f22ef01cSRoman Divacky   const Decl *D = GD.getDecl();
599f22ef01cSRoman Divacky 
600f22ef01cSRoman Divacky   DidCallStackSave = false;
601284c1978SDimitry Andric   CurCodeDecl = D;
60259d1ed5bSDimitry Andric   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
603f22ef01cSRoman Divacky   FnRetTy = RetTy;
604f22ef01cSRoman Divacky   CurFn = Fn;
6053b0f4066SDimitry Andric   CurFnInfo = &FnInfo;
606f22ef01cSRoman Divacky   assert(CurFn->isDeclaration() && "Function already has body?");
607f22ef01cSRoman Divacky 
60839d628a0SDimitry Andric   if (CGM.isInSanitizerBlacklist(Fn, Loc))
60939d628a0SDimitry Andric     SanOpts.clear();
610139f7f9bSDimitry Andric 
61133956c43SDimitry Andric   if (D) {
61233956c43SDimitry Andric     // Apply the no_sanitize* attributes to SanOpts.
61333956c43SDimitry Andric     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
61433956c43SDimitry Andric       SanOpts.Mask &= ~Attr->getMask();
61533956c43SDimitry Andric   }
61633956c43SDimitry Andric 
61733956c43SDimitry Andric   // Apply sanitizer attributes to the function.
6188f0fd8f6SDimitry Andric   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
61933956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
62033956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Thread))
62133956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
62233956c43SDimitry Andric   if (SanOpts.has(SanitizerKind::Memory))
62333956c43SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
6248f0fd8f6SDimitry Andric   if (SanOpts.has(SanitizerKind::SafeStack))
6258f0fd8f6SDimitry Andric     Fn->addFnAttr(llvm::Attribute::SafeStack);
62633956c43SDimitry Andric 
627f22ef01cSRoman Divacky   // Pass inline keyword to optimizer if it appears explicitly on any
62859d1ed5bSDimitry Andric   // declaration. Also, in the case of -fno-inline attach NoInline
62959d1ed5bSDimitry Andric   // attribute to all function that are not marked AlwaysInline.
63059d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
63159d1ed5bSDimitry Andric     if (!CGM.getCodeGenOpts().NoInline) {
63259d1ed5bSDimitry Andric       for (auto RI : FD->redecls())
633f22ef01cSRoman Divacky         if (RI->isInlineSpecified()) {
634139f7f9bSDimitry Andric           Fn->addFnAttr(llvm::Attribute::InlineHint);
635f22ef01cSRoman Divacky           break;
636f22ef01cSRoman Divacky         }
63759d1ed5bSDimitry Andric     } else if (!FD->hasAttr<AlwaysInlineAttr>())
63859d1ed5bSDimitry Andric       Fn->addFnAttr(llvm::Attribute::NoInline);
63959d1ed5bSDimitry Andric   }
640f22ef01cSRoman Divacky 
6413861d79fSDimitry Andric   if (getLangOpts().OpenCL) {
6422754fe60SDimitry Andric     // Add metadata for a kernel function.
6432754fe60SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
6447ae0e2c9SDimitry Andric       EmitOpenCLKernelMetadata(FD, Fn);
6452754fe60SDimitry Andric   }
6462754fe60SDimitry Andric 
647f785676fSDimitry Andric   // If we are checking function types, emit a function type signature as
64839d628a0SDimitry Andric   // prologue data.
64939d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
650f785676fSDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
65139d628a0SDimitry Andric       if (llvm::Constant *PrologueSig =
652f785676fSDimitry Andric               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
653f785676fSDimitry Andric         llvm::Constant *FTRTTIConst =
654f785676fSDimitry Andric             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
65539d628a0SDimitry Andric         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
65639d628a0SDimitry Andric         llvm::Constant *PrologueStructConst =
65739d628a0SDimitry Andric             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
65839d628a0SDimitry Andric         Fn->setPrologueData(PrologueStructConst);
659f785676fSDimitry Andric       }
660f785676fSDimitry Andric     }
661f785676fSDimitry Andric   }
662f785676fSDimitry Andric 
663f22ef01cSRoman Divacky   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
664f22ef01cSRoman Divacky 
665f22ef01cSRoman Divacky   // Create a marker to make it easy to insert allocas into the entryblock
666f22ef01cSRoman Divacky   // later.  Don't create this with the builder, because we don't want it
667f22ef01cSRoman Divacky   // folded.
668ffd1746dSEd Schouten   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
669ffd1746dSEd Schouten   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
670f22ef01cSRoman Divacky   if (Builder.isNamePreserving())
671f22ef01cSRoman Divacky     AllocaInsertPt->setName("allocapt");
672f22ef01cSRoman Divacky 
673ffd1746dSEd Schouten   ReturnBlock = getJumpDestInCurrentScope("return");
674f22ef01cSRoman Divacky 
675f22ef01cSRoman Divacky   Builder.SetInsertPoint(EntryBB);
676f22ef01cSRoman Divacky 
677f22ef01cSRoman Divacky   // Emit subprogram debug descriptor.
678f22ef01cSRoman Divacky   if (CGDebugInfo *DI = getDebugInfo()) {
679139f7f9bSDimitry Andric     SmallVector<QualType, 16> ArgTypes;
680dff0c46cSDimitry Andric     for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
681dff0c46cSDimitry Andric 	 i != e; ++i) {
682139f7f9bSDimitry Andric       ArgTypes.push_back((*i)->getType());
683dff0c46cSDimitry Andric     }
684dff0c46cSDimitry Andric 
6852754fe60SDimitry Andric     QualType FnType =
686139f7f9bSDimitry Andric       getContext().getFunctionType(RetTy, ArgTypes,
6872754fe60SDimitry Andric                                    FunctionProtoType::ExtProtoInfo());
68859d1ed5bSDimitry Andric     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
689f22ef01cSRoman Divacky   }
690f22ef01cSRoman Divacky 
6912754fe60SDimitry Andric   if (ShouldInstrumentFunction())
692ffd1746dSEd Schouten     EmitFunctionInstrumentation("__cyg_profile_func_enter");
693ffd1746dSEd Schouten 
6942754fe60SDimitry Andric   if (CGM.getCodeGenOpts().InstrumentForProfiling)
6952754fe60SDimitry Andric     EmitMCountInstrumentation();
6962754fe60SDimitry Andric 
697f22ef01cSRoman Divacky   if (RetTy->isVoidType()) {
698f22ef01cSRoman Divacky     // Void type; nothing to return.
69959d1ed5bSDimitry Andric     ReturnValue = nullptr;
70059d1ed5bSDimitry Andric 
70159d1ed5bSDimitry Andric     // Count the implicit return.
70259d1ed5bSDimitry Andric     if (!endsWithReturn(D))
70359d1ed5bSDimitry Andric       ++NumReturnExprs;
704f22ef01cSRoman Divacky   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
705139f7f9bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
706f22ef01cSRoman Divacky     // Indirect aggregate return; emit returned value directly into sret slot.
707f22ef01cSRoman Divacky     // This reduces code size, and affects correctness in C++.
70859d1ed5bSDimitry Andric     auto AI = CurFn->arg_begin();
70959d1ed5bSDimitry Andric     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
71059d1ed5bSDimitry Andric       ++AI;
71159d1ed5bSDimitry Andric     ReturnValue = AI;
71259d1ed5bSDimitry Andric   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
71359d1ed5bSDimitry Andric              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
71459d1ed5bSDimitry Andric     // Load the sret pointer from the argument struct and return into that.
71559d1ed5bSDimitry Andric     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
71659d1ed5bSDimitry Andric     llvm::Function::arg_iterator EI = CurFn->arg_end();
71759d1ed5bSDimitry Andric     --EI;
71833956c43SDimitry Andric     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx);
71959d1ed5bSDimitry Andric     ReturnValue = Builder.CreateLoad(Addr, "agg.result");
720f22ef01cSRoman Divacky   } else {
721f22ef01cSRoman Divacky     ReturnValue = CreateIRTemp(RetTy, "retval");
72217a519f9SDimitry Andric 
72317a519f9SDimitry Andric     // Tell the epilog emitter to autorelease the result.  We do this
72417a519f9SDimitry Andric     // now so that various specialized functions can suppress it
72517a519f9SDimitry Andric     // during their IR-generation.
726dff0c46cSDimitry Andric     if (getLangOpts().ObjCAutoRefCount &&
72717a519f9SDimitry Andric         !CurFnInfo->isReturnsRetained() &&
72817a519f9SDimitry Andric         RetTy->isObjCRetainableType())
72917a519f9SDimitry Andric       AutoreleaseResult = true;
730f22ef01cSRoman Divacky   }
731f22ef01cSRoman Divacky 
732f22ef01cSRoman Divacky   EmitStartEHSpec(CurCodeDecl);
73317a519f9SDimitry Andric 
73417a519f9SDimitry Andric   PrologueCleanupDepth = EHStack.stable_begin();
735f22ef01cSRoman Divacky   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
736f22ef01cSRoman Divacky 
737dff0c46cSDimitry Andric   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
738e580952dSDimitry Andric     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
739dff0c46cSDimitry Andric     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
740dff0c46cSDimitry Andric     if (MD->getParent()->isLambda() &&
741dff0c46cSDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
742dff0c46cSDimitry Andric       // We're in a lambda; figure out the captures.
743dff0c46cSDimitry Andric       MD->getParent()->getCaptureFields(LambdaCaptureFields,
744dff0c46cSDimitry Andric                                         LambdaThisCaptureField);
745dff0c46cSDimitry Andric       if (LambdaThisCaptureField) {
746dff0c46cSDimitry Andric         // If this lambda captures this, load it.
747284c1978SDimitry Andric         LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
748f785676fSDimitry Andric         CXXThisValue = EmitLoadOfLValue(ThisLValue,
749f785676fSDimitry Andric                                         SourceLocation()).getScalarVal();
750dff0c46cSDimitry Andric       }
75139d628a0SDimitry Andric       for (auto *FD : MD->getParent()->fields()) {
75239d628a0SDimitry Andric         if (FD->hasCapturedVLAType()) {
75339d628a0SDimitry Andric           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
75439d628a0SDimitry Andric                                            SourceLocation()).getScalarVal();
75539d628a0SDimitry Andric           auto VAT = FD->getCapturedVLAType();
75639d628a0SDimitry Andric           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
75739d628a0SDimitry Andric         }
75839d628a0SDimitry Andric       }
759dff0c46cSDimitry Andric     } else {
760dff0c46cSDimitry Andric       // Not in a lambda; just use 'this' from the method.
761dff0c46cSDimitry Andric       // FIXME: Should we generate a new load for each use of 'this'?  The
762dff0c46cSDimitry Andric       // fast register allocator would be happier...
763dff0c46cSDimitry Andric       CXXThisValue = CXXABIThisValue;
764dff0c46cSDimitry Andric     }
765dff0c46cSDimitry Andric   }
766f22ef01cSRoman Divacky 
767f22ef01cSRoman Divacky   // If any of the arguments have a variably modified type, make sure to
768f22ef01cSRoman Divacky   // emit the type size.
769f22ef01cSRoman Divacky   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
770f22ef01cSRoman Divacky        i != e; ++i) {
771139f7f9bSDimitry Andric     const VarDecl *VD = *i;
772139f7f9bSDimitry Andric 
773139f7f9bSDimitry Andric     // Dig out the type as written from ParmVarDecls; it's unclear whether
774139f7f9bSDimitry Andric     // the standard (C99 6.9.1p10) requires this, but we're following the
775139f7f9bSDimitry Andric     // precedent set by gcc.
776139f7f9bSDimitry Andric     QualType Ty;
777139f7f9bSDimitry Andric     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
778139f7f9bSDimitry Andric       Ty = PVD->getOriginalType();
779139f7f9bSDimitry Andric     else
780139f7f9bSDimitry Andric       Ty = VD->getType();
781f22ef01cSRoman Divacky 
782f22ef01cSRoman Divacky     if (Ty->isVariablyModifiedType())
78317a519f9SDimitry Andric       EmitVariablyModifiedType(Ty);
784f22ef01cSRoman Divacky   }
7856122f3e6SDimitry Andric   // Emit a location at the end of the prologue.
7866122f3e6SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo())
7876122f3e6SDimitry Andric     DI->EmitLocation(Builder, StartLoc);
788f22ef01cSRoman Divacky }
789f22ef01cSRoman Divacky 
790f785676fSDimitry Andric void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
791f785676fSDimitry Andric                                        const Stmt *Body) {
79233956c43SDimitry Andric   incrementProfileCounter(Body);
793f785676fSDimitry Andric   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
794139f7f9bSDimitry Andric     EmitCompoundStmtWithoutScope(*S);
795139f7f9bSDimitry Andric   else
796f785676fSDimitry Andric     EmitStmt(Body);
797f22ef01cSRoman Divacky }
798f22ef01cSRoman Divacky 
79959d1ed5bSDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks
80059d1ed5bSDimitry Andric /// such as switch cases need to not include the fall-through counts, so
80159d1ed5bSDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting,
80259d1ed5bSDimitry Andric /// this just calls EmitBlock().
80359d1ed5bSDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
80433956c43SDimitry Andric                                                const Stmt *S) {
80559d1ed5bSDimitry Andric   llvm::BasicBlock *SkipCountBB = nullptr;
80659d1ed5bSDimitry Andric   if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
80759d1ed5bSDimitry Andric     // When instrumenting for profiling, the fallthrough to certain
80859d1ed5bSDimitry Andric     // statements needs to skip over the instrumentation code so that we
80959d1ed5bSDimitry Andric     // get an accurate count.
81059d1ed5bSDimitry Andric     SkipCountBB = createBasicBlock("skipcount");
81159d1ed5bSDimitry Andric     EmitBranch(SkipCountBB);
81259d1ed5bSDimitry Andric   }
81359d1ed5bSDimitry Andric   EmitBlock(BB);
81433956c43SDimitry Andric   uint64_t CurrentCount = getCurrentProfileCount();
81533956c43SDimitry Andric   incrementProfileCounter(S);
81633956c43SDimitry Andric   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
81759d1ed5bSDimitry Andric   if (SkipCountBB)
81859d1ed5bSDimitry Andric     EmitBlock(SkipCountBB);
81959d1ed5bSDimitry Andric }
82059d1ed5bSDimitry Andric 
821e580952dSDimitry Andric /// Tries to mark the given function nounwind based on the
822e580952dSDimitry Andric /// non-existence of any throwing calls within it.  We believe this is
823e580952dSDimitry Andric /// lightweight enough to do at -O0.
824e580952dSDimitry Andric static void TryMarkNoThrow(llvm::Function *F) {
825e580952dSDimitry Andric   // LLVM treats 'nounwind' on a function as part of the type, so we
826e580952dSDimitry Andric   // can't do this on functions that can be overwritten.
827e580952dSDimitry Andric   if (F->mayBeOverridden()) return;
828e580952dSDimitry Andric 
829e580952dSDimitry Andric   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
830e580952dSDimitry Andric     for (llvm::BasicBlock::iterator
831e580952dSDimitry Andric            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
8326122f3e6SDimitry Andric       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
833e580952dSDimitry Andric         if (!Call->doesNotThrow())
834e580952dSDimitry Andric           return;
8356122f3e6SDimitry Andric       } else if (isa<llvm::ResumeInst>(&*BI)) {
8366122f3e6SDimitry Andric         return;
8376122f3e6SDimitry Andric       }
8383861d79fSDimitry Andric   F->setDoesNotThrow();
839e580952dSDimitry Andric }
840e580952dSDimitry Andric 
8413b0f4066SDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
8423b0f4066SDimitry Andric                                    const CGFunctionInfo &FnInfo) {
843f22ef01cSRoman Divacky   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
844f22ef01cSRoman Divacky 
845f22ef01cSRoman Divacky   // Check if we should generate debug info for this function.
846f785676fSDimitry Andric   if (FD->hasAttr<NoDebugAttr>())
84759d1ed5bSDimitry Andric     DebugInfo = nullptr; // disable debug info indefinitely for this function
848f22ef01cSRoman Divacky 
849f22ef01cSRoman Divacky   FunctionArgList Args;
85059d1ed5bSDimitry Andric   QualType ResTy = FD->getReturnType();
851f22ef01cSRoman Divacky 
852f22ef01cSRoman Divacky   CurGD = GD;
85359d1ed5bSDimitry Andric   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
85459d1ed5bSDimitry Andric   if (MD && MD->isInstance()) {
855f785676fSDimitry Andric     if (CGM.getCXXABI().HasThisReturn(GD))
856f785676fSDimitry Andric       ResTy = MD->getThisType(getContext());
85739d628a0SDimitry Andric     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
85839d628a0SDimitry Andric       ResTy = CGM.getContext().VoidPtrTy;
85959d1ed5bSDimitry Andric     CGM.getCXXABI().buildThisParam(*this, Args);
860f785676fSDimitry Andric   }
861f22ef01cSRoman Divacky 
86239d628a0SDimitry Andric   Args.append(FD->param_begin(), FD->param_end());
863f22ef01cSRoman Divacky 
86459d1ed5bSDimitry Andric   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
86559d1ed5bSDimitry Andric     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
86659d1ed5bSDimitry Andric 
867f22ef01cSRoman Divacky   SourceRange BodyRange;
868f22ef01cSRoman Divacky   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
869f785676fSDimitry Andric   CurEHLocation = BodyRange.getEnd();
870139f7f9bSDimitry Andric 
87159d1ed5bSDimitry Andric   // Use the location of the start of the function to determine where
87259d1ed5bSDimitry Andric   // the function definition is located. By default use the location
87359d1ed5bSDimitry Andric   // of the declaration as the location for the subprogram. A function
87459d1ed5bSDimitry Andric   // may lack a declaration in the source code if it is created by code
87559d1ed5bSDimitry Andric   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
87659d1ed5bSDimitry Andric   SourceLocation Loc = FD->getLocation();
87759d1ed5bSDimitry Andric 
87859d1ed5bSDimitry Andric   // If this is a function specialization then use the pattern body
87959d1ed5bSDimitry Andric   // as the location for the function.
88059d1ed5bSDimitry Andric   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
88159d1ed5bSDimitry Andric     if (SpecDecl->hasBody(SpecDecl))
88259d1ed5bSDimitry Andric       Loc = SpecDecl->getLocation();
88359d1ed5bSDimitry Andric 
884f22ef01cSRoman Divacky   // Emit the standard function prologue.
88559d1ed5bSDimitry Andric   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
886f22ef01cSRoman Divacky 
887f22ef01cSRoman Divacky   // Generate the body of the function.
88839d628a0SDimitry Andric   PGO.checkGlobalDecl(GD);
88959d1ed5bSDimitry Andric   PGO.assignRegionCounters(GD.getDecl(), CurFn);
890f22ef01cSRoman Divacky   if (isa<CXXDestructorDecl>(FD))
891f22ef01cSRoman Divacky     EmitDestructorBody(Args);
892f22ef01cSRoman Divacky   else if (isa<CXXConstructorDecl>(FD))
893f22ef01cSRoman Divacky     EmitConstructorBody(Args);
8943861d79fSDimitry Andric   else if (getLangOpts().CUDA &&
89533956c43SDimitry Andric            !getLangOpts().CUDAIsDevice &&
8966122f3e6SDimitry Andric            FD->hasAttr<CUDAGlobalAttr>())
89733956c43SDimitry Andric     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
898dff0c46cSDimitry Andric   else if (isa<CXXConversionDecl>(FD) &&
899dff0c46cSDimitry Andric            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
900dff0c46cSDimitry Andric     // The lambda conversion to block pointer is special; the semantics can't be
901dff0c46cSDimitry Andric     // expressed in the AST, so IRGen needs to special-case it.
902dff0c46cSDimitry Andric     EmitLambdaToBlockPointerBody(Args);
903dff0c46cSDimitry Andric   } else if (isa<CXXMethodDecl>(FD) &&
904dff0c46cSDimitry Andric              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
905f785676fSDimitry Andric     // The lambda static invoker function is special, because it forwards or
906dff0c46cSDimitry Andric     // clones the body of the function call operator (but is actually static).
907dff0c46cSDimitry Andric     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
908139f7f9bSDimitry Andric   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
909f785676fSDimitry Andric              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
910f785676fSDimitry Andric               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
911139f7f9bSDimitry Andric     // Implicit copy-assignment gets the same special treatment as implicit
912139f7f9bSDimitry Andric     // copy-constructors.
913139f7f9bSDimitry Andric     emitImplicitAssignmentOperatorBody(Args);
914f785676fSDimitry Andric   } else if (Stmt *Body = FD->getBody()) {
915f785676fSDimitry Andric     EmitFunctionBody(Args, Body);
916f785676fSDimitry Andric   } else
917f785676fSDimitry Andric     llvm_unreachable("no definition for emitted function");
918f22ef01cSRoman Divacky 
9193861d79fSDimitry Andric   // C++11 [stmt.return]p2:
9203861d79fSDimitry Andric   //   Flowing off the end of a function [...] results in undefined behavior in
9213861d79fSDimitry Andric   //   a value-returning function.
9223861d79fSDimitry Andric   // C11 6.9.1p12:
9233861d79fSDimitry Andric   //   If the '}' that terminates a function is reached, and the value of the
9243861d79fSDimitry Andric   //   function call is used by the caller, the behavior is undefined.
92539d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
92659d1ed5bSDimitry Andric       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
92739d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::Return)) {
92859d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
92939d628a0SDimitry Andric       llvm::Value *IsFalse = Builder.getFalse();
93039d628a0SDimitry Andric       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
93139d628a0SDimitry Andric                 "missing_return", EmitCheckSourceLocation(FD->getLocation()),
93239d628a0SDimitry Andric                 None);
9333dac3a9bSDimitry Andric     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
9343dac3a9bSDimitry Andric       EmitTrapCall(llvm::Intrinsic::trap);
9353dac3a9bSDimitry Andric     }
9363861d79fSDimitry Andric     Builder.CreateUnreachable();
9373861d79fSDimitry Andric     Builder.ClearInsertionPoint();
9383861d79fSDimitry Andric   }
9393861d79fSDimitry Andric 
940f22ef01cSRoman Divacky   // Emit the standard function epilogue.
941f22ef01cSRoman Divacky   FinishFunction(BodyRange.getEnd());
942f22ef01cSRoman Divacky 
943e580952dSDimitry Andric   // If we haven't marked the function nothrow through other means, do
944e580952dSDimitry Andric   // a quick pass now to see if we can.
945e580952dSDimitry Andric   if (!CurFn->doesNotThrow())
946e580952dSDimitry Andric     TryMarkNoThrow(CurFn);
947f22ef01cSRoman Divacky }
948f22ef01cSRoman Divacky 
949f22ef01cSRoman Divacky /// ContainsLabel - Return true if the statement contains a label in it.  If
950f22ef01cSRoman Divacky /// this statement is not executed normally, it not containing a label means
951f22ef01cSRoman Divacky /// that we can just remove the code.
952f22ef01cSRoman Divacky bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
953f22ef01cSRoman Divacky   // Null statement, not a label!
95459d1ed5bSDimitry Andric   if (!S) return false;
955f22ef01cSRoman Divacky 
956f22ef01cSRoman Divacky   // If this is a label, we have to emit the code, consider something like:
957f22ef01cSRoman Divacky   // if (0) {  ...  foo:  bar(); }  goto foo;
9583b0f4066SDimitry Andric   //
9593b0f4066SDimitry Andric   // TODO: If anyone cared, we could track __label__'s, since we know that you
9603b0f4066SDimitry Andric   // can't jump to one from outside their declared region.
961f22ef01cSRoman Divacky   if (isa<LabelStmt>(S))
962f22ef01cSRoman Divacky     return true;
963f22ef01cSRoman Divacky 
964f22ef01cSRoman Divacky   // If this is a case/default statement, and we haven't seen a switch, we have
965f22ef01cSRoman Divacky   // to emit the code.
966f22ef01cSRoman Divacky   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
967f22ef01cSRoman Divacky     return true;
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky   // If this is a switch statement, we want to ignore cases below it.
970f22ef01cSRoman Divacky   if (isa<SwitchStmt>(S))
971f22ef01cSRoman Divacky     IgnoreCaseStmts = true;
972f22ef01cSRoman Divacky 
973f22ef01cSRoman Divacky   // Scan subexpressions for verboten labels.
9743dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
9753dac3a9bSDimitry Andric     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
976f22ef01cSRoman Divacky       return true;
977f22ef01cSRoman Divacky 
978f22ef01cSRoman Divacky   return false;
979f22ef01cSRoman Divacky }
980f22ef01cSRoman Divacky 
9813b0f4066SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it.
9823b0f4066SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break
9833b0f4066SDimitry Andric /// inside of it, this is fine.
9843b0f4066SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) {
9853b0f4066SDimitry Andric   // Null statement, not a label!
98659d1ed5bSDimitry Andric   if (!S) return false;
987f22ef01cSRoman Divacky 
9883b0f4066SDimitry Andric   // If this is a switch or loop that defines its own break scope, then we can
9893b0f4066SDimitry Andric   // include it and anything inside of it.
9903b0f4066SDimitry Andric   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
9913b0f4066SDimitry Andric       isa<ForStmt>(S))
9923b0f4066SDimitry Andric     return false;
9933b0f4066SDimitry Andric 
9943b0f4066SDimitry Andric   if (isa<BreakStmt>(S))
9953b0f4066SDimitry Andric     return true;
9963b0f4066SDimitry Andric 
9973b0f4066SDimitry Andric   // Scan subexpressions for verboten breaks.
9983dac3a9bSDimitry Andric   for (const Stmt *SubStmt : S->children())
9993dac3a9bSDimitry Andric     if (containsBreak(SubStmt))
10003b0f4066SDimitry Andric       return true;
10013b0f4066SDimitry Andric 
10023b0f4066SDimitry Andric   return false;
10033b0f4066SDimitry Andric }
10043b0f4066SDimitry Andric 
10053b0f4066SDimitry Andric 
10063b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
10073b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
10083b0f4066SDimitry Andric /// constant folds return true and set the boolean result in Result.
10093b0f4066SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
10103b0f4066SDimitry Andric                                                    bool &ResultBool) {
10117ae0e2c9SDimitry Andric   llvm::APSInt ResultInt;
10123b0f4066SDimitry Andric   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
10133b0f4066SDimitry Andric     return false;
10143b0f4066SDimitry Andric 
10153b0f4066SDimitry Andric   ResultBool = ResultInt.getBoolValue();
10163b0f4066SDimitry Andric   return true;
10173b0f4066SDimitry Andric }
10183b0f4066SDimitry Andric 
10193b0f4066SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
10203b0f4066SDimitry Andric /// to a constant, or if it does but contains a label, return false.  If it
10213b0f4066SDimitry Andric /// constant folds return true and set the folded value.
10223b0f4066SDimitry Andric bool CodeGenFunction::
10237ae0e2c9SDimitry Andric ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
1024f22ef01cSRoman Divacky   // FIXME: Rename and handle conversion of other evaluatable things
1025f22ef01cSRoman Divacky   // to bool.
1026dff0c46cSDimitry Andric   llvm::APSInt Int;
1027dff0c46cSDimitry Andric   if (!Cond->EvaluateAsInt(Int, getContext()))
10283b0f4066SDimitry Andric     return false;  // Not foldable, not integer or not fully evaluatable.
1029f22ef01cSRoman Divacky 
1030f22ef01cSRoman Divacky   if (CodeGenFunction::ContainsLabel(Cond))
10313b0f4066SDimitry Andric     return false;  // Contains a label.
1032f22ef01cSRoman Divacky 
1033dff0c46cSDimitry Andric   ResultInt = Int;
10343b0f4066SDimitry Andric   return true;
1035f22ef01cSRoman Divacky }
1036f22ef01cSRoman Divacky 
1037f22ef01cSRoman Divacky 
10383b0f4066SDimitry Andric 
1039f22ef01cSRoman Divacky /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1040f22ef01cSRoman Divacky /// statement) to the specified blocks.  Based on the condition, this might try
1041f22ef01cSRoman Divacky /// to simplify the codegen of the conditional based on the branch.
1042f22ef01cSRoman Divacky ///
1043f22ef01cSRoman Divacky void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1044f22ef01cSRoman Divacky                                            llvm::BasicBlock *TrueBlock,
104559d1ed5bSDimitry Andric                                            llvm::BasicBlock *FalseBlock,
104659d1ed5bSDimitry Andric                                            uint64_t TrueCount) {
10473b0f4066SDimitry Andric   Cond = Cond->IgnoreParens();
1048f22ef01cSRoman Divacky 
1049f22ef01cSRoman Divacky   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
105059d1ed5bSDimitry Andric 
1051f22ef01cSRoman Divacky     // Handle X && Y in a condition.
1052e580952dSDimitry Andric     if (CondBOp->getOpcode() == BO_LAnd) {
1053f22ef01cSRoman Divacky       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1054f22ef01cSRoman Divacky       // folded if the case was simple enough.
10553b0f4066SDimitry Andric       bool ConstantBool = false;
10563b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
10573b0f4066SDimitry Andric           ConstantBool) {
1058f22ef01cSRoman Divacky         // br(1 && X) -> br(X).
105933956c43SDimitry Andric         incrementProfileCounter(CondBOp);
106059d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
106159d1ed5bSDimitry Andric                                     TrueCount);
1062f22ef01cSRoman Divacky       }
1063f22ef01cSRoman Divacky 
1064f22ef01cSRoman Divacky       // If we have "X && 1", simplify the code to use an uncond branch.
1065f22ef01cSRoman Divacky       // "X && 0" would have been constant folded to 0.
10663b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
10673b0f4066SDimitry Andric           ConstantBool) {
1068f22ef01cSRoman Divacky         // br(X && 1) -> br(X).
106959d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
107059d1ed5bSDimitry Andric                                     TrueCount);
1071f22ef01cSRoman Divacky       }
1072f22ef01cSRoman Divacky 
1073f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1074f22ef01cSRoman Divacky       // want to jump to the FalseBlock.
1075f22ef01cSRoman Divacky       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
107659d1ed5bSDimitry Andric       // The counter tells us how often we evaluate RHS, and all of TrueCount
107759d1ed5bSDimitry Andric       // can be propagated to that branch.
107833956c43SDimitry Andric       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
10792754fe60SDimitry Andric 
10802754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
108133956c43SDimitry Andric       {
108233956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
108359d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1084f22ef01cSRoman Divacky         EmitBlock(LHSTrue);
108533956c43SDimitry Andric       }
108633956c43SDimitry Andric 
108733956c43SDimitry Andric       incrementProfileCounter(CondBOp);
108833956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1089f22ef01cSRoman Divacky 
1090f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
10912754fe60SDimitry Andric       eval.begin(*this);
109259d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
10932754fe60SDimitry Andric       eval.end(*this);
1094f22ef01cSRoman Divacky 
1095f22ef01cSRoman Divacky       return;
10963b0f4066SDimitry Andric     }
10973b0f4066SDimitry Andric 
10983b0f4066SDimitry Andric     if (CondBOp->getOpcode() == BO_LOr) {
1099f22ef01cSRoman Divacky       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1100f22ef01cSRoman Divacky       // folded if the case was simple enough.
11013b0f4066SDimitry Andric       bool ConstantBool = false;
11023b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
11033b0f4066SDimitry Andric           !ConstantBool) {
1104f22ef01cSRoman Divacky         // br(0 || X) -> br(X).
110533956c43SDimitry Andric         incrementProfileCounter(CondBOp);
110659d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
110759d1ed5bSDimitry Andric                                     TrueCount);
1108f22ef01cSRoman Divacky       }
1109f22ef01cSRoman Divacky 
1110f22ef01cSRoman Divacky       // If we have "X || 0", simplify the code to use an uncond branch.
1111f22ef01cSRoman Divacky       // "X || 1" would have been constant folded to 1.
11123b0f4066SDimitry Andric       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
11133b0f4066SDimitry Andric           !ConstantBool) {
1114f22ef01cSRoman Divacky         // br(X || 0) -> br(X).
111559d1ed5bSDimitry Andric         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
111659d1ed5bSDimitry Andric                                     TrueCount);
1117f22ef01cSRoman Divacky       }
1118f22ef01cSRoman Divacky 
1119f22ef01cSRoman Divacky       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1120f22ef01cSRoman Divacky       // want to jump to the TrueBlock.
1121f22ef01cSRoman Divacky       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
112259d1ed5bSDimitry Andric       // We have the count for entry to the RHS and for the whole expression
112359d1ed5bSDimitry Andric       // being true, so we can divy up True count between the short circuit and
112459d1ed5bSDimitry Andric       // the RHS.
112533956c43SDimitry Andric       uint64_t LHSCount =
112633956c43SDimitry Andric           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
112759d1ed5bSDimitry Andric       uint64_t RHSCount = TrueCount - LHSCount;
11282754fe60SDimitry Andric 
11292754fe60SDimitry Andric       ConditionalEvaluation eval(*this);
113033956c43SDimitry Andric       {
113133956c43SDimitry Andric         ApplyDebugLocation DL(*this, Cond);
113259d1ed5bSDimitry Andric         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1133f22ef01cSRoman Divacky         EmitBlock(LHSFalse);
113433956c43SDimitry Andric       }
113533956c43SDimitry Andric 
113633956c43SDimitry Andric       incrementProfileCounter(CondBOp);
113733956c43SDimitry Andric       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1138f22ef01cSRoman Divacky 
1139f22ef01cSRoman Divacky       // Any temporaries created here are conditional.
11402754fe60SDimitry Andric       eval.begin(*this);
114159d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
114259d1ed5bSDimitry Andric 
11432754fe60SDimitry Andric       eval.end(*this);
1144f22ef01cSRoman Divacky 
1145f22ef01cSRoman Divacky       return;
1146f22ef01cSRoman Divacky     }
1147f22ef01cSRoman Divacky   }
1148f22ef01cSRoman Divacky 
1149f22ef01cSRoman Divacky   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1150f22ef01cSRoman Divacky     // br(!x, t, f) -> br(x, f, t)
115159d1ed5bSDimitry Andric     if (CondUOp->getOpcode() == UO_LNot) {
115259d1ed5bSDimitry Andric       // Negate the count.
115333956c43SDimitry Andric       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
115459d1ed5bSDimitry Andric       // Negate the condition and swap the destination blocks.
115559d1ed5bSDimitry Andric       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
115659d1ed5bSDimitry Andric                                   FalseCount);
115759d1ed5bSDimitry Andric     }
1158f22ef01cSRoman Divacky   }
1159f22ef01cSRoman Divacky 
1160f22ef01cSRoman Divacky   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1161f22ef01cSRoman Divacky     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1162f22ef01cSRoman Divacky     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1163f22ef01cSRoman Divacky     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
11642754fe60SDimitry Andric 
11652754fe60SDimitry Andric     ConditionalEvaluation cond(*this);
116633956c43SDimitry Andric     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
116733956c43SDimitry Andric                          getProfileCount(CondOp));
116859d1ed5bSDimitry Andric 
116959d1ed5bSDimitry Andric     // When computing PGO branch weights, we only know the overall count for
117059d1ed5bSDimitry Andric     // the true block. This code is essentially doing tail duplication of the
117159d1ed5bSDimitry Andric     // naive code-gen, introducing new edges for which counts are not
117259d1ed5bSDimitry Andric     // available. Divide the counts proportionally between the LHS and RHS of
117359d1ed5bSDimitry Andric     // the conditional operator.
117459d1ed5bSDimitry Andric     uint64_t LHSScaledTrueCount = 0;
117559d1ed5bSDimitry Andric     if (TrueCount) {
117633956c43SDimitry Andric       double LHSRatio =
117733956c43SDimitry Andric           getProfileCount(CondOp) / (double)getCurrentProfileCount();
117859d1ed5bSDimitry Andric       LHSScaledTrueCount = TrueCount * LHSRatio;
117959d1ed5bSDimitry Andric     }
11802754fe60SDimitry Andric 
11812754fe60SDimitry Andric     cond.begin(*this);
1182f22ef01cSRoman Divacky     EmitBlock(LHSBlock);
118333956c43SDimitry Andric     incrementProfileCounter(CondOp);
118433956c43SDimitry Andric     {
118533956c43SDimitry Andric       ApplyDebugLocation DL(*this, Cond);
118659d1ed5bSDimitry Andric       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
118759d1ed5bSDimitry Andric                            LHSScaledTrueCount);
118833956c43SDimitry Andric     }
11892754fe60SDimitry Andric     cond.end(*this);
11902754fe60SDimitry Andric 
11912754fe60SDimitry Andric     cond.begin(*this);
1192f22ef01cSRoman Divacky     EmitBlock(RHSBlock);
119359d1ed5bSDimitry Andric     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
119459d1ed5bSDimitry Andric                          TrueCount - LHSScaledTrueCount);
11952754fe60SDimitry Andric     cond.end(*this);
11962754fe60SDimitry Andric 
1197f22ef01cSRoman Divacky     return;
1198f22ef01cSRoman Divacky   }
1199f22ef01cSRoman Divacky 
1200284c1978SDimitry Andric   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1201284c1978SDimitry Andric     // Conditional operator handling can give us a throw expression as a
1202284c1978SDimitry Andric     // condition for a case like:
1203284c1978SDimitry Andric     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1204284c1978SDimitry Andric     // Fold this to:
1205284c1978SDimitry Andric     //   br(c, throw x, br(y, t, f))
1206284c1978SDimitry Andric     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1207284c1978SDimitry Andric     return;
1208284c1978SDimitry Andric   }
1209284c1978SDimitry Andric 
121059d1ed5bSDimitry Andric   // Create branch weights based on the number of times we get here and the
121159d1ed5bSDimitry Andric   // number of times the condition should be true.
121233956c43SDimitry Andric   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
121333956c43SDimitry Andric   llvm::MDNode *Weights =
121433956c43SDimitry Andric       createProfileWeights(TrueCount, CurrentCount - TrueCount);
121559d1ed5bSDimitry Andric 
1216f22ef01cSRoman Divacky   // Emit the code with the fully general case.
121733956c43SDimitry Andric   llvm::Value *CondV;
121833956c43SDimitry Andric   {
121933956c43SDimitry Andric     ApplyDebugLocation DL(*this, Cond);
122033956c43SDimitry Andric     CondV = EvaluateExprAsBool(Cond);
122133956c43SDimitry Andric   }
122259d1ed5bSDimitry Andric   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
1223f22ef01cSRoman Divacky }
1224f22ef01cSRoman Divacky 
1225f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
1226f22ef01cSRoman Divacky /// specified stmt yet.
1227f785676fSDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1228f785676fSDimitry Andric   CGM.ErrorUnsupported(S, Type);
1229f22ef01cSRoman Divacky }
1230f22ef01cSRoman Divacky 
12312754fe60SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a
12322754fe60SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern.
12332754fe60SDimitry Andric ///
12347ae0e2c9SDimitry Andric /// \param baseType the inner-most element type of the array
12352754fe60SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single
12362754fe60SDimitry Andric /// base element of the array
12372754fe60SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars
12382754fe60SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
12392754fe60SDimitry Andric                                llvm::Value *dest, llvm::Value *src,
12402754fe60SDimitry Andric                                llvm::Value *sizeInChars) {
12412754fe60SDimitry Andric   std::pair<CharUnits,CharUnits> baseSizeAndAlign
12422754fe60SDimitry Andric     = CGF.getContext().getTypeInfoInChars(baseType);
12432754fe60SDimitry Andric 
12442754fe60SDimitry Andric   CGBuilderTy &Builder = CGF.Builder;
12452754fe60SDimitry Andric 
12462754fe60SDimitry Andric   llvm::Value *baseSizeInChars
12472754fe60SDimitry Andric     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
12482754fe60SDimitry Andric 
12496122f3e6SDimitry Andric   llvm::Type *i8p = Builder.getInt8PtrTy();
12502754fe60SDimitry Andric 
12512754fe60SDimitry Andric   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
12522754fe60SDimitry Andric   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
12532754fe60SDimitry Andric 
12542754fe60SDimitry Andric   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
12552754fe60SDimitry Andric   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
12562754fe60SDimitry Andric   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
12572754fe60SDimitry Andric 
12582754fe60SDimitry Andric   // Make a loop over the VLA.  C99 guarantees that the VLA element
12592754fe60SDimitry Andric   // count must be nonzero.
12602754fe60SDimitry Andric   CGF.EmitBlock(loopBB);
12612754fe60SDimitry Andric 
12623b0f4066SDimitry Andric   llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
12632754fe60SDimitry Andric   cur->addIncoming(begin, originBB);
12642754fe60SDimitry Andric 
12652754fe60SDimitry Andric   // memcpy the individual element bit-pattern.
12662754fe60SDimitry Andric   Builder.CreateMemCpy(cur, src, baseSizeInChars,
12672754fe60SDimitry Andric                        baseSizeAndAlign.second.getQuantity(),
12682754fe60SDimitry Andric                        /*volatile*/ false);
12692754fe60SDimitry Andric 
12702754fe60SDimitry Andric   // Go to the next element.
127133956c43SDimitry Andric   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(),
127233956c43SDimitry Andric                                                          cur, 1, "vla.next");
12732754fe60SDimitry Andric 
12742754fe60SDimitry Andric   // Leave if that's the end of the VLA.
12752754fe60SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
12762754fe60SDimitry Andric   Builder.CreateCondBr(done, contBB, loopBB);
12772754fe60SDimitry Andric   cur->addIncoming(next, loopBB);
12782754fe60SDimitry Andric 
12792754fe60SDimitry Andric   CGF.EmitBlock(contBB);
12802754fe60SDimitry Andric }
12812754fe60SDimitry Andric 
1282f22ef01cSRoman Divacky void
1283f22ef01cSRoman Divacky CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
1284f22ef01cSRoman Divacky   // Ignore empty classes in C++.
12853861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1286f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1287f22ef01cSRoman Divacky       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1288f22ef01cSRoman Divacky         return;
1289f22ef01cSRoman Divacky     }
1290f22ef01cSRoman Divacky   }
1291f22ef01cSRoman Divacky 
1292e580952dSDimitry Andric   // Cast the dest ptr to the appropriate i8 pointer type.
1293e580952dSDimitry Andric   unsigned DestAS =
1294e580952dSDimitry Andric     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
12956122f3e6SDimitry Andric   llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1296f22ef01cSRoman Divacky   if (DestPtr->getType() != BP)
12976122f3e6SDimitry Andric     DestPtr = Builder.CreateBitCast(DestPtr, BP);
1298f22ef01cSRoman Divacky 
1299f22ef01cSRoman Divacky   // Get size and alignment info for this aggregate.
13003b0f4066SDimitry Andric   std::pair<CharUnits, CharUnits> TypeInfo =
13013b0f4066SDimitry Andric     getContext().getTypeInfoInChars(Ty);
13023b0f4066SDimitry Andric   CharUnits Size = TypeInfo.first;
13033b0f4066SDimitry Andric   CharUnits Align = TypeInfo.second;
13042754fe60SDimitry Andric 
13052754fe60SDimitry Andric   llvm::Value *SizeVal;
13062754fe60SDimitry Andric   const VariableArrayType *vla;
1307f22ef01cSRoman Divacky 
1308f22ef01cSRoman Divacky   // Don't bother emitting a zero-byte memset.
13093b0f4066SDimitry Andric   if (Size.isZero()) {
13102754fe60SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
13112754fe60SDimitry Andric     if (const VariableArrayType *vlaType =
13122754fe60SDimitry Andric           dyn_cast_or_null<VariableArrayType>(
13132754fe60SDimitry Andric                                           getContext().getAsArrayType(Ty))) {
131417a519f9SDimitry Andric       QualType eltType;
131517a519f9SDimitry Andric       llvm::Value *numElts;
131659d1ed5bSDimitry Andric       std::tie(numElts, eltType) = getVLASize(vlaType);
131717a519f9SDimitry Andric 
131817a519f9SDimitry Andric       SizeVal = numElts;
131917a519f9SDimitry Andric       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
132017a519f9SDimitry Andric       if (!eltSize.isOne())
132117a519f9SDimitry Andric         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
13222754fe60SDimitry Andric       vla = vlaType;
13232754fe60SDimitry Andric     } else {
1324f22ef01cSRoman Divacky       return;
13252754fe60SDimitry Andric     }
13262754fe60SDimitry Andric   } else {
132717a519f9SDimitry Andric     SizeVal = CGM.getSize(Size);
132859d1ed5bSDimitry Andric     vla = nullptr;
13292754fe60SDimitry Andric   }
1330e580952dSDimitry Andric 
1331e580952dSDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
1332e580952dSDimitry Andric   // Instead, create a null constant and copy it to the destination.
13332754fe60SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
13342754fe60SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
1335e580952dSDimitry Andric   if (!CGM.getTypes().isZeroInitializable(Ty)) {
13362754fe60SDimitry Andric     // For a VLA, emit a single element, then splat that over the VLA.
13372754fe60SDimitry Andric     if (vla) Ty = getContext().getBaseElementType(vla);
13382754fe60SDimitry Andric 
1339e580952dSDimitry Andric     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1340e580952dSDimitry Andric 
1341e580952dSDimitry Andric     llvm::GlobalVariable *NullVariable =
1342e580952dSDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1343e580952dSDimitry Andric                                /*isConstant=*/true,
1344e580952dSDimitry Andric                                llvm::GlobalVariable::PrivateLinkage,
13456122f3e6SDimitry Andric                                NullConstant, Twine());
1346e580952dSDimitry Andric     llvm::Value *SrcPtr =
1347e580952dSDimitry Andric       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1348e580952dSDimitry Andric 
13492754fe60SDimitry Andric     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1350e580952dSDimitry Andric 
1351e580952dSDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
13523b0f4066SDimitry Andric     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1353e580952dSDimitry Andric     return;
1354e580952dSDimitry Andric   }
1355e580952dSDimitry Andric 
1356e580952dSDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
1357e580952dSDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
1358e580952dSDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
13593b0f4066SDimitry Andric   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
13603b0f4066SDimitry Andric                        Align.getQuantity(), false);
1361f22ef01cSRoman Divacky }
1362f22ef01cSRoman Divacky 
13632754fe60SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1364f22ef01cSRoman Divacky   // Make sure that there is a block for the indirect goto.
136559d1ed5bSDimitry Andric   if (!IndirectBranch)
1366f22ef01cSRoman Divacky     GetIndirectGotoBlock();
1367f22ef01cSRoman Divacky 
1368e580952dSDimitry Andric   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1369f22ef01cSRoman Divacky 
1370f22ef01cSRoman Divacky   // Make sure the indirect branch includes all of the address-taken blocks.
1371f22ef01cSRoman Divacky   IndirectBranch->addDestination(BB);
1372f22ef01cSRoman Divacky   return llvm::BlockAddress::get(CurFn, BB);
1373f22ef01cSRoman Divacky }
1374f22ef01cSRoman Divacky 
1375f22ef01cSRoman Divacky llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1376f22ef01cSRoman Divacky   // If we already made the indirect branch for indirect goto, return its block.
1377f22ef01cSRoman Divacky   if (IndirectBranch) return IndirectBranch->getParent();
1378f22ef01cSRoman Divacky 
1379f22ef01cSRoman Divacky   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1380f22ef01cSRoman Divacky 
1381f22ef01cSRoman Divacky   // Create the PHI node that indirect gotos will add entries to.
13823b0f4066SDimitry Andric   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
13833b0f4066SDimitry Andric                                               "indirect.goto.dest");
1384f22ef01cSRoman Divacky 
1385f22ef01cSRoman Divacky   // Create the indirect branch instruction.
1386f22ef01cSRoman Divacky   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1387f22ef01cSRoman Divacky   return IndirectBranch->getParent();
1388f22ef01cSRoman Divacky }
1389f22ef01cSRoman Divacky 
139017a519f9SDimitry Andric /// Computes the length of an array in elements, as well as the base
139117a519f9SDimitry Andric /// element type and a properly-typed first element pointer.
139217a519f9SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
139317a519f9SDimitry Andric                                               QualType &baseType,
139417a519f9SDimitry Andric                                               llvm::Value *&addr) {
139517a519f9SDimitry Andric   const ArrayType *arrayType = origArrayType;
1396f22ef01cSRoman Divacky 
139717a519f9SDimitry Andric   // If it's a VLA, we have to load the stored size.  Note that
139817a519f9SDimitry Andric   // this is the size of the VLA in bytes, not its size in elements.
139959d1ed5bSDimitry Andric   llvm::Value *numVLAElements = nullptr;
140017a519f9SDimitry Andric   if (isa<VariableArrayType>(arrayType)) {
140117a519f9SDimitry Andric     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
140217a519f9SDimitry Andric 
140317a519f9SDimitry Andric     // Walk into all VLAs.  This doesn't require changes to addr,
140417a519f9SDimitry Andric     // which has type T* where T is the first non-VLA element type.
140517a519f9SDimitry Andric     do {
140617a519f9SDimitry Andric       QualType elementType = arrayType->getElementType();
140717a519f9SDimitry Andric       arrayType = getContext().getAsArrayType(elementType);
140817a519f9SDimitry Andric 
140917a519f9SDimitry Andric       // If we only have VLA components, 'addr' requires no adjustment.
141017a519f9SDimitry Andric       if (!arrayType) {
141117a519f9SDimitry Andric         baseType = elementType;
141217a519f9SDimitry Andric         return numVLAElements;
141317a519f9SDimitry Andric       }
141417a519f9SDimitry Andric     } while (isa<VariableArrayType>(arrayType));
141517a519f9SDimitry Andric 
141617a519f9SDimitry Andric     // We get out here only if we find a constant array type
141717a519f9SDimitry Andric     // inside the VLA.
1418f22ef01cSRoman Divacky   }
1419f22ef01cSRoman Divacky 
142017a519f9SDimitry Andric   // We have some number of constant-length arrays, so addr should
142117a519f9SDimitry Andric   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
142217a519f9SDimitry Andric   // down to the first element of addr.
14236122f3e6SDimitry Andric   SmallVector<llvm::Value*, 8> gepIndices;
142417a519f9SDimitry Andric 
142517a519f9SDimitry Andric   // GEP down to the array type.
142617a519f9SDimitry Andric   llvm::ConstantInt *zero = Builder.getInt32(0);
142717a519f9SDimitry Andric   gepIndices.push_back(zero);
142817a519f9SDimitry Andric 
142917a519f9SDimitry Andric   uint64_t countFromCLAs = 1;
14307ae0e2c9SDimitry Andric   QualType eltType;
143117a519f9SDimitry Andric 
14326122f3e6SDimitry Andric   llvm::ArrayType *llvmArrayType =
14337ae0e2c9SDimitry Andric     dyn_cast<llvm::ArrayType>(
143417a519f9SDimitry Andric       cast<llvm::PointerType>(addr->getType())->getElementType());
14357ae0e2c9SDimitry Andric   while (llvmArrayType) {
143617a519f9SDimitry Andric     assert(isa<ConstantArrayType>(arrayType));
143717a519f9SDimitry Andric     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
143817a519f9SDimitry Andric              == llvmArrayType->getNumElements());
143917a519f9SDimitry Andric 
144017a519f9SDimitry Andric     gepIndices.push_back(zero);
144117a519f9SDimitry Andric     countFromCLAs *= llvmArrayType->getNumElements();
14427ae0e2c9SDimitry Andric     eltType = arrayType->getElementType();
144317a519f9SDimitry Andric 
144417a519f9SDimitry Andric     llvmArrayType =
144517a519f9SDimitry Andric       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
144617a519f9SDimitry Andric     arrayType = getContext().getAsArrayType(arrayType->getElementType());
14477ae0e2c9SDimitry Andric     assert((!llvmArrayType || arrayType) &&
14487ae0e2c9SDimitry Andric            "LLVM and Clang types are out-of-synch");
144917a519f9SDimitry Andric   }
145017a519f9SDimitry Andric 
14517ae0e2c9SDimitry Andric   if (arrayType) {
14527ae0e2c9SDimitry Andric     // From this point onwards, the Clang array type has been emitted
14537ae0e2c9SDimitry Andric     // as some other type (probably a packed struct). Compute the array
14547ae0e2c9SDimitry Andric     // size, and just emit the 'begin' expression as a bitcast.
14557ae0e2c9SDimitry Andric     while (arrayType) {
14567ae0e2c9SDimitry Andric       countFromCLAs *=
14577ae0e2c9SDimitry Andric           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
14587ae0e2c9SDimitry Andric       eltType = arrayType->getElementType();
14597ae0e2c9SDimitry Andric       arrayType = getContext().getAsArrayType(eltType);
14607ae0e2c9SDimitry Andric     }
146117a519f9SDimitry Andric 
14623861d79fSDimitry Andric     unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
14637ae0e2c9SDimitry Andric     llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
14647ae0e2c9SDimitry Andric     addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
14657ae0e2c9SDimitry Andric   } else {
146617a519f9SDimitry Andric     // Create the actual GEP.
14676122f3e6SDimitry Andric     addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
14687ae0e2c9SDimitry Andric   }
14697ae0e2c9SDimitry Andric 
14707ae0e2c9SDimitry Andric   baseType = eltType;
147117a519f9SDimitry Andric 
147217a519f9SDimitry Andric   llvm::Value *numElements
147317a519f9SDimitry Andric     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
147417a519f9SDimitry Andric 
147517a519f9SDimitry Andric   // If we had any VLA dimensions, factor them in.
147617a519f9SDimitry Andric   if (numVLAElements)
147717a519f9SDimitry Andric     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
147817a519f9SDimitry Andric 
147917a519f9SDimitry Andric   return numElements;
148017a519f9SDimitry Andric }
148117a519f9SDimitry Andric 
148217a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
148317a519f9SDimitry Andric CodeGenFunction::getVLASize(QualType type) {
148417a519f9SDimitry Andric   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
148517a519f9SDimitry Andric   assert(vla && "type was not a variable array type!");
148617a519f9SDimitry Andric   return getVLASize(vla);
148717a519f9SDimitry Andric }
148817a519f9SDimitry Andric 
148917a519f9SDimitry Andric std::pair<llvm::Value*, QualType>
149017a519f9SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) {
149117a519f9SDimitry Andric   // The number of elements so far; always size_t.
149259d1ed5bSDimitry Andric   llvm::Value *numElements = nullptr;
149317a519f9SDimitry Andric 
149417a519f9SDimitry Andric   QualType elementType;
149517a519f9SDimitry Andric   do {
149617a519f9SDimitry Andric     elementType = type->getElementType();
149717a519f9SDimitry Andric     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
149817a519f9SDimitry Andric     assert(vlaSize && "no size for VLA!");
149917a519f9SDimitry Andric     assert(vlaSize->getType() == SizeTy);
150017a519f9SDimitry Andric 
150117a519f9SDimitry Andric     if (!numElements) {
150217a519f9SDimitry Andric       numElements = vlaSize;
150317a519f9SDimitry Andric     } else {
150417a519f9SDimitry Andric       // It's undefined behavior if this wraps around, so mark it that way.
150559d1ed5bSDimitry Andric       // FIXME: Teach -fsanitize=undefined to trap this.
150617a519f9SDimitry Andric       numElements = Builder.CreateNUWMul(numElements, vlaSize);
150717a519f9SDimitry Andric     }
150817a519f9SDimitry Andric   } while ((type = getContext().getAsVariableArrayType(elementType)));
150917a519f9SDimitry Andric 
151017a519f9SDimitry Andric   return std::pair<llvm::Value*,QualType>(numElements, elementType);
151117a519f9SDimitry Andric }
151217a519f9SDimitry Andric 
151317a519f9SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
151417a519f9SDimitry Andric   assert(type->isVariablyModifiedType() &&
1515f22ef01cSRoman Divacky          "Must pass variably modified type to EmitVLASizes!");
1516f22ef01cSRoman Divacky 
1517f22ef01cSRoman Divacky   EnsureInsertPoint();
1518f22ef01cSRoman Divacky 
151917a519f9SDimitry Andric   // We're going to walk down into the type and look for VLA
152017a519f9SDimitry Andric   // expressions.
152117a519f9SDimitry Andric   do {
152217a519f9SDimitry Andric     assert(type->isVariablyModifiedType());
1523f22ef01cSRoman Divacky 
152417a519f9SDimitry Andric     const Type *ty = type.getTypePtr();
152517a519f9SDimitry Andric     switch (ty->getTypeClass()) {
1526dff0c46cSDimitry Andric 
152717a519f9SDimitry Andric #define TYPE(Class, Base)
152817a519f9SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
1529dff0c46cSDimitry Andric #define NON_CANONICAL_TYPE(Class, Base)
153017a519f9SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1531dff0c46cSDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
153217a519f9SDimitry Andric #include "clang/AST/TypeNodes.def"
1533dff0c46cSDimitry Andric       llvm_unreachable("unexpected dependent type!");
1534f22ef01cSRoman Divacky 
153517a519f9SDimitry Andric     // These types are never variably-modified.
153617a519f9SDimitry Andric     case Type::Builtin:
153717a519f9SDimitry Andric     case Type::Complex:
153817a519f9SDimitry Andric     case Type::Vector:
153917a519f9SDimitry Andric     case Type::ExtVector:
154017a519f9SDimitry Andric     case Type::Record:
154117a519f9SDimitry Andric     case Type::Enum:
1542dff0c46cSDimitry Andric     case Type::Elaborated:
1543dff0c46cSDimitry Andric     case Type::TemplateSpecialization:
154417a519f9SDimitry Andric     case Type::ObjCObject:
154517a519f9SDimitry Andric     case Type::ObjCInterface:
154617a519f9SDimitry Andric     case Type::ObjCObjectPointer:
154717a519f9SDimitry Andric       llvm_unreachable("type class is never variably-modified!");
1548f22ef01cSRoman Divacky 
154959d1ed5bSDimitry Andric     case Type::Adjusted:
155059d1ed5bSDimitry Andric       type = cast<AdjustedType>(ty)->getAdjustedType();
155159d1ed5bSDimitry Andric       break;
155259d1ed5bSDimitry Andric 
1553f785676fSDimitry Andric     case Type::Decayed:
1554f785676fSDimitry Andric       type = cast<DecayedType>(ty)->getPointeeType();
1555f785676fSDimitry Andric       break;
1556f785676fSDimitry Andric 
155717a519f9SDimitry Andric     case Type::Pointer:
155817a519f9SDimitry Andric       type = cast<PointerType>(ty)->getPointeeType();
155917a519f9SDimitry Andric       break;
1560f22ef01cSRoman Divacky 
156117a519f9SDimitry Andric     case Type::BlockPointer:
156217a519f9SDimitry Andric       type = cast<BlockPointerType>(ty)->getPointeeType();
156317a519f9SDimitry Andric       break;
156417a519f9SDimitry Andric 
156517a519f9SDimitry Andric     case Type::LValueReference:
156617a519f9SDimitry Andric     case Type::RValueReference:
156717a519f9SDimitry Andric       type = cast<ReferenceType>(ty)->getPointeeType();
156817a519f9SDimitry Andric       break;
156917a519f9SDimitry Andric 
157017a519f9SDimitry Andric     case Type::MemberPointer:
157117a519f9SDimitry Andric       type = cast<MemberPointerType>(ty)->getPointeeType();
157217a519f9SDimitry Andric       break;
157317a519f9SDimitry Andric 
157417a519f9SDimitry Andric     case Type::ConstantArray:
157517a519f9SDimitry Andric     case Type::IncompleteArray:
157617a519f9SDimitry Andric       // Losing element qualification here is fine.
157717a519f9SDimitry Andric       type = cast<ArrayType>(ty)->getElementType();
157817a519f9SDimitry Andric       break;
157917a519f9SDimitry Andric 
158017a519f9SDimitry Andric     case Type::VariableArray: {
158117a519f9SDimitry Andric       // Losing element qualification here is fine.
158217a519f9SDimitry Andric       const VariableArrayType *vat = cast<VariableArrayType>(ty);
158317a519f9SDimitry Andric 
158417a519f9SDimitry Andric       // Unknown size indication requires no size computation.
158517a519f9SDimitry Andric       // Otherwise, evaluate and record it.
158617a519f9SDimitry Andric       if (const Expr *size = vat->getSizeExpr()) {
158717a519f9SDimitry Andric         // It's possible that we might have emitted this already,
158817a519f9SDimitry Andric         // e.g. with a typedef and a pointer to it.
158917a519f9SDimitry Andric         llvm::Value *&entry = VLASizeMap[size];
159017a519f9SDimitry Andric         if (!entry) {
15913861d79fSDimitry Andric           llvm::Value *Size = EmitScalarExpr(size);
15923861d79fSDimitry Andric 
15933861d79fSDimitry Andric           // C11 6.7.6.2p5:
15943861d79fSDimitry Andric           //   If the size is an expression that is not an integer constant
15953861d79fSDimitry Andric           //   expression [...] each time it is evaluated it shall have a value
15963861d79fSDimitry Andric           //   greater than zero.
159739d628a0SDimitry Andric           if (SanOpts.has(SanitizerKind::VLABound) &&
15983861d79fSDimitry Andric               size->getType()->isSignedIntegerType()) {
159959d1ed5bSDimitry Andric             SanitizerScope SanScope(this);
16003861d79fSDimitry Andric             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
16013861d79fSDimitry Andric             llvm::Constant *StaticArgs[] = {
16023861d79fSDimitry Andric               EmitCheckSourceLocation(size->getLocStart()),
16033861d79fSDimitry Andric               EmitCheckTypeDescriptor(size->getType())
16043861d79fSDimitry Andric             };
160539d628a0SDimitry Andric             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
160639d628a0SDimitry Andric                                      SanitizerKind::VLABound),
160739d628a0SDimitry Andric                       "vla_bound_not_positive", StaticArgs, Size);
16083861d79fSDimitry Andric           }
16093861d79fSDimitry Andric 
161017a519f9SDimitry Andric           // Always zexting here would be wrong if it weren't
161117a519f9SDimitry Andric           // undefined behavior to have a negative bound.
16123861d79fSDimitry Andric           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
161317a519f9SDimitry Andric         }
161417a519f9SDimitry Andric       }
161517a519f9SDimitry Andric       type = vat->getElementType();
161617a519f9SDimitry Andric       break;
1617f22ef01cSRoman Divacky     }
1618f22ef01cSRoman Divacky 
161917a519f9SDimitry Andric     case Type::FunctionProto:
162017a519f9SDimitry Andric     case Type::FunctionNoProto:
162159d1ed5bSDimitry Andric       type = cast<FunctionType>(ty)->getReturnType();
162217a519f9SDimitry Andric       break;
16236122f3e6SDimitry Andric 
1624dff0c46cSDimitry Andric     case Type::Paren:
1625dff0c46cSDimitry Andric     case Type::TypeOf:
1626dff0c46cSDimitry Andric     case Type::UnaryTransform:
1627dff0c46cSDimitry Andric     case Type::Attributed:
1628dff0c46cSDimitry Andric     case Type::SubstTemplateTypeParm:
1629f785676fSDimitry Andric     case Type::PackExpansion:
1630dff0c46cSDimitry Andric       // Keep walking after single level desugaring.
1631dff0c46cSDimitry Andric       type = type.getSingleStepDesugaredType(getContext());
1632dff0c46cSDimitry Andric       break;
1633dff0c46cSDimitry Andric 
1634dff0c46cSDimitry Andric     case Type::Typedef:
1635dff0c46cSDimitry Andric     case Type::Decltype:
1636dff0c46cSDimitry Andric     case Type::Auto:
1637dff0c46cSDimitry Andric       // Stop walking: nothing to do.
1638dff0c46cSDimitry Andric       return;
1639dff0c46cSDimitry Andric 
1640dff0c46cSDimitry Andric     case Type::TypeOfExpr:
1641dff0c46cSDimitry Andric       // Stop walking: emit typeof expression.
1642dff0c46cSDimitry Andric       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1643dff0c46cSDimitry Andric       return;
1644dff0c46cSDimitry Andric 
16456122f3e6SDimitry Andric     case Type::Atomic:
16466122f3e6SDimitry Andric       type = cast<AtomicType>(ty)->getValueType();
16476122f3e6SDimitry Andric       break;
1648f22ef01cSRoman Divacky     }
164917a519f9SDimitry Andric   } while (type->isVariablyModifiedType());
1650f22ef01cSRoman Divacky }
1651f22ef01cSRoman Divacky 
1652f22ef01cSRoman Divacky llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
16532754fe60SDimitry Andric   if (getContext().getBuiltinVaListType()->isArrayType())
1654f22ef01cSRoman Divacky     return EmitScalarExpr(E);
1655f22ef01cSRoman Divacky   return EmitLValue(E).getAddress();
1656f22ef01cSRoman Divacky }
1657f22ef01cSRoman Divacky 
1658e580952dSDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
16592754fe60SDimitry Andric                                               llvm::Constant *Init) {
1660e580952dSDimitry Andric   assert (Init && "Invalid DeclRefExpr initializer!");
1661e580952dSDimitry Andric   if (CGDebugInfo *Dbg = getDebugInfo())
16623861d79fSDimitry Andric     if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
16632754fe60SDimitry Andric       Dbg->EmitGlobalVariable(E->getDecl(), Init);
16642754fe60SDimitry Andric }
16652754fe60SDimitry Andric 
16662754fe60SDimitry Andric CodeGenFunction::PeepholeProtection
16672754fe60SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) {
16682754fe60SDimitry Andric   // At the moment, the only aggressive peephole we do in IR gen
16692754fe60SDimitry Andric   // is trunc(zext) folding, but if we add more, we can easily
16702754fe60SDimitry Andric   // extend this protection.
16712754fe60SDimitry Andric 
16722754fe60SDimitry Andric   if (!rvalue.isScalar()) return PeepholeProtection();
16732754fe60SDimitry Andric   llvm::Value *value = rvalue.getScalarVal();
16742754fe60SDimitry Andric   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
16752754fe60SDimitry Andric 
16762754fe60SDimitry Andric   // Just make an extra bitcast.
16772754fe60SDimitry Andric   assert(HaveInsertPoint());
16782754fe60SDimitry Andric   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
16792754fe60SDimitry Andric                                                   Builder.GetInsertBlock());
16802754fe60SDimitry Andric 
16812754fe60SDimitry Andric   PeepholeProtection protection;
16822754fe60SDimitry Andric   protection.Inst = inst;
16832754fe60SDimitry Andric   return protection;
16842754fe60SDimitry Andric }
16852754fe60SDimitry Andric 
16862754fe60SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
16872754fe60SDimitry Andric   if (!protection.Inst) return;
16882754fe60SDimitry Andric 
16892754fe60SDimitry Andric   // In theory, we could try to duplicate the peepholes now, but whatever.
16902754fe60SDimitry Andric   protection.Inst->eraseFromParent();
1691e580952dSDimitry Andric }
16926122f3e6SDimitry Andric 
16936122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
16946122f3e6SDimitry Andric                                                  llvm::Value *AnnotatedVal,
1695139f7f9bSDimitry Andric                                                  StringRef AnnotationStr,
16966122f3e6SDimitry Andric                                                  SourceLocation Location) {
16976122f3e6SDimitry Andric   llvm::Value *Args[4] = {
16986122f3e6SDimitry Andric     AnnotatedVal,
16996122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
17006122f3e6SDimitry Andric     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
17016122f3e6SDimitry Andric     CGM.EmitAnnotationLineNo(Location)
17026122f3e6SDimitry Andric   };
17036122f3e6SDimitry Andric   return Builder.CreateCall(AnnotationFn, Args);
17046122f3e6SDimitry Andric }
17056122f3e6SDimitry Andric 
17066122f3e6SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
17076122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
17086122f3e6SDimitry Andric   // FIXME We create a new bitcast for every annotation because that's what
17096122f3e6SDimitry Andric   // llvm-gcc was doing.
171059d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
17116122f3e6SDimitry Andric     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
17126122f3e6SDimitry Andric                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
171359d1ed5bSDimitry Andric                        I->getAnnotation(), D->getLocation());
17146122f3e6SDimitry Andric }
17156122f3e6SDimitry Andric 
17166122f3e6SDimitry Andric llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
17176122f3e6SDimitry Andric                                                    llvm::Value *V) {
17186122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
17196122f3e6SDimitry Andric   llvm::Type *VTy = V->getType();
17206122f3e6SDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
17216122f3e6SDimitry Andric                                     CGM.Int8PtrTy);
17226122f3e6SDimitry Andric 
172359d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
17246122f3e6SDimitry Andric     // FIXME Always emit the cast inst so we can differentiate between
17256122f3e6SDimitry Andric     // annotation on the first field of a struct and annotation on the struct
17266122f3e6SDimitry Andric     // itself.
17276122f3e6SDimitry Andric     if (VTy != CGM.Int8PtrTy)
17286122f3e6SDimitry Andric       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
172959d1ed5bSDimitry Andric     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
17306122f3e6SDimitry Andric     V = Builder.CreateBitCast(V, VTy);
17316122f3e6SDimitry Andric   }
17326122f3e6SDimitry Andric 
17336122f3e6SDimitry Andric   return V;
17346122f3e6SDimitry Andric }
1735f785676fSDimitry Andric 
1736f785676fSDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
173759d1ed5bSDimitry Andric 
173859d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
173959d1ed5bSDimitry Andric     : CGF(CGF) {
174059d1ed5bSDimitry Andric   assert(!CGF->IsSanitizerScope);
174159d1ed5bSDimitry Andric   CGF->IsSanitizerScope = true;
174259d1ed5bSDimitry Andric }
174359d1ed5bSDimitry Andric 
174459d1ed5bSDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() {
174559d1ed5bSDimitry Andric   CGF->IsSanitizerScope = false;
174659d1ed5bSDimitry Andric }
174759d1ed5bSDimitry Andric 
174859d1ed5bSDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I,
174959d1ed5bSDimitry Andric                                    const llvm::Twine &Name,
175059d1ed5bSDimitry Andric                                    llvm::BasicBlock *BB,
175159d1ed5bSDimitry Andric                                    llvm::BasicBlock::iterator InsertPt) const {
175259d1ed5bSDimitry Andric   LoopStack.InsertHelper(I);
175339d628a0SDimitry Andric   if (IsSanitizerScope)
175439d628a0SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
175559d1ed5bSDimitry Andric }
175659d1ed5bSDimitry Andric 
175759d1ed5bSDimitry Andric template <bool PreserveNames>
175859d1ed5bSDimitry Andric void CGBuilderInserter<PreserveNames>::InsertHelper(
175959d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
176059d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const {
176159d1ed5bSDimitry Andric   llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
176259d1ed5bSDimitry Andric                                                               InsertPt);
176359d1ed5bSDimitry Andric   if (CGF)
176459d1ed5bSDimitry Andric     CGF->InsertHelper(I, Name, BB, InsertPt);
176559d1ed5bSDimitry Andric }
176659d1ed5bSDimitry Andric 
176759d1ed5bSDimitry Andric #ifdef NDEBUG
176859d1ed5bSDimitry Andric #define PreserveNames false
176959d1ed5bSDimitry Andric #else
177059d1ed5bSDimitry Andric #define PreserveNames true
177159d1ed5bSDimitry Andric #endif
177259d1ed5bSDimitry Andric template void CGBuilderInserter<PreserveNames>::InsertHelper(
177359d1ed5bSDimitry Andric     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
177459d1ed5bSDimitry Andric     llvm::BasicBlock::iterator InsertPt) const;
177559d1ed5bSDimitry Andric #undef PreserveNames
1776