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