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