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