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