CodeGenFunction.h revision 224145
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 "clang/AST/Type.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/Frontend/CodeGenOptions.h"
22#include "clang/Basic/ABI.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/Support/ValueHandle.h"
28#include "CodeGenModule.h"
29#include "CGBuilder.h"
30#include "CGValue.h"
31
32namespace llvm {
33  class BasicBlock;
34  class LLVMContext;
35  class MDNode;
36  class Module;
37  class SwitchInst;
38  class Twine;
39  class Value;
40  class CallSite;
41}
42
43namespace clang {
44  class APValue;
45  class ASTContext;
46  class CXXDestructorDecl;
47  class CXXForRangeStmt;
48  class CXXTryStmt;
49  class Decl;
50  class LabelDecl;
51  class EnumConstantDecl;
52  class FunctionDecl;
53  class FunctionProtoType;
54  class LabelStmt;
55  class ObjCContainerDecl;
56  class ObjCInterfaceDecl;
57  class ObjCIvarDecl;
58  class ObjCMethodDecl;
59  class ObjCImplementationDecl;
60  class ObjCPropertyImplDecl;
61  class TargetInfo;
62  class TargetCodeGenInfo;
63  class VarDecl;
64  class ObjCForCollectionStmt;
65  class ObjCAtTryStmt;
66  class ObjCAtThrowStmt;
67  class ObjCAtSynchronizedStmt;
68  class ObjCAutoreleasePoolStmt;
69
70namespace CodeGen {
71  class CodeGenTypes;
72  class CGDebugInfo;
73  class CGFunctionInfo;
74  class CGRecordLayout;
75  class CGBlockInfo;
76  class CGCXXABI;
77  class BlockFlags;
78  class BlockFieldFlags;
79
80/// A branch fixup.  These are required when emitting a goto to a
81/// label which hasn't been emitted yet.  The goto is optimistically
82/// emitted as a branch to the basic block for the label, and (if it
83/// occurs in a scope with non-trivial cleanups) a fixup is added to
84/// the innermost cleanup.  When a (normal) cleanup is popped, any
85/// unresolved fixups in that scope are threaded through the cleanup.
86struct BranchFixup {
87  /// The block containing the terminator which needs to be modified
88  /// into a switch if this fixup is resolved into the current scope.
89  /// If null, LatestBranch points directly to the destination.
90  llvm::BasicBlock *OptimisticBranchBlock;
91
92  /// The ultimate destination of the branch.
93  ///
94  /// This can be set to null to indicate that this fixup was
95  /// successfully resolved.
96  llvm::BasicBlock *Destination;
97
98  /// The destination index value.
99  unsigned DestinationIndex;
100
101  /// The initial branch of the fixup.
102  llvm::BranchInst *InitialBranch;
103};
104
105template <class T> struct InvariantValue {
106  typedef T type;
107  typedef T saved_type;
108  static bool needsSaving(type value) { return false; }
109  static saved_type save(CodeGenFunction &CGF, type value) { return value; }
110  static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
111};
112
113/// A metaprogramming class for ensuring that a value will dominate an
114/// arbitrary position in a function.
115template <class T> struct DominatingValue : InvariantValue<T> {};
116
117template <class T, bool mightBeInstruction =
118            llvm::is_base_of<llvm::Value, T>::value &&
119            !llvm::is_base_of<llvm::Constant, T>::value &&
120            !llvm::is_base_of<llvm::BasicBlock, T>::value>
121struct DominatingPointer;
122template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
123// template <class T> struct DominatingPointer<T,true> at end of file
124
125template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
126
127enum CleanupKind {
128  EHCleanup = 0x1,
129  NormalCleanup = 0x2,
130  NormalAndEHCleanup = EHCleanup | NormalCleanup,
131
132  InactiveCleanup = 0x4,
133  InactiveEHCleanup = EHCleanup | InactiveCleanup,
134  InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
135  InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
136};
137
138/// A stack of scopes which respond to exceptions, including cleanups
139/// and catch blocks.
140class EHScopeStack {
141public:
142  /// A saved depth on the scope stack.  This is necessary because
143  /// pushing scopes onto the stack invalidates iterators.
144  class stable_iterator {
145    friend class EHScopeStack;
146
147    /// Offset from StartOfData to EndOfBuffer.
148    ptrdiff_t Size;
149
150    stable_iterator(ptrdiff_t Size) : Size(Size) {}
151
152  public:
153    static stable_iterator invalid() { return stable_iterator(-1); }
154    stable_iterator() : Size(-1) {}
155
156    bool isValid() const { return Size >= 0; }
157
158    /// Returns true if this scope encloses I.
159    /// Returns false if I is invalid.
160    /// This scope must be valid.
161    bool encloses(stable_iterator I) const { return Size <= I.Size; }
162
163    /// Returns true if this scope strictly encloses I: that is,
164    /// if it encloses I and is not I.
165    /// Returns false is I is invalid.
166    /// This scope must be valid.
167    bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
168
169    friend bool operator==(stable_iterator A, stable_iterator B) {
170      return A.Size == B.Size;
171    }
172    friend bool operator!=(stable_iterator A, stable_iterator B) {
173      return A.Size != B.Size;
174    }
175  };
176
177  /// Information for lazily generating a cleanup.  Subclasses must be
178  /// POD-like: cleanups will not be destructed, and they will be
179  /// allocated on the cleanup stack and freely copied and moved
180  /// around.
181  ///
182  /// Cleanup implementations should generally be declared in an
183  /// anonymous namespace.
184  class Cleanup {
185    // Anchor the construction vtable.
186    virtual void anchor();
187  public:
188    /// Generation flags.
189    class Flags {
190      enum {
191        F_IsForEH             = 0x1,
192        F_IsNormalCleanupKind = 0x2,
193        F_IsEHCleanupKind     = 0x4
194      };
195      unsigned flags;
196
197    public:
198      Flags() : flags(0) {}
199
200      /// isForEH - true if the current emission is for an EH cleanup.
201      bool isForEHCleanup() const { return flags & F_IsForEH; }
202      bool isForNormalCleanup() const { return !isForEHCleanup(); }
203      void setIsForEHCleanup() { flags |= F_IsForEH; }
204
205      bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
206      void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
207
208      /// isEHCleanupKind - true if the cleanup was pushed as an EH
209      /// cleanup.
210      bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
211      void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
212    };
213
214    // Provide a virtual destructor to suppress a very common warning
215    // that unfortunately cannot be suppressed without this.  Cleanups
216    // should not rely on this destructor ever being called.
217    virtual ~Cleanup() {}
218
219    /// Emit the cleanup.  For normal cleanups, this is run in the
220    /// same EH context as when the cleanup was pushed, i.e. the
221    /// immediately-enclosing context of the cleanup scope.  For
222    /// EH cleanups, this is run in a terminate context.
223    ///
224    // \param IsForEHCleanup true if this is for an EH cleanup, false
225    ///  if for a normal cleanup.
226    virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
227  };
228
229  /// ConditionalCleanupN stores the saved form of its N parameters,
230  /// then restores them and performs the cleanup.
231  template <class T, class A0>
232  class ConditionalCleanup1 : public Cleanup {
233    typedef typename DominatingValue<A0>::saved_type A0_saved;
234    A0_saved a0_saved;
235
236    void Emit(CodeGenFunction &CGF, Flags flags) {
237      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
238      T(a0).Emit(CGF, flags);
239    }
240
241  public:
242    ConditionalCleanup1(A0_saved a0)
243      : a0_saved(a0) {}
244  };
245
246  template <class T, class A0, class A1>
247  class ConditionalCleanup2 : public Cleanup {
248    typedef typename DominatingValue<A0>::saved_type A0_saved;
249    typedef typename DominatingValue<A1>::saved_type A1_saved;
250    A0_saved a0_saved;
251    A1_saved a1_saved;
252
253    void Emit(CodeGenFunction &CGF, Flags flags) {
254      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
255      A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
256      T(a0, a1).Emit(CGF, flags);
257    }
258
259  public:
260    ConditionalCleanup2(A0_saved a0, A1_saved a1)
261      : a0_saved(a0), a1_saved(a1) {}
262  };
263
264  template <class T, class A0, class A1, class A2>
265  class ConditionalCleanup3 : public Cleanup {
266    typedef typename DominatingValue<A0>::saved_type A0_saved;
267    typedef typename DominatingValue<A1>::saved_type A1_saved;
268    typedef typename DominatingValue<A2>::saved_type A2_saved;
269    A0_saved a0_saved;
270    A1_saved a1_saved;
271    A2_saved a2_saved;
272
273    void Emit(CodeGenFunction &CGF, Flags flags) {
274      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
275      A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
276      A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
277      T(a0, a1, a2).Emit(CGF, flags);
278    }
279
280  public:
281    ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
282      : a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
283  };
284
285  template <class T, class A0, class A1, class A2, class A3>
286  class ConditionalCleanup4 : public Cleanup {
287    typedef typename DominatingValue<A0>::saved_type A0_saved;
288    typedef typename DominatingValue<A1>::saved_type A1_saved;
289    typedef typename DominatingValue<A2>::saved_type A2_saved;
290    typedef typename DominatingValue<A3>::saved_type A3_saved;
291    A0_saved a0_saved;
292    A1_saved a1_saved;
293    A2_saved a2_saved;
294    A3_saved a3_saved;
295
296    void Emit(CodeGenFunction &CGF, Flags flags) {
297      A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
298      A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
299      A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
300      A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
301      T(a0, a1, a2, a3).Emit(CGF, flags);
302    }
303
304  public:
305    ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
306      : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
307  };
308
309private:
310  // The implementation for this class is in CGException.h and
311  // CGException.cpp; the definition is here because it's used as a
312  // member of CodeGenFunction.
313
314  /// The start of the scope-stack buffer, i.e. the allocated pointer
315  /// for the buffer.  All of these pointers are either simultaneously
316  /// null or simultaneously valid.
317  char *StartOfBuffer;
318
319  /// The end of the buffer.
320  char *EndOfBuffer;
321
322  /// The first valid entry in the buffer.
323  char *StartOfData;
324
325  /// The innermost normal cleanup on the stack.
326  stable_iterator InnermostNormalCleanup;
327
328  /// The innermost EH cleanup on the stack.
329  stable_iterator InnermostEHCleanup;
330
331  /// The number of catches on the stack.
332  unsigned CatchDepth;
333
334  /// The current EH destination index.  Reset to FirstCatchIndex
335  /// whenever the last EH cleanup is popped.
336  unsigned NextEHDestIndex;
337  enum { FirstEHDestIndex = 1 };
338
339  /// The current set of branch fixups.  A branch fixup is a jump to
340  /// an as-yet unemitted label, i.e. a label for which we don't yet
341  /// know the EH stack depth.  Whenever we pop a cleanup, we have
342  /// to thread all the current branch fixups through it.
343  ///
344  /// Fixups are recorded as the Use of the respective branch or
345  /// switch statement.  The use points to the final destination.
346  /// When popping out of a cleanup, these uses are threaded through
347  /// the cleanup and adjusted to point to the new cleanup.
348  ///
349  /// Note that branches are allowed to jump into protected scopes
350  /// in certain situations;  e.g. the following code is legal:
351  ///     struct A { ~A(); }; // trivial ctor, non-trivial dtor
352  ///     goto foo;
353  ///     A a;
354  ///    foo:
355  ///     bar();
356  llvm::SmallVector<BranchFixup, 8> BranchFixups;
357
358  char *allocate(size_t Size);
359
360  void *pushCleanup(CleanupKind K, size_t DataSize);
361
362public:
363  EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
364                   InnermostNormalCleanup(stable_end()),
365                   InnermostEHCleanup(stable_end()),
366                   CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {}
367  ~EHScopeStack() { delete[] StartOfBuffer; }
368
369  // Variadic templates would make this not terrible.
370
371  /// Push a lazily-created cleanup on the stack.
372  template <class T>
373  void pushCleanup(CleanupKind Kind) {
374    void *Buffer = pushCleanup(Kind, sizeof(T));
375    Cleanup *Obj = new(Buffer) T();
376    (void) Obj;
377  }
378
379  /// Push a lazily-created cleanup on the stack.
380  template <class T, class A0>
381  void pushCleanup(CleanupKind Kind, A0 a0) {
382    void *Buffer = pushCleanup(Kind, sizeof(T));
383    Cleanup *Obj = new(Buffer) T(a0);
384    (void) Obj;
385  }
386
387  /// Push a lazily-created cleanup on the stack.
388  template <class T, class A0, class A1>
389  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
390    void *Buffer = pushCleanup(Kind, sizeof(T));
391    Cleanup *Obj = new(Buffer) T(a0, a1);
392    (void) Obj;
393  }
394
395  /// Push a lazily-created cleanup on the stack.
396  template <class T, class A0, class A1, class A2>
397  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
398    void *Buffer = pushCleanup(Kind, sizeof(T));
399    Cleanup *Obj = new(Buffer) T(a0, a1, a2);
400    (void) Obj;
401  }
402
403  /// Push a lazily-created cleanup on the stack.
404  template <class T, class A0, class A1, class A2, class A3>
405  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
406    void *Buffer = pushCleanup(Kind, sizeof(T));
407    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
408    (void) Obj;
409  }
410
411  /// Push a lazily-created cleanup on the stack.
412  template <class T, class A0, class A1, class A2, class A3, class A4>
413  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
414    void *Buffer = pushCleanup(Kind, sizeof(T));
415    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
416    (void) Obj;
417  }
418
419  // Feel free to add more variants of the following:
420
421  /// Push a cleanup with non-constant storage requirements on the
422  /// stack.  The cleanup type must provide an additional static method:
423  ///   static size_t getExtraSize(size_t);
424  /// The argument to this method will be the value N, which will also
425  /// be passed as the first argument to the constructor.
426  ///
427  /// The data stored in the extra storage must obey the same
428  /// restrictions as normal cleanup member data.
429  ///
430  /// The pointer returned from this method is valid until the cleanup
431  /// stack is modified.
432  template <class T, class A0, class A1, class A2>
433  T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
434    void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
435    return new (Buffer) T(N, a0, a1, a2);
436  }
437
438  /// Pops a cleanup scope off the stack.  This should only be called
439  /// by CodeGenFunction::PopCleanupBlock.
440  void popCleanup();
441
442  /// Push a set of catch handlers on the stack.  The catch is
443  /// uninitialized and will need to have the given number of handlers
444  /// set on it.
445  class EHCatchScope *pushCatch(unsigned NumHandlers);
446
447  /// Pops a catch scope off the stack.
448  void popCatch();
449
450  /// Push an exceptions filter on the stack.
451  class EHFilterScope *pushFilter(unsigned NumFilters);
452
453  /// Pops an exceptions filter off the stack.
454  void popFilter();
455
456  /// Push a terminate handler on the stack.
457  void pushTerminate();
458
459  /// Pops a terminate handler off the stack.
460  void popTerminate();
461
462  /// Determines whether the exception-scopes stack is empty.
463  bool empty() const { return StartOfData == EndOfBuffer; }
464
465  bool requiresLandingPad() const {
466    return (CatchDepth || hasEHCleanups());
467  }
468
469  /// Determines whether there are any normal cleanups on the stack.
470  bool hasNormalCleanups() const {
471    return InnermostNormalCleanup != stable_end();
472  }
473
474  /// Returns the innermost normal cleanup on the stack, or
475  /// stable_end() if there are no normal cleanups.
476  stable_iterator getInnermostNormalCleanup() const {
477    return InnermostNormalCleanup;
478  }
479  stable_iterator getInnermostActiveNormalCleanup() const; // CGException.h
480
481  /// Determines whether there are any EH cleanups on the stack.
482  bool hasEHCleanups() const {
483    return InnermostEHCleanup != stable_end();
484  }
485
486  /// Returns the innermost EH cleanup on the stack, or stable_end()
487  /// if there are no EH cleanups.
488  stable_iterator getInnermostEHCleanup() const {
489    return InnermostEHCleanup;
490  }
491  stable_iterator getInnermostActiveEHCleanup() const; // CGException.h
492
493  /// An unstable reference to a scope-stack depth.  Invalidated by
494  /// pushes but not pops.
495  class iterator;
496
497  /// Returns an iterator pointing to the innermost EH scope.
498  iterator begin() const;
499
500  /// Returns an iterator pointing to the outermost EH scope.
501  iterator end() const;
502
503  /// Create a stable reference to the top of the EH stack.  The
504  /// returned reference is valid until that scope is popped off the
505  /// stack.
506  stable_iterator stable_begin() const {
507    return stable_iterator(EndOfBuffer - StartOfData);
508  }
509
510  /// Create a stable reference to the bottom of the EH stack.
511  static stable_iterator stable_end() {
512    return stable_iterator(0);
513  }
514
515  /// Translates an iterator into a stable_iterator.
516  stable_iterator stabilize(iterator it) const;
517
518  /// Finds the nearest cleanup enclosing the given iterator.
519  /// Returns stable_iterator::invalid() if there are no such cleanups.
520  stable_iterator getEnclosingEHCleanup(iterator it) const;
521
522  /// Turn a stable reference to a scope depth into a unstable pointer
523  /// to the EH stack.
524  iterator find(stable_iterator save) const;
525
526  /// Removes the cleanup pointed to by the given stable_iterator.
527  void removeCleanup(stable_iterator save);
528
529  /// Add a branch fixup to the current cleanup scope.
530  BranchFixup &addBranchFixup() {
531    assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
532    BranchFixups.push_back(BranchFixup());
533    return BranchFixups.back();
534  }
535
536  unsigned getNumBranchFixups() const { return BranchFixups.size(); }
537  BranchFixup &getBranchFixup(unsigned I) {
538    assert(I < getNumBranchFixups());
539    return BranchFixups[I];
540  }
541
542  /// Pops lazily-removed fixups from the end of the list.  This
543  /// should only be called by procedures which have just popped a
544  /// cleanup or resolved one or more fixups.
545  void popNullFixups();
546
547  /// Clears the branch-fixups list.  This should only be called by
548  /// ResolveAllBranchFixups.
549  void clearFixups() { BranchFixups.clear(); }
550
551  /// Gets the next EH destination index.
552  unsigned getNextEHDestIndex() { return NextEHDestIndex++; }
553};
554
555/// CodeGenFunction - This class organizes the per-function state that is used
556/// while generating LLVM code.
557class CodeGenFunction : public CodeGenTypeCache {
558  CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
559  void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
560
561  friend class CGCXXABI;
562public:
563  /// A jump destination is an abstract label, branching to which may
564  /// require a jump out through normal cleanups.
565  struct JumpDest {
566    JumpDest() : Block(0), ScopeDepth(), Index(0) {}
567    JumpDest(llvm::BasicBlock *Block,
568             EHScopeStack::stable_iterator Depth,
569             unsigned Index)
570      : Block(Block), ScopeDepth(Depth), Index(Index) {}
571
572    bool isValid() const { return Block != 0; }
573    llvm::BasicBlock *getBlock() const { return Block; }
574    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
575    unsigned getDestIndex() const { return Index; }
576
577  private:
578    llvm::BasicBlock *Block;
579    EHScopeStack::stable_iterator ScopeDepth;
580    unsigned Index;
581  };
582
583  /// An unwind destination is an abstract label, branching to which
584  /// may require a jump out through EH cleanups.
585  struct UnwindDest {
586    UnwindDest() : Block(0), ScopeDepth(), Index(0) {}
587    UnwindDest(llvm::BasicBlock *Block,
588               EHScopeStack::stable_iterator Depth,
589               unsigned Index)
590      : Block(Block), ScopeDepth(Depth), Index(Index) {}
591
592    bool isValid() const { return Block != 0; }
593    llvm::BasicBlock *getBlock() const { return Block; }
594    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
595    unsigned getDestIndex() const { return Index; }
596
597  private:
598    llvm::BasicBlock *Block;
599    EHScopeStack::stable_iterator ScopeDepth;
600    unsigned Index;
601  };
602
603  CodeGenModule &CGM;  // Per-module state.
604  const TargetInfo &Target;
605
606  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
607  CGBuilderTy Builder;
608
609  /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
610  /// This excludes BlockDecls.
611  const Decl *CurFuncDecl;
612  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
613  const Decl *CurCodeDecl;
614  const CGFunctionInfo *CurFnInfo;
615  QualType FnRetTy;
616  llvm::Function *CurFn;
617
618  /// CurGD - The GlobalDecl for the current function being compiled.
619  GlobalDecl CurGD;
620
621  /// PrologueCleanupDepth - The cleanup depth enclosing all the
622  /// cleanups associated with the parameters.
623  EHScopeStack::stable_iterator PrologueCleanupDepth;
624
625  /// ReturnBlock - Unified return block.
626  JumpDest ReturnBlock;
627
628  /// ReturnValue - The temporary alloca to hold the return value. This is null
629  /// iff the function has no return value.
630  llvm::Value *ReturnValue;
631
632  /// RethrowBlock - Unified rethrow block.
633  UnwindDest RethrowBlock;
634
635  /// AllocaInsertPoint - This is an instruction in the entry block before which
636  /// we prefer to insert allocas.
637  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
638
639  bool CatchUndefined;
640
641  /// In ARC, whether we should autorelease the return value.
642  bool AutoreleaseResult;
643
644  const CodeGen::CGBlockInfo *BlockInfo;
645  llvm::Value *BlockPointer;
646
647  /// \brief A mapping from NRVO variables to the flags used to indicate
648  /// when the NRVO has been applied to this variable.
649  llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
650
651  EHScopeStack EHStack;
652
653  /// i32s containing the indexes of the cleanup destinations.
654  llvm::AllocaInst *NormalCleanupDest;
655  llvm::AllocaInst *EHCleanupDest;
656
657  unsigned NextCleanupDestIndex;
658
659  /// The exception slot.  All landing pads write the current
660  /// exception pointer into this alloca.
661  llvm::Value *ExceptionSlot;
662
663  /// The selector slot.  Under the MandatoryCleanup model, all
664  /// landing pads write the current selector value into this alloca.
665  llvm::AllocaInst *EHSelectorSlot;
666
667  /// Emits a landing pad for the current EH stack.
668  llvm::BasicBlock *EmitLandingPad();
669
670  llvm::BasicBlock *getInvokeDestImpl();
671
672  /// Set up the last cleaup that was pushed as a conditional
673  /// full-expression cleanup.
674  void initFullExprCleanup();
675
676  template <class T>
677  typename DominatingValue<T>::saved_type saveValueInCond(T value) {
678    return DominatingValue<T>::save(*this, value);
679  }
680
681public:
682  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
683  /// rethrows.
684  llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
685
686  /// A class controlling the emission of a finally block.
687  class FinallyInfo {
688    /// Where the catchall's edge through the cleanup should go.
689    JumpDest RethrowDest;
690
691    /// A function to call to enter the catch.
692    llvm::Constant *BeginCatchFn;
693
694    /// An i1 variable indicating whether or not the @finally is
695    /// running for an exception.
696    llvm::AllocaInst *ForEHVar;
697
698    /// An i8* variable into which the exception pointer to rethrow
699    /// has been saved.
700    llvm::AllocaInst *SavedExnVar;
701
702  public:
703    void enter(CodeGenFunction &CGF, const Stmt *Finally,
704               llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
705               llvm::Constant *rethrowFn);
706    void exit(CodeGenFunction &CGF);
707  };
708
709  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
710  /// current full-expression.  Safe against the possibility that
711  /// we're currently inside a conditionally-evaluated expression.
712  template <class T, class A0>
713  void pushFullExprCleanup(CleanupKind kind, A0 a0) {
714    // If we're not in a conditional branch, or if none of the
715    // arguments requires saving, then use the unconditional cleanup.
716    if (!isInConditionalBranch())
717      return EHStack.pushCleanup<T>(kind, a0);
718
719    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
720
721    typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
722    EHStack.pushCleanup<CleanupType>(kind, a0_saved);
723    initFullExprCleanup();
724  }
725
726  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
727  /// current full-expression.  Safe against the possibility that
728  /// we're currently inside a conditionally-evaluated expression.
729  template <class T, class A0, class A1>
730  void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
731    // If we're not in a conditional branch, or if none of the
732    // arguments requires saving, then use the unconditional cleanup.
733    if (!isInConditionalBranch())
734      return EHStack.pushCleanup<T>(kind, a0, a1);
735
736    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
737    typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
738
739    typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
740    EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
741    initFullExprCleanup();
742  }
743
744  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
745  /// current full-expression.  Safe against the possibility that
746  /// we're currently inside a conditionally-evaluated expression.
747  template <class T, class A0, class A1, class A2>
748  void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
749    // If we're not in a conditional branch, or if none of the
750    // arguments requires saving, then use the unconditional cleanup.
751    if (!isInConditionalBranch()) {
752      return EHStack.pushCleanup<T>(kind, a0, a1, a2);
753    }
754
755    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
756    typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
757    typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
758
759    typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
760    EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
761    initFullExprCleanup();
762  }
763
764  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
765  /// current full-expression.  Safe against the possibility that
766  /// we're currently inside a conditionally-evaluated expression.
767  template <class T, class A0, class A1, class A2, class A3>
768  void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
769    // If we're not in a conditional branch, or if none of the
770    // arguments requires saving, then use the unconditional cleanup.
771    if (!isInConditionalBranch()) {
772      return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
773    }
774
775    typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
776    typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
777    typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
778    typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
779
780    typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
781    EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
782                                     a2_saved, a3_saved);
783    initFullExprCleanup();
784  }
785
786  /// PushDestructorCleanup - Push a cleanup to call the
787  /// complete-object destructor of an object of the given type at the
788  /// given address.  Does nothing if T is not a C++ class type with a
789  /// non-trivial destructor.
790  void PushDestructorCleanup(QualType T, llvm::Value *Addr);
791
792  /// PushDestructorCleanup - Push a cleanup to call the
793  /// complete-object variant of the given destructor on the object at
794  /// the given address.
795  void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
796                             llvm::Value *Addr);
797
798  /// PopCleanupBlock - Will pop the cleanup entry on the stack and
799  /// process all branch fixups.
800  void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
801
802  /// DeactivateCleanupBlock - Deactivates the given cleanup block.
803  /// The block cannot be reactivated.  Pops it if it's the top of the
804  /// stack.
805  void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
806
807  /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
808  /// Cannot be used to resurrect a deactivated cleanup.
809  void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
810
811  /// \brief Enters a new scope for capturing cleanups, all of which
812  /// will be executed once the scope is exited.
813  class RunCleanupsScope {
814    CodeGenFunction& CGF;
815    EHScopeStack::stable_iterator CleanupStackDepth;
816    bool OldDidCallStackSave;
817    bool PerformCleanup;
818
819    RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
820    RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
821
822  public:
823    /// \brief Enter a new cleanup scope.
824    explicit RunCleanupsScope(CodeGenFunction &CGF)
825      : CGF(CGF), PerformCleanup(true)
826    {
827      CleanupStackDepth = CGF.EHStack.stable_begin();
828      OldDidCallStackSave = CGF.DidCallStackSave;
829      CGF.DidCallStackSave = false;
830    }
831
832    /// \brief Exit this cleanup scope, emitting any accumulated
833    /// cleanups.
834    ~RunCleanupsScope() {
835      if (PerformCleanup) {
836        CGF.DidCallStackSave = OldDidCallStackSave;
837        CGF.PopCleanupBlocks(CleanupStackDepth);
838      }
839    }
840
841    /// \brief Determine whether this scope requires any cleanups.
842    bool requiresCleanups() const {
843      return CGF.EHStack.stable_begin() != CleanupStackDepth;
844    }
845
846    /// \brief Force the emission of cleanups now, instead of waiting
847    /// until this object is destroyed.
848    void ForceCleanup() {
849      assert(PerformCleanup && "Already forced cleanup");
850      CGF.DidCallStackSave = OldDidCallStackSave;
851      CGF.PopCleanupBlocks(CleanupStackDepth);
852      PerformCleanup = false;
853    }
854  };
855
856
857  /// PopCleanupBlocks - Takes the old cleanup stack size and emits
858  /// the cleanup blocks that have been added.
859  void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
860
861  void ResolveBranchFixups(llvm::BasicBlock *Target);
862
863  /// The given basic block lies in the current EH scope, but may be a
864  /// target of a potentially scope-crossing jump; get a stable handle
865  /// to which we can perform this jump later.
866  JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
867    return JumpDest(Target,
868                    EHStack.getInnermostNormalCleanup(),
869                    NextCleanupDestIndex++);
870  }
871
872  /// The given basic block lies in the current EH scope, but may be a
873  /// target of a potentially scope-crossing jump; get a stable handle
874  /// to which we can perform this jump later.
875  JumpDest getJumpDestInCurrentScope(llvm::StringRef Name = llvm::StringRef()) {
876    return getJumpDestInCurrentScope(createBasicBlock(Name));
877  }
878
879  /// EmitBranchThroughCleanup - Emit a branch from the current insert
880  /// block through the normal cleanup handling code (if any) and then
881  /// on to \arg Dest.
882  void EmitBranchThroughCleanup(JumpDest Dest);
883
884  /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
885  /// specified destination obviously has no cleanups to run.  'false' is always
886  /// a conservatively correct answer for this method.
887  bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
888
889  /// EmitBranchThroughEHCleanup - Emit a branch from the current
890  /// insert block through the EH cleanup handling code (if any) and
891  /// then on to \arg Dest.
892  void EmitBranchThroughEHCleanup(UnwindDest Dest);
893
894  /// getRethrowDest - Returns the unified outermost-scope rethrow
895  /// destination.
896  UnwindDest getRethrowDest();
897
898  /// An object to manage conditionally-evaluated expressions.
899  class ConditionalEvaluation {
900    llvm::BasicBlock *StartBB;
901
902  public:
903    ConditionalEvaluation(CodeGenFunction &CGF)
904      : StartBB(CGF.Builder.GetInsertBlock()) {}
905
906    void begin(CodeGenFunction &CGF) {
907      assert(CGF.OutermostConditional != this);
908      if (!CGF.OutermostConditional)
909        CGF.OutermostConditional = this;
910    }
911
912    void end(CodeGenFunction &CGF) {
913      assert(CGF.OutermostConditional != 0);
914      if (CGF.OutermostConditional == this)
915        CGF.OutermostConditional = 0;
916    }
917
918    /// Returns a block which will be executed prior to each
919    /// evaluation of the conditional code.
920    llvm::BasicBlock *getStartingBlock() const {
921      return StartBB;
922    }
923  };
924
925  /// isInConditionalBranch - Return true if we're currently emitting
926  /// one branch or the other of a conditional expression.
927  bool isInConditionalBranch() const { return OutermostConditional != 0; }
928
929  /// An RAII object to record that we're evaluating a statement
930  /// expression.
931  class StmtExprEvaluation {
932    CodeGenFunction &CGF;
933
934    /// We have to save the outermost conditional: cleanups in a
935    /// statement expression aren't conditional just because the
936    /// StmtExpr is.
937    ConditionalEvaluation *SavedOutermostConditional;
938
939  public:
940    StmtExprEvaluation(CodeGenFunction &CGF)
941      : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
942      CGF.OutermostConditional = 0;
943    }
944
945    ~StmtExprEvaluation() {
946      CGF.OutermostConditional = SavedOutermostConditional;
947      CGF.EnsureInsertPoint();
948    }
949  };
950
951  /// An object which temporarily prevents a value from being
952  /// destroyed by aggressive peephole optimizations that assume that
953  /// all uses of a value have been realized in the IR.
954  class PeepholeProtection {
955    llvm::Instruction *Inst;
956    friend class CodeGenFunction;
957
958  public:
959    PeepholeProtection() : Inst(0) {}
960  };
961
962  /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
963  class OpaqueValueMapping {
964    CodeGenFunction &CGF;
965    const OpaqueValueExpr *OpaqueValue;
966    bool BoundLValue;
967    CodeGenFunction::PeepholeProtection Protection;
968
969  public:
970    static bool shouldBindAsLValue(const Expr *expr) {
971      return expr->isGLValue() || expr->getType()->isRecordType();
972    }
973
974    /// Build the opaque value mapping for the given conditional
975    /// operator if it's the GNU ?: extension.  This is a common
976    /// enough pattern that the convenience operator is really
977    /// helpful.
978    ///
979    OpaqueValueMapping(CodeGenFunction &CGF,
980                       const AbstractConditionalOperator *op) : CGF(CGF) {
981      if (isa<ConditionalOperator>(op)) {
982        OpaqueValue = 0;
983        BoundLValue = false;
984        return;
985      }
986
987      const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
988      init(e->getOpaqueValue(), e->getCommon());
989    }
990
991    OpaqueValueMapping(CodeGenFunction &CGF,
992                       const OpaqueValueExpr *opaqueValue,
993                       LValue lvalue)
994      : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(true) {
995      assert(opaqueValue && "no opaque value expression!");
996      assert(shouldBindAsLValue(opaqueValue));
997      initLValue(lvalue);
998    }
999
1000    OpaqueValueMapping(CodeGenFunction &CGF,
1001                       const OpaqueValueExpr *opaqueValue,
1002                       RValue rvalue)
1003      : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(false) {
1004      assert(opaqueValue && "no opaque value expression!");
1005      assert(!shouldBindAsLValue(opaqueValue));
1006      initRValue(rvalue);
1007    }
1008
1009    void pop() {
1010      assert(OpaqueValue && "mapping already popped!");
1011      popImpl();
1012      OpaqueValue = 0;
1013    }
1014
1015    ~OpaqueValueMapping() {
1016      if (OpaqueValue) popImpl();
1017    }
1018
1019  private:
1020    void popImpl() {
1021      if (BoundLValue)
1022        CGF.OpaqueLValues.erase(OpaqueValue);
1023      else {
1024        CGF.OpaqueRValues.erase(OpaqueValue);
1025        CGF.unprotectFromPeepholes(Protection);
1026      }
1027    }
1028
1029    void init(const OpaqueValueExpr *ov, const Expr *e) {
1030      OpaqueValue = ov;
1031      BoundLValue = shouldBindAsLValue(ov);
1032      assert(BoundLValue == shouldBindAsLValue(e)
1033             && "inconsistent expression value kinds!");
1034      if (BoundLValue)
1035        initLValue(CGF.EmitLValue(e));
1036      else
1037        initRValue(CGF.EmitAnyExpr(e));
1038    }
1039
1040    void initLValue(const LValue &lv) {
1041      CGF.OpaqueLValues.insert(std::make_pair(OpaqueValue, lv));
1042    }
1043
1044    void initRValue(const RValue &rv) {
1045      // Work around an extremely aggressive peephole optimization in
1046      // EmitScalarConversion which assumes that all other uses of a
1047      // value are extant.
1048      Protection = CGF.protectFromPeepholes(rv);
1049      CGF.OpaqueRValues.insert(std::make_pair(OpaqueValue, rv));
1050    }
1051  };
1052
1053  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
1054  /// number that holds the value.
1055  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
1056
1057  /// BuildBlockByrefAddress - Computes address location of the
1058  /// variable which is declared as __block.
1059  llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
1060                                      const VarDecl *V);
1061private:
1062  CGDebugInfo *DebugInfo;
1063  bool DisableDebugInfo;
1064
1065  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1066  /// calling llvm.stacksave for multiple VLAs in the same scope.
1067  bool DidCallStackSave;
1068
1069  /// IndirectBranch - The first time an indirect goto is seen we create a block
1070  /// with an indirect branch.  Every time we see the address of a label taken,
1071  /// we add the label to the indirect goto.  Every subsequent indirect goto is
1072  /// codegen'd as a jump to the IndirectBranch's basic block.
1073  llvm::IndirectBrInst *IndirectBranch;
1074
1075  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1076  /// decls.
1077  typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
1078  DeclMapTy LocalDeclMap;
1079
1080  /// LabelMap - This keeps track of the LLVM basic block for each C label.
1081  llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1082
1083  // BreakContinueStack - This keeps track of where break and continue
1084  // statements should jump to.
1085  struct BreakContinue {
1086    BreakContinue(JumpDest Break, JumpDest Continue)
1087      : BreakBlock(Break), ContinueBlock(Continue) {}
1088
1089    JumpDest BreakBlock;
1090    JumpDest ContinueBlock;
1091  };
1092  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
1093
1094  /// SwitchInsn - This is nearest current switch instruction. It is null if if
1095  /// current context is not in a switch.
1096  llvm::SwitchInst *SwitchInsn;
1097
1098  /// CaseRangeBlock - This block holds if condition check for last case
1099  /// statement range in current switch instruction.
1100  llvm::BasicBlock *CaseRangeBlock;
1101
1102  /// OpaqueLValues - Keeps track of the current set of opaque value
1103  /// expressions.
1104  llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1105  llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1106
1107  // VLASizeMap - This keeps track of the associated size for each VLA type.
1108  // We track this by the size expression rather than the type itself because
1109  // in certain situations, like a const qualifier applied to an VLA typedef,
1110  // multiple VLA types can share the same size expression.
1111  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1112  // enter/leave scopes.
1113  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1114
1115  /// A block containing a single 'unreachable' instruction.  Created
1116  /// lazily by getUnreachableBlock().
1117  llvm::BasicBlock *UnreachableBlock;
1118
1119  /// CXXThisDecl - When generating code for a C++ member function,
1120  /// this will hold the implicit 'this' declaration.
1121  ImplicitParamDecl *CXXThisDecl;
1122  llvm::Value *CXXThisValue;
1123
1124  /// CXXVTTDecl - When generating code for a base object constructor or
1125  /// base object destructor with virtual bases, this will hold the implicit
1126  /// VTT parameter.
1127  ImplicitParamDecl *CXXVTTDecl;
1128  llvm::Value *CXXVTTValue;
1129
1130  /// OutermostConditional - Points to the outermost active
1131  /// conditional control.  This is used so that we know if a
1132  /// temporary should be destroyed conditionally.
1133  ConditionalEvaluation *OutermostConditional;
1134
1135
1136  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
1137  /// type as well as the field number that contains the actual data.
1138  llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
1139                                              unsigned> > ByRefValueInfo;
1140
1141  llvm::BasicBlock *TerminateLandingPad;
1142  llvm::BasicBlock *TerminateHandler;
1143  llvm::BasicBlock *TrapBB;
1144
1145public:
1146  CodeGenFunction(CodeGenModule &cgm);
1147
1148  CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1149  ASTContext &getContext() const { return CGM.getContext(); }
1150  CGDebugInfo *getDebugInfo() {
1151    if (DisableDebugInfo)
1152      return NULL;
1153    return DebugInfo;
1154  }
1155  void disableDebugInfo() { DisableDebugInfo = true; }
1156  void enableDebugInfo() { DisableDebugInfo = false; }
1157
1158  bool shouldUseFusedARCCalls() {
1159    return CGM.getCodeGenOpts().OptimizationLevel == 0;
1160  }
1161
1162  const LangOptions &getLangOptions() const { return CGM.getLangOptions(); }
1163
1164  /// Returns a pointer to the function's exception object slot, which
1165  /// is assigned in every landing pad.
1166  llvm::Value *getExceptionSlot();
1167  llvm::Value *getEHSelectorSlot();
1168
1169  llvm::Value *getNormalCleanupDestSlot();
1170  llvm::Value *getEHCleanupDestSlot();
1171
1172  llvm::BasicBlock *getUnreachableBlock() {
1173    if (!UnreachableBlock) {
1174      UnreachableBlock = createBasicBlock("unreachable");
1175      new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1176    }
1177    return UnreachableBlock;
1178  }
1179
1180  llvm::BasicBlock *getInvokeDest() {
1181    if (!EHStack.requiresLandingPad()) return 0;
1182    return getInvokeDestImpl();
1183  }
1184
1185  llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1186
1187  //===--------------------------------------------------------------------===//
1188  //                                  Cleanups
1189  //===--------------------------------------------------------------------===//
1190
1191  typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
1192
1193  void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1194                                        llvm::Value *arrayEndPointer,
1195                                        QualType elementType,
1196                                        Destroyer &destroyer);
1197  void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1198                                      llvm::Value *arrayEnd,
1199                                      QualType elementType,
1200                                      Destroyer &destroyer);
1201
1202  void pushDestroy(QualType::DestructionKind dtorKind,
1203                   llvm::Value *addr, QualType type);
1204  void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
1205                   Destroyer &destroyer, bool useEHCleanupForArray);
1206  void emitDestroy(llvm::Value *addr, QualType type, Destroyer &destroyer,
1207                   bool useEHCleanupForArray);
1208  llvm::Function *generateDestroyHelper(llvm::Constant *addr,
1209                                        QualType type,
1210                                        Destroyer &destroyer,
1211                                        bool useEHCleanupForArray);
1212  void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1213                        QualType type, Destroyer &destroyer,
1214                        bool checkZeroLength, bool useEHCleanup);
1215
1216  Destroyer &getDestroyer(QualType::DestructionKind destructionKind);
1217
1218  /// Determines whether an EH cleanup is required to destroy a type
1219  /// with the given destruction kind.
1220  bool needsEHCleanup(QualType::DestructionKind kind) {
1221    switch (kind) {
1222    case QualType::DK_none:
1223      return false;
1224    case QualType::DK_cxx_destructor:
1225    case QualType::DK_objc_weak_lifetime:
1226      return getLangOptions().Exceptions;
1227    case QualType::DK_objc_strong_lifetime:
1228      return getLangOptions().Exceptions &&
1229             CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1230    }
1231    llvm_unreachable("bad destruction kind");
1232  }
1233
1234  CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1235    return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1236  }
1237
1238  //===--------------------------------------------------------------------===//
1239  //                                  Objective-C
1240  //===--------------------------------------------------------------------===//
1241
1242  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1243
1244  void StartObjCMethod(const ObjCMethodDecl *MD,
1245                       const ObjCContainerDecl *CD,
1246                       SourceLocation StartLoc);
1247
1248  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1249  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1250                          const ObjCPropertyImplDecl *PID);
1251  void GenerateObjCGetterBody(ObjCIvarDecl *Ivar, bool IsAtomic, bool IsStrong);
1252  void GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
1253                                    ObjCIvarDecl *Ivar);
1254
1255  void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1256                                  ObjCMethodDecl *MD, bool ctor);
1257
1258  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1259  /// for the given property.
1260  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1261                          const ObjCPropertyImplDecl *PID);
1262  bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
1263  bool IvarTypeWithAggrGCObjects(QualType Ty);
1264
1265  //===--------------------------------------------------------------------===//
1266  //                                  Block Bits
1267  //===--------------------------------------------------------------------===//
1268
1269  llvm::Value *EmitBlockLiteral(const BlockExpr *);
1270  llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
1271                                           const CGBlockInfo &Info,
1272                                           const llvm::StructType *,
1273                                           llvm::Constant *BlockVarLayout);
1274
1275  llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1276                                        const CGBlockInfo &Info,
1277                                        const Decl *OuterFuncDecl,
1278                                        const DeclMapTy &ldm);
1279
1280  llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1281  llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1282
1283  void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1284
1285  class AutoVarEmission;
1286
1287  void emitByrefStructureInit(const AutoVarEmission &emission);
1288  void enterByrefCleanup(const AutoVarEmission &emission);
1289
1290  llvm::Value *LoadBlockStruct() {
1291    assert(BlockPointer && "no block pointer set!");
1292    return BlockPointer;
1293  }
1294
1295  void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
1296  void AllocateBlockDecl(const BlockDeclRefExpr *E);
1297  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
1298    return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
1299  }
1300  llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1301  const llvm::Type *BuildByRefType(const VarDecl *var);
1302
1303  void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1304                    const CGFunctionInfo &FnInfo);
1305  void StartFunction(GlobalDecl GD, QualType RetTy,
1306                     llvm::Function *Fn,
1307                     const CGFunctionInfo &FnInfo,
1308                     const FunctionArgList &Args,
1309                     SourceLocation StartLoc);
1310
1311  void EmitConstructorBody(FunctionArgList &Args);
1312  void EmitDestructorBody(FunctionArgList &Args);
1313  void EmitFunctionBody(FunctionArgList &Args);
1314
1315  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
1316  /// emission when possible.
1317  void EmitReturnBlock();
1318
1319  /// FinishFunction - Complete IR generation of the current function. It is
1320  /// legal to call this function even if there is no current insertion point.
1321  void FinishFunction(SourceLocation EndLoc=SourceLocation());
1322
1323  /// GenerateThunk - Generate a thunk for the given method.
1324  void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1325                     GlobalDecl GD, const ThunkInfo &Thunk);
1326
1327  void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1328                            GlobalDecl GD, const ThunkInfo &Thunk);
1329
1330  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1331                        FunctionArgList &Args);
1332
1333  /// InitializeVTablePointer - Initialize the vtable pointer of the given
1334  /// subobject.
1335  ///
1336  void InitializeVTablePointer(BaseSubobject Base,
1337                               const CXXRecordDecl *NearestVBase,
1338                               CharUnits OffsetFromNearestVBase,
1339                               llvm::Constant *VTable,
1340                               const CXXRecordDecl *VTableClass);
1341
1342  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1343  void InitializeVTablePointers(BaseSubobject Base,
1344                                const CXXRecordDecl *NearestVBase,
1345                                CharUnits OffsetFromNearestVBase,
1346                                bool BaseIsNonVirtualPrimaryBase,
1347                                llvm::Constant *VTable,
1348                                const CXXRecordDecl *VTableClass,
1349                                VisitedVirtualBasesSetTy& VBases);
1350
1351  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1352
1353  /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1354  /// to by This.
1355  llvm::Value *GetVTablePtr(llvm::Value *This, const llvm::Type *Ty);
1356
1357  /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1358  /// given phase of destruction for a destructor.  The end result
1359  /// should call destructors on members and base classes in reverse
1360  /// order of their construction.
1361  void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1362
1363  /// ShouldInstrumentFunction - Return true if the current function should be
1364  /// instrumented with __cyg_profile_func_* calls
1365  bool ShouldInstrumentFunction();
1366
1367  /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1368  /// instrumentation function with the current function and the call site, if
1369  /// function instrumentation is enabled.
1370  void EmitFunctionInstrumentation(const char *Fn);
1371
1372  /// EmitMCountInstrumentation - Emit call to .mcount.
1373  void EmitMCountInstrumentation();
1374
1375  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1376  /// arguments for the given function. This is also responsible for naming the
1377  /// LLVM function arguments.
1378  void EmitFunctionProlog(const CGFunctionInfo &FI,
1379                          llvm::Function *Fn,
1380                          const FunctionArgList &Args);
1381
1382  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1383  /// given temporary.
1384  void EmitFunctionEpilog(const CGFunctionInfo &FI);
1385
1386  /// EmitStartEHSpec - Emit the start of the exception spec.
1387  void EmitStartEHSpec(const Decl *D);
1388
1389  /// EmitEndEHSpec - Emit the end of the exception spec.
1390  void EmitEndEHSpec(const Decl *D);
1391
1392  /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1393  llvm::BasicBlock *getTerminateLandingPad();
1394
1395  /// getTerminateHandler - Return a handler (not a landing pad, just
1396  /// a catch handler) that just calls terminate.  This is used when
1397  /// a terminate scope encloses a try.
1398  llvm::BasicBlock *getTerminateHandler();
1399
1400  llvm::Type *ConvertTypeForMem(QualType T);
1401  llvm::Type *ConvertType(QualType T);
1402  llvm::Type *ConvertType(const TypeDecl *T) {
1403    return ConvertType(getContext().getTypeDeclType(T));
1404  }
1405
1406  /// LoadObjCSelf - Load the value of self. This function is only valid while
1407  /// generating code for an Objective-C method.
1408  llvm::Value *LoadObjCSelf();
1409
1410  /// TypeOfSelfObject - Return type of object that this self represents.
1411  QualType TypeOfSelfObject();
1412
1413  /// hasAggregateLLVMType - Return true if the specified AST type will map into
1414  /// an aggregate LLVM type or is void.
1415  static bool hasAggregateLLVMType(QualType T);
1416
1417  /// createBasicBlock - Create an LLVM basic block.
1418  llvm::BasicBlock *createBasicBlock(llvm::StringRef name = "",
1419                                     llvm::Function *parent = 0,
1420                                     llvm::BasicBlock *before = 0) {
1421#ifdef NDEBUG
1422    return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1423#else
1424    return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1425#endif
1426  }
1427
1428  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1429  /// label maps to.
1430  JumpDest getJumpDestForLabel(const LabelDecl *S);
1431
1432  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1433  /// another basic block, simplify it. This assumes that no other code could
1434  /// potentially reference the basic block.
1435  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1436
1437  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1438  /// adding a fall-through branch from the current insert block if
1439  /// necessary. It is legal to call this function even if there is no current
1440  /// insertion point.
1441  ///
1442  /// IsFinished - If true, indicates that the caller has finished emitting
1443  /// branches to the given block and does not expect to emit code into it. This
1444  /// means the block can be ignored if it is unreachable.
1445  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1446
1447  /// EmitBranch - Emit a branch to the specified basic block from the current
1448  /// insert block, taking care to avoid creation of branches from dummy
1449  /// blocks. It is legal to call this function even if there is no current
1450  /// insertion point.
1451  ///
1452  /// This function clears the current insertion point. The caller should follow
1453  /// calls to this function with calls to Emit*Block prior to generation new
1454  /// code.
1455  void EmitBranch(llvm::BasicBlock *Block);
1456
1457  /// HaveInsertPoint - True if an insertion point is defined. If not, this
1458  /// indicates that the current code being emitted is unreachable.
1459  bool HaveInsertPoint() const {
1460    return Builder.GetInsertBlock() != 0;
1461  }
1462
1463  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1464  /// emitted IR has a place to go. Note that by definition, if this function
1465  /// creates a block then that block is unreachable; callers may do better to
1466  /// detect when no insertion point is defined and simply skip IR generation.
1467  void EnsureInsertPoint() {
1468    if (!HaveInsertPoint())
1469      EmitBlock(createBasicBlock());
1470  }
1471
1472  /// ErrorUnsupported - Print out an error that codegen doesn't support the
1473  /// specified stmt yet.
1474  void ErrorUnsupported(const Stmt *S, const char *Type,
1475                        bool OmitOnError=false);
1476
1477  //===--------------------------------------------------------------------===//
1478  //                                  Helpers
1479  //===--------------------------------------------------------------------===//
1480
1481  LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) {
1482    return LValue::MakeAddr(V, T, Alignment, getContext(),
1483                            CGM.getTBAAInfo(T));
1484  }
1485
1486  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1487  /// block. The caller is responsible for setting an appropriate alignment on
1488  /// the alloca.
1489  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
1490                                     const llvm::Twine &Name = "tmp");
1491
1492  /// InitTempAlloca - Provide an initial value for the given alloca.
1493  void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
1494
1495  /// CreateIRTemp - Create a temporary IR object of the given type, with
1496  /// appropriate alignment. This routine should only be used when an temporary
1497  /// value needs to be stored into an alloca (for example, to avoid explicit
1498  /// PHI construction), but the type is the IR type, not the type appropriate
1499  /// for storing in memory.
1500  llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
1501
1502  /// CreateMemTemp - Create a temporary memory object of the given type, with
1503  /// appropriate alignment.
1504  llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
1505
1506  /// CreateAggTemp - Create a temporary memory object for the given
1507  /// aggregate type.
1508  AggValueSlot CreateAggTemp(QualType T, const llvm::Twine &Name = "tmp") {
1509    return AggValueSlot::forAddr(CreateMemTemp(T, Name), T.getQualifiers(),
1510                                 false);
1511  }
1512
1513  /// Emit a cast to void* in the appropriate address space.
1514  llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1515
1516  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1517  /// expression and compare the result against zero, returning an Int1Ty value.
1518  llvm::Value *EvaluateExprAsBool(const Expr *E);
1519
1520  /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1521  void EmitIgnoredExpr(const Expr *E);
1522
1523  /// EmitAnyExpr - Emit code to compute the specified expression which can have
1524  /// any type.  The result is returned as an RValue struct.  If this is an
1525  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1526  /// the result should be returned.
1527  ///
1528  /// \param IgnoreResult - True if the resulting value isn't used.
1529  RValue EmitAnyExpr(const Expr *E,
1530                     AggValueSlot AggSlot = AggValueSlot::ignored(),
1531                     bool IgnoreResult = false);
1532
1533  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1534  // or the value of the expression, depending on how va_list is defined.
1535  llvm::Value *EmitVAListRef(const Expr *E);
1536
1537  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1538  /// always be accessible even if no aggregate location is provided.
1539  RValue EmitAnyExprToTemp(const Expr *E);
1540
1541  /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1542  /// arbitrary expression into the given memory location.
1543  void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1544                        Qualifiers Quals, bool IsInitializer);
1545
1546  /// EmitExprAsInit - Emits the code necessary to initialize a
1547  /// location in memory with the given initializer.
1548  void EmitExprAsInit(const Expr *init, const ValueDecl *D,
1549                      LValue lvalue, bool capturedByInit);
1550
1551  /// EmitAggregateCopy - Emit an aggrate copy.
1552  ///
1553  /// \param isVolatile - True iff either the source or the destination is
1554  /// volatile.
1555  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1556                         QualType EltTy, bool isVolatile=false);
1557
1558  /// StartBlock - Start new block named N. If insert block is a dummy block
1559  /// then reuse it.
1560  void StartBlock(const char *N);
1561
1562  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
1563  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
1564    return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
1565  }
1566
1567  /// GetAddrOfLocalVar - Return the address of a local variable.
1568  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1569    llvm::Value *Res = LocalDeclMap[VD];
1570    assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1571    return Res;
1572  }
1573
1574  /// getOpaqueLValueMapping - Given an opaque value expression (which
1575  /// must be mapped to an l-value), return its mapping.
1576  const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1577    assert(OpaqueValueMapping::shouldBindAsLValue(e));
1578
1579    llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1580      it = OpaqueLValues.find(e);
1581    assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
1582    return it->second;
1583  }
1584
1585  /// getOpaqueRValueMapping - Given an opaque value expression (which
1586  /// must be mapped to an r-value), return its mapping.
1587  const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
1588    assert(!OpaqueValueMapping::shouldBindAsLValue(e));
1589
1590    llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
1591      it = OpaqueRValues.find(e);
1592    assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
1593    return it->second;
1594  }
1595
1596  /// getAccessedFieldNo - Given an encoded value and a result number, return
1597  /// the input field number being accessed.
1598  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1599
1600  llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
1601  llvm::BasicBlock *GetIndirectGotoBlock();
1602
1603  /// EmitNullInitialization - Generate code to set a value of the given type to
1604  /// null, If the type contains data member pointers, they will be initialized
1605  /// to -1 in accordance with the Itanium C++ ABI.
1606  void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1607
1608  // EmitVAArg - Generate code to get an argument from the passed in pointer
1609  // and update it accordingly. The return value is a pointer to the argument.
1610  // FIXME: We should be able to get rid of this method and use the va_arg
1611  // instruction in LLVM instead once it works well enough.
1612  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1613
1614  /// emitArrayLength - Compute the length of an array, even if it's a
1615  /// VLA, and drill down to the base element type.
1616  llvm::Value *emitArrayLength(const ArrayType *arrayType,
1617                               QualType &baseType,
1618                               llvm::Value *&addr);
1619
1620  /// EmitVLASize - Capture all the sizes for the VLA expressions in
1621  /// the given variably-modified type and store them in the VLASizeMap.
1622  ///
1623  /// This function can be called with a null (unreachable) insert point.
1624  void EmitVariablyModifiedType(QualType Ty);
1625
1626  /// getVLASize - Returns an LLVM value that corresponds to the size,
1627  /// in non-variably-sized elements, of a variable length array type,
1628  /// plus that largest non-variably-sized element type.  Assumes that
1629  /// the type has already been emitted with EmitVariablyModifiedType.
1630  std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
1631  std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
1632
1633  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1634  /// generating code for an C++ member function.
1635  llvm::Value *LoadCXXThis() {
1636    assert(CXXThisValue && "no 'this' value for this function");
1637    return CXXThisValue;
1638  }
1639
1640  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1641  /// virtual bases.
1642  llvm::Value *LoadCXXVTT() {
1643    assert(CXXVTTValue && "no VTT value for this function");
1644    return CXXVTTValue;
1645  }
1646
1647  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1648  /// complete class to the given direct base.
1649  llvm::Value *
1650  GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1651                                        const CXXRecordDecl *Derived,
1652                                        const CXXRecordDecl *Base,
1653                                        bool BaseIsVirtual);
1654
1655  /// GetAddressOfBaseClass - This function will add the necessary delta to the
1656  /// load of 'this' and returns address of the base class.
1657  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1658                                     const CXXRecordDecl *Derived,
1659                                     CastExpr::path_const_iterator PathBegin,
1660                                     CastExpr::path_const_iterator PathEnd,
1661                                     bool NullCheckValue);
1662
1663  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1664                                        const CXXRecordDecl *Derived,
1665                                        CastExpr::path_const_iterator PathBegin,
1666                                        CastExpr::path_const_iterator PathEnd,
1667                                        bool NullCheckValue);
1668
1669  llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
1670                                         const CXXRecordDecl *ClassDecl,
1671                                         const CXXRecordDecl *BaseClassDecl);
1672
1673  void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1674                                      CXXCtorType CtorType,
1675                                      const FunctionArgList &Args);
1676  // It's important not to confuse this and the previous function. Delegating
1677  // constructors are the C++0x feature. The constructor delegate optimization
1678  // is used to reduce duplication in the base and complete consturctors where
1679  // they are substantially the same.
1680  void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1681                                        const FunctionArgList &Args);
1682  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1683                              bool ForVirtualBase, llvm::Value *This,
1684                              CallExpr::const_arg_iterator ArgBeg,
1685                              CallExpr::const_arg_iterator ArgEnd);
1686
1687  void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1688                              llvm::Value *This, llvm::Value *Src,
1689                              CallExpr::const_arg_iterator ArgBeg,
1690                              CallExpr::const_arg_iterator ArgEnd);
1691
1692  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1693                                  const ConstantArrayType *ArrayTy,
1694                                  llvm::Value *ArrayPtr,
1695                                  CallExpr::const_arg_iterator ArgBeg,
1696                                  CallExpr::const_arg_iterator ArgEnd,
1697                                  bool ZeroInitialization = false);
1698
1699  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1700                                  llvm::Value *NumElements,
1701                                  llvm::Value *ArrayPtr,
1702                                  CallExpr::const_arg_iterator ArgBeg,
1703                                  CallExpr::const_arg_iterator ArgEnd,
1704                                  bool ZeroInitialization = false);
1705
1706  static Destroyer destroyCXXObject;
1707
1708  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1709                             bool ForVirtualBase, llvm::Value *This);
1710
1711  void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
1712                               llvm::Value *NumElements);
1713
1714  void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
1715
1716  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1717  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1718
1719  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1720                      QualType DeleteTy);
1721
1722  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1723  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1724
1725  void EmitCheck(llvm::Value *, unsigned Size);
1726
1727  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1728                                       bool isInc, bool isPre);
1729  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1730                                         bool isInc, bool isPre);
1731  //===--------------------------------------------------------------------===//
1732  //                            Declaration Emission
1733  //===--------------------------------------------------------------------===//
1734
1735  /// EmitDecl - Emit a declaration.
1736  ///
1737  /// This function can be called with a null (unreachable) insert point.
1738  void EmitDecl(const Decl &D);
1739
1740  /// EmitVarDecl - Emit a local variable declaration.
1741  ///
1742  /// This function can be called with a null (unreachable) insert point.
1743  void EmitVarDecl(const VarDecl &D);
1744
1745  void EmitScalarInit(const Expr *init, const ValueDecl *D,
1746                      LValue lvalue, bool capturedByInit);
1747  void EmitScalarInit(llvm::Value *init, LValue lvalue);
1748
1749  typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1750                             llvm::Value *Address);
1751
1752  /// EmitAutoVarDecl - Emit an auto variable declaration.
1753  ///
1754  /// This function can be called with a null (unreachable) insert point.
1755  void EmitAutoVarDecl(const VarDecl &D);
1756
1757  class AutoVarEmission {
1758    friend class CodeGenFunction;
1759
1760    const VarDecl *Variable;
1761
1762    /// The alignment of the variable.
1763    CharUnits Alignment;
1764
1765    /// The address of the alloca.  Null if the variable was emitted
1766    /// as a global constant.
1767    llvm::Value *Address;
1768
1769    llvm::Value *NRVOFlag;
1770
1771    /// True if the variable is a __block variable.
1772    bool IsByRef;
1773
1774    /// True if the variable is of aggregate type and has a constant
1775    /// initializer.
1776    bool IsConstantAggregate;
1777
1778    struct Invalid {};
1779    AutoVarEmission(Invalid) : Variable(0) {}
1780
1781    AutoVarEmission(const VarDecl &variable)
1782      : Variable(&variable), Address(0), NRVOFlag(0),
1783        IsByRef(false), IsConstantAggregate(false) {}
1784
1785    bool wasEmittedAsGlobal() const { return Address == 0; }
1786
1787  public:
1788    static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
1789
1790    /// Returns the address of the object within this declaration.
1791    /// Note that this does not chase the forwarding pointer for
1792    /// __block decls.
1793    llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
1794      if (!IsByRef) return Address;
1795
1796      return CGF.Builder.CreateStructGEP(Address,
1797                                         CGF.getByRefValueLLVMField(Variable),
1798                                         Variable->getNameAsString());
1799    }
1800  };
1801  AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
1802  void EmitAutoVarInit(const AutoVarEmission &emission);
1803  void EmitAutoVarCleanups(const AutoVarEmission &emission);
1804  void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
1805                              QualType::DestructionKind dtorKind);
1806
1807  void EmitStaticVarDecl(const VarDecl &D,
1808                         llvm::GlobalValue::LinkageTypes Linkage);
1809
1810  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1811  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
1812
1813  /// protectFromPeepholes - Protect a value that we're intending to
1814  /// store to the side, but which will probably be used later, from
1815  /// aggressive peepholing optimizations that might delete it.
1816  ///
1817  /// Pass the result to unprotectFromPeepholes to declare that
1818  /// protection is no longer required.
1819  ///
1820  /// There's no particular reason why this shouldn't apply to
1821  /// l-values, it's just that no existing peepholes work on pointers.
1822  PeepholeProtection protectFromPeepholes(RValue rvalue);
1823  void unprotectFromPeepholes(PeepholeProtection protection);
1824
1825  //===--------------------------------------------------------------------===//
1826  //                             Statement Emission
1827  //===--------------------------------------------------------------------===//
1828
1829  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1830  void EmitStopPoint(const Stmt *S);
1831
1832  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1833  /// this function even if there is no current insertion point.
1834  ///
1835  /// This function may clear the current insertion point; callers should use
1836  /// EnsureInsertPoint if they wish to subsequently generate code without first
1837  /// calling EmitBlock, EmitBranch, or EmitStmt.
1838  void EmitStmt(const Stmt *S);
1839
1840  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1841  /// necessarily require an insertion point or debug information; typically
1842  /// because the statement amounts to a jump or a container of other
1843  /// statements.
1844  ///
1845  /// \return True if the statement was handled.
1846  bool EmitSimpleStmt(const Stmt *S);
1847
1848  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1849                          AggValueSlot AVS = AggValueSlot::ignored());
1850
1851  /// EmitLabel - Emit the block for the given label. It is legal to call this
1852  /// function even if there is no current insertion point.
1853  void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
1854
1855  void EmitLabelStmt(const LabelStmt &S);
1856  void EmitGotoStmt(const GotoStmt &S);
1857  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1858  void EmitIfStmt(const IfStmt &S);
1859  void EmitWhileStmt(const WhileStmt &S);
1860  void EmitDoStmt(const DoStmt &S);
1861  void EmitForStmt(const ForStmt &S);
1862  void EmitReturnStmt(const ReturnStmt &S);
1863  void EmitDeclStmt(const DeclStmt &S);
1864  void EmitBreakStmt(const BreakStmt &S);
1865  void EmitContinueStmt(const ContinueStmt &S);
1866  void EmitSwitchStmt(const SwitchStmt &S);
1867  void EmitDefaultStmt(const DefaultStmt &S);
1868  void EmitCaseStmt(const CaseStmt &S);
1869  void EmitCaseStmtRange(const CaseStmt &S);
1870  void EmitAsmStmt(const AsmStmt &S);
1871
1872  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1873  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1874  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1875  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1876  void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
1877
1878  llvm::Constant *getUnwindResumeFn();
1879  llvm::Constant *getUnwindResumeOrRethrowFn();
1880  void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1881  void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1882
1883  void EmitCXXTryStmt(const CXXTryStmt &S);
1884  void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
1885
1886  //===--------------------------------------------------------------------===//
1887  //                         LValue Expression Emission
1888  //===--------------------------------------------------------------------===//
1889
1890  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1891  RValue GetUndefRValue(QualType Ty);
1892
1893  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1894  /// and issue an ErrorUnsupported style diagnostic (using the
1895  /// provided Name).
1896  RValue EmitUnsupportedRValue(const Expr *E,
1897                               const char *Name);
1898
1899  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1900  /// an ErrorUnsupported style diagnostic (using the provided Name).
1901  LValue EmitUnsupportedLValue(const Expr *E,
1902                               const char *Name);
1903
1904  /// EmitLValue - Emit code to compute a designator that specifies the location
1905  /// of the expression.
1906  ///
1907  /// This can return one of two things: a simple address or a bitfield
1908  /// reference.  In either case, the LLVM Value* in the LValue structure is
1909  /// guaranteed to be an LLVM pointer type.
1910  ///
1911  /// If this returns a bitfield reference, nothing about the pointee type of
1912  /// the LLVM value is known: For example, it may not be a pointer to an
1913  /// integer.
1914  ///
1915  /// If this returns a normal address, and if the lvalue's C type is fixed
1916  /// size, this method guarantees that the returned pointer type will point to
1917  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
1918  /// variable length type, this is not possible.
1919  ///
1920  LValue EmitLValue(const Expr *E);
1921
1922  /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1923  /// checking code to guard against undefined behavior.  This is only
1924  /// suitable when we know that the address will be used to access the
1925  /// object.
1926  LValue EmitCheckedLValue(const Expr *E);
1927
1928  /// EmitToMemory - Change a scalar value from its value
1929  /// representation to its in-memory representation.
1930  llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
1931
1932  /// EmitFromMemory - Change a scalar value from its memory
1933  /// representation to its value representation.
1934  llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
1935
1936  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1937  /// care to appropriately convert from the memory representation to
1938  /// the LLVM value representation.
1939  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1940                                unsigned Alignment, QualType Ty,
1941                                llvm::MDNode *TBAAInfo = 0);
1942
1943  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1944  /// care to appropriately convert from the memory representation to
1945  /// the LLVM value representation.  The l-value must be a simple
1946  /// l-value.
1947  llvm::Value *EmitLoadOfScalar(LValue lvalue);
1948
1949  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1950  /// care to appropriately convert from the memory representation to
1951  /// the LLVM value representation.
1952  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1953                         bool Volatile, unsigned Alignment, QualType Ty,
1954                         llvm::MDNode *TBAAInfo = 0);
1955
1956  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1957  /// care to appropriately convert from the memory representation to
1958  /// the LLVM value representation.  The l-value must be a simple
1959  /// l-value.
1960  void EmitStoreOfScalar(llvm::Value *value, LValue lvalue);
1961
1962  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1963  /// this method emits the address of the lvalue, then loads the result as an
1964  /// rvalue, returning the rvalue.
1965  RValue EmitLoadOfLValue(LValue V);
1966  RValue EmitLoadOfExtVectorElementLValue(LValue V);
1967  RValue EmitLoadOfBitfieldLValue(LValue LV);
1968  RValue EmitLoadOfPropertyRefLValue(LValue LV,
1969                                 ReturnValueSlot Return = ReturnValueSlot());
1970
1971  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1972  /// lvalue, where both are guaranteed to the have the same type, and that type
1973  /// is 'Ty'.
1974  void EmitStoreThroughLValue(RValue Src, LValue Dst);
1975  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
1976  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst);
1977
1978  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1979  /// EmitStoreThroughLValue.
1980  ///
1981  /// \param Result [out] - If non-null, this will be set to a Value* for the
1982  /// bit-field contents after the store, appropriate for use as the result of
1983  /// an assignment to the bit-field.
1984  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1985                                      llvm::Value **Result=0);
1986
1987  /// Emit an l-value for an assignment (simple or compound) of complex type.
1988  LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
1989  LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
1990
1991  // Note: only available for agg return types
1992  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1993  LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
1994  // Note: only available for agg return types
1995  LValue EmitCallExprLValue(const CallExpr *E);
1996  // Note: only available for agg return types
1997  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1998  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1999  LValue EmitStringLiteralLValue(const StringLiteral *E);
2000  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
2001  LValue EmitPredefinedLValue(const PredefinedExpr *E);
2002  LValue EmitUnaryOpLValue(const UnaryOperator *E);
2003  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
2004  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
2005  LValue EmitMemberExpr(const MemberExpr *E);
2006  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
2007  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
2008  LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
2009  LValue EmitCastLValue(const CastExpr *E);
2010  LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
2011  LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2012  LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
2013
2014  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2015                              const ObjCIvarDecl *Ivar);
2016  LValue EmitLValueForAnonRecordField(llvm::Value* Base,
2017                                      const IndirectFieldDecl* Field,
2018                                      unsigned CVRQualifiers);
2019  LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
2020                            unsigned CVRQualifiers);
2021
2022  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2023  /// if the Field is a reference, this will return the address of the reference
2024  /// and not the address of the value stored in the reference.
2025  LValue EmitLValueForFieldInitialization(llvm::Value* Base,
2026                                          const FieldDecl* Field,
2027                                          unsigned CVRQualifiers);
2028
2029  LValue EmitLValueForIvar(QualType ObjectTy,
2030                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
2031                           unsigned CVRQualifiers);
2032
2033  LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
2034                                unsigned CVRQualifiers);
2035
2036  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
2037
2038  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2039  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2040  LValue EmitExprWithCleanupsLValue(const ExprWithCleanups *E);
2041  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2042
2043  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
2044  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
2045  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
2046  LValue EmitStmtExprLValue(const StmtExpr *E);
2047  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
2048  LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
2049  void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
2050
2051  //===--------------------------------------------------------------------===//
2052  //                         Scalar Expression Emission
2053  //===--------------------------------------------------------------------===//
2054
2055  /// EmitCall - Generate a call of the given function, expecting the given
2056  /// result type, and using the given argument list which specifies both the
2057  /// LLVM arguments and the types they were derived from.
2058  ///
2059  /// \param TargetDecl - If given, the decl of the function in a direct call;
2060  /// used to set attributes on the call (noreturn, etc.).
2061  RValue EmitCall(const CGFunctionInfo &FnInfo,
2062                  llvm::Value *Callee,
2063                  ReturnValueSlot ReturnValue,
2064                  const CallArgList &Args,
2065                  const Decl *TargetDecl = 0,
2066                  llvm::Instruction **callOrInvoke = 0);
2067
2068  RValue EmitCall(QualType FnType, llvm::Value *Callee,
2069                  ReturnValueSlot ReturnValue,
2070                  CallExpr::const_arg_iterator ArgBeg,
2071                  CallExpr::const_arg_iterator ArgEnd,
2072                  const Decl *TargetDecl = 0);
2073  RValue EmitCallExpr(const CallExpr *E,
2074                      ReturnValueSlot ReturnValue = ReturnValueSlot());
2075
2076  llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2077                                  llvm::ArrayRef<llvm::Value *> Args,
2078                                  const llvm::Twine &Name = "");
2079  llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2080                                  const llvm::Twine &Name = "");
2081
2082  llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
2083                                const llvm::Type *Ty);
2084  llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
2085                                llvm::Value *This, const llvm::Type *Ty);
2086  llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
2087                                         NestedNameSpecifier *Qual,
2088                                         const llvm::Type *Ty);
2089
2090  llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
2091                                                   CXXDtorType Type,
2092                                                   const CXXRecordDecl *RD);
2093
2094  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
2095                           llvm::Value *Callee,
2096                           ReturnValueSlot ReturnValue,
2097                           llvm::Value *This,
2098                           llvm::Value *VTT,
2099                           CallExpr::const_arg_iterator ArgBeg,
2100                           CallExpr::const_arg_iterator ArgEnd);
2101  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
2102                               ReturnValueSlot ReturnValue);
2103  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
2104                                      ReturnValueSlot ReturnValue);
2105
2106  llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2107                                           const CXXMethodDecl *MD,
2108                                           llvm::Value *This);
2109  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
2110                                       const CXXMethodDecl *MD,
2111                                       ReturnValueSlot ReturnValue);
2112
2113
2114  RValue EmitBuiltinExpr(const FunctionDecl *FD,
2115                         unsigned BuiltinID, const CallExpr *E);
2116
2117  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
2118
2119  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
2120  /// is unhandled by the current target.
2121  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2122
2123  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2124  llvm::Value *EmitNeonCall(llvm::Function *F,
2125                            llvm::SmallVectorImpl<llvm::Value*> &O,
2126                            const char *name,
2127                            unsigned shift = 0, bool rightshift = false);
2128  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
2129  llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
2130                                   bool negateForRightShift);
2131
2132  llvm::Value *BuildVector(const llvm::SmallVectorImpl<llvm::Value*> &Ops);
2133  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2134  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2135
2136  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
2137  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
2138  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
2139  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
2140                             ReturnValueSlot Return = ReturnValueSlot());
2141
2142  /// Retrieves the default cleanup kind for an ARC cleanup.
2143  /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
2144  CleanupKind getARCCleanupKind() {
2145    return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
2146             ? NormalAndEHCleanup : NormalCleanup;
2147  }
2148
2149  // ARC primitives.
2150  void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
2151  void EmitARCDestroyWeak(llvm::Value *addr);
2152  llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
2153  llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
2154  llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
2155                                bool ignored);
2156  void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
2157  void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
2158  llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
2159  llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
2160  llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
2161                                  bool ignored);
2162  llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
2163                                      bool ignored);
2164  llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
2165  llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
2166  llvm::Value *EmitARCRetainBlock(llvm::Value *value);
2167  void EmitARCRelease(llvm::Value *value, bool precise);
2168  llvm::Value *EmitARCAutorelease(llvm::Value *value);
2169  llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
2170  llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
2171  llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
2172
2173  std::pair<LValue,llvm::Value*>
2174  EmitARCStoreAutoreleasing(const BinaryOperator *e);
2175  std::pair<LValue,llvm::Value*>
2176  EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
2177
2178  llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
2179  llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
2180  llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
2181
2182  llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
2183  llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
2184
2185  static Destroyer destroyARCStrongImprecise;
2186  static Destroyer destroyARCStrongPrecise;
2187  static Destroyer destroyARCWeak;
2188
2189  void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
2190  llvm::Value *EmitObjCAutoreleasePoolPush();
2191  llvm::Value *EmitObjCMRRAutoreleasePoolPush();
2192  void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
2193  void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
2194
2195  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
2196  /// expression. Will emit a temporary variable if E is not an LValue.
2197  RValue EmitReferenceBindingToExpr(const Expr* E,
2198                                    const NamedDecl *InitializedDecl);
2199
2200  //===--------------------------------------------------------------------===//
2201  //                           Expression Emission
2202  //===--------------------------------------------------------------------===//
2203
2204  // Expressions are broken into three classes: scalar, complex, aggregate.
2205
2206  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
2207  /// scalar type, returning the result.
2208  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
2209
2210  /// EmitScalarConversion - Emit a conversion from the specified type to the
2211  /// specified destination type, both of which are LLVM scalar types.
2212  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
2213                                    QualType DstTy);
2214
2215  /// EmitComplexToScalarConversion - Emit a conversion from the specified
2216  /// complex type to the specified destination type, where the destination type
2217  /// is an LLVM scalar type.
2218  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
2219                                             QualType DstTy);
2220
2221
2222  /// EmitAggExpr - Emit the computation of the specified expression
2223  /// of aggregate type.  The result is computed into the given slot,
2224  /// which may be null to indicate that the value is not needed.
2225  void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false);
2226
2227  /// EmitAggExprToLValue - Emit the computation of the specified expression of
2228  /// aggregate type into a temporary LValue.
2229  LValue EmitAggExprToLValue(const Expr *E);
2230
2231  /// EmitGCMemmoveCollectable - Emit special API for structs with object
2232  /// pointers.
2233  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
2234                                QualType Ty);
2235
2236  /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2237  /// make sure it survives garbage collection until this point.
2238  void EmitExtendGCLifetime(llvm::Value *object);
2239
2240  /// EmitComplexExpr - Emit the computation of the specified expression of
2241  /// complex type, returning the result.
2242  ComplexPairTy EmitComplexExpr(const Expr *E,
2243                                bool IgnoreReal = false,
2244                                bool IgnoreImag = false);
2245
2246  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
2247  /// of complex type, storing into the specified Value*.
2248  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
2249                               bool DestIsVolatile);
2250
2251  /// StoreComplexToAddr - Store a complex number into the specified address.
2252  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
2253                          bool DestIsVolatile);
2254  /// LoadComplexFromAddr - Load a complex number from the specified address.
2255  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
2256
2257  /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
2258  /// a static local variable.
2259  llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
2260                                            const char *Separator,
2261                                       llvm::GlobalValue::LinkageTypes Linkage);
2262
2263  /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
2264  /// global variable that has already been created for it.  If the initializer
2265  /// has a different type than GV does, this may free GV and return a different
2266  /// one.  Otherwise it just returns GV.
2267  llvm::GlobalVariable *
2268  AddInitializerToStaticVarDecl(const VarDecl &D,
2269                                llvm::GlobalVariable *GV);
2270
2271
2272  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
2273  /// variable with global storage.
2274  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
2275
2276  /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
2277  /// with the C++ runtime so that its destructor will be called at exit.
2278  void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
2279                                     llvm::Constant *DeclPtr);
2280
2281  /// Emit code in this function to perform a guarded variable
2282  /// initialization.  Guarded initializations are used when it's not
2283  /// possible to prove that an initialization will be done exactly
2284  /// once, e.g. with a static local variable or a static data member
2285  /// of a class template.
2286  void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr);
2287
2288  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
2289  /// variables.
2290  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
2291                                 llvm::Constant **Decls,
2292                                 unsigned NumDecls);
2293
2294  /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
2295  /// variables.
2296  void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
2297                                 const std::vector<std::pair<llvm::WeakVH,
2298                                   llvm::Constant*> > &DtorsAndObjects);
2299
2300  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
2301                                        const VarDecl *D,
2302                                        llvm::GlobalVariable *Addr);
2303
2304  void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
2305
2306  void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
2307                                  const Expr *Exp);
2308
2309  RValue EmitExprWithCleanups(const ExprWithCleanups *E,
2310                              AggValueSlot Slot =AggValueSlot::ignored());
2311
2312  void EmitCXXThrowExpr(const CXXThrowExpr *E);
2313
2314  //===--------------------------------------------------------------------===//
2315  //                             Internal Helpers
2316  //===--------------------------------------------------------------------===//
2317
2318  /// ContainsLabel - Return true if the statement contains a label in it.  If
2319  /// this statement is not executed normally, it not containing a label means
2320  /// that we can just remove the code.
2321  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
2322
2323  /// containsBreak - Return true if the statement contains a break out of it.
2324  /// If the statement (recursively) contains a switch or loop with a break
2325  /// inside of it, this is fine.
2326  static bool containsBreak(const Stmt *S);
2327
2328  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2329  /// to a constant, or if it does but contains a label, return false.  If it
2330  /// constant folds return true and set the boolean result in Result.
2331  bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
2332
2333  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2334  /// to a constant, or if it does but contains a label, return false.  If it
2335  /// constant folds return true and set the folded value.
2336  bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &Result);
2337
2338  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
2339  /// if statement) to the specified blocks.  Based on the condition, this might
2340  /// try to simplify the codegen of the conditional based on the branch.
2341  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
2342                            llvm::BasicBlock *FalseBlock);
2343
2344  /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
2345  /// generate a branch around the created basic block as necessary.
2346  llvm::BasicBlock *getTrapBB();
2347
2348  /// EmitCallArg - Emit a single call argument.
2349  void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
2350
2351  /// EmitDelegateCallArg - We are performing a delegate call; that
2352  /// is, the current function is delegating to another one.  Produce
2353  /// a r-value suitable for passing the given parameter.
2354  void EmitDelegateCallArg(CallArgList &args, const VarDecl *param);
2355
2356private:
2357  void EmitReturnOfRValue(RValue RV, QualType Ty);
2358
2359  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
2360  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
2361  ///
2362  /// \param AI - The first function argument of the expansion.
2363  /// \return The argument following the last expanded function
2364  /// argument.
2365  llvm::Function::arg_iterator
2366  ExpandTypeFromArgs(QualType Ty, LValue Dst,
2367                     llvm::Function::arg_iterator AI);
2368
2369  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
2370  /// Ty, into individual arguments on the provided vector \arg Args. See
2371  /// ABIArgInfo::Expand.
2372  void ExpandTypeToArgs(QualType Ty, RValue Src,
2373                        llvm::SmallVector<llvm::Value*, 16> &Args,
2374                        llvm::FunctionType *IRFuncTy);
2375
2376  llvm::Value* EmitAsmInput(const AsmStmt &S,
2377                            const TargetInfo::ConstraintInfo &Info,
2378                            const Expr *InputExpr, std::string &ConstraintStr);
2379
2380  llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
2381                                  const TargetInfo::ConstraintInfo &Info,
2382                                  LValue InputValue, QualType InputType,
2383                                  std::string &ConstraintStr);
2384
2385  /// EmitCallArgs - Emit call arguments for a function.
2386  /// The CallArgTypeInfo parameter is used for iterating over the known
2387  /// argument types of the function being called.
2388  template<typename T>
2389  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
2390                    CallExpr::const_arg_iterator ArgBeg,
2391                    CallExpr::const_arg_iterator ArgEnd) {
2392      CallExpr::const_arg_iterator Arg = ArgBeg;
2393
2394    // First, use the argument types that the type info knows about
2395    if (CallArgTypeInfo) {
2396      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
2397           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
2398        assert(Arg != ArgEnd && "Running over edge of argument list!");
2399        QualType ArgType = *I;
2400#ifndef NDEBUG
2401        QualType ActualArgType = Arg->getType();
2402        if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
2403          QualType ActualBaseType =
2404            ActualArgType->getAs<PointerType>()->getPointeeType();
2405          QualType ArgBaseType =
2406            ArgType->getAs<PointerType>()->getPointeeType();
2407          if (ArgBaseType->isVariableArrayType()) {
2408            if (const VariableArrayType *VAT =
2409                getContext().getAsVariableArrayType(ActualBaseType)) {
2410              if (!VAT->getSizeExpr())
2411                ActualArgType = ArgType;
2412            }
2413          }
2414        }
2415        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
2416               getTypePtr() ==
2417               getContext().getCanonicalType(ActualArgType).getTypePtr() &&
2418               "type mismatch in call argument!");
2419#endif
2420        EmitCallArg(Args, *Arg, ArgType);
2421      }
2422
2423      // Either we've emitted all the call args, or we have a call to a
2424      // variadic function.
2425      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
2426             "Extra arguments in non-variadic function!");
2427
2428    }
2429
2430    // If we still have any arguments, emit them using the type of the argument.
2431    for (; Arg != ArgEnd; ++Arg)
2432      EmitCallArg(Args, *Arg, Arg->getType());
2433  }
2434
2435  const TargetCodeGenInfo &getTargetHooks() const {
2436    return CGM.getTargetCodeGenInfo();
2437  }
2438
2439  void EmitDeclMetadata();
2440
2441  CodeGenModule::ByrefHelpers *
2442  buildByrefHelpers(const llvm::StructType &byrefType,
2443                    const AutoVarEmission &emission);
2444};
2445
2446/// Helper class with most of the code for saving a value for a
2447/// conditional expression cleanup.
2448struct DominatingLLVMValue {
2449  typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
2450
2451  /// Answer whether the given value needs extra work to be saved.
2452  static bool needsSaving(llvm::Value *value) {
2453    // If it's not an instruction, we don't need to save.
2454    if (!isa<llvm::Instruction>(value)) return false;
2455
2456    // If it's an instruction in the entry block, we don't need to save.
2457    llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
2458    return (block != &block->getParent()->getEntryBlock());
2459  }
2460
2461  /// Try to save the given value.
2462  static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
2463    if (!needsSaving(value)) return saved_type(value, false);
2464
2465    // Otherwise we need an alloca.
2466    llvm::Value *alloca =
2467      CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
2468    CGF.Builder.CreateStore(value, alloca);
2469
2470    return saved_type(alloca, true);
2471  }
2472
2473  static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
2474    if (!value.getInt()) return value.getPointer();
2475    return CGF.Builder.CreateLoad(value.getPointer());
2476  }
2477};
2478
2479/// A partial specialization of DominatingValue for llvm::Values that
2480/// might be llvm::Instructions.
2481template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
2482  typedef T *type;
2483  static type restore(CodeGenFunction &CGF, saved_type value) {
2484    return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
2485  }
2486};
2487
2488/// A specialization of DominatingValue for RValue.
2489template <> struct DominatingValue<RValue> {
2490  typedef RValue type;
2491  class saved_type {
2492    enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
2493                AggregateAddress, ComplexAddress };
2494
2495    llvm::Value *Value;
2496    Kind K;
2497    saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
2498
2499  public:
2500    static bool needsSaving(RValue value);
2501    static saved_type save(CodeGenFunction &CGF, RValue value);
2502    RValue restore(CodeGenFunction &CGF);
2503
2504    // implementations in CGExprCXX.cpp
2505  };
2506
2507  static bool needsSaving(type value) {
2508    return saved_type::needsSaving(value);
2509  }
2510  static saved_type save(CodeGenFunction &CGF, type value) {
2511    return saved_type::save(CGF, value);
2512  }
2513  static type restore(CodeGenFunction &CGF, saved_type value) {
2514    return value.restore(CGF);
2515  }
2516};
2517
2518}  // end namespace CodeGen
2519}  // end namespace clang
2520
2521#endif
2522