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