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