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 
1606   /// Struct with all informations about dynamic [sub]class needed to set vptr.
1607   struct VPtr {
1608     BaseSubobject Base;
1609     const CXXRecordDecl *NearestVBase;
1610     CharUnits OffsetFromNearestVBase;
1611     const CXXRecordDecl *VTableClass;
1612   };
1613 
1614   /// Initialize the vtable pointer of the given subobject.
1615   void InitializeVTablePointer(const VPtr &vptr);
1616 
1617   typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1618 
1619   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1620   VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1621 
1622   void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1623                          CharUnits OffsetFromNearestVBase,
1624                          bool BaseIsNonVirtualPrimaryBase,
1625                          const CXXRecordDecl *VTableClass,
1626                          VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1627 
1628   void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1629 
1630   /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1631   /// to by This.
1632   llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1633                             const CXXRecordDecl *VTableClass);
1634 
1635   enum CFITypeCheckKind {
1636     CFITCK_VCall,
1637     CFITCK_NVCall,
1638     CFITCK_DerivedCast,
1639     CFITCK_UnrelatedCast,
1640     CFITCK_ICall,
1641   };
1642 
1643   /// \brief Derived is the presumed address of an object of type T after a
1644   /// cast. If T is a polymorphic class type, emit a check that the virtual
1645   /// table for Derived belongs to a class derived from T.
1646   void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1647                                  bool MayBeNull, CFITypeCheckKind TCK,
1648                                  SourceLocation Loc);
1649 
1650   /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1651   /// If vptr CFI is enabled, emit a check that VTable is valid.
1652   void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1653                                  CFITypeCheckKind TCK, SourceLocation Loc);
1654 
1655   /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1656   /// RD using llvm.type.test.
1657   void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1658                           CFITypeCheckKind TCK, SourceLocation Loc);
1659 
1660   /// If whole-program virtual table optimization is enabled, emit an assumption
1661   /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1662   /// enabled, emit a check that VTable is a member of RD's type identifier.
1663   void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1664                                     llvm::Value *VTable, SourceLocation Loc);
1665 
1666   /// Returns whether we should perform a type checked load when loading a
1667   /// virtual function for virtual calls to members of RD. This is generally
1668   /// true when both vcall CFI and whole-program-vtables are enabled.
1669   bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1670 
1671   /// Emit a type checked load from the given vtable.
1672   llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1673                                          uint64_t VTableByteOffset);
1674 
1675   /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1676   /// expr can be devirtualized.
1677   bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1678                                          const CXXMethodDecl *MD);
1679 
1680   /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1681   /// given phase of destruction for a destructor.  The end result
1682   /// should call destructors on members and base classes in reverse
1683   /// order of their construction.
1684   void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1685 
1686   /// ShouldInstrumentFunction - Return true if the current function should be
1687   /// instrumented with __cyg_profile_func_* calls
1688   bool ShouldInstrumentFunction();
1689 
1690   /// ShouldXRayInstrument - Return true if the current function should be
1691   /// instrumented with XRay nop sleds.
1692   bool ShouldXRayInstrumentFunction() const;
1693 
1694   /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1695   /// instrumentation function with the current function and the call site, if
1696   /// function instrumentation is enabled.
1697   void EmitFunctionInstrumentation(const char *Fn);
1698 
1699   /// EmitMCountInstrumentation - Emit call to .mcount.
1700   void EmitMCountInstrumentation();
1701 
1702   /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1703   /// arguments for the given function. This is also responsible for naming the
1704   /// LLVM function arguments.
1705   void EmitFunctionProlog(const CGFunctionInfo &FI,
1706                           llvm::Function *Fn,
1707                           const FunctionArgList &Args);
1708 
1709   /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1710   /// given temporary.
1711   void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1712                           SourceLocation EndLoc);
1713 
1714   /// EmitStartEHSpec - Emit the start of the exception spec.
1715   void EmitStartEHSpec(const Decl *D);
1716 
1717   /// EmitEndEHSpec - Emit the end of the exception spec.
1718   void EmitEndEHSpec(const Decl *D);
1719 
1720   /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1721   llvm::BasicBlock *getTerminateLandingPad();
1722 
1723   /// getTerminateHandler - Return a handler (not a landing pad, just
1724   /// a catch handler) that just calls terminate.  This is used when
1725   /// a terminate scope encloses a try.
1726   llvm::BasicBlock *getTerminateHandler();
1727 
1728   llvm::Type *ConvertTypeForMem(QualType T);
1729   llvm::Type *ConvertType(QualType T);
1730   llvm::Type *ConvertType(const TypeDecl *T) {
1731     return ConvertType(getContext().getTypeDeclType(T));
1732   }
1733 
1734   /// LoadObjCSelf - Load the value of self. This function is only valid while
1735   /// generating code for an Objective-C method.
1736   llvm::Value *LoadObjCSelf();
1737 
1738   /// TypeOfSelfObject - Return type of object that this self represents.
1739   QualType TypeOfSelfObject();
1740 
1741   /// hasAggregateLLVMType - Return true if the specified AST type will map into
1742   /// an aggregate LLVM type or is void.
1743   static TypeEvaluationKind getEvaluationKind(QualType T);
1744 
1745   static bool hasScalarEvaluationKind(QualType T) {
1746     return getEvaluationKind(T) == TEK_Scalar;
1747   }
1748 
1749   static bool hasAggregateEvaluationKind(QualType T) {
1750     return getEvaluationKind(T) == TEK_Aggregate;
1751   }
1752 
1753   /// createBasicBlock - Create an LLVM basic block.
1754   llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1755                                      llvm::Function *parent = nullptr,
1756                                      llvm::BasicBlock *before = nullptr) {
1757 #ifdef NDEBUG
1758     return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1759 #else
1760     return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1761 #endif
1762   }
1763 
1764   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1765   /// label maps to.
1766   JumpDest getJumpDestForLabel(const LabelDecl *S);
1767 
1768   /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1769   /// another basic block, simplify it. This assumes that no other code could
1770   /// potentially reference the basic block.
1771   void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1772 
1773   /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1774   /// adding a fall-through branch from the current insert block if
1775   /// necessary. It is legal to call this function even if there is no current
1776   /// insertion point.
1777   ///
1778   /// IsFinished - If true, indicates that the caller has finished emitting
1779   /// branches to the given block and does not expect to emit code into it. This
1780   /// means the block can be ignored if it is unreachable.
1781   void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1782 
1783   /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1784   /// near its uses, and leave the insertion point in it.
1785   void EmitBlockAfterUses(llvm::BasicBlock *BB);
1786 
1787   /// EmitBranch - Emit a branch to the specified basic block from the current
1788   /// insert block, taking care to avoid creation of branches from dummy
1789   /// blocks. It is legal to call this function even if there is no current
1790   /// insertion point.
1791   ///
1792   /// This function clears the current insertion point. The caller should follow
1793   /// calls to this function with calls to Emit*Block prior to generation new
1794   /// code.
1795   void EmitBranch(llvm::BasicBlock *Block);
1796 
1797   /// HaveInsertPoint - True if an insertion point is defined. If not, this
1798   /// indicates that the current code being emitted is unreachable.
1799   bool HaveInsertPoint() const {
1800     return Builder.GetInsertBlock() != nullptr;
1801   }
1802 
1803   /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1804   /// emitted IR has a place to go. Note that by definition, if this function
1805   /// creates a block then that block is unreachable; callers may do better to
1806   /// detect when no insertion point is defined and simply skip IR generation.
1807   void EnsureInsertPoint() {
1808     if (!HaveInsertPoint())
1809       EmitBlock(createBasicBlock());
1810   }
1811 
1812   /// ErrorUnsupported - Print out an error that codegen doesn't support the
1813   /// specified stmt yet.
1814   void ErrorUnsupported(const Stmt *S, const char *Type);
1815 
1816   //===--------------------------------------------------------------------===//
1817   //                                  Helpers
1818   //===--------------------------------------------------------------------===//
1819 
1820   LValue MakeAddrLValue(Address Addr, QualType T,
1821                         AlignmentSource AlignSource = AlignmentSource::Type) {
1822     return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
1823                             CGM.getTBAAInfo(T));
1824   }
1825 
1826   LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1827                         AlignmentSource AlignSource = AlignmentSource::Type) {
1828     return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1829                             AlignSource, CGM.getTBAAInfo(T));
1830   }
1831 
1832   LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1833   LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1834   CharUnits getNaturalTypeAlignment(QualType T,
1835                                     AlignmentSource *Source = nullptr,
1836                                     bool forPointeeType = false);
1837   CharUnits getNaturalPointeeTypeAlignment(QualType T,
1838                                            AlignmentSource *Source = nullptr);
1839 
1840   Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1841                               AlignmentSource *Source = nullptr);
1842   LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1843 
1844   Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1845                             AlignmentSource *Source = nullptr);
1846   LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1847 
1848   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1849   /// block. The caller is responsible for setting an appropriate alignment on
1850   /// the alloca.
1851   llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1852                                      const Twine &Name = "tmp");
1853   Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1854                            const Twine &Name = "tmp");
1855 
1856   /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1857   /// default ABI alignment of the given LLVM type.
1858   ///
1859   /// IMPORTANT NOTE: This is *not* generally the right alignment for
1860   /// any given AST type that happens to have been lowered to the
1861   /// given IR type.  This should only ever be used for function-local,
1862   /// IR-driven manipulations like saving and restoring a value.  Do
1863   /// not hand this address off to arbitrary IRGen routines, and especially
1864   /// do not pass it as an argument to a function that might expect a
1865   /// properly ABI-aligned value.
1866   Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1867                                        const Twine &Name = "tmp");
1868 
1869   /// InitTempAlloca - Provide an initial value for the given alloca which
1870   /// will be observable at all locations in the function.
1871   ///
1872   /// The address should be something that was returned from one of
1873   /// the CreateTempAlloca or CreateMemTemp routines, and the
1874   /// initializer must be valid in the entry block (i.e. it must
1875   /// either be a constant or an argument value).
1876   void InitTempAlloca(Address Alloca, llvm::Value *Value);
1877 
1878   /// CreateIRTemp - Create a temporary IR object of the given type, with
1879   /// appropriate alignment. This routine should only be used when an temporary
1880   /// value needs to be stored into an alloca (for example, to avoid explicit
1881   /// PHI construction), but the type is the IR type, not the type appropriate
1882   /// for storing in memory.
1883   ///
1884   /// That is, this is exactly equivalent to CreateMemTemp, but calling
1885   /// ConvertType instead of ConvertTypeForMem.
1886   Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1887 
1888   /// CreateMemTemp - Create a temporary memory object of the given type, with
1889   /// appropriate alignment.
1890   Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1891   Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1892 
1893   /// CreateAggTemp - Create a temporary memory object for the given
1894   /// aggregate type.
1895   AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1896     return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1897                                  T.getQualifiers(),
1898                                  AggValueSlot::IsNotDestructed,
1899                                  AggValueSlot::DoesNotNeedGCBarriers,
1900                                  AggValueSlot::IsNotAliased);
1901   }
1902 
1903   /// Emit a cast to void* in the appropriate address space.
1904   llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1905 
1906   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1907   /// expression and compare the result against zero, returning an Int1Ty value.
1908   llvm::Value *EvaluateExprAsBool(const Expr *E);
1909 
1910   /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1911   void EmitIgnoredExpr(const Expr *E);
1912 
1913   /// EmitAnyExpr - Emit code to compute the specified expression which can have
1914   /// any type.  The result is returned as an RValue struct.  If this is an
1915   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1916   /// the result should be returned.
1917   ///
1918   /// \param ignoreResult True if the resulting value isn't used.
1919   RValue EmitAnyExpr(const Expr *E,
1920                      AggValueSlot aggSlot = AggValueSlot::ignored(),
1921                      bool ignoreResult = false);
1922 
1923   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1924   // or the value of the expression, depending on how va_list is defined.
1925   Address EmitVAListRef(const Expr *E);
1926 
1927   /// Emit a "reference" to a __builtin_ms_va_list; this is
1928   /// always the value of the expression, because a __builtin_ms_va_list is a
1929   /// pointer to a char.
1930   Address EmitMSVAListRef(const Expr *E);
1931 
1932   /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1933   /// always be accessible even if no aggregate location is provided.
1934   RValue EmitAnyExprToTemp(const Expr *E);
1935 
1936   /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1937   /// arbitrary expression into the given memory location.
1938   void EmitAnyExprToMem(const Expr *E, Address Location,
1939                         Qualifiers Quals, bool IsInitializer);
1940 
1941   void EmitAnyExprToExn(const Expr *E, Address Addr);
1942 
1943   /// EmitExprAsInit - Emits the code necessary to initialize a
1944   /// location in memory with the given initializer.
1945   void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
1946                       bool capturedByInit);
1947 
1948   /// hasVolatileMember - returns true if aggregate type has a volatile
1949   /// member.
1950   bool hasVolatileMember(QualType T) {
1951     if (const RecordType *RT = T->getAs<RecordType>()) {
1952       const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1953       return RD->hasVolatileMember();
1954     }
1955     return false;
1956   }
1957   /// EmitAggregateCopy - Emit an aggregate assignment.
1958   ///
1959   /// The difference to EmitAggregateCopy is that tail padding is not copied.
1960   /// This is required for correctness when assigning non-POD structures in C++.
1961   void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
1962                            QualType EltTy) {
1963     bool IsVolatile = hasVolatileMember(EltTy);
1964     EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
1965   }
1966 
1967   void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
1968                              QualType DestTy, QualType SrcTy) {
1969     EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
1970                       /*IsAssignment=*/false);
1971   }
1972 
1973   /// EmitAggregateCopy - Emit an aggregate copy.
1974   ///
1975   /// \param isVolatile - True iff either the source or the destination is
1976   /// volatile.
1977   /// \param isAssignment - If false, allow padding to be copied.  This often
1978   /// yields more efficient.
1979   void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
1980                          QualType EltTy, bool isVolatile=false,
1981                          bool isAssignment = false);
1982 
1983   /// GetAddrOfLocalVar - Return the address of a local variable.
1984   Address GetAddrOfLocalVar(const VarDecl *VD) {
1985     auto it = LocalDeclMap.find(VD);
1986     assert(it != LocalDeclMap.end() &&
1987            "Invalid argument to GetAddrOfLocalVar(), no decl!");
1988     return it->second;
1989   }
1990 
1991   /// getOpaqueLValueMapping - Given an opaque value expression (which
1992   /// must be mapped to an l-value), return its mapping.
1993   const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1994     assert(OpaqueValueMapping::shouldBindAsLValue(e));
1995 
1996     llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1997       it = OpaqueLValues.find(e);
1998     assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
1999     return it->second;
2000   }
2001 
2002   /// getOpaqueRValueMapping - Given an opaque value expression (which
2003   /// must be mapped to an r-value), return its mapping.
2004   const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2005     assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2006 
2007     llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2008       it = OpaqueRValues.find(e);
2009     assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2010     return it->second;
2011   }
2012 
2013   /// Get the index of the current ArrayInitLoopExpr, if any.
2014   llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2015 
2016   /// getAccessedFieldNo - Given an encoded value and a result number, return
2017   /// the input field number being accessed.
2018   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2019 
2020   llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2021   llvm::BasicBlock *GetIndirectGotoBlock();
2022 
2023   /// EmitNullInitialization - Generate code to set a value of the given type to
2024   /// null, If the type contains data member pointers, they will be initialized
2025   /// to -1 in accordance with the Itanium C++ ABI.
2026   void EmitNullInitialization(Address DestPtr, QualType Ty);
2027 
2028   /// Emits a call to an LLVM variable-argument intrinsic, either
2029   /// \c llvm.va_start or \c llvm.va_end.
2030   /// \param ArgValue A reference to the \c va_list as emitted by either
2031   /// \c EmitVAListRef or \c EmitMSVAListRef.
2032   /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2033   /// calls \c llvm.va_end.
2034   llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2035 
2036   /// Generate code to get an argument from the passed in pointer
2037   /// and update it accordingly.
2038   /// \param VE The \c VAArgExpr for which to generate code.
2039   /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2040   /// either \c EmitVAListRef or \c EmitMSVAListRef.
2041   /// \returns A pointer to the argument.
2042   // FIXME: We should be able to get rid of this method and use the va_arg
2043   // instruction in LLVM instead once it works well enough.
2044   Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2045 
2046   /// emitArrayLength - Compute the length of an array, even if it's a
2047   /// VLA, and drill down to the base element type.
2048   llvm::Value *emitArrayLength(const ArrayType *arrayType,
2049                                QualType &baseType,
2050                                Address &addr);
2051 
2052   /// EmitVLASize - Capture all the sizes for the VLA expressions in
2053   /// the given variably-modified type and store them in the VLASizeMap.
2054   ///
2055   /// This function can be called with a null (unreachable) insert point.
2056   void EmitVariablyModifiedType(QualType Ty);
2057 
2058   /// getVLASize - Returns an LLVM value that corresponds to the size,
2059   /// in non-variably-sized elements, of a variable length array type,
2060   /// plus that largest non-variably-sized element type.  Assumes that
2061   /// the type has already been emitted with EmitVariablyModifiedType.
2062   std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2063   std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2064 
2065   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2066   /// generating code for an C++ member function.
2067   llvm::Value *LoadCXXThis() {
2068     assert(CXXThisValue && "no 'this' value for this function");
2069     return CXXThisValue;
2070   }
2071   Address LoadCXXThisAddress();
2072 
2073   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2074   /// virtual bases.
2075   // FIXME: Every place that calls LoadCXXVTT is something
2076   // that needs to be abstracted properly.
2077   llvm::Value *LoadCXXVTT() {
2078     assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2079     return CXXStructorImplicitParamValue;
2080   }
2081 
2082   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2083   /// complete class to the given direct base.
2084   Address
2085   GetAddressOfDirectBaseInCompleteClass(Address Value,
2086                                         const CXXRecordDecl *Derived,
2087                                         const CXXRecordDecl *Base,
2088                                         bool BaseIsVirtual);
2089 
2090   static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2091 
2092   /// GetAddressOfBaseClass - This function will add the necessary delta to the
2093   /// load of 'this' and returns address of the base class.
2094   Address GetAddressOfBaseClass(Address Value,
2095                                 const CXXRecordDecl *Derived,
2096                                 CastExpr::path_const_iterator PathBegin,
2097                                 CastExpr::path_const_iterator PathEnd,
2098                                 bool NullCheckValue, SourceLocation Loc);
2099 
2100   Address GetAddressOfDerivedClass(Address Value,
2101                                    const CXXRecordDecl *Derived,
2102                                    CastExpr::path_const_iterator PathBegin,
2103                                    CastExpr::path_const_iterator PathEnd,
2104                                    bool NullCheckValue);
2105 
2106   /// GetVTTParameter - Return the VTT parameter that should be passed to a
2107   /// base constructor/destructor with virtual bases.
2108   /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2109   /// to ItaniumCXXABI.cpp together with all the references to VTT.
2110   llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2111                                bool Delegating);
2112 
2113   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2114                                       CXXCtorType CtorType,
2115                                       const FunctionArgList &Args,
2116                                       SourceLocation Loc);
2117   // It's important not to confuse this and the previous function. Delegating
2118   // constructors are the C++0x feature. The constructor delegate optimization
2119   // is used to reduce duplication in the base and complete consturctors where
2120   // they are substantially the same.
2121   void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2122                                         const FunctionArgList &Args);
2123 
2124   /// Emit a call to an inheriting constructor (that is, one that invokes a
2125   /// constructor inherited from a base class) by inlining its definition. This
2126   /// is necessary if the ABI does not support forwarding the arguments to the
2127   /// base class constructor (because they're variadic or similar).
2128   void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2129                                                CXXCtorType CtorType,
2130                                                bool ForVirtualBase,
2131                                                bool Delegating,
2132                                                CallArgList &Args);
2133 
2134   /// Emit a call to a constructor inherited from a base class, passing the
2135   /// current constructor's arguments along unmodified (without even making
2136   /// a copy).
2137   void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2138                                        bool ForVirtualBase, Address This,
2139                                        bool InheritedFromVBase,
2140                                        const CXXInheritedCtorInitExpr *E);
2141 
2142   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2143                               bool ForVirtualBase, bool Delegating,
2144                               Address This, const CXXConstructExpr *E);
2145 
2146   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2147                               bool ForVirtualBase, bool Delegating,
2148                               Address This, CallArgList &Args);
2149 
2150   /// Emit assumption load for all bases. Requires to be be called only on
2151   /// most-derived class and not under construction of the object.
2152   void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2153 
2154   /// Emit assumption that vptr load == global vtable.
2155   void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2156 
2157   void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2158                                       Address This, Address Src,
2159                                       const CXXConstructExpr *E);
2160 
2161   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2162                                   const ArrayType *ArrayTy,
2163                                   Address ArrayPtr,
2164                                   const CXXConstructExpr *E,
2165                                   bool ZeroInitialization = false);
2166 
2167   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2168                                   llvm::Value *NumElements,
2169                                   Address ArrayPtr,
2170                                   const CXXConstructExpr *E,
2171                                   bool ZeroInitialization = false);
2172 
2173   static Destroyer destroyCXXObject;
2174 
2175   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2176                              bool ForVirtualBase, bool Delegating,
2177                              Address This);
2178 
2179   void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2180                                llvm::Type *ElementTy, Address NewPtr,
2181                                llvm::Value *NumElements,
2182                                llvm::Value *AllocSizeWithoutCookie);
2183 
2184   void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2185                         Address Ptr);
2186 
2187   llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2188   void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2189 
2190   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2191   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2192 
2193   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2194                       QualType DeleteTy, llvm::Value *NumElements = nullptr,
2195                       CharUnits CookieSize = CharUnits());
2196 
2197   RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2198                                   const Expr *Arg, bool IsDelete);
2199 
2200   llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2201   llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2202   Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2203 
2204   /// \brief Situations in which we might emit a check for the suitability of a
2205   ///        pointer or glvalue.
2206   enum TypeCheckKind {
2207     /// Checking the operand of a load. Must be suitably sized and aligned.
2208     TCK_Load,
2209     /// Checking the destination of a store. Must be suitably sized and aligned.
2210     TCK_Store,
2211     /// Checking the bound value in a reference binding. Must be suitably sized
2212     /// and aligned, but is not required to refer to an object (until the
2213     /// reference is used), per core issue 453.
2214     TCK_ReferenceBinding,
2215     /// Checking the object expression in a non-static data member access. Must
2216     /// be an object within its lifetime.
2217     TCK_MemberAccess,
2218     /// Checking the 'this' pointer for a call to a non-static member function.
2219     /// Must be an object within its lifetime.
2220     TCK_MemberCall,
2221     /// Checking the 'this' pointer for a constructor call.
2222     TCK_ConstructorCall,
2223     /// Checking the operand of a static_cast to a derived pointer type. Must be
2224     /// null or an object within its lifetime.
2225     TCK_DowncastPointer,
2226     /// Checking the operand of a static_cast to a derived reference type. Must
2227     /// be an object within its lifetime.
2228     TCK_DowncastReference,
2229     /// Checking the operand of a cast to a base object. Must be suitably sized
2230     /// and aligned.
2231     TCK_Upcast,
2232     /// Checking the operand of a cast to a virtual base object. Must be an
2233     /// object within its lifetime.
2234     TCK_UpcastToVirtualBase
2235   };
2236 
2237   /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2238   /// calls to EmitTypeCheck can be skipped.
2239   bool sanitizePerformTypeCheck() const;
2240 
2241   /// \brief Emit a check that \p V is the address of storage of the
2242   /// appropriate size and alignment for an object of type \p Type.
2243   void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2244                      QualType Type, CharUnits Alignment = CharUnits::Zero(),
2245                      bool SkipNullCheck = false);
2246 
2247   /// \brief Emit a check that \p Base points into an array object, which
2248   /// we can access at index \p Index. \p Accessed should be \c false if we
2249   /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2250   void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2251                        QualType IndexType, bool Accessed);
2252 
2253   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2254                                        bool isInc, bool isPre);
2255   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2256                                          bool isInc, bool isPre);
2257 
2258   void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2259                                llvm::Value *OffsetValue = nullptr) {
2260     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2261                                       OffsetValue);
2262   }
2263 
2264   /// Converts Location to a DebugLoc, if debug information is enabled.
2265   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2266 
2267 
2268   //===--------------------------------------------------------------------===//
2269   //                            Declaration Emission
2270   //===--------------------------------------------------------------------===//
2271 
2272   /// EmitDecl - Emit a declaration.
2273   ///
2274   /// This function can be called with a null (unreachable) insert point.
2275   void EmitDecl(const Decl &D);
2276 
2277   /// EmitVarDecl - Emit a local variable declaration.
2278   ///
2279   /// This function can be called with a null (unreachable) insert point.
2280   void EmitVarDecl(const VarDecl &D);
2281 
2282   void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2283                       bool capturedByInit);
2284 
2285   typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2286                              llvm::Value *Address);
2287 
2288   /// \brief Determine whether the given initializer is trivial in the sense
2289   /// that it requires no code to be generated.
2290   bool isTrivialInitializer(const Expr *Init);
2291 
2292   /// EmitAutoVarDecl - Emit an auto variable declaration.
2293   ///
2294   /// This function can be called with a null (unreachable) insert point.
2295   void EmitAutoVarDecl(const VarDecl &D);
2296 
2297   class AutoVarEmission {
2298     friend class CodeGenFunction;
2299 
2300     const VarDecl *Variable;
2301 
2302     /// The address of the alloca.  Invalid if the variable was emitted
2303     /// as a global constant.
2304     Address Addr;
2305 
2306     llvm::Value *NRVOFlag;
2307 
2308     /// True if the variable is a __block variable.
2309     bool IsByRef;
2310 
2311     /// True if the variable is of aggregate type and has a constant
2312     /// initializer.
2313     bool IsConstantAggregate;
2314 
2315     /// Non-null if we should use lifetime annotations.
2316     llvm::Value *SizeForLifetimeMarkers;
2317 
2318     struct Invalid {};
2319     AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2320 
2321     AutoVarEmission(const VarDecl &variable)
2322       : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2323         IsByRef(false), IsConstantAggregate(false),
2324         SizeForLifetimeMarkers(nullptr) {}
2325 
2326     bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2327 
2328   public:
2329     static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2330 
2331     bool useLifetimeMarkers() const {
2332       return SizeForLifetimeMarkers != nullptr;
2333     }
2334     llvm::Value *getSizeForLifetimeMarkers() const {
2335       assert(useLifetimeMarkers());
2336       return SizeForLifetimeMarkers;
2337     }
2338 
2339     /// Returns the raw, allocated address, which is not necessarily
2340     /// the address of the object itself.
2341     Address getAllocatedAddress() const {
2342       return Addr;
2343     }
2344 
2345     /// Returns the address of the object within this declaration.
2346     /// Note that this does not chase the forwarding pointer for
2347     /// __block decls.
2348     Address getObjectAddress(CodeGenFunction &CGF) const {
2349       if (!IsByRef) return Addr;
2350 
2351       return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2352     }
2353   };
2354   AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2355   void EmitAutoVarInit(const AutoVarEmission &emission);
2356   void EmitAutoVarCleanups(const AutoVarEmission &emission);
2357   void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2358                               QualType::DestructionKind dtorKind);
2359 
2360   void EmitStaticVarDecl(const VarDecl &D,
2361                          llvm::GlobalValue::LinkageTypes Linkage);
2362 
2363   class ParamValue {
2364     llvm::Value *Value;
2365     unsigned Alignment;
2366     ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2367   public:
2368     static ParamValue forDirect(llvm::Value *value) {
2369       return ParamValue(value, 0);
2370     }
2371     static ParamValue forIndirect(Address addr) {
2372       assert(!addr.getAlignment().isZero());
2373       return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2374     }
2375 
2376     bool isIndirect() const { return Alignment != 0; }
2377     llvm::Value *getAnyValue() const { return Value; }
2378 
2379     llvm::Value *getDirectValue() const {
2380       assert(!isIndirect());
2381       return Value;
2382     }
2383 
2384     Address getIndirectAddress() const {
2385       assert(isIndirect());
2386       return Address(Value, CharUnits::fromQuantity(Alignment));
2387     }
2388   };
2389 
2390   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2391   void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2392 
2393   /// protectFromPeepholes - Protect a value that we're intending to
2394   /// store to the side, but which will probably be used later, from
2395   /// aggressive peepholing optimizations that might delete it.
2396   ///
2397   /// Pass the result to unprotectFromPeepholes to declare that
2398   /// protection is no longer required.
2399   ///
2400   /// There's no particular reason why this shouldn't apply to
2401   /// l-values, it's just that no existing peepholes work on pointers.
2402   PeepholeProtection protectFromPeepholes(RValue rvalue);
2403   void unprotectFromPeepholes(PeepholeProtection protection);
2404 
2405   //===--------------------------------------------------------------------===//
2406   //                             Statement Emission
2407   //===--------------------------------------------------------------------===//
2408 
2409   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2410   void EmitStopPoint(const Stmt *S);
2411 
2412   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2413   /// this function even if there is no current insertion point.
2414   ///
2415   /// This function may clear the current insertion point; callers should use
2416   /// EnsureInsertPoint if they wish to subsequently generate code without first
2417   /// calling EmitBlock, EmitBranch, or EmitStmt.
2418   void EmitStmt(const Stmt *S);
2419 
2420   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2421   /// necessarily require an insertion point or debug information; typically
2422   /// because the statement amounts to a jump or a container of other
2423   /// statements.
2424   ///
2425   /// \return True if the statement was handled.
2426   bool EmitSimpleStmt(const Stmt *S);
2427 
2428   Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2429                            AggValueSlot AVS = AggValueSlot::ignored());
2430   Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2431                                        bool GetLast = false,
2432                                        AggValueSlot AVS =
2433                                                 AggValueSlot::ignored());
2434 
2435   /// EmitLabel - Emit the block for the given label. It is legal to call this
2436   /// function even if there is no current insertion point.
2437   void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2438 
2439   void EmitLabelStmt(const LabelStmt &S);
2440   void EmitAttributedStmt(const AttributedStmt &S);
2441   void EmitGotoStmt(const GotoStmt &S);
2442   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2443   void EmitIfStmt(const IfStmt &S);
2444 
2445   void EmitWhileStmt(const WhileStmt &S,
2446                      ArrayRef<const Attr *> Attrs = None);
2447   void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2448   void EmitForStmt(const ForStmt &S,
2449                    ArrayRef<const Attr *> Attrs = None);
2450   void EmitReturnStmt(const ReturnStmt &S);
2451   void EmitDeclStmt(const DeclStmt &S);
2452   void EmitBreakStmt(const BreakStmt &S);
2453   void EmitContinueStmt(const ContinueStmt &S);
2454   void EmitSwitchStmt(const SwitchStmt &S);
2455   void EmitDefaultStmt(const DefaultStmt &S);
2456   void EmitCaseStmt(const CaseStmt &S);
2457   void EmitCaseStmtRange(const CaseStmt &S);
2458   void EmitAsmStmt(const AsmStmt &S);
2459 
2460   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2461   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2462   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2463   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2464   void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2465 
2466   void EmitCoroutineBody(const CoroutineBodyStmt &S);
2467   RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2468 
2469   void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2470   void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2471 
2472   void EmitCXXTryStmt(const CXXTryStmt &S);
2473   void EmitSEHTryStmt(const SEHTryStmt &S);
2474   void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2475   void EnterSEHTryStmt(const SEHTryStmt &S);
2476   void ExitSEHTryStmt(const SEHTryStmt &S);
2477 
2478   void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2479                               const Stmt *OutlinedStmt);
2480 
2481   llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2482                                             const SEHExceptStmt &Except);
2483 
2484   llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2485                                              const SEHFinallyStmt &Finally);
2486 
2487   void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2488                                 llvm::Value *ParentFP,
2489                                 llvm::Value *EntryEBP);
2490   llvm::Value *EmitSEHExceptionCode();
2491   llvm::Value *EmitSEHExceptionInfo();
2492   llvm::Value *EmitSEHAbnormalTermination();
2493 
2494   /// Scan the outlined statement for captures from the parent function. For
2495   /// each capture, mark the capture as escaped and emit a call to
2496   /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2497   void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2498                           bool IsFilter);
2499 
2500   /// Recovers the address of a local in a parent function. ParentVar is the
2501   /// address of the variable used in the immediate parent function. It can
2502   /// either be an alloca or a call to llvm.localrecover if there are nested
2503   /// outlined functions. ParentFP is the frame pointer of the outermost parent
2504   /// frame.
2505   Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2506                                     Address ParentVar,
2507                                     llvm::Value *ParentFP);
2508 
2509   void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2510                            ArrayRef<const Attr *> Attrs = None);
2511 
2512   /// Returns calculated size of the specified type.
2513   llvm::Value *getTypeSize(QualType Ty);
2514   LValue InitCapturedStruct(const CapturedStmt &S);
2515   llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2516   llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2517   Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2518   llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2519   void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2520                                   SmallVectorImpl<llvm::Value *> &CapturedVars);
2521   void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2522                           SourceLocation Loc);
2523   /// \brief Perform element by element copying of arrays with type \a
2524   /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2525   /// generated by \a CopyGen.
2526   ///
2527   /// \param DestAddr Address of the destination array.
2528   /// \param SrcAddr Address of the source array.
2529   /// \param OriginalType Type of destination and source arrays.
2530   /// \param CopyGen Copying procedure that copies value of single array element
2531   /// to another single array element.
2532   void EmitOMPAggregateAssign(
2533       Address DestAddr, Address SrcAddr, QualType OriginalType,
2534       const llvm::function_ref<void(Address, Address)> &CopyGen);
2535   /// \brief Emit proper copying of data from one variable to another.
2536   ///
2537   /// \param OriginalType Original type of the copied variables.
2538   /// \param DestAddr Destination address.
2539   /// \param SrcAddr Source address.
2540   /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2541   /// type of the base array element).
2542   /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2543   /// the base array element).
2544   /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2545   /// DestVD.
2546   void EmitOMPCopy(QualType OriginalType,
2547                    Address DestAddr, Address SrcAddr,
2548                    const VarDecl *DestVD, const VarDecl *SrcVD,
2549                    const Expr *Copy);
2550   /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2551   /// \a X = \a E \a BO \a E.
2552   ///
2553   /// \param X Value to be updated.
2554   /// \param E Update value.
2555   /// \param BO Binary operation for update operation.
2556   /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2557   /// expression, false otherwise.
2558   /// \param AO Atomic ordering of the generated atomic instructions.
2559   /// \param CommonGen Code generator for complex expressions that cannot be
2560   /// expressed through atomicrmw instruction.
2561   /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2562   /// generated, <false, RValue::get(nullptr)> otherwise.
2563   std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2564       LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2565       llvm::AtomicOrdering AO, SourceLocation Loc,
2566       const llvm::function_ref<RValue(RValue)> &CommonGen);
2567   bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2568                                  OMPPrivateScope &PrivateScope);
2569   void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2570                             OMPPrivateScope &PrivateScope);
2571   void EmitOMPUseDevicePtrClause(
2572       const OMPClause &C, OMPPrivateScope &PrivateScope,
2573       const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2574   /// \brief Emit code for copyin clause in \a D directive. The next code is
2575   /// generated at the start of outlined functions for directives:
2576   /// \code
2577   /// threadprivate_var1 = master_threadprivate_var1;
2578   /// operator=(threadprivate_var2, master_threadprivate_var2);
2579   /// ...
2580   /// __kmpc_barrier(&loc, global_tid);
2581   /// \endcode
2582   ///
2583   /// \param D OpenMP directive possibly with 'copyin' clause(s).
2584   /// \returns true if at least one copyin variable is found, false otherwise.
2585   bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2586   /// \brief Emit initial code for lastprivate variables. If some variable is
2587   /// not also firstprivate, then the default initialization is used. Otherwise
2588   /// initialization of this variable is performed by EmitOMPFirstprivateClause
2589   /// method.
2590   ///
2591   /// \param D Directive that may have 'lastprivate' directives.
2592   /// \param PrivateScope Private scope for capturing lastprivate variables for
2593   /// proper codegen in internal captured statement.
2594   ///
2595   /// \returns true if there is at least one lastprivate variable, false
2596   /// otherwise.
2597   bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2598                                     OMPPrivateScope &PrivateScope);
2599   /// \brief Emit final copying of lastprivate values to original variables at
2600   /// the end of the worksharing or simd directive.
2601   ///
2602   /// \param D Directive that has at least one 'lastprivate' directives.
2603   /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2604   /// it is the last iteration of the loop code in associated directive, or to
2605   /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2606   void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2607                                      bool NoFinals,
2608                                      llvm::Value *IsLastIterCond = nullptr);
2609   /// Emit initial code for linear clauses.
2610   void EmitOMPLinearClause(const OMPLoopDirective &D,
2611                            CodeGenFunction::OMPPrivateScope &PrivateScope);
2612   /// Emit final code for linear clauses.
2613   /// \param CondGen Optional conditional code for final part of codegen for
2614   /// linear clause.
2615   void EmitOMPLinearClauseFinal(
2616       const OMPLoopDirective &D,
2617       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2618   /// \brief Emit initial code for reduction variables. Creates reduction copies
2619   /// and initializes them with the values according to OpenMP standard.
2620   ///
2621   /// \param D Directive (possibly) with the 'reduction' clause.
2622   /// \param PrivateScope Private scope for capturing reduction variables for
2623   /// proper codegen in internal captured statement.
2624   ///
2625   void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2626                                   OMPPrivateScope &PrivateScope);
2627   /// \brief Emit final update of reduction values to original variables at
2628   /// the end of the directive.
2629   ///
2630   /// \param D Directive that has at least one 'reduction' directives.
2631   void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
2632   /// \brief Emit initial code for linear variables. Creates private copies
2633   /// and initializes them with the values according to OpenMP standard.
2634   ///
2635   /// \param D Directive (possibly) with the 'linear' clause.
2636   void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2637 
2638   typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2639                                         llvm::Value * /*OutlinedFn*/,
2640                                         const OMPTaskDataTy & /*Data*/)>
2641       TaskGenTy;
2642   void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2643                                  const RegionCodeGenTy &BodyGen,
2644                                  const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2645 
2646   void EmitOMPParallelDirective(const OMPParallelDirective &S);
2647   void EmitOMPSimdDirective(const OMPSimdDirective &S);
2648   void EmitOMPForDirective(const OMPForDirective &S);
2649   void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2650   void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2651   void EmitOMPSectionDirective(const OMPSectionDirective &S);
2652   void EmitOMPSingleDirective(const OMPSingleDirective &S);
2653   void EmitOMPMasterDirective(const OMPMasterDirective &S);
2654   void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2655   void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2656   void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2657   void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2658   void EmitOMPTaskDirective(const OMPTaskDirective &S);
2659   void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2660   void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2661   void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2662   void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2663   void EmitOMPFlushDirective(const OMPFlushDirective &S);
2664   void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2665   void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2666   void EmitOMPTargetDirective(const OMPTargetDirective &S);
2667   void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2668   void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2669   void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2670   void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2671   void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2672   void
2673   EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2674   void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2675   void
2676   EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2677   void EmitOMPCancelDirective(const OMPCancelDirective &S);
2678   void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2679   void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2680   void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2681   void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2682   void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
2683   void EmitOMPDistributeParallelForDirective(
2684       const OMPDistributeParallelForDirective &S);
2685   void EmitOMPDistributeParallelForSimdDirective(
2686       const OMPDistributeParallelForSimdDirective &S);
2687   void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2688   void EmitOMPTargetParallelForSimdDirective(
2689       const OMPTargetParallelForSimdDirective &S);
2690   void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2691   void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2692   void
2693   EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2694   void EmitOMPTeamsDistributeParallelForSimdDirective(
2695       const OMPTeamsDistributeParallelForSimdDirective &S);
2696   void EmitOMPTeamsDistributeParallelForDirective(
2697       const OMPTeamsDistributeParallelForDirective &S);
2698   void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &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