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