1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the internal per-function state used for llvm translation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
16 
17 #include "CGBuilder.h"
18 #include "CGDebugInfo.h"
19 #include "CGLoopInfo.h"
20 #include "CGValue.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "EHScopeStack.h"
24 #include "VarBypassDetector.h"
25 #include "clang/AST/CharUnits.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/ABI.h"
31 #include "clang/Basic/CapturedStmt.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Frontend/CodeGenOptions.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Utils/SanitizerStats.h"
41 
42 namespace llvm {
43 class BasicBlock;
44 class LLVMContext;
45 class MDNode;
46 class Module;
47 class SwitchInst;
48 class Twine;
49 class Value;
50 class CallSite;
51 }
52 
53 namespace clang {
54 class ASTContext;
55 class BlockDecl;
56 class CXXDestructorDecl;
57 class CXXForRangeStmt;
58 class CXXTryStmt;
59 class Decl;
60 class LabelDecl;
61 class EnumConstantDecl;
62 class FunctionDecl;
63 class FunctionProtoType;
64 class LabelStmt;
65 class ObjCContainerDecl;
66 class ObjCInterfaceDecl;
67 class ObjCIvarDecl;
68 class ObjCMethodDecl;
69 class ObjCImplementationDecl;
70 class ObjCPropertyImplDecl;
71 class TargetInfo;
72 class VarDecl;
73 class ObjCForCollectionStmt;
74 class ObjCAtTryStmt;
75 class ObjCAtThrowStmt;
76 class ObjCAtSynchronizedStmt;
77 class ObjCAutoreleasePoolStmt;
78 
79 namespace CodeGen {
80 class CodeGenTypes;
81 class CGCallee;
82 class CGFunctionInfo;
83 class CGRecordLayout;
84 class CGBlockInfo;
85 class CGCXXABI;
86 class BlockByrefHelpers;
87 class BlockByrefInfo;
88 class BlockFlags;
89 class BlockFieldFlags;
90 class RegionCodeGenTy;
91 class TargetCodeGenInfo;
92 struct OMPTaskDataTy;
93 struct CGCoroData;
94 
95 /// The kind of evaluation to perform on values of a particular
96 /// type.  Basically, is the code in CGExprScalar, CGExprComplex, or
97 /// CGExprAgg?
98 ///
99 /// TODO: should vectors maybe be split out into their own thing?
100 enum TypeEvaluationKind {
101   TEK_Scalar,
102   TEK_Complex,
103   TEK_Aggregate
104 };
105 
106 #define LIST_SANITIZER_CHECKS                                                  \
107   SANITIZER_CHECK(AddOverflow, add_overflow, 0)                                \
108   SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0)                  \
109   SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0)                             \
110   SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0)                          \
111   SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0)            \
112   SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0)                   \
113   SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0)             \
114   SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0)                     \
115   SANITIZER_CHECK(MissingReturn, missing_return, 0)                            \
116   SANITIZER_CHECK(MulOverflow, mul_overflow, 0)                                \
117   SANITIZER_CHECK(NegateOverflow, negate_overflow, 0)                          \
118   SANITIZER_CHECK(NonnullArg, nonnull_arg, 0)                                  \
119   SANITIZER_CHECK(NonnullReturn, nonnull_return, 0)                            \
120   SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0)                               \
121   SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0)                    \
122   SANITIZER_CHECK(SubOverflow, sub_overflow, 0)                                \
123   SANITIZER_CHECK(TypeMismatch, type_mismatch, 0)                              \
124   SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
125 
126 enum SanitizerHandler {
127 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
128   LIST_SANITIZER_CHECKS
129 #undef SANITIZER_CHECK
130 };
131 
132 /// CodeGenFunction - This class organizes the per-function state that is used
133 /// while generating LLVM code.
134 class CodeGenFunction : public CodeGenTypeCache {
135   CodeGenFunction(const CodeGenFunction &) = delete;
136   void operator=(const CodeGenFunction &) = delete;
137 
138   friend class CGCXXABI;
139 public:
140   /// A jump destination is an abstract label, branching to which may
141   /// require a jump out through normal cleanups.
142   struct JumpDest {
143     JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
144     JumpDest(llvm::BasicBlock *Block,
145              EHScopeStack::stable_iterator Depth,
146              unsigned Index)
147       : Block(Block), ScopeDepth(Depth), Index(Index) {}
148 
149     bool isValid() const { return Block != nullptr; }
150     llvm::BasicBlock *getBlock() const { return Block; }
151     EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
152     unsigned getDestIndex() const { return Index; }
153 
154     // This should be used cautiously.
155     void setScopeDepth(EHScopeStack::stable_iterator depth) {
156       ScopeDepth = depth;
157     }
158 
159   private:
160     llvm::BasicBlock *Block;
161     EHScopeStack::stable_iterator ScopeDepth;
162     unsigned Index;
163   };
164 
165   CodeGenModule &CGM;  // Per-module state.
166   const TargetInfo &Target;
167 
168   typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
169   LoopInfoStack LoopStack;
170   CGBuilderTy Builder;
171 
172   // Stores variables for which we can't generate correct lifetime markers
173   // because of jumps.
174   VarBypassDetector Bypasses;
175 
176   /// \brief CGBuilder insert helper. This function is called after an
177   /// instruction is created using Builder.
178   void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
179                     llvm::BasicBlock *BB,
180                     llvm::BasicBlock::iterator InsertPt) const;
181 
182   /// CurFuncDecl - Holds the Decl for the current outermost
183   /// non-closure context.
184   const Decl *CurFuncDecl;
185   /// CurCodeDecl - This is the inner-most code context, which includes blocks.
186   const Decl *CurCodeDecl;
187   const CGFunctionInfo *CurFnInfo;
188   QualType FnRetTy;
189   llvm::Function *CurFn;
190 
191   // Holds coroutine data if the current function is a coroutine. We use a
192   // wrapper to manage its lifetime, so that we don't have to define CGCoroData
193   // in this header.
194   struct CGCoroInfo {
195     std::unique_ptr<CGCoroData> Data;
196     CGCoroInfo();
197     ~CGCoroInfo();
198   };
199   CGCoroInfo CurCoro;
200 
201   /// CurGD - The GlobalDecl for the current function being compiled.
202   GlobalDecl CurGD;
203 
204   /// PrologueCleanupDepth - The cleanup depth enclosing all the
205   /// cleanups associated with the parameters.
206   EHScopeStack::stable_iterator PrologueCleanupDepth;
207 
208   /// ReturnBlock - Unified return block.
209   JumpDest ReturnBlock;
210 
211   /// ReturnValue - The temporary alloca to hold the return
212   /// value. This is invalid iff the function has no return value.
213   Address ReturnValue;
214 
215   /// AllocaInsertPoint - This is an instruction in the entry block before which
216   /// we prefer to insert allocas.
217   llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
218 
219   /// \brief API for captured statement code generation.
220   class CGCapturedStmtInfo {
221   public:
222     explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
223         : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
224     explicit CGCapturedStmtInfo(const CapturedStmt &S,
225                                 CapturedRegionKind K = CR_Default)
226       : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
227 
228       RecordDecl::field_iterator Field =
229         S.getCapturedRecordDecl()->field_begin();
230       for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
231                                                 E = S.capture_end();
232            I != E; ++I, ++Field) {
233         if (I->capturesThis())
234           CXXThisFieldDecl = *Field;
235         else if (I->capturesVariable())
236           CaptureFields[I->getCapturedVar()] = *Field;
237         else if (I->capturesVariableByCopy())
238           CaptureFields[I->getCapturedVar()] = *Field;
239       }
240     }
241 
242     virtual ~CGCapturedStmtInfo();
243 
244     CapturedRegionKind getKind() const { return Kind; }
245 
246     virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
247     // \brief Retrieve the value of the context parameter.
248     virtual llvm::Value *getContextValue() const { return ThisValue; }
249 
250     /// \brief Lookup the captured field decl for a variable.
251     virtual const FieldDecl *lookup(const VarDecl *VD) const {
252       return CaptureFields.lookup(VD);
253     }
254 
255     bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
256     virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
257 
258     static bool classof(const CGCapturedStmtInfo *) {
259       return true;
260     }
261 
262     /// \brief Emit the captured statement body.
263     virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
264       CGF.incrementProfileCounter(S);
265       CGF.EmitStmt(S);
266     }
267 
268     /// \brief Get the name of the capture helper.
269     virtual StringRef getHelperName() const { return "__captured_stmt"; }
270 
271   private:
272     /// \brief The kind of captured statement being generated.
273     CapturedRegionKind Kind;
274 
275     /// \brief Keep the map between VarDecl and FieldDecl.
276     llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
277 
278     /// \brief The base address of the captured record, passed in as the first
279     /// argument of the parallel region function.
280     llvm::Value *ThisValue;
281 
282     /// \brief Captured 'this' type.
283     FieldDecl *CXXThisFieldDecl;
284   };
285   CGCapturedStmtInfo *CapturedStmtInfo;
286 
287   /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
288   class CGCapturedStmtRAII {
289   private:
290     CodeGenFunction &CGF;
291     CGCapturedStmtInfo *PrevCapturedStmtInfo;
292   public:
293     CGCapturedStmtRAII(CodeGenFunction &CGF,
294                        CGCapturedStmtInfo *NewCapturedStmtInfo)
295         : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
296       CGF.CapturedStmtInfo = NewCapturedStmtInfo;
297     }
298     ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
299   };
300 
301   /// \brief Sanitizers enabled for this function.
302   SanitizerSet SanOpts;
303 
304   /// \brief True if CodeGen currently emits code implementing sanitizer checks.
305   bool IsSanitizerScope;
306 
307   /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
308   class SanitizerScope {
309     CodeGenFunction *CGF;
310   public:
311     SanitizerScope(CodeGenFunction *CGF);
312     ~SanitizerScope();
313   };
314 
315   /// In C++, whether we are code generating a thunk.  This controls whether we
316   /// should emit cleanups.
317   bool CurFuncIsThunk;
318 
319   /// In ARC, whether we should autorelease the return value.
320   bool AutoreleaseResult;
321 
322   /// Whether we processed a Microsoft-style asm block during CodeGen. These can
323   /// potentially set the return value.
324   bool SawAsmBlock;
325 
326   const FunctionDecl *CurSEHParent = nullptr;
327 
328   /// True if the current function is an outlined SEH helper. This can be a
329   /// finally block or filter expression.
330   bool IsOutlinedSEHHelper;
331 
332   const CodeGen::CGBlockInfo *BlockInfo;
333   llvm::Value *BlockPointer;
334 
335   llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
336   FieldDecl *LambdaThisCaptureField;
337 
338   /// \brief A mapping from NRVO variables to the flags used to indicate
339   /// when the NRVO has been applied to this variable.
340   llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
341 
342   EHScopeStack EHStack;
343   llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
344   llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
345 
346   llvm::Instruction *CurrentFuncletPad = nullptr;
347 
348   class CallLifetimeEnd final : public EHScopeStack::Cleanup {
349     llvm::Value *Addr;
350     llvm::Value *Size;
351 
352   public:
353     CallLifetimeEnd(Address addr, llvm::Value *size)
354         : Addr(addr.getPointer()), Size(size) {}
355 
356     void Emit(CodeGenFunction &CGF, Flags flags) override {
357       CGF.EmitLifetimeEnd(Size, Addr);
358     }
359   };
360 
361   /// Header for data within LifetimeExtendedCleanupStack.
362   struct LifetimeExtendedCleanupHeader {
363     /// The size of the following cleanup object.
364     unsigned Size;
365     /// The kind of cleanup to push: a value from the CleanupKind enumeration.
366     CleanupKind Kind;
367 
368     size_t getSize() const { return Size; }
369     CleanupKind getKind() const { return Kind; }
370   };
371 
372   /// i32s containing the indexes of the cleanup destinations.
373   llvm::AllocaInst *NormalCleanupDest;
374 
375   unsigned NextCleanupDestIndex;
376 
377   /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
378   CGBlockInfo *FirstBlockInfo;
379 
380   /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
381   llvm::BasicBlock *EHResumeBlock;
382 
383   /// The exception slot.  All landing pads write the current exception pointer
384   /// into this alloca.
385   llvm::Value *ExceptionSlot;
386 
387   /// The selector slot.  Under the MandatoryCleanup model, all landing pads
388   /// write the current selector value into this alloca.
389   llvm::AllocaInst *EHSelectorSlot;
390 
391   /// A stack of exception code slots. Entering an __except block pushes a slot
392   /// on the stack and leaving pops one. The __exception_code() intrinsic loads
393   /// a value from the top of the stack.
394   SmallVector<Address, 1> SEHCodeSlotStack;
395 
396   /// Value returned by __exception_info intrinsic.
397   llvm::Value *SEHInfo = nullptr;
398 
399   /// Emits a landing pad for the current EH stack.
400   llvm::BasicBlock *EmitLandingPad();
401 
402   llvm::BasicBlock *getInvokeDestImpl();
403 
404   template <class T>
405   typename DominatingValue<T>::saved_type saveValueInCond(T value) {
406     return DominatingValue<T>::save(*this, value);
407   }
408 
409 public:
410   /// ObjCEHValueStack - Stack of Objective-C exception values, used for
411   /// rethrows.
412   SmallVector<llvm::Value*, 8> ObjCEHValueStack;
413 
414   /// A class controlling the emission of a finally block.
415   class FinallyInfo {
416     /// Where the catchall's edge through the cleanup should go.
417     JumpDest RethrowDest;
418 
419     /// A function to call to enter the catch.
420     llvm::Constant *BeginCatchFn;
421 
422     /// An i1 variable indicating whether or not the @finally is
423     /// running for an exception.
424     llvm::AllocaInst *ForEHVar;
425 
426     /// An i8* variable into which the exception pointer to rethrow
427     /// has been saved.
428     llvm::AllocaInst *SavedExnVar;
429 
430   public:
431     void enter(CodeGenFunction &CGF, const Stmt *Finally,
432                llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
433                llvm::Constant *rethrowFn);
434     void exit(CodeGenFunction &CGF);
435   };
436 
437   /// Returns true inside SEH __try blocks.
438   bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
439 
440   /// Returns true while emitting a cleanuppad.
441   bool isCleanupPadScope() const {
442     return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
443   }
444 
445   /// pushFullExprCleanup - Push a cleanup to be run at the end of the
446   /// current full-expression.  Safe against the possibility that
447   /// we're currently inside a conditionally-evaluated expression.
448   template <class T, class... As>
449   void pushFullExprCleanup(CleanupKind kind, As... A) {
450     // If we're not in a conditional branch, or if none of the
451     // arguments requires saving, then use the unconditional cleanup.
452     if (!isInConditionalBranch())
453       return EHStack.pushCleanup<T>(kind, A...);
454 
455     // Stash values in a tuple so we can guarantee the order of saves.
456     typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
457     SavedTuple Saved{saveValueInCond(A)...};
458 
459     typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
460     EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
461     initFullExprCleanup();
462   }
463 
464   /// \brief Queue a cleanup to be pushed after finishing the current
465   /// full-expression.
466   template <class T, class... As>
467   void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
468     assert(!isInConditionalBranch() && "can't defer conditional cleanup");
469 
470     LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
471 
472     size_t OldSize = LifetimeExtendedCleanupStack.size();
473     LifetimeExtendedCleanupStack.resize(
474         LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
475 
476     static_assert(sizeof(Header) % alignof(T) == 0,
477                   "Cleanup will be allocated on misaligned address");
478     char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
479     new (Buffer) LifetimeExtendedCleanupHeader(Header);
480     new (Buffer + sizeof(Header)) T(A...);
481   }
482 
483   /// Set up the last cleaup that was pushed as a conditional
484   /// full-expression cleanup.
485   void initFullExprCleanup();
486 
487   /// PushDestructorCleanup - Push a cleanup to call the
488   /// complete-object destructor of an object of the given type at the
489   /// given address.  Does nothing if T is not a C++ class type with a
490   /// non-trivial destructor.
491   void PushDestructorCleanup(QualType T, Address Addr);
492 
493   /// PushDestructorCleanup - Push a cleanup to call the
494   /// complete-object variant of the given destructor on the object at
495   /// the given address.
496   void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
497 
498   /// PopCleanupBlock - Will pop the cleanup entry on the stack and
499   /// process all branch fixups.
500   void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
501 
502   /// DeactivateCleanupBlock - Deactivates the given cleanup block.
503   /// The block cannot be reactivated.  Pops it if it's the top of the
504   /// stack.
505   ///
506   /// \param DominatingIP - An instruction which is known to
507   ///   dominate the current IP (if set) and which lies along
508   ///   all paths of execution between the current IP and the
509   ///   the point at which the cleanup comes into scope.
510   void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
511                               llvm::Instruction *DominatingIP);
512 
513   /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
514   /// Cannot be used to resurrect a deactivated cleanup.
515   ///
516   /// \param DominatingIP - An instruction which is known to
517   ///   dominate the current IP (if set) and which lies along
518   ///   all paths of execution between the current IP and the
519   ///   the point at which the cleanup comes into scope.
520   void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
521                             llvm::Instruction *DominatingIP);
522 
523   /// \brief Enters a new scope for capturing cleanups, all of which
524   /// will be executed once the scope is exited.
525   class RunCleanupsScope {
526     EHScopeStack::stable_iterator CleanupStackDepth;
527     size_t LifetimeExtendedCleanupStackSize;
528     bool OldDidCallStackSave;
529   protected:
530     bool PerformCleanup;
531   private:
532 
533     RunCleanupsScope(const RunCleanupsScope &) = delete;
534     void operator=(const RunCleanupsScope &) = delete;
535 
536   protected:
537     CodeGenFunction& CGF;
538 
539   public:
540     /// \brief Enter a new cleanup scope.
541     explicit RunCleanupsScope(CodeGenFunction &CGF)
542       : PerformCleanup(true), CGF(CGF)
543     {
544       CleanupStackDepth = CGF.EHStack.stable_begin();
545       LifetimeExtendedCleanupStackSize =
546           CGF.LifetimeExtendedCleanupStack.size();
547       OldDidCallStackSave = CGF.DidCallStackSave;
548       CGF.DidCallStackSave = false;
549     }
550 
551     /// \brief Exit this cleanup scope, emitting any accumulated
552     /// cleanups.
553     ~RunCleanupsScope() {
554       if (PerformCleanup) {
555         CGF.DidCallStackSave = OldDidCallStackSave;
556         CGF.PopCleanupBlocks(CleanupStackDepth,
557                              LifetimeExtendedCleanupStackSize);
558       }
559     }
560 
561     /// \brief Determine whether this scope requires any cleanups.
562     bool requiresCleanups() const {
563       return CGF.EHStack.stable_begin() != CleanupStackDepth;
564     }
565 
566     /// \brief Force the emission of cleanups now, instead of waiting
567     /// until this object is destroyed.
568     void ForceCleanup() {
569       assert(PerformCleanup && "Already forced cleanup");
570       CGF.DidCallStackSave = OldDidCallStackSave;
571       CGF.PopCleanupBlocks(CleanupStackDepth,
572                            LifetimeExtendedCleanupStackSize);
573       PerformCleanup = false;
574     }
575   };
576 
577   class LexicalScope : public RunCleanupsScope {
578     SourceRange Range;
579     SmallVector<const LabelDecl*, 4> Labels;
580     LexicalScope *ParentScope;
581 
582     LexicalScope(const LexicalScope &) = delete;
583     void operator=(const LexicalScope &) = delete;
584 
585   public:
586     /// \brief Enter a new cleanup scope.
587     explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
588       : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
589       CGF.CurLexicalScope = this;
590       if (CGDebugInfo *DI = CGF.getDebugInfo())
591         DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
592     }
593 
594     void addLabel(const LabelDecl *label) {
595       assert(PerformCleanup && "adding label to dead scope?");
596       Labels.push_back(label);
597     }
598 
599     /// \brief Exit this cleanup scope, emitting any accumulated
600     /// cleanups.
601     ~LexicalScope() {
602       if (CGDebugInfo *DI = CGF.getDebugInfo())
603         DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
604 
605       // If we should perform a cleanup, force them now.  Note that
606       // this ends the cleanup scope before rescoping any labels.
607       if (PerformCleanup) {
608         ApplyDebugLocation DL(CGF, Range.getEnd());
609         ForceCleanup();
610       }
611     }
612 
613     /// \brief Force the emission of cleanups now, instead of waiting
614     /// until this object is destroyed.
615     void ForceCleanup() {
616       CGF.CurLexicalScope = ParentScope;
617       RunCleanupsScope::ForceCleanup();
618 
619       if (!Labels.empty())
620         rescopeLabels();
621     }
622 
623     void rescopeLabels();
624   };
625 
626   typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
627 
628   /// \brief The scope used to remap some variables as private in the OpenMP
629   /// loop body (or other captured region emitted without outlining), and to
630   /// restore old vars back on exit.
631   class OMPPrivateScope : public RunCleanupsScope {
632     DeclMapTy SavedLocals;
633     DeclMapTy SavedPrivates;
634 
635   private:
636     OMPPrivateScope(const OMPPrivateScope &) = delete;
637     void operator=(const OMPPrivateScope &) = delete;
638 
639   public:
640     /// \brief Enter a new OpenMP private scope.
641     explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
642 
643     /// \brief Registers \a LocalVD variable as a private and apply \a
644     /// PrivateGen function for it to generate corresponding private variable.
645     /// \a PrivateGen returns an address of the generated private variable.
646     /// \return true if the variable is registered as private, false if it has
647     /// been privatized already.
648     bool
649     addPrivate(const VarDecl *LocalVD,
650                llvm::function_ref<Address()> PrivateGen) {
651       assert(PerformCleanup && "adding private to dead scope");
652 
653       // Only save it once.
654       if (SavedLocals.count(LocalVD)) return false;
655 
656       // Copy the existing local entry to SavedLocals.
657       auto it = CGF.LocalDeclMap.find(LocalVD);
658       if (it != CGF.LocalDeclMap.end()) {
659         SavedLocals.insert({LocalVD, it->second});
660       } else {
661         SavedLocals.insert({LocalVD, Address::invalid()});
662       }
663 
664       // Generate the private entry.
665       Address Addr = PrivateGen();
666       QualType VarTy = LocalVD->getType();
667       if (VarTy->isReferenceType()) {
668         Address Temp = CGF.CreateMemTemp(VarTy);
669         CGF.Builder.CreateStore(Addr.getPointer(), Temp);
670         Addr = Temp;
671       }
672       SavedPrivates.insert({LocalVD, Addr});
673 
674       return true;
675     }
676 
677     /// \brief Privatizes local variables previously registered as private.
678     /// Registration is separate from the actual privatization to allow
679     /// initializers use values of the original variables, not the private one.
680     /// This is important, for example, if the private variable is a class
681     /// variable initialized by a constructor that references other private
682     /// variables. But at initialization original variables must be used, not
683     /// private copies.
684     /// \return true if at least one variable was privatized, false otherwise.
685     bool Privatize() {
686       copyInto(SavedPrivates, CGF.LocalDeclMap);
687       SavedPrivates.clear();
688       return !SavedLocals.empty();
689     }
690 
691     void ForceCleanup() {
692       RunCleanupsScope::ForceCleanup();
693       copyInto(SavedLocals, CGF.LocalDeclMap);
694       SavedLocals.clear();
695     }
696 
697     /// \brief Exit scope - all the mapped variables are restored.
698     ~OMPPrivateScope() {
699       if (PerformCleanup)
700         ForceCleanup();
701     }
702 
703     /// Checks if the global variable is captured in current function.
704     bool isGlobalVarCaptured(const VarDecl *VD) const {
705       return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
706     }
707 
708   private:
709     /// Copy all the entries in the source map over the corresponding
710     /// entries in the destination, which must exist.
711     static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
712       for (auto &pair : src) {
713         if (!pair.second.isValid()) {
714           dest.erase(pair.first);
715           continue;
716         }
717 
718         auto it = dest.find(pair.first);
719         if (it != dest.end()) {
720           it->second = pair.second;
721         } else {
722           dest.insert(pair);
723         }
724       }
725     }
726   };
727 
728   /// \brief Takes the old cleanup stack size and emits the cleanup blocks
729   /// that have been added.
730   void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
731 
732   /// \brief Takes the old cleanup stack size and emits the cleanup blocks
733   /// that have been added, then adds all lifetime-extended cleanups from
734   /// the given position to the stack.
735   void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
736                         size_t OldLifetimeExtendedStackSize);
737 
738   void ResolveBranchFixups(llvm::BasicBlock *Target);
739 
740   /// The given basic block lies in the current EH scope, but may be a
741   /// target of a potentially scope-crossing jump; get a stable handle
742   /// to which we can perform this jump later.
743   JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
744     return JumpDest(Target,
745                     EHStack.getInnermostNormalCleanup(),
746                     NextCleanupDestIndex++);
747   }
748 
749   /// The given basic block lies in the current EH scope, but may be a
750   /// target of a potentially scope-crossing jump; get a stable handle
751   /// to which we can perform this jump later.
752   JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
753     return getJumpDestInCurrentScope(createBasicBlock(Name));
754   }
755 
756   /// EmitBranchThroughCleanup - Emit a branch from the current insert
757   /// block through the normal cleanup handling code (if any) and then
758   /// on to \arg Dest.
759   void EmitBranchThroughCleanup(JumpDest Dest);
760 
761   /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
762   /// specified destination obviously has no cleanups to run.  'false' is always
763   /// a conservatively correct answer for this method.
764   bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
765 
766   /// popCatchScope - Pops the catch scope at the top of the EHScope
767   /// stack, emitting any required code (other than the catch handlers
768   /// themselves).
769   void popCatchScope();
770 
771   llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
772   llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
773   llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
774 
775   /// An object to manage conditionally-evaluated expressions.
776   class ConditionalEvaluation {
777     llvm::BasicBlock *StartBB;
778 
779   public:
780     ConditionalEvaluation(CodeGenFunction &CGF)
781       : StartBB(CGF.Builder.GetInsertBlock()) {}
782 
783     void begin(CodeGenFunction &CGF) {
784       assert(CGF.OutermostConditional != this);
785       if (!CGF.OutermostConditional)
786         CGF.OutermostConditional = this;
787     }
788 
789     void end(CodeGenFunction &CGF) {
790       assert(CGF.OutermostConditional != nullptr);
791       if (CGF.OutermostConditional == this)
792         CGF.OutermostConditional = nullptr;
793     }
794 
795     /// Returns a block which will be executed prior to each
796     /// evaluation of the conditional code.
797     llvm::BasicBlock *getStartingBlock() const {
798       return StartBB;
799     }
800   };
801 
802   /// isInConditionalBranch - Return true if we're currently emitting
803   /// one branch or the other of a conditional expression.
804   bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
805 
806   void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
807     assert(isInConditionalBranch());
808     llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
809     auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
810     store->setAlignment(addr.getAlignment().getQuantity());
811   }
812 
813   /// An RAII object to record that we're evaluating a statement
814   /// expression.
815   class StmtExprEvaluation {
816     CodeGenFunction &CGF;
817 
818     /// We have to save the outermost conditional: cleanups in a
819     /// statement expression aren't conditional just because the
820     /// StmtExpr is.
821     ConditionalEvaluation *SavedOutermostConditional;
822 
823   public:
824     StmtExprEvaluation(CodeGenFunction &CGF)
825       : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
826       CGF.OutermostConditional = nullptr;
827     }
828 
829     ~StmtExprEvaluation() {
830       CGF.OutermostConditional = SavedOutermostConditional;
831       CGF.EnsureInsertPoint();
832     }
833   };
834 
835   /// An object which temporarily prevents a value from being
836   /// destroyed by aggressive peephole optimizations that assume that
837   /// all uses of a value have been realized in the IR.
838   class PeepholeProtection {
839     llvm::Instruction *Inst;
840     friend class CodeGenFunction;
841 
842   public:
843     PeepholeProtection() : Inst(nullptr) {}
844   };
845 
846   /// A non-RAII class containing all the information about a bound
847   /// opaque value.  OpaqueValueMapping, below, is a RAII wrapper for
848   /// this which makes individual mappings very simple; using this
849   /// class directly is useful when you have a variable number of
850   /// opaque values or don't want the RAII functionality for some
851   /// reason.
852   class OpaqueValueMappingData {
853     const OpaqueValueExpr *OpaqueValue;
854     bool BoundLValue;
855     CodeGenFunction::PeepholeProtection Protection;
856 
857     OpaqueValueMappingData(const OpaqueValueExpr *ov,
858                            bool boundLValue)
859       : OpaqueValue(ov), BoundLValue(boundLValue) {}
860   public:
861     OpaqueValueMappingData() : OpaqueValue(nullptr) {}
862 
863     static bool shouldBindAsLValue(const Expr *expr) {
864       // gl-values should be bound as l-values for obvious reasons.
865       // Records should be bound as l-values because IR generation
866       // always keeps them in memory.  Expressions of function type
867       // act exactly like l-values but are formally required to be
868       // r-values in C.
869       return expr->isGLValue() ||
870              expr->getType()->isFunctionType() ||
871              hasAggregateEvaluationKind(expr->getType());
872     }
873 
874     static OpaqueValueMappingData bind(CodeGenFunction &CGF,
875                                        const OpaqueValueExpr *ov,
876                                        const Expr *e) {
877       if (shouldBindAsLValue(ov))
878         return bind(CGF, ov, CGF.EmitLValue(e));
879       return bind(CGF, ov, CGF.EmitAnyExpr(e));
880     }
881 
882     static OpaqueValueMappingData bind(CodeGenFunction &CGF,
883                                        const OpaqueValueExpr *ov,
884                                        const LValue &lv) {
885       assert(shouldBindAsLValue(ov));
886       CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
887       return OpaqueValueMappingData(ov, true);
888     }
889 
890     static OpaqueValueMappingData bind(CodeGenFunction &CGF,
891                                        const OpaqueValueExpr *ov,
892                                        const RValue &rv) {
893       assert(!shouldBindAsLValue(ov));
894       CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
895 
896       OpaqueValueMappingData data(ov, false);
897 
898       // Work around an extremely aggressive peephole optimization in
899       // EmitScalarConversion which assumes that all other uses of a
900       // value are extant.
901       data.Protection = CGF.protectFromPeepholes(rv);
902 
903       return data;
904     }
905 
906     bool isValid() const { return OpaqueValue != nullptr; }
907     void clear() { OpaqueValue = nullptr; }
908 
909     void unbind(CodeGenFunction &CGF) {
910       assert(OpaqueValue && "no data to unbind!");
911 
912       if (BoundLValue) {
913         CGF.OpaqueLValues.erase(OpaqueValue);
914       } else {
915         CGF.OpaqueRValues.erase(OpaqueValue);
916         CGF.unprotectFromPeepholes(Protection);
917       }
918     }
919   };
920 
921   /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
922   class OpaqueValueMapping {
923     CodeGenFunction &CGF;
924     OpaqueValueMappingData Data;
925 
926   public:
927     static bool shouldBindAsLValue(const Expr *expr) {
928       return OpaqueValueMappingData::shouldBindAsLValue(expr);
929     }
930 
931     /// Build the opaque value mapping for the given conditional
932     /// operator if it's the GNU ?: extension.  This is a common
933     /// enough pattern that the convenience operator is really
934     /// helpful.
935     ///
936     OpaqueValueMapping(CodeGenFunction &CGF,
937                        const AbstractConditionalOperator *op) : CGF(CGF) {
938       if (isa<ConditionalOperator>(op))
939         // Leave Data empty.
940         return;
941 
942       const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
943       Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
944                                           e->getCommon());
945     }
946 
947     /// Build the opaque value mapping for an OpaqueValueExpr whose source
948     /// expression is set to the expression the OVE represents.
949     OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
950         : CGF(CGF) {
951       if (OV) {
952         assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
953                                       "for OVE with no source expression");
954         Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
955       }
956     }
957 
958     OpaqueValueMapping(CodeGenFunction &CGF,
959                        const OpaqueValueExpr *opaqueValue,
960                        LValue lvalue)
961       : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
962     }
963 
964     OpaqueValueMapping(CodeGenFunction &CGF,
965                        const OpaqueValueExpr *opaqueValue,
966                        RValue rvalue)
967       : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
968     }
969 
970     void pop() {
971       Data.unbind(CGF);
972       Data.clear();
973     }
974 
975     ~OpaqueValueMapping() {
976       if (Data.isValid()) Data.unbind(CGF);
977     }
978   };
979 
980 private:
981   CGDebugInfo *DebugInfo;
982   bool DisableDebugInfo;
983 
984   /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
985   /// calling llvm.stacksave for multiple VLAs in the same scope.
986   bool DidCallStackSave;
987 
988   /// IndirectBranch - The first time an indirect goto is seen we create a block
989   /// with an indirect branch.  Every time we see the address of a label taken,
990   /// we add the label to the indirect goto.  Every subsequent indirect goto is
991   /// codegen'd as a jump to the IndirectBranch's basic block.
992   llvm::IndirectBrInst *IndirectBranch;
993 
994   /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
995   /// decls.
996   DeclMapTy LocalDeclMap;
997 
998   /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
999   /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1000   /// parameter.
1001   llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1002       SizeArguments;
1003 
1004   /// Track escaped local variables with auto storage. Used during SEH
1005   /// outlining to produce a call to llvm.localescape.
1006   llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1007 
1008   /// LabelMap - This keeps track of the LLVM basic block for each C label.
1009   llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1010 
1011   // BreakContinueStack - This keeps track of where break and continue
1012   // statements should jump to.
1013   struct BreakContinue {
1014     BreakContinue(JumpDest Break, JumpDest Continue)
1015       : BreakBlock(Break), ContinueBlock(Continue) {}
1016 
1017     JumpDest BreakBlock;
1018     JumpDest ContinueBlock;
1019   };
1020   SmallVector<BreakContinue, 8> BreakContinueStack;
1021 
1022   /// Handles cancellation exit points in OpenMP-related constructs.
1023   class OpenMPCancelExitStack {
1024     /// Tracks cancellation exit point and join point for cancel-related exit
1025     /// and normal exit.
1026     struct CancelExit {
1027       CancelExit() = default;
1028       CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1029                  JumpDest ContBlock)
1030           : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1031       OpenMPDirectiveKind Kind = OMPD_unknown;
1032       /// true if the exit block has been emitted already by the special
1033       /// emitExit() call, false if the default codegen is used.
1034       bool HasBeenEmitted = false;
1035       JumpDest ExitBlock;
1036       JumpDest ContBlock;
1037     };
1038 
1039     SmallVector<CancelExit, 8> Stack;
1040 
1041   public:
1042     OpenMPCancelExitStack() : Stack(1) {}
1043     ~OpenMPCancelExitStack() = default;
1044     /// Fetches the exit block for the current OpenMP construct.
1045     JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1046     /// Emits exit block with special codegen procedure specific for the related
1047     /// OpenMP construct + emits code for normal construct cleanup.
1048     void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1049                   const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1050       if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1051         assert(CGF.getOMPCancelDestination(Kind).isValid());
1052         assert(CGF.HaveInsertPoint());
1053         assert(!Stack.back().HasBeenEmitted);
1054         auto IP = CGF.Builder.saveAndClearIP();
1055         CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1056         CodeGen(CGF);
1057         CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1058         CGF.Builder.restoreIP(IP);
1059         Stack.back().HasBeenEmitted = true;
1060       }
1061       CodeGen(CGF);
1062     }
1063     /// Enter the cancel supporting \a Kind construct.
1064     /// \param Kind OpenMP directive that supports cancel constructs.
1065     /// \param HasCancel true, if the construct has inner cancel directive,
1066     /// false otherwise.
1067     void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1068       Stack.push_back({Kind,
1069                        HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1070                                  : JumpDest(),
1071                        HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1072                                  : JumpDest()});
1073     }
1074     /// Emits default exit point for the cancel construct (if the special one
1075     /// has not be used) + join point for cancel/normal exits.
1076     void exit(CodeGenFunction &CGF) {
1077       if (getExitBlock().isValid()) {
1078         assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1079         bool HaveIP = CGF.HaveInsertPoint();
1080         if (!Stack.back().HasBeenEmitted) {
1081           if (HaveIP)
1082             CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1083           CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1084           CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1085         }
1086         CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1087         if (!HaveIP) {
1088           CGF.Builder.CreateUnreachable();
1089           CGF.Builder.ClearInsertionPoint();
1090         }
1091       }
1092       Stack.pop_back();
1093     }
1094   };
1095   OpenMPCancelExitStack OMPCancelStack;
1096 
1097   /// Controls insertion of cancellation exit blocks in worksharing constructs.
1098   class OMPCancelStackRAII {
1099     CodeGenFunction &CGF;
1100 
1101   public:
1102     OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1103                        bool HasCancel)
1104         : CGF(CGF) {
1105       CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1106     }
1107     ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1108   };
1109 
1110   CodeGenPGO PGO;
1111 
1112   /// Calculate branch weights appropriate for PGO data
1113   llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1114   llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1115   llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1116                                             uint64_t LoopCount);
1117 
1118 public:
1119   /// Increment the profiler's counter for the given statement.
1120   void incrementProfileCounter(const Stmt *S) {
1121     if (CGM.getCodeGenOpts().hasProfileClangInstr())
1122       PGO.emitCounterIncrement(Builder, S);
1123     PGO.setCurrentStmt(S);
1124   }
1125 
1126   /// Get the profiler's count for the given statement.
1127   uint64_t getProfileCount(const Stmt *S) {
1128     Optional<uint64_t> Count = PGO.getStmtCount(S);
1129     if (!Count.hasValue())
1130       return 0;
1131     return *Count;
1132   }
1133 
1134   /// Set the profiler's current count.
1135   void setCurrentProfileCount(uint64_t Count) {
1136     PGO.setCurrentRegionCount(Count);
1137   }
1138 
1139   /// Get the profiler's current count. This is generally the count for the most
1140   /// recently incremented counter.
1141   uint64_t getCurrentProfileCount() {
1142     return PGO.getCurrentRegionCount();
1143   }
1144 
1145 private:
1146 
1147   /// SwitchInsn - This is nearest current switch instruction. It is null if
1148   /// current context is not in a switch.
1149   llvm::SwitchInst *SwitchInsn;
1150   /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1151   SmallVector<uint64_t, 16> *SwitchWeights;
1152 
1153   /// CaseRangeBlock - This block holds if condition check for last case
1154   /// statement range in current switch instruction.
1155   llvm::BasicBlock *CaseRangeBlock;
1156 
1157   /// OpaqueLValues - Keeps track of the current set of opaque value
1158   /// expressions.
1159   llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1160   llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1161 
1162   // VLASizeMap - This keeps track of the associated size for each VLA type.
1163   // We track this by the size expression rather than the type itself because
1164   // in certain situations, like a const qualifier applied to an VLA typedef,
1165   // multiple VLA types can share the same size expression.
1166   // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1167   // enter/leave scopes.
1168   llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1169 
1170   /// A block containing a single 'unreachable' instruction.  Created
1171   /// lazily by getUnreachableBlock().
1172   llvm::BasicBlock *UnreachableBlock;
1173 
1174   /// Counts of the number return expressions in the function.
1175   unsigned NumReturnExprs;
1176 
1177   /// Count the number of simple (constant) return expressions in the function.
1178   unsigned NumSimpleReturnExprs;
1179 
1180   /// The last regular (non-return) debug location (breakpoint) in the function.
1181   SourceLocation LastStopPoint;
1182 
1183 public:
1184   /// A scope within which we are constructing the fields of an object which
1185   /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1186   /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1187   class FieldConstructionScope {
1188   public:
1189     FieldConstructionScope(CodeGenFunction &CGF, Address This)
1190         : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1191       CGF.CXXDefaultInitExprThis = This;
1192     }
1193     ~FieldConstructionScope() {
1194       CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1195     }
1196 
1197   private:
1198     CodeGenFunction &CGF;
1199     Address OldCXXDefaultInitExprThis;
1200   };
1201 
1202   /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1203   /// is overridden to be the object under construction.
1204   class CXXDefaultInitExprScope {
1205   public:
1206     CXXDefaultInitExprScope(CodeGenFunction &CGF)
1207       : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1208         OldCXXThisAlignment(CGF.CXXThisAlignment) {
1209       CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1210       CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1211     }
1212     ~CXXDefaultInitExprScope() {
1213       CGF.CXXThisValue = OldCXXThisValue;
1214       CGF.CXXThisAlignment = OldCXXThisAlignment;
1215     }
1216 
1217   public:
1218     CodeGenFunction &CGF;
1219     llvm::Value *OldCXXThisValue;
1220     CharUnits OldCXXThisAlignment;
1221   };
1222 
1223   /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1224   /// current loop index is overridden.
1225   class ArrayInitLoopExprScope {
1226   public:
1227     ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1228       : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1229       CGF.ArrayInitIndex = Index;
1230     }
1231     ~ArrayInitLoopExprScope() {
1232       CGF.ArrayInitIndex = OldArrayInitIndex;
1233     }
1234 
1235   private:
1236     CodeGenFunction &CGF;
1237     llvm::Value *OldArrayInitIndex;
1238   };
1239 
1240   class InlinedInheritingConstructorScope {
1241   public:
1242     InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1243         : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1244           OldCurCodeDecl(CGF.CurCodeDecl),
1245           OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1246           OldCXXABIThisValue(CGF.CXXABIThisValue),
1247           OldCXXThisValue(CGF.CXXThisValue),
1248           OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1249           OldCXXThisAlignment(CGF.CXXThisAlignment),
1250           OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1251           OldCXXInheritedCtorInitExprArgs(
1252               std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1253       CGF.CurGD = GD;
1254       CGF.CurFuncDecl = CGF.CurCodeDecl =
1255           cast<CXXConstructorDecl>(GD.getDecl());
1256       CGF.CXXABIThisDecl = nullptr;
1257       CGF.CXXABIThisValue = nullptr;
1258       CGF.CXXThisValue = nullptr;
1259       CGF.CXXABIThisAlignment = CharUnits();
1260       CGF.CXXThisAlignment = CharUnits();
1261       CGF.ReturnValue = Address::invalid();
1262       CGF.FnRetTy = QualType();
1263       CGF.CXXInheritedCtorInitExprArgs.clear();
1264     }
1265     ~InlinedInheritingConstructorScope() {
1266       CGF.CurGD = OldCurGD;
1267       CGF.CurFuncDecl = OldCurFuncDecl;
1268       CGF.CurCodeDecl = OldCurCodeDecl;
1269       CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1270       CGF.CXXABIThisValue = OldCXXABIThisValue;
1271       CGF.CXXThisValue = OldCXXThisValue;
1272       CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1273       CGF.CXXThisAlignment = OldCXXThisAlignment;
1274       CGF.ReturnValue = OldReturnValue;
1275       CGF.FnRetTy = OldFnRetTy;
1276       CGF.CXXInheritedCtorInitExprArgs =
1277           std::move(OldCXXInheritedCtorInitExprArgs);
1278     }
1279 
1280   private:
1281     CodeGenFunction &CGF;
1282     GlobalDecl OldCurGD;
1283     const Decl *OldCurFuncDecl;
1284     const Decl *OldCurCodeDecl;
1285     ImplicitParamDecl *OldCXXABIThisDecl;
1286     llvm::Value *OldCXXABIThisValue;
1287     llvm::Value *OldCXXThisValue;
1288     CharUnits OldCXXABIThisAlignment;
1289     CharUnits OldCXXThisAlignment;
1290     Address OldReturnValue;
1291     QualType OldFnRetTy;
1292     CallArgList OldCXXInheritedCtorInitExprArgs;
1293   };
1294 
1295 private:
1296   /// CXXThisDecl - When generating code for a C++ member function,
1297   /// this will hold the implicit 'this' declaration.
1298   ImplicitParamDecl *CXXABIThisDecl;
1299   llvm::Value *CXXABIThisValue;
1300   llvm::Value *CXXThisValue;
1301   CharUnits CXXABIThisAlignment;
1302   CharUnits CXXThisAlignment;
1303 
1304   /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1305   /// this expression.
1306   Address CXXDefaultInitExprThis = Address::invalid();
1307 
1308   /// The current array initialization index when evaluating an
1309   /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1310   llvm::Value *ArrayInitIndex = nullptr;
1311 
1312   /// The values of function arguments to use when evaluating
1313   /// CXXInheritedCtorInitExprs within this context.
1314   CallArgList CXXInheritedCtorInitExprArgs;
1315 
1316   /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1317   /// destructor, this will hold the implicit argument (e.g. VTT).
1318   ImplicitParamDecl *CXXStructorImplicitParamDecl;
1319   llvm::Value *CXXStructorImplicitParamValue;
1320 
1321   /// OutermostConditional - Points to the outermost active
1322   /// conditional control.  This is used so that we know if a
1323   /// temporary should be destroyed conditionally.
1324   ConditionalEvaluation *OutermostConditional;
1325 
1326   /// The current lexical scope.
1327   LexicalScope *CurLexicalScope;
1328 
1329   /// The current source location that should be used for exception
1330   /// handling code.
1331   SourceLocation CurEHLocation;
1332 
1333   /// BlockByrefInfos - For each __block variable, contains
1334   /// information about the layout of the variable.
1335   llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1336 
1337   llvm::BasicBlock *TerminateLandingPad;
1338   llvm::BasicBlock *TerminateHandler;
1339   llvm::BasicBlock *TrapBB;
1340 
1341   /// True if we need emit the life-time markers.
1342   const bool ShouldEmitLifetimeMarkers;
1343 
1344   /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
1345   /// In the kernel metadata node, reference the kernel function and metadata
1346   /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
1347   /// - A node for the vec_type_hint(<type>) qualifier contains string
1348   ///   "vec_type_hint", an undefined value of the <type> data type,
1349   ///   and a Boolean that is true if the <type> is integer and signed.
1350   /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
1351   ///   "work_group_size_hint", and three 32-bit integers X, Y and Z.
1352   /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
1353   ///   "reqd_work_group_size", and three 32-bit integers X, Y and Z.
1354   void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1355                                 llvm::Function *Fn);
1356 
1357 public:
1358   CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1359   ~CodeGenFunction();
1360 
1361   CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1362   ASTContext &getContext() const { return CGM.getContext(); }
1363   CGDebugInfo *getDebugInfo() {
1364     if (DisableDebugInfo)
1365       return nullptr;
1366     return DebugInfo;
1367   }
1368   void disableDebugInfo() { DisableDebugInfo = true; }
1369   void enableDebugInfo() { DisableDebugInfo = false; }
1370 
1371   bool shouldUseFusedARCCalls() {
1372     return CGM.getCodeGenOpts().OptimizationLevel == 0;
1373   }
1374 
1375   const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1376 
1377   /// Returns a pointer to the function's exception object and selector slot,
1378   /// which is assigned in every landing pad.
1379   Address getExceptionSlot();
1380   Address getEHSelectorSlot();
1381 
1382   /// Returns the contents of the function's exception object and selector
1383   /// slots.
1384   llvm::Value *getExceptionFromSlot();
1385   llvm::Value *getSelectorFromSlot();
1386 
1387   Address getNormalCleanupDestSlot();
1388 
1389   llvm::BasicBlock *getUnreachableBlock() {
1390     if (!UnreachableBlock) {
1391       UnreachableBlock = createBasicBlock("unreachable");
1392       new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1393     }
1394     return UnreachableBlock;
1395   }
1396 
1397   llvm::BasicBlock *getInvokeDest() {
1398     if (!EHStack.requiresLandingPad()) return nullptr;
1399     return getInvokeDestImpl();
1400   }
1401 
1402   bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1403 
1404   const TargetInfo &getTarget() const { return Target; }
1405   llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1406 
1407   //===--------------------------------------------------------------------===//
1408   //                                  Cleanups
1409   //===--------------------------------------------------------------------===//
1410 
1411   typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1412 
1413   void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1414                                         Address arrayEndPointer,
1415                                         QualType elementType,
1416                                         CharUnits elementAlignment,
1417                                         Destroyer *destroyer);
1418   void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1419                                       llvm::Value *arrayEnd,
1420                                       QualType elementType,
1421                                       CharUnits elementAlignment,
1422                                       Destroyer *destroyer);
1423 
1424   void pushDestroy(QualType::DestructionKind dtorKind,
1425                    Address addr, QualType type);
1426   void pushEHDestroy(QualType::DestructionKind dtorKind,
1427                      Address addr, QualType type);
1428   void pushDestroy(CleanupKind kind, Address addr, QualType type,
1429                    Destroyer *destroyer, bool useEHCleanupForArray);
1430   void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1431                                    QualType type, Destroyer *destroyer,
1432                                    bool useEHCleanupForArray);
1433   void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1434                                    llvm::Value *CompletePtr,
1435                                    QualType ElementType);
1436   void pushStackRestore(CleanupKind kind, Address SPMem);
1437   void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1438                    bool useEHCleanupForArray);
1439   llvm::Function *generateDestroyHelper(Address addr, QualType type,
1440                                         Destroyer *destroyer,
1441                                         bool useEHCleanupForArray,
1442                                         const VarDecl *VD);
1443   void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1444                         QualType elementType, CharUnits elementAlign,
1445                         Destroyer *destroyer,
1446                         bool checkZeroLength, bool useEHCleanup);
1447 
1448   Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1449 
1450   /// Determines whether an EH cleanup is required to destroy a type
1451   /// with the given destruction kind.
1452   bool needsEHCleanup(QualType::DestructionKind kind) {
1453     switch (kind) {
1454     case QualType::DK_none:
1455       return false;
1456     case QualType::DK_cxx_destructor:
1457     case QualType::DK_objc_weak_lifetime:
1458       return getLangOpts().Exceptions;
1459     case QualType::DK_objc_strong_lifetime:
1460       return getLangOpts().Exceptions &&
1461              CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1462     }
1463     llvm_unreachable("bad destruction kind");
1464   }
1465 
1466   CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1467     return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1468   }
1469 
1470   //===--------------------------------------------------------------------===//
1471   //                                  Objective-C
1472   //===--------------------------------------------------------------------===//
1473 
1474   void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1475 
1476   void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1477 
1478   /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1479   void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1480                           const ObjCPropertyImplDecl *PID);
1481   void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1482                               const ObjCPropertyImplDecl *propImpl,
1483                               const ObjCMethodDecl *GetterMothodDecl,
1484                               llvm::Constant *AtomicHelperFn);
1485 
1486   void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1487                                   ObjCMethodDecl *MD, bool ctor);
1488 
1489   /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1490   /// for the given property.
1491   void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1492                           const ObjCPropertyImplDecl *PID);
1493   void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1494                               const ObjCPropertyImplDecl *propImpl,
1495                               llvm::Constant *AtomicHelperFn);
1496 
1497   //===--------------------------------------------------------------------===//
1498   //                                  Block Bits
1499   //===--------------------------------------------------------------------===//
1500 
1501   llvm::Value *EmitBlockLiteral(const BlockExpr *);
1502   llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
1503   static void destroyBlockInfos(CGBlockInfo *info);
1504 
1505   llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1506                                         const CGBlockInfo &Info,
1507                                         const DeclMapTy &ldm,
1508                                         bool IsLambdaConversionToBlock);
1509 
1510   llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1511   llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1512   llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1513                                              const ObjCPropertyImplDecl *PID);
1514   llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1515                                              const ObjCPropertyImplDecl *PID);
1516   llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1517 
1518   void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1519 
1520   class AutoVarEmission;
1521 
1522   void emitByrefStructureInit(const AutoVarEmission &emission);
1523   void enterByrefCleanup(const AutoVarEmission &emission);
1524 
1525   void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1526                                 llvm::Value *ptr);
1527 
1528   Address LoadBlockStruct();
1529   Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1530 
1531   /// BuildBlockByrefAddress - Computes the location of the
1532   /// data in a variable which is declared as __block.
1533   Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1534                                 bool followForward = true);
1535   Address emitBlockByrefAddress(Address baseAddr,
1536                                 const BlockByrefInfo &info,
1537                                 bool followForward,
1538                                 const llvm::Twine &name);
1539 
1540   const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1541 
1542   QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1543 
1544   void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1545                     const CGFunctionInfo &FnInfo);
1546   /// \brief Emit code for the start of a function.
1547   /// \param Loc       The location to be associated with the function.
1548   /// \param StartLoc  The location of the function body.
1549   void StartFunction(GlobalDecl GD,
1550                      QualType RetTy,
1551                      llvm::Function *Fn,
1552                      const CGFunctionInfo &FnInfo,
1553                      const FunctionArgList &Args,
1554                      SourceLocation Loc = SourceLocation(),
1555                      SourceLocation StartLoc = SourceLocation());
1556 
1557   void EmitConstructorBody(FunctionArgList &Args);
1558   void EmitDestructorBody(FunctionArgList &Args);
1559   void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1560   void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1561   void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1562 
1563   void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1564                                   CallArgList &CallArgs);
1565   void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1566   void EmitLambdaBlockInvokeBody();
1567   void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1568   void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1569   void EmitAsanPrologueOrEpilogue(bool Prologue);
1570 
1571   /// \brief Emit the unified return block, trying to avoid its emission when
1572   /// possible.
1573   /// \return The debug location of the user written return statement if the
1574   /// return block is is avoided.
1575   llvm::DebugLoc EmitReturnBlock();
1576 
1577   /// FinishFunction - Complete IR generation of the current function. It is
1578   /// legal to call this function even if there is no current insertion point.
1579   void FinishFunction(SourceLocation EndLoc=SourceLocation());
1580 
1581   void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1582                   const CGFunctionInfo &FnInfo);
1583 
1584   void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1585                                  const ThunkInfo *Thunk);
1586 
1587   void FinishThunk();
1588 
1589   /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1590   void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1591                          llvm::Value *Callee);
1592 
1593   /// Generate a thunk for the given method.
1594   void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1595                      GlobalDecl GD, const ThunkInfo &Thunk);
1596 
1597   llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1598                                        const CGFunctionInfo &FnInfo,
1599                                        GlobalDecl GD, const ThunkInfo &Thunk);
1600 
1601   void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1602                         FunctionArgList &Args);
1603 
1604   void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
1605                                ArrayRef<VarDecl *> ArrayIndexes);
1606 
1607   /// Struct with all informations about dynamic [sub]class needed to set vptr.
1608   struct VPtr {
1609     BaseSubobject Base;
1610     const CXXRecordDecl *NearestVBase;
1611     CharUnits OffsetFromNearestVBase;
1612     const CXXRecordDecl *VTableClass;
1613   };
1614 
1615   /// Initialize the vtable pointer of the given subobject.
1616   void InitializeVTablePointer(const VPtr &vptr);
1617 
1618   typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1619 
1620   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1621   VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1622 
1623   void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1624                          CharUnits OffsetFromNearestVBase,
1625                          bool BaseIsNonVirtualPrimaryBase,
1626                          const CXXRecordDecl *VTableClass,
1627                          VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1628 
1629   void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1630 
1631   /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1632   /// to by This.
1633   llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1634                             const CXXRecordDecl *VTableClass);
1635 
1636   enum CFITypeCheckKind {
1637     CFITCK_VCall,
1638     CFITCK_NVCall,
1639     CFITCK_DerivedCast,
1640     CFITCK_UnrelatedCast,
1641     CFITCK_ICall,
1642   };
1643 
1644   /// \brief Derived is the presumed address of an object of type T after a
1645   /// cast. If T is a polymorphic class type, emit a check that the virtual
1646   /// table for Derived belongs to a class derived from T.
1647   void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1648                                  bool MayBeNull, CFITypeCheckKind TCK,
1649                                  SourceLocation Loc);
1650 
1651   /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1652   /// If vptr CFI is enabled, emit a check that VTable is valid.
1653   void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1654                                  CFITypeCheckKind TCK, SourceLocation Loc);
1655 
1656   /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1657   /// RD using llvm.type.test.
1658   void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1659                           CFITypeCheckKind TCK, SourceLocation Loc);
1660 
1661   /// If whole-program virtual table optimization is enabled, emit an assumption
1662   /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1663   /// enabled, emit a check that VTable is a member of RD's type identifier.
1664   void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1665                                     llvm::Value *VTable, SourceLocation Loc);
1666 
1667   /// Returns whether we should perform a type checked load when loading a
1668   /// virtual function for virtual calls to members of RD. This is generally
1669   /// true when both vcall CFI and whole-program-vtables are enabled.
1670   bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1671 
1672   /// Emit a type checked load from the given vtable.
1673   llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1674                                          uint64_t VTableByteOffset);
1675 
1676   /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1677   /// expr can be devirtualized.
1678   bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1679                                          const CXXMethodDecl *MD);
1680 
1681   /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1682   /// given phase of destruction for a destructor.  The end result
1683   /// should call destructors on members and base classes in reverse
1684   /// order of their construction.
1685   void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1686 
1687   /// ShouldInstrumentFunction - Return true if the current function should be
1688   /// instrumented with __cyg_profile_func_* calls
1689   bool ShouldInstrumentFunction();
1690 
1691   /// ShouldXRayInstrument - Return true if the current function should be
1692   /// instrumented with XRay nop sleds.
1693   bool ShouldXRayInstrumentFunction() const;
1694 
1695   /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1696   /// instrumentation function with the current function and the call site, if
1697   /// function instrumentation is enabled.
1698   void EmitFunctionInstrumentation(const char *Fn);
1699 
1700   /// EmitMCountInstrumentation - Emit call to .mcount.
1701   void EmitMCountInstrumentation();
1702 
1703   /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1704   /// arguments for the given function. This is also responsible for naming the
1705   /// LLVM function arguments.
1706   void EmitFunctionProlog(const CGFunctionInfo &FI,
1707                           llvm::Function *Fn,
1708                           const FunctionArgList &Args);
1709 
1710   /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1711   /// given temporary.
1712   void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1713                           SourceLocation EndLoc);
1714 
1715   /// EmitStartEHSpec - Emit the start of the exception spec.
1716   void EmitStartEHSpec(const Decl *D);
1717 
1718   /// EmitEndEHSpec - Emit the end of the exception spec.
1719   void EmitEndEHSpec(const Decl *D);
1720 
1721   /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1722   llvm::BasicBlock *getTerminateLandingPad();
1723 
1724   /// getTerminateHandler - Return a handler (not a landing pad, just
1725   /// a catch handler) that just calls terminate.  This is used when
1726   /// a terminate scope encloses a try.
1727   llvm::BasicBlock *getTerminateHandler();
1728 
1729   llvm::Type *ConvertTypeForMem(QualType T);
1730   llvm::Type *ConvertType(QualType T);
1731   llvm::Type *ConvertType(const TypeDecl *T) {
1732     return ConvertType(getContext().getTypeDeclType(T));
1733   }
1734 
1735   /// LoadObjCSelf - Load the value of self. This function is only valid while
1736   /// generating code for an Objective-C method.
1737   llvm::Value *LoadObjCSelf();
1738 
1739   /// TypeOfSelfObject - Return type of object that this self represents.
1740   QualType TypeOfSelfObject();
1741 
1742   /// hasAggregateLLVMType - Return true if the specified AST type will map into
1743   /// an aggregate LLVM type or is void.
1744   static TypeEvaluationKind getEvaluationKind(QualType T);
1745 
1746   static bool hasScalarEvaluationKind(QualType T) {
1747     return getEvaluationKind(T) == TEK_Scalar;
1748   }
1749 
1750   static bool hasAggregateEvaluationKind(QualType T) {
1751     return getEvaluationKind(T) == TEK_Aggregate;
1752   }
1753 
1754   /// createBasicBlock - Create an LLVM basic block.
1755   llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1756                                      llvm::Function *parent = nullptr,
1757                                      llvm::BasicBlock *before = nullptr) {
1758 #ifdef NDEBUG
1759     return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1760 #else
1761     return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1762 #endif
1763   }
1764 
1765   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1766   /// label maps to.
1767   JumpDest getJumpDestForLabel(const LabelDecl *S);
1768 
1769   /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1770   /// another basic block, simplify it. This assumes that no other code could
1771   /// potentially reference the basic block.
1772   void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1773 
1774   /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1775   /// adding a fall-through branch from the current insert block if
1776   /// necessary. It is legal to call this function even if there is no current
1777   /// insertion point.
1778   ///
1779   /// IsFinished - If true, indicates that the caller has finished emitting
1780   /// branches to the given block and does not expect to emit code into it. This
1781   /// means the block can be ignored if it is unreachable.
1782   void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1783 
1784   /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1785   /// near its uses, and leave the insertion point in it.
1786   void EmitBlockAfterUses(llvm::BasicBlock *BB);
1787 
1788   /// EmitBranch - Emit a branch to the specified basic block from the current
1789   /// insert block, taking care to avoid creation of branches from dummy
1790   /// blocks. It is legal to call this function even if there is no current
1791   /// insertion point.
1792   ///
1793   /// This function clears the current insertion point. The caller should follow
1794   /// calls to this function with calls to Emit*Block prior to generation new
1795   /// code.
1796   void EmitBranch(llvm::BasicBlock *Block);
1797 
1798   /// HaveInsertPoint - True if an insertion point is defined. If not, this
1799   /// indicates that the current code being emitted is unreachable.
1800   bool HaveInsertPoint() const {
1801     return Builder.GetInsertBlock() != nullptr;
1802   }
1803 
1804   /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1805   /// emitted IR has a place to go. Note that by definition, if this function
1806   /// creates a block then that block is unreachable; callers may do better to
1807   /// detect when no insertion point is defined and simply skip IR generation.
1808   void EnsureInsertPoint() {
1809     if (!HaveInsertPoint())
1810       EmitBlock(createBasicBlock());
1811   }
1812 
1813   /// ErrorUnsupported - Print out an error that codegen doesn't support the
1814   /// specified stmt yet.
1815   void ErrorUnsupported(const Stmt *S, const char *Type);
1816 
1817   //===--------------------------------------------------------------------===//
1818   //                                  Helpers
1819   //===--------------------------------------------------------------------===//
1820 
1821   LValue MakeAddrLValue(Address Addr, QualType T,
1822                         AlignmentSource AlignSource = AlignmentSource::Type) {
1823     return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
1824                             CGM.getTBAAInfo(T));
1825   }
1826 
1827   LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1828                         AlignmentSource AlignSource = AlignmentSource::Type) {
1829     return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1830                             AlignSource, CGM.getTBAAInfo(T));
1831   }
1832 
1833   LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1834   LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1835   CharUnits getNaturalTypeAlignment(QualType T,
1836                                     AlignmentSource *Source = nullptr,
1837                                     bool forPointeeType = false);
1838   CharUnits getNaturalPointeeTypeAlignment(QualType T,
1839                                            AlignmentSource *Source = nullptr);
1840 
1841   Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1842                               AlignmentSource *Source = nullptr);
1843   LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1844 
1845   Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1846                             AlignmentSource *Source = nullptr);
1847   LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1848 
1849   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1850   /// block. The caller is responsible for setting an appropriate alignment on
1851   /// the alloca.
1852   llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1853                                      const Twine &Name = "tmp");
1854   Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1855                            const Twine &Name = "tmp");
1856 
1857   /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1858   /// default ABI alignment of the given LLVM type.
1859   ///
1860   /// IMPORTANT NOTE: This is *not* generally the right alignment for
1861   /// any given AST type that happens to have been lowered to the
1862   /// given IR type.  This should only ever be used for function-local,
1863   /// IR-driven manipulations like saving and restoring a value.  Do
1864   /// not hand this address off to arbitrary IRGen routines, and especially
1865   /// do not pass it as an argument to a function that might expect a
1866   /// properly ABI-aligned value.
1867   Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1868                                        const Twine &Name = "tmp");
1869 
1870   /// InitTempAlloca - Provide an initial value for the given alloca which
1871   /// will be observable at all locations in the function.
1872   ///
1873   /// The address should be something that was returned from one of
1874   /// the CreateTempAlloca or CreateMemTemp routines, and the
1875   /// initializer must be valid in the entry block (i.e. it must
1876   /// either be a constant or an argument value).
1877   void InitTempAlloca(Address Alloca, llvm::Value *Value);
1878 
1879   /// CreateIRTemp - Create a temporary IR object of the given type, with
1880   /// appropriate alignment. This routine should only be used when an temporary
1881   /// value needs to be stored into an alloca (for example, to avoid explicit
1882   /// PHI construction), but the type is the IR type, not the type appropriate
1883   /// for storing in memory.
1884   ///
1885   /// That is, this is exactly equivalent to CreateMemTemp, but calling
1886   /// ConvertType instead of ConvertTypeForMem.
1887   Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1888 
1889   /// CreateMemTemp - Create a temporary memory object of the given type, with
1890   /// appropriate alignment.
1891   Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1892   Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1893 
1894   /// CreateAggTemp - Create a temporary memory object for the given
1895   /// aggregate type.
1896   AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1897     return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1898                                  T.getQualifiers(),
1899                                  AggValueSlot::IsNotDestructed,
1900                                  AggValueSlot::DoesNotNeedGCBarriers,
1901                                  AggValueSlot::IsNotAliased);
1902   }
1903 
1904   /// Emit a cast to void* in the appropriate address space.
1905   llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1906 
1907   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1908   /// expression and compare the result against zero, returning an Int1Ty value.
1909   llvm::Value *EvaluateExprAsBool(const Expr *E);
1910 
1911   /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1912   void EmitIgnoredExpr(const Expr *E);
1913 
1914   /// EmitAnyExpr - Emit code to compute the specified expression which can have
1915   /// any type.  The result is returned as an RValue struct.  If this is an
1916   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1917   /// the result should be returned.
1918   ///
1919   /// \param ignoreResult True if the resulting value isn't used.
1920   RValue EmitAnyExpr(const Expr *E,
1921                      AggValueSlot aggSlot = AggValueSlot::ignored(),
1922                      bool ignoreResult = false);
1923 
1924   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1925   // or the value of the expression, depending on how va_list is defined.
1926   Address EmitVAListRef(const Expr *E);
1927 
1928   /// Emit a "reference" to a __builtin_ms_va_list; this is
1929   /// always the value of the expression, because a __builtin_ms_va_list is a
1930   /// pointer to a char.
1931   Address EmitMSVAListRef(const Expr *E);
1932 
1933   /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1934   /// always be accessible even if no aggregate location is provided.
1935   RValue EmitAnyExprToTemp(const Expr *E);
1936 
1937   /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1938   /// arbitrary expression into the given memory location.
1939   void EmitAnyExprToMem(const Expr *E, Address Location,
1940                         Qualifiers Quals, bool IsInitializer);
1941 
1942   void EmitAnyExprToExn(const Expr *E, Address Addr);
1943 
1944   /// EmitExprAsInit - Emits the code necessary to initialize a
1945   /// location in memory with the given initializer.
1946   void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
1947                       bool capturedByInit);
1948 
1949   /// hasVolatileMember - returns true if aggregate type has a volatile
1950   /// member.
1951   bool hasVolatileMember(QualType T) {
1952     if (const RecordType *RT = T->getAs<RecordType>()) {
1953       const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1954       return RD->hasVolatileMember();
1955     }
1956     return false;
1957   }
1958   /// EmitAggregateCopy - Emit an aggregate assignment.
1959   ///
1960   /// The difference to EmitAggregateCopy is that tail padding is not copied.
1961   /// This is required for correctness when assigning non-POD structures in C++.
1962   void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
1963                            QualType EltTy) {
1964     bool IsVolatile = hasVolatileMember(EltTy);
1965     EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
1966   }
1967 
1968   void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
1969                              QualType DestTy, QualType SrcTy) {
1970     EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
1971                       /*IsAssignment=*/false);
1972   }
1973 
1974   /// EmitAggregateCopy - Emit an aggregate copy.
1975   ///
1976   /// \param isVolatile - True iff either the source or the destination is
1977   /// volatile.
1978   /// \param isAssignment - If false, allow padding to be copied.  This often
1979   /// yields more efficient.
1980   void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
1981                          QualType EltTy, bool isVolatile=false,
1982                          bool isAssignment = false);
1983 
1984   /// GetAddrOfLocalVar - Return the address of a local variable.
1985   Address GetAddrOfLocalVar(const VarDecl *VD) {
1986     auto it = LocalDeclMap.find(VD);
1987     assert(it != LocalDeclMap.end() &&
1988            "Invalid argument to GetAddrOfLocalVar(), no decl!");
1989     return it->second;
1990   }
1991 
1992   /// getOpaqueLValueMapping - Given an opaque value expression (which
1993   /// must be mapped to an l-value), return its mapping.
1994   const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1995     assert(OpaqueValueMapping::shouldBindAsLValue(e));
1996 
1997     llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1998       it = OpaqueLValues.find(e);
1999     assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2000     return it->second;
2001   }
2002 
2003   /// getOpaqueRValueMapping - Given an opaque value expression (which
2004   /// must be mapped to an r-value), return its mapping.
2005   const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2006     assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2007 
2008     llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2009       it = OpaqueRValues.find(e);
2010     assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2011     return it->second;
2012   }
2013 
2014   /// Get the index of the current ArrayInitLoopExpr, if any.
2015   llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2016 
2017   /// getAccessedFieldNo - Given an encoded value and a result number, return
2018   /// the input field number being accessed.
2019   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2020 
2021   llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2022   llvm::BasicBlock *GetIndirectGotoBlock();
2023 
2024   /// EmitNullInitialization - Generate code to set a value of the given type to
2025   /// null, If the type contains data member pointers, they will be initialized
2026   /// to -1 in accordance with the Itanium C++ ABI.
2027   void EmitNullInitialization(Address DestPtr, QualType Ty);
2028 
2029   /// Emits a call to an LLVM variable-argument intrinsic, either
2030   /// \c llvm.va_start or \c llvm.va_end.
2031   /// \param ArgValue A reference to the \c va_list as emitted by either
2032   /// \c EmitVAListRef or \c EmitMSVAListRef.
2033   /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2034   /// calls \c llvm.va_end.
2035   llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2036 
2037   /// Generate code to get an argument from the passed in pointer
2038   /// and update it accordingly.
2039   /// \param VE The \c VAArgExpr for which to generate code.
2040   /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2041   /// either \c EmitVAListRef or \c EmitMSVAListRef.
2042   /// \returns A pointer to the argument.
2043   // FIXME: We should be able to get rid of this method and use the va_arg
2044   // instruction in LLVM instead once it works well enough.
2045   Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2046 
2047   /// emitArrayLength - Compute the length of an array, even if it's a
2048   /// VLA, and drill down to the base element type.
2049   llvm::Value *emitArrayLength(const ArrayType *arrayType,
2050                                QualType &baseType,
2051                                Address &addr);
2052 
2053   /// EmitVLASize - Capture all the sizes for the VLA expressions in
2054   /// the given variably-modified type and store them in the VLASizeMap.
2055   ///
2056   /// This function can be called with a null (unreachable) insert point.
2057   void EmitVariablyModifiedType(QualType Ty);
2058 
2059   /// getVLASize - Returns an LLVM value that corresponds to the size,
2060   /// in non-variably-sized elements, of a variable length array type,
2061   /// plus that largest non-variably-sized element type.  Assumes that
2062   /// the type has already been emitted with EmitVariablyModifiedType.
2063   std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2064   std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2065 
2066   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2067   /// generating code for an C++ member function.
2068   llvm::Value *LoadCXXThis() {
2069     assert(CXXThisValue && "no 'this' value for this function");
2070     return CXXThisValue;
2071   }
2072   Address LoadCXXThisAddress();
2073 
2074   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2075   /// virtual bases.
2076   // FIXME: Every place that calls LoadCXXVTT is something
2077   // that needs to be abstracted properly.
2078   llvm::Value *LoadCXXVTT() {
2079     assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2080     return CXXStructorImplicitParamValue;
2081   }
2082 
2083   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2084   /// complete class to the given direct base.
2085   Address
2086   GetAddressOfDirectBaseInCompleteClass(Address Value,
2087                                         const CXXRecordDecl *Derived,
2088                                         const CXXRecordDecl *Base,
2089                                         bool BaseIsVirtual);
2090 
2091   static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2092 
2093   /// GetAddressOfBaseClass - This function will add the necessary delta to the
2094   /// load of 'this' and returns address of the base class.
2095   Address GetAddressOfBaseClass(Address Value,
2096                                 const CXXRecordDecl *Derived,
2097                                 CastExpr::path_const_iterator PathBegin,
2098                                 CastExpr::path_const_iterator PathEnd,
2099                                 bool NullCheckValue, SourceLocation Loc);
2100 
2101   Address GetAddressOfDerivedClass(Address Value,
2102                                    const CXXRecordDecl *Derived,
2103                                    CastExpr::path_const_iterator PathBegin,
2104                                    CastExpr::path_const_iterator PathEnd,
2105                                    bool NullCheckValue);
2106 
2107   /// GetVTTParameter - Return the VTT parameter that should be passed to a
2108   /// base constructor/destructor with virtual bases.
2109   /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2110   /// to ItaniumCXXABI.cpp together with all the references to VTT.
2111   llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2112                                bool Delegating);
2113 
2114   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2115                                       CXXCtorType CtorType,
2116                                       const FunctionArgList &Args,
2117                                       SourceLocation Loc);
2118   // It's important not to confuse this and the previous function. Delegating
2119   // constructors are the C++0x feature. The constructor delegate optimization
2120   // is used to reduce duplication in the base and complete consturctors where
2121   // they are substantially the same.
2122   void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2123                                         const FunctionArgList &Args);
2124 
2125   /// Emit a call to an inheriting constructor (that is, one that invokes a
2126   /// constructor inherited from a base class) by inlining its definition. This
2127   /// is necessary if the ABI does not support forwarding the arguments to the
2128   /// base class constructor (because they're variadic or similar).
2129   void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2130                                                CXXCtorType CtorType,
2131                                                bool ForVirtualBase,
2132                                                bool Delegating,
2133                                                CallArgList &Args);
2134 
2135   /// Emit a call to a constructor inherited from a base class, passing the
2136   /// current constructor's arguments along unmodified (without even making
2137   /// a copy).
2138   void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2139                                        bool ForVirtualBase, Address This,
2140                                        bool InheritedFromVBase,
2141                                        const CXXInheritedCtorInitExpr *E);
2142 
2143   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2144                               bool ForVirtualBase, bool Delegating,
2145                               Address This, const CXXConstructExpr *E);
2146 
2147   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2148                               bool ForVirtualBase, bool Delegating,
2149                               Address This, CallArgList &Args);
2150 
2151   /// Emit assumption load for all bases. Requires to be be called only on
2152   /// most-derived class and not under construction of the object.
2153   void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2154 
2155   /// Emit assumption that vptr load == global vtable.
2156   void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2157 
2158   void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2159                                       Address This, Address Src,
2160                                       const CXXConstructExpr *E);
2161 
2162   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2163                                   const ArrayType *ArrayTy,
2164                                   Address ArrayPtr,
2165                                   const CXXConstructExpr *E,
2166                                   bool ZeroInitialization = false);
2167 
2168   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2169                                   llvm::Value *NumElements,
2170                                   Address ArrayPtr,
2171                                   const CXXConstructExpr *E,
2172                                   bool ZeroInitialization = false);
2173 
2174   static Destroyer destroyCXXObject;
2175 
2176   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2177                              bool ForVirtualBase, bool Delegating,
2178                              Address This);
2179 
2180   void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2181                                llvm::Type *ElementTy, Address NewPtr,
2182                                llvm::Value *NumElements,
2183                                llvm::Value *AllocSizeWithoutCookie);
2184 
2185   void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2186                         Address Ptr);
2187 
2188   llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2189   void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2190 
2191   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2192   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2193 
2194   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2195                       QualType DeleteTy, llvm::Value *NumElements = nullptr,
2196                       CharUnits CookieSize = CharUnits());
2197 
2198   RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2199                                   const Expr *Arg, bool IsDelete);
2200 
2201   llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2202   llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2203   Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2204 
2205   /// \brief Situations in which we might emit a check for the suitability of a
2206   ///        pointer or glvalue.
2207   enum TypeCheckKind {
2208     /// Checking the operand of a load. Must be suitably sized and aligned.
2209     TCK_Load,
2210     /// Checking the destination of a store. Must be suitably sized and aligned.
2211     TCK_Store,
2212     /// Checking the bound value in a reference binding. Must be suitably sized
2213     /// and aligned, but is not required to refer to an object (until the
2214     /// reference is used), per core issue 453.
2215     TCK_ReferenceBinding,
2216     /// Checking the object expression in a non-static data member access. Must
2217     /// be an object within its lifetime.
2218     TCK_MemberAccess,
2219     /// Checking the 'this' pointer for a call to a non-static member function.
2220     /// Must be an object within its lifetime.
2221     TCK_MemberCall,
2222     /// Checking the 'this' pointer for a constructor call.
2223     TCK_ConstructorCall,
2224     /// Checking the operand of a static_cast to a derived pointer type. Must be
2225     /// null or an object within its lifetime.
2226     TCK_DowncastPointer,
2227     /// Checking the operand of a static_cast to a derived reference type. Must
2228     /// be an object within its lifetime.
2229     TCK_DowncastReference,
2230     /// Checking the operand of a cast to a base object. Must be suitably sized
2231     /// and aligned.
2232     TCK_Upcast,
2233     /// Checking the operand of a cast to a virtual base object. Must be an
2234     /// object within its lifetime.
2235     TCK_UpcastToVirtualBase
2236   };
2237 
2238   /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2239   /// calls to EmitTypeCheck can be skipped.
2240   bool sanitizePerformTypeCheck() const;
2241 
2242   /// \brief Emit a check that \p V is the address of storage of the
2243   /// appropriate size and alignment for an object of type \p Type.
2244   void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2245                      QualType Type, CharUnits Alignment = CharUnits::Zero(),
2246                      bool SkipNullCheck = false);
2247 
2248   /// \brief Emit a check that \p Base points into an array object, which
2249   /// we can access at index \p Index. \p Accessed should be \c false if we
2250   /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2251   void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2252                        QualType IndexType, bool Accessed);
2253 
2254   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2255                                        bool isInc, bool isPre);
2256   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2257                                          bool isInc, bool isPre);
2258 
2259   void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2260                                llvm::Value *OffsetValue = nullptr) {
2261     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2262                                       OffsetValue);
2263   }
2264 
2265   /// Converts Location to a DebugLoc, if debug information is enabled.
2266   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2267 
2268 
2269   //===--------------------------------------------------------------------===//
2270   //                            Declaration Emission
2271   //===--------------------------------------------------------------------===//
2272 
2273   /// EmitDecl - Emit a declaration.
2274   ///
2275   /// This function can be called with a null (unreachable) insert point.
2276   void EmitDecl(const Decl &D);
2277 
2278   /// EmitVarDecl - Emit a local variable declaration.
2279   ///
2280   /// This function can be called with a null (unreachable) insert point.
2281   void EmitVarDecl(const VarDecl &D);
2282 
2283   void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2284                       bool capturedByInit);
2285 
2286   typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2287                              llvm::Value *Address);
2288 
2289   /// \brief Determine whether the given initializer is trivial in the sense
2290   /// that it requires no code to be generated.
2291   bool isTrivialInitializer(const Expr *Init);
2292 
2293   /// EmitAutoVarDecl - Emit an auto variable declaration.
2294   ///
2295   /// This function can be called with a null (unreachable) insert point.
2296   void EmitAutoVarDecl(const VarDecl &D);
2297 
2298   class AutoVarEmission {
2299     friend class CodeGenFunction;
2300 
2301     const VarDecl *Variable;
2302 
2303     /// The address of the alloca.  Invalid if the variable was emitted
2304     /// as a global constant.
2305     Address Addr;
2306 
2307     llvm::Value *NRVOFlag;
2308 
2309     /// True if the variable is a __block variable.
2310     bool IsByRef;
2311 
2312     /// True if the variable is of aggregate type and has a constant
2313     /// initializer.
2314     bool IsConstantAggregate;
2315 
2316     /// Non-null if we should use lifetime annotations.
2317     llvm::Value *SizeForLifetimeMarkers;
2318 
2319     struct Invalid {};
2320     AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2321 
2322     AutoVarEmission(const VarDecl &variable)
2323       : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2324         IsByRef(false), IsConstantAggregate(false),
2325         SizeForLifetimeMarkers(nullptr) {}
2326 
2327     bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2328 
2329   public:
2330     static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2331 
2332     bool useLifetimeMarkers() const {
2333       return SizeForLifetimeMarkers != nullptr;
2334     }
2335     llvm::Value *getSizeForLifetimeMarkers() const {
2336       assert(useLifetimeMarkers());
2337       return SizeForLifetimeMarkers;
2338     }
2339 
2340     /// Returns the raw, allocated address, which is not necessarily
2341     /// the address of the object itself.
2342     Address getAllocatedAddress() const {
2343       return Addr;
2344     }
2345 
2346     /// Returns the address of the object within this declaration.
2347     /// Note that this does not chase the forwarding pointer for
2348     /// __block decls.
2349     Address getObjectAddress(CodeGenFunction &CGF) const {
2350       if (!IsByRef) return Addr;
2351 
2352       return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2353     }
2354   };
2355   AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2356   void EmitAutoVarInit(const AutoVarEmission &emission);
2357   void EmitAutoVarCleanups(const AutoVarEmission &emission);
2358   void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2359                               QualType::DestructionKind dtorKind);
2360 
2361   void EmitStaticVarDecl(const VarDecl &D,
2362                          llvm::GlobalValue::LinkageTypes Linkage);
2363 
2364   class ParamValue {
2365     llvm::Value *Value;
2366     unsigned Alignment;
2367     ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2368   public:
2369     static ParamValue forDirect(llvm::Value *value) {
2370       return ParamValue(value, 0);
2371     }
2372     static ParamValue forIndirect(Address addr) {
2373       assert(!addr.getAlignment().isZero());
2374       return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2375     }
2376 
2377     bool isIndirect() const { return Alignment != 0; }
2378     llvm::Value *getAnyValue() const { return Value; }
2379 
2380     llvm::Value *getDirectValue() const {
2381       assert(!isIndirect());
2382       return Value;
2383     }
2384 
2385     Address getIndirectAddress() const {
2386       assert(isIndirect());
2387       return Address(Value, CharUnits::fromQuantity(Alignment));
2388     }
2389   };
2390 
2391   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2392   void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2393 
2394   /// protectFromPeepholes - Protect a value that we're intending to
2395   /// store to the side, but which will probably be used later, from
2396   /// aggressive peepholing optimizations that might delete it.
2397   ///
2398   /// Pass the result to unprotectFromPeepholes to declare that
2399   /// protection is no longer required.
2400   ///
2401   /// There's no particular reason why this shouldn't apply to
2402   /// l-values, it's just that no existing peepholes work on pointers.
2403   PeepholeProtection protectFromPeepholes(RValue rvalue);
2404   void unprotectFromPeepholes(PeepholeProtection protection);
2405 
2406   //===--------------------------------------------------------------------===//
2407   //                             Statement Emission
2408   //===--------------------------------------------------------------------===//
2409 
2410   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2411   void EmitStopPoint(const Stmt *S);
2412 
2413   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2414   /// this function even if there is no current insertion point.
2415   ///
2416   /// This function may clear the current insertion point; callers should use
2417   /// EnsureInsertPoint if they wish to subsequently generate code without first
2418   /// calling EmitBlock, EmitBranch, or EmitStmt.
2419   void EmitStmt(const Stmt *S);
2420 
2421   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2422   /// necessarily require an insertion point or debug information; typically
2423   /// because the statement amounts to a jump or a container of other
2424   /// statements.
2425   ///
2426   /// \return True if the statement was handled.
2427   bool EmitSimpleStmt(const Stmt *S);
2428 
2429   Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2430                            AggValueSlot AVS = AggValueSlot::ignored());
2431   Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2432                                        bool GetLast = false,
2433                                        AggValueSlot AVS =
2434                                                 AggValueSlot::ignored());
2435 
2436   /// EmitLabel - Emit the block for the given label. It is legal to call this
2437   /// function even if there is no current insertion point.
2438   void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2439 
2440   void EmitLabelStmt(const LabelStmt &S);
2441   void EmitAttributedStmt(const AttributedStmt &S);
2442   void EmitGotoStmt(const GotoStmt &S);
2443   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2444   void EmitIfStmt(const IfStmt &S);
2445 
2446   void EmitWhileStmt(const WhileStmt &S,
2447                      ArrayRef<const Attr *> Attrs = None);
2448   void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2449   void EmitForStmt(const ForStmt &S,
2450                    ArrayRef<const Attr *> Attrs = None);
2451   void EmitReturnStmt(const ReturnStmt &S);
2452   void EmitDeclStmt(const DeclStmt &S);
2453   void EmitBreakStmt(const BreakStmt &S);
2454   void EmitContinueStmt(const ContinueStmt &S);
2455   void EmitSwitchStmt(const SwitchStmt &S);
2456   void EmitDefaultStmt(const DefaultStmt &S);
2457   void EmitCaseStmt(const CaseStmt &S);
2458   void EmitCaseStmtRange(const CaseStmt &S);
2459   void EmitAsmStmt(const AsmStmt &S);
2460 
2461   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2462   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2463   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2464   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2465   void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2466 
2467   void EmitCoroutineBody(const CoroutineBodyStmt &S);
2468   RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2469 
2470   void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2471   void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2472 
2473   void EmitCXXTryStmt(const CXXTryStmt &S);
2474   void EmitSEHTryStmt(const SEHTryStmt &S);
2475   void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2476   void EnterSEHTryStmt(const SEHTryStmt &S);
2477   void ExitSEHTryStmt(const SEHTryStmt &S);
2478 
2479   void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2480                               const Stmt *OutlinedStmt);
2481 
2482   llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2483                                             const SEHExceptStmt &Except);
2484 
2485   llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2486                                              const SEHFinallyStmt &Finally);
2487 
2488   void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2489                                 llvm::Value *ParentFP,
2490                                 llvm::Value *EntryEBP);
2491   llvm::Value *EmitSEHExceptionCode();
2492   llvm::Value *EmitSEHExceptionInfo();
2493   llvm::Value *EmitSEHAbnormalTermination();
2494 
2495   /// Scan the outlined statement for captures from the parent function. For
2496   /// each capture, mark the capture as escaped and emit a call to
2497   /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2498   void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2499                           bool IsFilter);
2500 
2501   /// Recovers the address of a local in a parent function. ParentVar is the
2502   /// address of the variable used in the immediate parent function. It can
2503   /// either be an alloca or a call to llvm.localrecover if there are nested
2504   /// outlined functions. ParentFP is the frame pointer of the outermost parent
2505   /// frame.
2506   Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2507                                     Address ParentVar,
2508                                     llvm::Value *ParentFP);
2509 
2510   void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2511                            ArrayRef<const Attr *> Attrs = None);
2512 
2513   /// Returns calculated size of the specified type.
2514   llvm::Value *getTypeSize(QualType Ty);
2515   LValue InitCapturedStruct(const CapturedStmt &S);
2516   llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2517   llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2518   Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2519   llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2520   void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2521                                   SmallVectorImpl<llvm::Value *> &CapturedVars);
2522   void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2523                           SourceLocation Loc);
2524   /// \brief Perform element by element copying of arrays with type \a
2525   /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2526   /// generated by \a CopyGen.
2527   ///
2528   /// \param DestAddr Address of the destination array.
2529   /// \param SrcAddr Address of the source array.
2530   /// \param OriginalType Type of destination and source arrays.
2531   /// \param CopyGen Copying procedure that copies value of single array element
2532   /// to another single array element.
2533   void EmitOMPAggregateAssign(
2534       Address DestAddr, Address SrcAddr, QualType OriginalType,
2535       const llvm::function_ref<void(Address, Address)> &CopyGen);
2536   /// \brief Emit proper copying of data from one variable to another.
2537   ///
2538   /// \param OriginalType Original type of the copied variables.
2539   /// \param DestAddr Destination address.
2540   /// \param SrcAddr Source address.
2541   /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2542   /// type of the base array element).
2543   /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2544   /// the base array element).
2545   /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2546   /// DestVD.
2547   void EmitOMPCopy(QualType OriginalType,
2548                    Address DestAddr, Address SrcAddr,
2549                    const VarDecl *DestVD, const VarDecl *SrcVD,
2550                    const Expr *Copy);
2551   /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2552   /// \a X = \a E \a BO \a E.
2553   ///
2554   /// \param X Value to be updated.
2555   /// \param E Update value.
2556   /// \param BO Binary operation for update operation.
2557   /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2558   /// expression, false otherwise.
2559   /// \param AO Atomic ordering of the generated atomic instructions.
2560   /// \param CommonGen Code generator for complex expressions that cannot be
2561   /// expressed through atomicrmw instruction.
2562   /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2563   /// generated, <false, RValue::get(nullptr)> otherwise.
2564   std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2565       LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2566       llvm::AtomicOrdering AO, SourceLocation Loc,
2567       const llvm::function_ref<RValue(RValue)> &CommonGen);
2568   bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2569                                  OMPPrivateScope &PrivateScope);
2570   void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2571                             OMPPrivateScope &PrivateScope);
2572   void EmitOMPUseDevicePtrClause(
2573       const OMPClause &C, OMPPrivateScope &PrivateScope,
2574       const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2575   /// \brief Emit code for copyin clause in \a D directive. The next code is
2576   /// generated at the start of outlined functions for directives:
2577   /// \code
2578   /// threadprivate_var1 = master_threadprivate_var1;
2579   /// operator=(threadprivate_var2, master_threadprivate_var2);
2580   /// ...
2581   /// __kmpc_barrier(&loc, global_tid);
2582   /// \endcode
2583   ///
2584   /// \param D OpenMP directive possibly with 'copyin' clause(s).
2585   /// \returns true if at least one copyin variable is found, false otherwise.
2586   bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2587   /// \brief Emit initial code for lastprivate variables. If some variable is
2588   /// not also firstprivate, then the default initialization is used. Otherwise
2589   /// initialization of this variable is performed by EmitOMPFirstprivateClause
2590   /// method.
2591   ///
2592   /// \param D Directive that may have 'lastprivate' directives.
2593   /// \param PrivateScope Private scope for capturing lastprivate variables for
2594   /// proper codegen in internal captured statement.
2595   ///
2596   /// \returns true if there is at least one lastprivate variable, false
2597   /// otherwise.
2598   bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2599                                     OMPPrivateScope &PrivateScope);
2600   /// \brief Emit final copying of lastprivate values to original variables at
2601   /// the end of the worksharing or simd directive.
2602   ///
2603   /// \param D Directive that has at least one 'lastprivate' directives.
2604   /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2605   /// it is the last iteration of the loop code in associated directive, or to
2606   /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2607   void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2608                                      bool NoFinals,
2609                                      llvm::Value *IsLastIterCond = nullptr);
2610   /// Emit initial code for linear clauses.
2611   void EmitOMPLinearClause(const OMPLoopDirective &D,
2612                            CodeGenFunction::OMPPrivateScope &PrivateScope);
2613   /// Emit final code for linear clauses.
2614   /// \param CondGen Optional conditional code for final part of codegen for
2615   /// linear clause.
2616   void EmitOMPLinearClauseFinal(
2617       const OMPLoopDirective &D,
2618       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2619   /// \brief Emit initial code for reduction variables. Creates reduction copies
2620   /// and initializes them with the values according to OpenMP standard.
2621   ///
2622   /// \param D Directive (possibly) with the 'reduction' clause.
2623   /// \param PrivateScope Private scope for capturing reduction variables for
2624   /// proper codegen in internal captured statement.
2625   ///
2626   void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2627                                   OMPPrivateScope &PrivateScope);
2628   /// \brief Emit final update of reduction values to original variables at
2629   /// the end of the directive.
2630   ///
2631   /// \param D Directive that has at least one 'reduction' directives.
2632   void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
2633   /// \brief Emit initial code for linear variables. Creates private copies
2634   /// and initializes them with the values according to OpenMP standard.
2635   ///
2636   /// \param D Directive (possibly) with the 'linear' clause.
2637   void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2638 
2639   typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2640                                         llvm::Value * /*OutlinedFn*/,
2641                                         const OMPTaskDataTy & /*Data*/)>
2642       TaskGenTy;
2643   void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2644                                  const RegionCodeGenTy &BodyGen,
2645                                  const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2646 
2647   void EmitOMPParallelDirective(const OMPParallelDirective &S);
2648   void EmitOMPSimdDirective(const OMPSimdDirective &S);
2649   void EmitOMPForDirective(const OMPForDirective &S);
2650   void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2651   void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2652   void EmitOMPSectionDirective(const OMPSectionDirective &S);
2653   void EmitOMPSingleDirective(const OMPSingleDirective &S);
2654   void EmitOMPMasterDirective(const OMPMasterDirective &S);
2655   void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2656   void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2657   void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2658   void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2659   void EmitOMPTaskDirective(const OMPTaskDirective &S);
2660   void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2661   void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2662   void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2663   void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2664   void EmitOMPFlushDirective(const OMPFlushDirective &S);
2665   void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2666   void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2667   void EmitOMPTargetDirective(const OMPTargetDirective &S);
2668   void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2669   void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2670   void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2671   void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2672   void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2673   void
2674   EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2675   void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2676   void
2677   EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2678   void EmitOMPCancelDirective(const OMPCancelDirective &S);
2679   void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2680   void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2681   void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2682   void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2683   void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
2684   void EmitOMPDistributeParallelForDirective(
2685       const OMPDistributeParallelForDirective &S);
2686   void EmitOMPDistributeParallelForSimdDirective(
2687       const OMPDistributeParallelForSimdDirective &S);
2688   void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2689   void EmitOMPTargetParallelForSimdDirective(
2690       const OMPTargetParallelForSimdDirective &S);
2691   void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2692   void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2693   void
2694   EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2695   void EmitOMPTeamsDistributeParallelForSimdDirective(
2696       const OMPTeamsDistributeParallelForSimdDirective &S);
2697   void EmitOMPTeamsDistributeParallelForDirective(
2698       const OMPTeamsDistributeParallelForDirective &S);
2699 
2700   /// Emit outlined function for the target directive.
2701   static std::pair<llvm::Function * /*OutlinedFn*/,
2702                    llvm::Constant * /*OutlinedFnID*/>
2703   EmitOMPTargetDirectiveOutlinedFunction(CodeGenModule &CGM,
2704                                          const OMPTargetDirective &S,
2705                                          StringRef ParentName,
2706                                          bool IsOffloadEntry);
2707   /// \brief Emit inner loop of the worksharing/simd construct.
2708   ///
2709   /// \param S Directive, for which the inner loop must be emitted.
2710   /// \param RequiresCleanup true, if directive has some associated private
2711   /// variables.
2712   /// \param LoopCond Bollean condition for loop continuation.
2713   /// \param IncExpr Increment expression for loop control variable.
2714   /// \param BodyGen Generator for the inner body of the inner loop.
2715   /// \param PostIncGen Genrator for post-increment code (required for ordered
2716   /// loop directvies).
2717   void EmitOMPInnerLoop(
2718       const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2719       const Expr *IncExpr,
2720       const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2721       const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2722 
2723   JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2724   /// Emit initial code for loop counters of loop-based directives.
2725   void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2726                                   OMPPrivateScope &LoopScope);
2727 
2728 private:
2729   /// Helpers for the OpenMP loop directives.
2730   void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2731   void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2732   void EmitOMPSimdFinal(
2733       const OMPLoopDirective &D,
2734       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2735   /// \brief Emit code for the worksharing loop-based directive.
2736   /// \return true, if this construct has any lastprivate clause, false -
2737   /// otherwise.
2738   bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
2739   void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered,
2740       const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2741       Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2742   void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2743                            bool IsMonotonic, const OMPLoopDirective &S,
2744                            OMPPrivateScope &LoopScope, bool Ordered, Address LB,
2745                            Address UB, Address ST, Address IL,
2746                            llvm::Value *Chunk);
2747   void EmitOMPDistributeOuterLoop(
2748       OpenMPDistScheduleClauseKind ScheduleKind,
2749       const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
2750       Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2751   /// \brief Emit code for sections directive.
2752   void EmitSections(const OMPExecutableDirective &S);
2753 
2754 public:
2755 
2756   //===--------------------------------------------------------------------===//
2757   //                         LValue Expression Emission
2758   //===--------------------------------------------------------------------===//
2759 
2760   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2761   RValue GetUndefRValue(QualType Ty);
2762 
2763   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2764   /// and issue an ErrorUnsupported style diagnostic (using the
2765   /// provided Name).
2766   RValue EmitUnsupportedRValue(const Expr *E,
2767                                const char *Name);
2768 
2769   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2770   /// an ErrorUnsupported style diagnostic (using the provided Name).
2771   LValue EmitUnsupportedLValue(const Expr *E,
2772                                const char *Name);
2773 
2774   /// EmitLValue - Emit code to compute a designator that specifies the location
2775   /// of the expression.
2776   ///
2777   /// This can return one of two things: a simple address or a bitfield
2778   /// reference.  In either case, the LLVM Value* in the LValue structure is
2779   /// guaranteed to be an LLVM pointer type.
2780   ///
2781   /// If this returns a bitfield reference, nothing about the pointee type of
2782   /// the LLVM value is known: For example, it may not be a pointer to an
2783   /// integer.
2784   ///
2785   /// If this returns a normal address, and if the lvalue's C type is fixed
2786   /// size, this method guarantees that the returned pointer type will point to
2787   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
2788   /// variable length type, this is not possible.
2789   ///
2790   LValue EmitLValue(const Expr *E);
2791 
2792   /// \brief Same as EmitLValue but additionally we generate checking code to
2793   /// guard against undefined behavior.  This is only suitable when we know
2794   /// that the address will be used to access the object.
2795   LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2796 
2797   RValue convertTempToRValue(Address addr, QualType type,
2798                              SourceLocation Loc);
2799 
2800   void EmitAtomicInit(Expr *E, LValue lvalue);
2801 
2802   bool LValueIsSuitableForInlineAtomic(LValue Src);
2803 
2804   RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2805                         AggValueSlot Slot = AggValueSlot::ignored());
2806 
2807   RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2808                         llvm::AtomicOrdering AO, bool IsVolatile = false,
2809                         AggValueSlot slot = AggValueSlot::ignored());
2810 
2811   void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2812 
2813   void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2814                        bool IsVolatile, bool isInit);
2815 
2816   std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2817       LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2818       llvm::AtomicOrdering Success =
2819           llvm::AtomicOrdering::SequentiallyConsistent,
2820       llvm::AtomicOrdering Failure =
2821           llvm::AtomicOrdering::SequentiallyConsistent,
2822       bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2823 
2824   void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2825                         const llvm::function_ref<RValue(RValue)> &UpdateOp,
2826                         bool IsVolatile);
2827 
2828   /// EmitToMemory - Change a scalar value from its value
2829   /// representation to its in-memory representation.
2830   llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2831 
2832   /// EmitFromMemory - Change a scalar value from its memory
2833   /// representation to its value representation.
2834   llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2835 
2836   /// EmitLoadOfScalar - Load a scalar value from an address, taking
2837   /// care to appropriately convert from the memory representation to
2838   /// the LLVM value representation.
2839   llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2840                                 SourceLocation Loc,
2841                                 AlignmentSource AlignSource =
2842                                   AlignmentSource::Type,
2843                                 llvm::MDNode *TBAAInfo = nullptr,
2844                                 QualType TBAABaseTy = QualType(),
2845                                 uint64_t TBAAOffset = 0,
2846                                 bool isNontemporal = false);
2847 
2848   /// EmitLoadOfScalar - Load a scalar value from an address, taking
2849   /// care to appropriately convert from the memory representation to
2850   /// the LLVM value representation.  The l-value must be a simple
2851   /// l-value.
2852   llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
2853 
2854   /// EmitStoreOfScalar - Store a scalar value to an address, taking
2855   /// care to appropriately convert from the memory representation to
2856   /// the LLVM value representation.
2857   void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2858                          bool Volatile, QualType Ty,
2859                          AlignmentSource AlignSource = AlignmentSource::Type,
2860                          llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
2861                          QualType TBAABaseTy = QualType(),
2862                          uint64_t TBAAOffset = 0, bool isNontemporal = false);
2863 
2864   /// EmitStoreOfScalar - Store a scalar value to an address, taking
2865   /// care to appropriately convert from the memory representation to
2866   /// the LLVM value representation.  The l-value must be a simple
2867   /// l-value.  The isInit flag indicates whether this is an initialization.
2868   /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2869   void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
2870 
2871   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2872   /// this method emits the address of the lvalue, then loads the result as an
2873   /// rvalue, returning the rvalue.
2874   RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
2875   RValue EmitLoadOfExtVectorElementLValue(LValue V);
2876   RValue EmitLoadOfBitfieldLValue(LValue LV);
2877   RValue EmitLoadOfGlobalRegLValue(LValue LV);
2878 
2879   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2880   /// lvalue, where both are guaranteed to the have the same type, and that type
2881   /// is 'Ty'.
2882   void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
2883   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
2884   void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
2885 
2886   /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2887   /// as EmitStoreThroughLValue.
2888   ///
2889   /// \param Result [out] - If non-null, this will be set to a Value* for the
2890   /// bit-field contents after the store, appropriate for use as the result of
2891   /// an assignment to the bit-field.
2892   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2893                                       llvm::Value **Result=nullptr);
2894 
2895   /// Emit an l-value for an assignment (simple or compound) of complex type.
2896   LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
2897   LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
2898   LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
2899                                              llvm::Value *&Result);
2900 
2901   // Note: only available for agg return types
2902   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
2903   LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
2904   // Note: only available for agg return types
2905   LValue EmitCallExprLValue(const CallExpr *E);
2906   // Note: only available for agg return types
2907   LValue EmitVAArgExprLValue(const VAArgExpr *E);
2908   LValue EmitDeclRefLValue(const DeclRefExpr *E);
2909   LValue EmitStringLiteralLValue(const StringLiteral *E);
2910   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
2911   LValue EmitPredefinedLValue(const PredefinedExpr *E);
2912   LValue EmitUnaryOpLValue(const UnaryOperator *E);
2913   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2914                                 bool Accessed = false);
2915   LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2916                                  bool IsLowerBound = true);
2917   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
2918   LValue EmitMemberExpr(const MemberExpr *E);
2919   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
2920   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
2921   LValue EmitInitListLValue(const InitListExpr *E);
2922   LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
2923   LValue EmitCastLValue(const CastExpr *E);
2924   LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2925   LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
2926 
2927   Address EmitExtVectorElementLValue(LValue V);
2928 
2929   RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
2930 
2931   Address EmitArrayToPointerDecay(const Expr *Array,
2932                                   AlignmentSource *AlignSource = nullptr);
2933 
2934   class ConstantEmission {
2935     llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
2936     ConstantEmission(llvm::Constant *C, bool isReference)
2937       : ValueAndIsReference(C, isReference) {}
2938   public:
2939     ConstantEmission() {}
2940     static ConstantEmission forReference(llvm::Constant *C) {
2941       return ConstantEmission(C, true);
2942     }
2943     static ConstantEmission forValue(llvm::Constant *C) {
2944       return ConstantEmission(C, false);
2945     }
2946 
2947     explicit operator bool() const {
2948       return ValueAndIsReference.getOpaqueValue() != nullptr;
2949     }
2950 
2951     bool isReference() const { return ValueAndIsReference.getInt(); }
2952     LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
2953       assert(isReference());
2954       return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
2955                                             refExpr->getType());
2956     }
2957 
2958     llvm::Constant *getValue() const {
2959       assert(!isReference());
2960       return ValueAndIsReference.getPointer();
2961     }
2962   };
2963 
2964   ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
2965 
2966   RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
2967                                 AggValueSlot slot = AggValueSlot::ignored());
2968   LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
2969 
2970   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2971                               const ObjCIvarDecl *Ivar);
2972   LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
2973   LValue EmitLValueForLambdaField(const FieldDecl *Field);
2974 
2975   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2976   /// if the Field is a reference, this will return the address of the reference
2977   /// and not the address of the value stored in the reference.
2978   LValue EmitLValueForFieldInitialization(LValue Base,
2979                                           const FieldDecl* Field);
2980 
2981   LValue EmitLValueForIvar(QualType ObjectTy,
2982                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
2983                            unsigned CVRQualifiers);
2984 
2985   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2986   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2987   LValue EmitLambdaLValue(const LambdaExpr *E);
2988   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2989   LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
2990 
2991   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
2992   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
2993   LValue EmitStmtExprLValue(const StmtExpr *E);
2994   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
2995   LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
2996   void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
2997 
2998   //===--------------------------------------------------------------------===//
2999   //                         Scalar Expression Emission
3000   //===--------------------------------------------------------------------===//
3001 
3002   /// EmitCall - Generate a call of the given function, expecting the given
3003   /// result type, and using the given argument list which specifies both the
3004   /// LLVM arguments and the types they were derived from.
3005   RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3006                   ReturnValueSlot ReturnValue, const CallArgList &Args,
3007                   llvm::Instruction **callOrInvoke = nullptr);
3008 
3009   RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3010                   ReturnValueSlot ReturnValue,
3011                   llvm::Value *Chain = nullptr);
3012   RValue EmitCallExpr(const CallExpr *E,
3013                       ReturnValueSlot ReturnValue = ReturnValueSlot());
3014   RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3015   CGCallee EmitCallee(const Expr *E);
3016 
3017   void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3018 
3019   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3020                                   const Twine &name = "");
3021   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3022                                   ArrayRef<llvm::Value*> args,
3023                                   const Twine &name = "");
3024   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3025                                           const Twine &name = "");
3026   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3027                                           ArrayRef<llvm::Value*> args,
3028                                           const Twine &name = "");
3029 
3030   llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3031                                   ArrayRef<llvm::Value *> Args,
3032                                   const Twine &Name = "");
3033   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3034                                          ArrayRef<llvm::Value*> args,
3035                                          const Twine &name = "");
3036   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3037                                          const Twine &name = "");
3038   void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3039                                        ArrayRef<llvm::Value*> args);
3040 
3041   CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3042                                      NestedNameSpecifier *Qual,
3043                                      llvm::Type *Ty);
3044 
3045   CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3046                                                CXXDtorType Type,
3047                                                const CXXRecordDecl *RD);
3048 
3049   RValue
3050   EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3051                               const CGCallee &Callee,
3052                               ReturnValueSlot ReturnValue, llvm::Value *This,
3053                               llvm::Value *ImplicitParam,
3054                               QualType ImplicitParamTy, const CallExpr *E,
3055                               CallArgList *RtlArgs);
3056   RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3057                                const CGCallee &Callee,
3058                                llvm::Value *This, llvm::Value *ImplicitParam,
3059                                QualType ImplicitParamTy, const CallExpr *E,
3060                                StructorType Type);
3061   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3062                                ReturnValueSlot ReturnValue);
3063   RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3064                                                const CXXMethodDecl *MD,
3065                                                ReturnValueSlot ReturnValue,
3066                                                bool HasQualifier,
3067                                                NestedNameSpecifier *Qualifier,
3068                                                bool IsArrow, const Expr *Base);
3069   // Compute the object pointer.
3070   Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3071                                           llvm::Value *memberPtr,
3072                                           const MemberPointerType *memberPtrType,
3073                                           AlignmentSource *AlignSource = nullptr);
3074   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3075                                       ReturnValueSlot ReturnValue);
3076 
3077   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3078                                        const CXXMethodDecl *MD,
3079                                        ReturnValueSlot ReturnValue);
3080   RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3081 
3082   RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3083                                 ReturnValueSlot ReturnValue);
3084 
3085   RValue EmitCUDADevicePrintfCallExpr(const CallExpr *E,
3086                                       ReturnValueSlot ReturnValue);
3087 
3088   RValue EmitBuiltinExpr(const FunctionDecl *FD,
3089                          unsigned BuiltinID, const CallExpr *E,
3090                          ReturnValueSlot ReturnValue);
3091 
3092   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3093 
3094   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3095   /// is unhandled by the current target.
3096   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3097 
3098   llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3099                                              const llvm::CmpInst::Predicate Fp,
3100                                              const llvm::CmpInst::Predicate Ip,
3101                                              const llvm::Twine &Name = "");
3102   llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3103 
3104   llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3105                                          unsigned LLVMIntrinsic,
3106                                          unsigned AltLLVMIntrinsic,
3107                                          const char *NameHint,
3108                                          unsigned Modifier,
3109                                          const CallExpr *E,
3110                                          SmallVectorImpl<llvm::Value *> &Ops,
3111                                          Address PtrOp0, Address PtrOp1);
3112   llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3113                                           unsigned Modifier, llvm::Type *ArgTy,
3114                                           const CallExpr *E);
3115   llvm::Value *EmitNeonCall(llvm::Function *F,
3116                             SmallVectorImpl<llvm::Value*> &O,
3117                             const char *name,
3118                             unsigned shift = 0, bool rightshift = false);
3119   llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3120   llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3121                                    bool negateForRightShift);
3122   llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3123                                  llvm::Type *Ty, bool usgn, const char *name);
3124   llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3125   llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3126 
3127   llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3128   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3129   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3130   llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3131   llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3132   llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3133   llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3134                                           const CallExpr *E);
3135 
3136 private:
3137   enum class MSVCIntrin;
3138 
3139 public:
3140   llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3141 
3142   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3143   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3144   llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3145   llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3146   llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3147   llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3148                                 const ObjCMethodDecl *MethodWithObjects);
3149   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3150   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3151                              ReturnValueSlot Return = ReturnValueSlot());
3152 
3153   /// Retrieves the default cleanup kind for an ARC cleanup.
3154   /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3155   CleanupKind getARCCleanupKind() {
3156     return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3157              ? NormalAndEHCleanup : NormalCleanup;
3158   }
3159 
3160   // ARC primitives.
3161   void EmitARCInitWeak(Address addr, llvm::Value *value);
3162   void EmitARCDestroyWeak(Address addr);
3163   llvm::Value *EmitARCLoadWeak(Address addr);
3164   llvm::Value *EmitARCLoadWeakRetained(Address addr);
3165   llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3166   void EmitARCCopyWeak(Address dst, Address src);
3167   void EmitARCMoveWeak(Address dst, Address src);
3168   llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3169   llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3170   llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3171                                   bool resultIgnored);
3172   llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3173                                       bool resultIgnored);
3174   llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3175   llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3176   llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3177   void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3178   void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3179   llvm::Value *EmitARCAutorelease(llvm::Value *value);
3180   llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3181   llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3182   llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3183   llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3184 
3185   std::pair<LValue,llvm::Value*>
3186   EmitARCStoreAutoreleasing(const BinaryOperator *e);
3187   std::pair<LValue,llvm::Value*>
3188   EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3189   std::pair<LValue,llvm::Value*>
3190   EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3191 
3192   llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3193   llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3194   llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3195 
3196   llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3197   llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3198                                             bool allowUnsafeClaim);
3199   llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3200   llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3201   llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3202 
3203   void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3204 
3205   static Destroyer destroyARCStrongImprecise;
3206   static Destroyer destroyARCStrongPrecise;
3207   static Destroyer destroyARCWeak;
3208 
3209   void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3210   llvm::Value *EmitObjCAutoreleasePoolPush();
3211   llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3212   void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3213   void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3214 
3215   /// \brief Emits a reference binding to the passed in expression.
3216   RValue EmitReferenceBindingToExpr(const Expr *E);
3217 
3218   //===--------------------------------------------------------------------===//
3219   //                           Expression Emission
3220   //===--------------------------------------------------------------------===//
3221 
3222   // Expressions are broken into three classes: scalar, complex, aggregate.
3223 
3224   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3225   /// scalar type, returning the result.
3226   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3227 
3228   /// Emit a conversion from the specified type to the specified destination
3229   /// type, both of which are LLVM scalar types.
3230   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3231                                     QualType DstTy, SourceLocation Loc);
3232 
3233   /// Emit a conversion from the specified complex type to the specified
3234   /// destination type, where the destination type is an LLVM scalar type.
3235   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3236                                              QualType DstTy,
3237                                              SourceLocation Loc);
3238 
3239   /// EmitAggExpr - Emit the computation of the specified expression
3240   /// of aggregate type.  The result is computed into the given slot,
3241   /// which may be null to indicate that the value is not needed.
3242   void EmitAggExpr(const Expr *E, AggValueSlot AS);
3243 
3244   /// EmitAggExprToLValue - Emit the computation of the specified expression of
3245   /// aggregate type into a temporary LValue.
3246   LValue EmitAggExprToLValue(const Expr *E);
3247 
3248   /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3249   /// make sure it survives garbage collection until this point.
3250   void EmitExtendGCLifetime(llvm::Value *object);
3251 
3252   /// EmitComplexExpr - Emit the computation of the specified expression of
3253   /// complex type, returning the result.
3254   ComplexPairTy EmitComplexExpr(const Expr *E,
3255                                 bool IgnoreReal = false,
3256                                 bool IgnoreImag = false);
3257 
3258   /// EmitComplexExprIntoLValue - Emit the given expression of complex
3259   /// type and place its result into the specified l-value.
3260   void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3261 
3262   /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3263   void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3264 
3265   /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3266   ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3267 
3268   Address emitAddrOfRealComponent(Address complex, QualType complexType);
3269   Address emitAddrOfImagComponent(Address complex, QualType complexType);
3270 
3271   /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3272   /// global variable that has already been created for it.  If the initializer
3273   /// has a different type than GV does, this may free GV and return a different
3274   /// one.  Otherwise it just returns GV.
3275   llvm::GlobalVariable *
3276   AddInitializerToStaticVarDecl(const VarDecl &D,
3277                                 llvm::GlobalVariable *GV);
3278 
3279 
3280   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3281   /// variable with global storage.
3282   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3283                                 bool PerformInit);
3284 
3285   llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3286                                    llvm::Constant *Addr);
3287 
3288   /// Call atexit() with a function that passes the given argument to
3289   /// the given function.
3290   void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3291                                     llvm::Constant *addr);
3292 
3293   /// Emit code in this function to perform a guarded variable
3294   /// initialization.  Guarded initializations are used when it's not
3295   /// possible to prove that an initialization will be done exactly
3296   /// once, e.g. with a static local variable or a static data member
3297   /// of a class template.
3298   void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3299                           bool PerformInit);
3300 
3301   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3302   /// variables.
3303   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3304                                  ArrayRef<llvm::Function *> CXXThreadLocals,
3305                                  Address Guard = Address::invalid());
3306 
3307   /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3308   /// variables.
3309   void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
3310                                   const std::vector<std::pair<llvm::WeakVH,
3311                                   llvm::Constant*> > &DtorsAndObjects);
3312 
3313   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3314                                         const VarDecl *D,
3315                                         llvm::GlobalVariable *Addr,
3316                                         bool PerformInit);
3317 
3318   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3319 
3320   void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3321 
3322   void enterFullExpression(const ExprWithCleanups *E) {
3323     if (E->getNumObjects() == 0) return;
3324     enterNonTrivialFullExpression(E);
3325   }
3326   void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3327 
3328   void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3329 
3330   void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3331 
3332   RValue EmitAtomicExpr(AtomicExpr *E);
3333 
3334   //===--------------------------------------------------------------------===//
3335   //                         Annotations Emission
3336   //===--------------------------------------------------------------------===//
3337 
3338   /// Emit an annotation call (intrinsic or builtin).
3339   llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3340                                   llvm::Value *AnnotatedVal,
3341                                   StringRef AnnotationStr,
3342                                   SourceLocation Location);
3343 
3344   /// Emit local annotations for the local variable V, declared by D.
3345   void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3346 
3347   /// Emit field annotations for the given field & value. Returns the
3348   /// annotation result.
3349   Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3350 
3351   //===--------------------------------------------------------------------===//
3352   //                             Internal Helpers
3353   //===--------------------------------------------------------------------===//
3354 
3355   /// ContainsLabel - Return true if the statement contains a label in it.  If
3356   /// this statement is not executed normally, it not containing a label means
3357   /// that we can just remove the code.
3358   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3359 
3360   /// containsBreak - Return true if the statement contains a break out of it.
3361   /// If the statement (recursively) contains a switch or loop with a break
3362   /// inside of it, this is fine.
3363   static bool containsBreak(const Stmt *S);
3364 
3365   /// Determine if the given statement might introduce a declaration into the
3366   /// current scope, by being a (possibly-labelled) DeclStmt.
3367   static bool mightAddDeclToScope(const Stmt *S);
3368 
3369   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3370   /// to a constant, or if it does but contains a label, return false.  If it
3371   /// constant folds return true and set the boolean result in Result.
3372   bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3373                                     bool AllowLabels = false);
3374 
3375   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3376   /// to a constant, or if it does but contains a label, return false.  If it
3377   /// constant folds return true and set the folded value.
3378   bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3379                                     bool AllowLabels = false);
3380 
3381   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3382   /// if statement) to the specified blocks.  Based on the condition, this might
3383   /// try to simplify the codegen of the conditional based on the branch.
3384   /// TrueCount should be the number of times we expect the condition to
3385   /// evaluate to true based on PGO data.
3386   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3387                             llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3388 
3389   /// \brief Emit a description of a type in a format suitable for passing to
3390   /// a runtime sanitizer handler.
3391   llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3392 
3393   /// \brief Convert a value into a format suitable for passing to a runtime
3394   /// sanitizer handler.
3395   llvm::Value *EmitCheckValue(llvm::Value *V);
3396 
3397   /// \brief Emit a description of a source location in a format suitable for
3398   /// passing to a runtime sanitizer handler.
3399   llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3400 
3401   /// \brief Create a basic block that will call a handler function in a
3402   /// sanitizer runtime with the provided arguments, and create a conditional
3403   /// branch to it.
3404   void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3405                  SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3406                  ArrayRef<llvm::Value *> DynamicArgs);
3407 
3408   /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3409   /// if Cond if false.
3410   void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3411                             llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3412                             ArrayRef<llvm::Constant *> StaticArgs);
3413 
3414   /// \brief Create a basic block that will call the trap intrinsic, and emit a
3415   /// conditional branch to it, for the -ftrapv checks.
3416   void EmitTrapCheck(llvm::Value *Checked);
3417 
3418   /// \brief Emit a call to trap or debugtrap and attach function attribute
3419   /// "trap-func-name" if specified.
3420   llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3421 
3422   /// \brief Emit a cross-DSO CFI failure handling function.
3423   void EmitCfiCheckFail();
3424 
3425   /// \brief Create a check for a function parameter that may potentially be
3426   /// declared as non-null.
3427   void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3428                            const FunctionDecl *FD, unsigned ParmNum);
3429 
3430   /// EmitCallArg - Emit a single call argument.
3431   void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3432 
3433   /// EmitDelegateCallArg - We are performing a delegate call; that
3434   /// is, the current function is delegating to another one.  Produce
3435   /// a r-value suitable for passing the given parameter.
3436   void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3437                            SourceLocation loc);
3438 
3439   /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3440   /// point operation, expressed as the maximum relative error in ulp.
3441   void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3442 
3443 private:
3444   llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3445   void EmitReturnOfRValue(RValue RV, QualType Ty);
3446 
3447   void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3448 
3449   llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3450   DeferredReplacements;
3451 
3452   /// Set the address of a local variable.
3453   void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3454     assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3455     LocalDeclMap.insert({VD, Addr});
3456   }
3457 
3458   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3459   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3460   ///
3461   /// \param AI - The first function argument of the expansion.
3462   void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3463                           SmallVectorImpl<llvm::Value *>::iterator &AI);
3464 
3465   /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3466   /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3467   /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3468   void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3469                         SmallVectorImpl<llvm::Value *> &IRCallArgs,
3470                         unsigned &IRCallArgPos);
3471 
3472   llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3473                             const Expr *InputExpr, std::string &ConstraintStr);
3474 
3475   llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3476                                   LValue InputValue, QualType InputType,
3477                                   std::string &ConstraintStr,
3478                                   SourceLocation Loc);
3479 
3480   /// \brief Attempts to statically evaluate the object size of E. If that
3481   /// fails, emits code to figure the size of E out for us. This is
3482   /// pass_object_size aware.
3483   llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3484                                                llvm::IntegerType *ResType);
3485 
3486   /// \brief Emits the size of E, as required by __builtin_object_size. This
3487   /// function is aware of pass_object_size parameters, and will act accordingly
3488   /// if E is a parameter with the pass_object_size attribute.
3489   llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3490                                      llvm::IntegerType *ResType);
3491 
3492 public:
3493 #ifndef NDEBUG
3494   // Determine whether the given argument is an Objective-C method
3495   // that may have type parameters in its signature.
3496   static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3497     const DeclContext *dc = method->getDeclContext();
3498     if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3499       return classDecl->getTypeParamListAsWritten();
3500     }
3501 
3502     if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3503       return catDecl->getTypeParamList();
3504     }
3505 
3506     return false;
3507   }
3508 
3509   template<typename T>
3510   static bool isObjCMethodWithTypeParams(const T *) { return false; }
3511 #endif
3512 
3513   enum class EvaluationOrder {
3514     ///! No language constraints on evaluation order.
3515     Default,
3516     ///! Language semantics require left-to-right evaluation.
3517     ForceLeftToRight,
3518     ///! Language semantics require right-to-left evaluation.
3519     ForceRightToLeft
3520   };
3521 
3522   /// EmitCallArgs - Emit call arguments for a function.
3523   template <typename T>
3524   void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3525                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3526                     const FunctionDecl *CalleeDecl = nullptr,
3527                     unsigned ParamsToSkip = 0,
3528                     EvaluationOrder Order = EvaluationOrder::Default) {
3529     SmallVector<QualType, 16> ArgTypes;
3530     CallExpr::const_arg_iterator Arg = ArgRange.begin();
3531 
3532     assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3533            "Can't skip parameters if type info is not provided");
3534     if (CallArgTypeInfo) {
3535 #ifndef NDEBUG
3536       bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3537 #endif
3538 
3539       // First, use the argument types that the type info knows about
3540       for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3541                 E = CallArgTypeInfo->param_type_end();
3542            I != E; ++I, ++Arg) {
3543         assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3544         assert((isGenericMethod ||
3545                 ((*I)->isVariablyModifiedType() ||
3546                  (*I).getNonReferenceType()->isObjCRetainableType() ||
3547                  getContext()
3548                          .getCanonicalType((*I).getNonReferenceType())
3549                          .getTypePtr() ==
3550                      getContext()
3551                          .getCanonicalType((*Arg)->getType())
3552                          .getTypePtr())) &&
3553                "type mismatch in call argument!");
3554         ArgTypes.push_back(*I);
3555       }
3556     }
3557 
3558     // Either we've emitted all the call args, or we have a call to variadic
3559     // function.
3560     assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3561             CallArgTypeInfo->isVariadic()) &&
3562            "Extra arguments in non-variadic function!");
3563 
3564     // If we still have any arguments, emit them using the type of the argument.
3565     for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3566       ArgTypes.push_back(getVarArgType(A));
3567 
3568     EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip, Order);
3569   }
3570 
3571   void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3572                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3573                     const FunctionDecl *CalleeDecl = nullptr,
3574                     unsigned ParamsToSkip = 0,
3575                     EvaluationOrder Order = EvaluationOrder::Default);
3576 
3577   /// EmitPointerWithAlignment - Given an expression with a pointer
3578   /// type, emit the value and compute our best estimate of the
3579   /// alignment of the pointee.
3580   ///
3581   /// Note that this function will conservatively fall back on the type
3582   /// when it doesn't
3583   ///
3584   /// \param Source - If non-null, this will be initialized with
3585   ///   information about the source of the alignment.  Note that this
3586   ///   function will conservatively fall back on the type when it
3587   ///   doesn't recognize the expression, which means that sometimes
3588   ///
3589   ///   a worst-case One
3590   ///   reasonable way to use this information is when there's a
3591   ///   language guarantee that the pointer must be aligned to some
3592   ///   stricter value, and we're simply trying to ensure that
3593   ///   sufficiently obvious uses of under-aligned objects don't get
3594   ///   miscompiled; for example, a placement new into the address of
3595   ///   a local variable.  In such a case, it's quite reasonable to
3596   ///   just ignore the returned alignment when it isn't from an
3597   ///   explicit source.
3598   Address EmitPointerWithAlignment(const Expr *Addr,
3599                                    AlignmentSource *Source = nullptr);
3600 
3601   void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3602 
3603 private:
3604   QualType getVarArgType(const Expr *Arg);
3605 
3606   const TargetCodeGenInfo &getTargetHooks() const {
3607     return CGM.getTargetCodeGenInfo();
3608   }
3609 
3610   void EmitDeclMetadata();
3611 
3612   BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3613                                   const AutoVarEmission &emission);
3614 
3615   void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3616 
3617   llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3618 };
3619 
3620 /// Helper class with most of the code for saving a value for a
3621 /// conditional expression cleanup.
3622 struct DominatingLLVMValue {
3623   typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3624 
3625   /// Answer whether the given value needs extra work to be saved.
3626   static bool needsSaving(llvm::Value *value) {
3627     // If it's not an instruction, we don't need to save.
3628     if (!isa<llvm::Instruction>(value)) return false;
3629 
3630     // If it's an instruction in the entry block, we don't need to save.
3631     llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3632     return (block != &block->getParent()->getEntryBlock());
3633   }
3634 
3635   /// Try to save the given value.
3636   static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3637     if (!needsSaving(value)) return saved_type(value, false);
3638 
3639     // Otherwise, we need an alloca.
3640     auto align = CharUnits::fromQuantity(
3641               CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3642     Address alloca =
3643       CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3644     CGF.Builder.CreateStore(value, alloca);
3645 
3646     return saved_type(alloca.getPointer(), true);
3647   }
3648 
3649   static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3650     // If the value says it wasn't saved, trust that it's still dominating.
3651     if (!value.getInt()) return value.getPointer();
3652 
3653     // Otherwise, it should be an alloca instruction, as set up in save().
3654     auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3655     return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3656   }
3657 };
3658 
3659 /// A partial specialization of DominatingValue for llvm::Values that
3660 /// might be llvm::Instructions.
3661 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3662   typedef T *type;
3663   static type restore(CodeGenFunction &CGF, saved_type value) {
3664     return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3665   }
3666 };
3667 
3668 /// A specialization of DominatingValue for Address.
3669 template <> struct DominatingValue<Address> {
3670   typedef Address type;
3671 
3672   struct saved_type {
3673     DominatingLLVMValue::saved_type SavedValue;
3674     CharUnits Alignment;
3675   };
3676 
3677   static bool needsSaving(type value) {
3678     return DominatingLLVMValue::needsSaving(value.getPointer());
3679   }
3680   static saved_type save(CodeGenFunction &CGF, type value) {
3681     return { DominatingLLVMValue::save(CGF, value.getPointer()),
3682              value.getAlignment() };
3683   }
3684   static type restore(CodeGenFunction &CGF, saved_type value) {
3685     return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3686                    value.Alignment);
3687   }
3688 };
3689 
3690 /// A specialization of DominatingValue for RValue.
3691 template <> struct DominatingValue<RValue> {
3692   typedef RValue type;
3693   class saved_type {
3694     enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3695                 AggregateAddress, ComplexAddress };
3696 
3697     llvm::Value *Value;
3698     unsigned K : 3;
3699     unsigned Align : 29;
3700     saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3701       : Value(v), K(k), Align(a) {}
3702 
3703   public:
3704     static bool needsSaving(RValue value);
3705     static saved_type save(CodeGenFunction &CGF, RValue value);
3706     RValue restore(CodeGenFunction &CGF);
3707 
3708     // implementations in CGCleanup.cpp
3709   };
3710 
3711   static bool needsSaving(type value) {
3712     return saved_type::needsSaving(value);
3713   }
3714   static saved_type save(CodeGenFunction &CGF, type value) {
3715     return saved_type::save(CGF, value);
3716   }
3717   static type restore(CodeGenFunction &CGF, saved_type value) {
3718     return value.restore(CGF);
3719   }
3720 };
3721 
3722 }  // end namespace CodeGen
3723 }  // end namespace clang
3724 
3725 #endif
3726