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