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