CodeGenFunction.h revision 25c2c8fb9309050612009a6571e2660e75531348
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/Basic/TargetInfo.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/Support/ValueHandle.h"
25#include "CodeGenModule.h"
26#include "CGBlocks.h"
27#include "CGBuilder.h"
28#include "CGCall.h"
29#include "CGCXX.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 CXXTryStmt;
48  class Decl;
49  class EnumConstantDecl;
50  class FunctionDecl;
51  class FunctionProtoType;
52  class LabelStmt;
53  class ObjCContainerDecl;
54  class ObjCInterfaceDecl;
55  class ObjCIvarDecl;
56  class ObjCMethodDecl;
57  class ObjCImplementationDecl;
58  class ObjCPropertyImplDecl;
59  class TargetInfo;
60  class TargetCodeGenInfo;
61  class VarDecl;
62  class ObjCForCollectionStmt;
63  class ObjCAtTryStmt;
64  class ObjCAtThrowStmt;
65  class ObjCAtSynchronizedStmt;
66
67namespace CodeGen {
68  class CodeGenTypes;
69  class CGDebugInfo;
70  class CGFunctionInfo;
71  class CGRecordLayout;
72  class CGBlockInfo;
73
74/// A branch fixup.  These are required when emitting a goto to a
75/// label which hasn't been emitted yet.  The goto is optimistically
76/// emitted as a branch to the basic block for the label, and (if it
77/// occurs in a scope with non-trivial cleanups) a fixup is added to
78/// the innermost cleanup.  When a (normal) cleanup is popped, any
79/// unresolved fixups in that scope are threaded through the cleanup.
80struct BranchFixup {
81  /// The block containing the terminator which needs to be modified
82  /// into a switch if this fixup is resolved into the current scope.
83  /// If null, LatestBranch points directly to the destination.
84  llvm::BasicBlock *OptimisticBranchBlock;
85
86  /// The ultimate destination of the branch.
87  ///
88  /// This can be set to null to indicate that this fixup was
89  /// successfully resolved.
90  llvm::BasicBlock *Destination;
91
92  /// The destination index value.
93  unsigned DestinationIndex;
94
95  /// The initial branch of the fixup.
96  llvm::BranchInst *InitialBranch;
97};
98
99enum CleanupKind { NormalAndEHCleanup, EHCleanup, NormalCleanup };
100
101/// A stack of scopes which respond to exceptions, including cleanups
102/// and catch blocks.
103class EHScopeStack {
104public:
105  /// A saved depth on the scope stack.  This is necessary because
106  /// pushing scopes onto the stack invalidates iterators.
107  class stable_iterator {
108    friend class EHScopeStack;
109
110    /// Offset from StartOfData to EndOfBuffer.
111    ptrdiff_t Size;
112
113    stable_iterator(ptrdiff_t Size) : Size(Size) {}
114
115  public:
116    static stable_iterator invalid() { return stable_iterator(-1); }
117    stable_iterator() : Size(-1) {}
118
119    bool isValid() const { return Size >= 0; }
120
121    bool encloses(stable_iterator I) const { return Size <= I.Size; }
122    bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
123
124    friend bool operator==(stable_iterator A, stable_iterator B) {
125      return A.Size == B.Size;
126    }
127    friend bool operator!=(stable_iterator A, stable_iterator B) {
128      return A.Size != B.Size;
129    }
130  };
131
132  /// Information for lazily generating a cleanup.  Subclasses must be
133  /// POD-like: cleanups will not be destructed, and they will be
134  /// allocated on the cleanup stack and freely copied and moved
135  /// around.
136  ///
137  /// Cleanup implementations should generally be declared in an
138  /// anonymous namespace.
139  class Cleanup {
140  public:
141    // Anchor the construction vtable.  We use the destructor because
142    // gcc gives an obnoxious warning if there are virtual methods
143    // with an accessible non-virtual destructor.  Unfortunately,
144    // declaring this destructor makes it non-trivial, but there
145    // doesn't seem to be any other way around this warning.
146    //
147    // This destructor will never be called.
148    virtual ~Cleanup();
149
150    /// Emit the cleanup.  For normal cleanups, this is run in the
151    /// same EH context as when the cleanup was pushed, i.e. the
152    /// immediately-enclosing context of the cleanup scope.  For
153    /// EH cleanups, this is run in a terminate context.
154    ///
155    // \param IsForEHCleanup true if this is for an EH cleanup, false
156    ///  if for a normal cleanup.
157    virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0;
158  };
159
160private:
161  // The implementation for this class is in CGException.h and
162  // CGException.cpp; the definition is here because it's used as a
163  // member of CodeGenFunction.
164
165  /// The start of the scope-stack buffer, i.e. the allocated pointer
166  /// for the buffer.  All of these pointers are either simultaneously
167  /// null or simultaneously valid.
168  char *StartOfBuffer;
169
170  /// The end of the buffer.
171  char *EndOfBuffer;
172
173  /// The first valid entry in the buffer.
174  char *StartOfData;
175
176  /// The innermost normal cleanup on the stack.
177  stable_iterator InnermostNormalCleanup;
178
179  /// The innermost EH cleanup on the stack.
180  stable_iterator InnermostEHCleanup;
181
182  /// The number of catches on the stack.
183  unsigned CatchDepth;
184
185  /// The current EH destination index.  Reset to FirstCatchIndex
186  /// whenever the last EH cleanup is popped.
187  unsigned NextEHDestIndex;
188  enum { FirstEHDestIndex = 1 };
189
190  /// The current set of branch fixups.  A branch fixup is a jump to
191  /// an as-yet unemitted label, i.e. a label for which we don't yet
192  /// know the EH stack depth.  Whenever we pop a cleanup, we have
193  /// to thread all the current branch fixups through it.
194  ///
195  /// Fixups are recorded as the Use of the respective branch or
196  /// switch statement.  The use points to the final destination.
197  /// When popping out of a cleanup, these uses are threaded through
198  /// the cleanup and adjusted to point to the new cleanup.
199  ///
200  /// Note that branches are allowed to jump into protected scopes
201  /// in certain situations;  e.g. the following code is legal:
202  ///     struct A { ~A(); }; // trivial ctor, non-trivial dtor
203  ///     goto foo;
204  ///     A a;
205  ///    foo:
206  ///     bar();
207  llvm::SmallVector<BranchFixup, 8> BranchFixups;
208
209  char *allocate(size_t Size);
210
211  void *pushCleanup(CleanupKind K, size_t DataSize);
212
213public:
214  EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
215                   InnermostNormalCleanup(stable_end()),
216                   InnermostEHCleanup(stable_end()),
217                   CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {}
218  ~EHScopeStack() { delete[] StartOfBuffer; }
219
220  // Variadic templates would make this not terrible.
221
222  /// Push a lazily-created cleanup on the stack.
223  template <class T>
224  void pushCleanup(CleanupKind Kind) {
225    void *Buffer = pushCleanup(Kind, sizeof(T));
226    Cleanup *Obj = new(Buffer) T();
227    (void) Obj;
228  }
229
230  /// Push a lazily-created cleanup on the stack.
231  template <class T, class A0>
232  void pushCleanup(CleanupKind Kind, A0 a0) {
233    void *Buffer = pushCleanup(Kind, sizeof(T));
234    Cleanup *Obj = new(Buffer) T(a0);
235    (void) Obj;
236  }
237
238  /// Push a lazily-created cleanup on the stack.
239  template <class T, class A0, class A1>
240  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
241    void *Buffer = pushCleanup(Kind, sizeof(T));
242    Cleanup *Obj = new(Buffer) T(a0, a1);
243    (void) Obj;
244  }
245
246  /// Push a lazily-created cleanup on the stack.
247  template <class T, class A0, class A1, class A2>
248  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
249    void *Buffer = pushCleanup(Kind, sizeof(T));
250    Cleanup *Obj = new(Buffer) T(a0, a1, a2);
251    (void) Obj;
252  }
253
254  /// Push a lazily-created cleanup on the stack.
255  template <class T, class A0, class A1, class A2, class A3>
256  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
257    void *Buffer = pushCleanup(Kind, sizeof(T));
258    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
259    (void) Obj;
260  }
261
262  /// Push a lazily-created cleanup on the stack.
263  template <class T, class A0, class A1, class A2, class A3, class A4>
264  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
265    void *Buffer = pushCleanup(Kind, sizeof(T));
266    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
267    (void) Obj;
268  }
269
270  /// Pops a cleanup scope off the stack.  This should only be called
271  /// by CodeGenFunction::PopCleanupBlock.
272  void popCleanup();
273
274  /// Push a set of catch handlers on the stack.  The catch is
275  /// uninitialized and will need to have the given number of handlers
276  /// set on it.
277  class EHCatchScope *pushCatch(unsigned NumHandlers);
278
279  /// Pops a catch scope off the stack.
280  void popCatch();
281
282  /// Push an exceptions filter on the stack.
283  class EHFilterScope *pushFilter(unsigned NumFilters);
284
285  /// Pops an exceptions filter off the stack.
286  void popFilter();
287
288  /// Push a terminate handler on the stack.
289  void pushTerminate();
290
291  /// Pops a terminate handler off the stack.
292  void popTerminate();
293
294  /// Determines whether the exception-scopes stack is empty.
295  bool empty() const { return StartOfData == EndOfBuffer; }
296
297  bool requiresLandingPad() const {
298    return (CatchDepth || hasEHCleanups());
299  }
300
301  /// Determines whether there are any normal cleanups on the stack.
302  bool hasNormalCleanups() const {
303    return InnermostNormalCleanup != stable_end();
304  }
305
306  /// Returns the innermost normal cleanup on the stack, or
307  /// stable_end() if there are no normal cleanups.
308  stable_iterator getInnermostNormalCleanup() const {
309    return InnermostNormalCleanup;
310  }
311
312  /// Determines whether there are any EH cleanups on the stack.
313  bool hasEHCleanups() const {
314    return InnermostEHCleanup != stable_end();
315  }
316
317  /// Returns the innermost EH cleanup on the stack, or stable_end()
318  /// if there are no EH cleanups.
319  stable_iterator getInnermostEHCleanup() const {
320    return InnermostEHCleanup;
321  }
322
323  /// An unstable reference to a scope-stack depth.  Invalidated by
324  /// pushes but not pops.
325  class iterator;
326
327  /// Returns an iterator pointing to the innermost EH scope.
328  iterator begin() const;
329
330  /// Returns an iterator pointing to the outermost EH scope.
331  iterator end() const;
332
333  /// Create a stable reference to the top of the EH stack.  The
334  /// returned reference is valid until that scope is popped off the
335  /// stack.
336  stable_iterator stable_begin() const {
337    return stable_iterator(EndOfBuffer - StartOfData);
338  }
339
340  /// Create a stable reference to the bottom of the EH stack.
341  static stable_iterator stable_end() {
342    return stable_iterator(0);
343  }
344
345  /// Translates an iterator into a stable_iterator.
346  stable_iterator stabilize(iterator it) const;
347
348  /// Finds the nearest cleanup enclosing the given iterator.
349  /// Returns stable_iterator::invalid() if there are no such cleanups.
350  stable_iterator getEnclosingEHCleanup(iterator it) const;
351
352  /// Turn a stable reference to a scope depth into a unstable pointer
353  /// to the EH stack.
354  iterator find(stable_iterator save) const;
355
356  /// Removes the cleanup pointed to by the given stable_iterator.
357  void removeCleanup(stable_iterator save);
358
359  /// Add a branch fixup to the current cleanup scope.
360  BranchFixup &addBranchFixup() {
361    assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
362    BranchFixups.push_back(BranchFixup());
363    return BranchFixups.back();
364  }
365
366  unsigned getNumBranchFixups() const { return BranchFixups.size(); }
367  BranchFixup &getBranchFixup(unsigned I) {
368    assert(I < getNumBranchFixups());
369    return BranchFixups[I];
370  }
371
372  /// Pops lazily-removed fixups from the end of the list.  This
373  /// should only be called by procedures which have just popped a
374  /// cleanup or resolved one or more fixups.
375  void popNullFixups();
376
377  /// Clears the branch-fixups list.  This should only be called by
378  /// CodeGenFunction::ResolveAllBranchFixups.
379  void clearFixups() { BranchFixups.clear(); }
380
381  /// Gets the next EH destination index.
382  unsigned getNextEHDestIndex() { return NextEHDestIndex++; }
383};
384
385/// CodeGenFunction - This class organizes the per-function state that is used
386/// while generating LLVM code.
387class CodeGenFunction : public BlockFunction {
388  CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
389  void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
390public:
391  /// A jump destination is an abstract label, branching to which may
392  /// require a jump out through normal cleanups.
393  struct JumpDest {
394    JumpDest() : Block(0), ScopeDepth(), Index(0) {}
395    JumpDest(llvm::BasicBlock *Block,
396             EHScopeStack::stable_iterator Depth,
397             unsigned Index)
398      : Block(Block), ScopeDepth(Depth), Index(Index) {}
399
400    bool isValid() const { return Block != 0; }
401    llvm::BasicBlock *getBlock() const { return Block; }
402    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
403    unsigned getDestIndex() const { return Index; }
404
405  private:
406    llvm::BasicBlock *Block;
407    EHScopeStack::stable_iterator ScopeDepth;
408    unsigned Index;
409  };
410
411  /// An unwind destination is an abstract label, branching to which
412  /// may require a jump out through EH cleanups.
413  struct UnwindDest {
414    UnwindDest() : Block(0), ScopeDepth(), Index(0) {}
415    UnwindDest(llvm::BasicBlock *Block,
416               EHScopeStack::stable_iterator Depth,
417               unsigned Index)
418      : Block(Block), ScopeDepth(Depth), Index(Index) {}
419
420    bool isValid() const { return Block != 0; }
421    llvm::BasicBlock *getBlock() const { return Block; }
422    EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
423    unsigned getDestIndex() const { return Index; }
424
425  private:
426    llvm::BasicBlock *Block;
427    EHScopeStack::stable_iterator ScopeDepth;
428    unsigned Index;
429  };
430
431  CodeGenModule &CGM;  // Per-module state.
432  const TargetInfo &Target;
433
434  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
435  CGBuilderTy Builder;
436
437  /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
438  /// This excludes BlockDecls.
439  const Decl *CurFuncDecl;
440  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
441  const Decl *CurCodeDecl;
442  const CGFunctionInfo *CurFnInfo;
443  QualType FnRetTy;
444  llvm::Function *CurFn;
445
446  /// CurGD - The GlobalDecl for the current function being compiled.
447  GlobalDecl CurGD;
448
449  /// ReturnBlock - Unified return block.
450  JumpDest ReturnBlock;
451
452  /// ReturnValue - The temporary alloca to hold the return value. This is null
453  /// iff the function has no return value.
454  llvm::Value *ReturnValue;
455
456  /// RethrowBlock - Unified rethrow block.
457  UnwindDest RethrowBlock;
458
459  /// AllocaInsertPoint - This is an instruction in the entry block before which
460  /// we prefer to insert allocas.
461  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
462
463  // intptr_t, i32, i64
464  const llvm::IntegerType *IntPtrTy, *Int32Ty, *Int64Ty;
465  uint32_t LLVMPointerWidth;
466
467  bool Exceptions;
468  bool CatchUndefined;
469
470  /// \brief A mapping from NRVO variables to the flags used to indicate
471  /// when the NRVO has been applied to this variable.
472  llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
473
474  EHScopeStack EHStack;
475
476  /// i32s containing the indexes of the cleanup destinations.
477  llvm::AllocaInst *NormalCleanupDest;
478  llvm::AllocaInst *EHCleanupDest;
479
480  unsigned NextCleanupDestIndex;
481
482  /// The exception slot.  All landing pads write the current
483  /// exception pointer into this alloca.
484  llvm::Value *ExceptionSlot;
485
486  /// Emits a landing pad for the current EH stack.
487  llvm::BasicBlock *EmitLandingPad();
488
489  llvm::BasicBlock *getInvokeDestImpl();
490
491public:
492  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
493  /// rethrows.
494  llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
495
496  // A struct holding information about a finally block's IR
497  // generation.  For now, doesn't actually hold anything.
498  struct FinallyInfo {
499  };
500
501  FinallyInfo EnterFinallyBlock(const Stmt *Stmt,
502                                llvm::Constant *BeginCatchFn,
503                                llvm::Constant *EndCatchFn,
504                                llvm::Constant *RethrowFn);
505  void ExitFinallyBlock(FinallyInfo &FinallyInfo);
506
507  /// PushDestructorCleanup - Push a cleanup to call the
508  /// complete-object destructor of an object of the given type at the
509  /// given address.  Does nothing if T is not a C++ class type with a
510  /// non-trivial destructor.
511  void PushDestructorCleanup(QualType T, llvm::Value *Addr);
512
513  /// PushDestructorCleanup - Push a cleanup to call the
514  /// complete-object variant of the given destructor on the object at
515  /// the given address.
516  void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
517                             llvm::Value *Addr);
518
519  /// PopCleanupBlock - Will pop the cleanup entry on the stack and
520  /// process all branch fixups.
521  void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
522
523  /// \brief Enters a new scope for capturing cleanups, all of which
524  /// will be executed once the scope is exited.
525  class RunCleanupsScope {
526    CodeGenFunction& CGF;
527    EHScopeStack::stable_iterator CleanupStackDepth;
528    bool OldDidCallStackSave;
529    bool PerformCleanup;
530
531    RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
532    RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
533
534  public:
535    /// \brief Enter a new cleanup scope.
536    explicit RunCleanupsScope(CodeGenFunction &CGF)
537      : CGF(CGF), PerformCleanup(true)
538    {
539      CleanupStackDepth = CGF.EHStack.stable_begin();
540      OldDidCallStackSave = CGF.DidCallStackSave;
541    }
542
543    /// \brief Exit this cleanup scope, emitting any accumulated
544    /// cleanups.
545    ~RunCleanupsScope() {
546      if (PerformCleanup) {
547        CGF.DidCallStackSave = OldDidCallStackSave;
548        CGF.PopCleanupBlocks(CleanupStackDepth);
549      }
550    }
551
552    /// \brief Determine whether this scope requires any cleanups.
553    bool requiresCleanups() const {
554      return CGF.EHStack.stable_begin() != CleanupStackDepth;
555    }
556
557    /// \brief Force the emission of cleanups now, instead of waiting
558    /// until this object is destroyed.
559    void ForceCleanup() {
560      assert(PerformCleanup && "Already forced cleanup");
561      CGF.DidCallStackSave = OldDidCallStackSave;
562      CGF.PopCleanupBlocks(CleanupStackDepth);
563      PerformCleanup = false;
564    }
565  };
566
567
568  /// PopCleanupBlocks - Takes the old cleanup stack size and emits
569  /// the cleanup blocks that have been added.
570  void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
571
572  void ResolveAllBranchFixups(llvm::SwitchInst *Switch);
573  void ResolveBranchFixups(llvm::BasicBlock *Target);
574
575  /// The given basic block lies in the current EH scope, but may be a
576  /// target of a potentially scope-crossing jump; get a stable handle
577  /// to which we can perform this jump later.
578  JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
579    return JumpDest(Target,
580                    EHStack.getInnermostNormalCleanup(),
581                    NextCleanupDestIndex++);
582  }
583
584  /// The given basic block lies in the current EH scope, but may be a
585  /// target of a potentially scope-crossing jump; get a stable handle
586  /// to which we can perform this jump later.
587  JumpDest getJumpDestInCurrentScope(const char *Name = 0) {
588    return getJumpDestInCurrentScope(createBasicBlock(Name));
589  }
590
591  /// EmitBranchThroughCleanup - Emit a branch from the current insert
592  /// block through the normal cleanup handling code (if any) and then
593  /// on to \arg Dest.
594  void EmitBranchThroughCleanup(JumpDest Dest);
595
596  /// EmitBranchThroughEHCleanup - Emit a branch from the current
597  /// insert block through the EH cleanup handling code (if any) and
598  /// then on to \arg Dest.
599  void EmitBranchThroughEHCleanup(UnwindDest Dest);
600
601  /// getRethrowDest - Returns the unified outermost-scope rethrow
602  /// destination.
603  UnwindDest getRethrowDest();
604
605  /// BeginConditionalBranch - Should be called before a conditional part of an
606  /// expression is emitted. For example, before the RHS of the expression below
607  /// is emitted:
608  ///
609  /// b && f(T());
610  ///
611  /// This is used to make sure that any temporaries created in the conditional
612  /// branch are only destroyed if the branch is taken.
613  void BeginConditionalBranch() {
614    ++ConditionalBranchLevel;
615  }
616
617  /// EndConditionalBranch - Should be called after a conditional part of an
618  /// expression has been emitted.
619  void EndConditionalBranch() {
620    assert(ConditionalBranchLevel != 0 &&
621           "Conditional branch mismatch!");
622
623    --ConditionalBranchLevel;
624  }
625
626private:
627  CGDebugInfo *DebugInfo;
628
629  /// IndirectBranch - The first time an indirect goto is seen we create a block
630  /// with an indirect branch.  Every time we see the address of a label taken,
631  /// we add the label to the indirect goto.  Every subsequent indirect goto is
632  /// codegen'd as a jump to the IndirectBranch's basic block.
633  llvm::IndirectBrInst *IndirectBranch;
634
635  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
636  /// decls.
637  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
638
639  /// LabelMap - This keeps track of the LLVM basic block for each C label.
640  llvm::DenseMap<const LabelStmt*, JumpDest> LabelMap;
641
642  // BreakContinueStack - This keeps track of where break and continue
643  // statements should jump to.
644  struct BreakContinue {
645    BreakContinue(JumpDest Break, JumpDest Continue)
646      : BreakBlock(Break), ContinueBlock(Continue) {}
647
648    JumpDest BreakBlock;
649    JumpDest ContinueBlock;
650  };
651  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
652
653  /// SwitchInsn - This is nearest current switch instruction. It is null if if
654  /// current context is not in a switch.
655  llvm::SwitchInst *SwitchInsn;
656
657  /// CaseRangeBlock - This block holds if condition check for last case
658  /// statement range in current switch instruction.
659  llvm::BasicBlock *CaseRangeBlock;
660
661  // VLASizeMap - This keeps track of the associated size for each VLA type.
662  // We track this by the size expression rather than the type itself because
663  // in certain situations, like a const qualifier applied to an VLA typedef,
664  // multiple VLA types can share the same size expression.
665  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
666  // enter/leave scopes.
667  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
668
669  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
670  /// calling llvm.stacksave for multiple VLAs in the same scope.
671  bool DidCallStackSave;
672
673  /// A block containing a single 'unreachable' instruction.  Created
674  /// lazily by getUnreachableBlock().
675  llvm::BasicBlock *UnreachableBlock;
676
677  /// CXXThisDecl - When generating code for a C++ member function,
678  /// this will hold the implicit 'this' declaration.
679  ImplicitParamDecl *CXXThisDecl;
680  llvm::Value *CXXThisValue;
681
682  /// CXXVTTDecl - When generating code for a base object constructor or
683  /// base object destructor with virtual bases, this will hold the implicit
684  /// VTT parameter.
685  ImplicitParamDecl *CXXVTTDecl;
686  llvm::Value *CXXVTTValue;
687
688  /// ConditionalBranchLevel - Contains the nesting level of the current
689  /// conditional branch. This is used so that we know if a temporary should be
690  /// destroyed conditionally.
691  unsigned ConditionalBranchLevel;
692
693
694  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
695  /// type as well as the field number that contains the actual data.
696  llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
697                                              unsigned> > ByRefValueInfo;
698
699  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
700  /// number that holds the value.
701  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
702
703  llvm::BasicBlock *TerminateLandingPad;
704  llvm::BasicBlock *TerminateHandler;
705  llvm::BasicBlock *TrapBB;
706
707public:
708  CodeGenFunction(CodeGenModule &cgm);
709
710  ASTContext &getContext() const;
711  CGDebugInfo *getDebugInfo() { return DebugInfo; }
712
713  /// Returns a pointer to the function's exception object slot, which
714  /// is assigned in every landing pad.
715  llvm::Value *getExceptionSlot();
716
717  llvm::Value *getNormalCleanupDestSlot();
718  llvm::Value *getEHCleanupDestSlot();
719
720  llvm::BasicBlock *getUnreachableBlock() {
721    if (!UnreachableBlock) {
722      UnreachableBlock = createBasicBlock("unreachable");
723      new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
724    }
725    return UnreachableBlock;
726  }
727
728  llvm::BasicBlock *getInvokeDest() {
729    if (!EHStack.requiresLandingPad()) return 0;
730    return getInvokeDestImpl();
731  }
732
733  llvm::LLVMContext &getLLVMContext() { return VMContext; }
734
735  //===--------------------------------------------------------------------===//
736  //                                  Objective-C
737  //===--------------------------------------------------------------------===//
738
739  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
740
741  void StartObjCMethod(const ObjCMethodDecl *MD,
742                       const ObjCContainerDecl *CD);
743
744  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
745  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
746                          const ObjCPropertyImplDecl *PID);
747  void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
748                                  ObjCMethodDecl *MD, bool ctor);
749
750  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
751  /// for the given property.
752  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
753                          const ObjCPropertyImplDecl *PID);
754  bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
755  bool IvarTypeWithAggrGCObjects(QualType Ty);
756
757  //===--------------------------------------------------------------------===//
758  //                                  Block Bits
759  //===--------------------------------------------------------------------===//
760
761  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
762  llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
763                                           const CGBlockInfo &Info,
764                                           const llvm::StructType *,
765                                           llvm::Constant *BlockVarLayout,
766                                           std::vector<HelperInfo> *);
767
768  llvm::Function *GenerateBlockFunction(GlobalDecl GD,
769                                        const BlockExpr *BExpr,
770                                        CGBlockInfo &Info,
771                                        const Decl *OuterFuncDecl,
772                                        llvm::Constant *& BlockVarLayout,
773                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm);
774
775  llvm::Value *LoadBlockStruct();
776
777  void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
778  void AllocateBlockDecl(const BlockDeclRefExpr *E);
779  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
780    return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
781  }
782  llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
783  const llvm::Type *BuildByRefType(const ValueDecl *D);
784
785  void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
786  void StartFunction(GlobalDecl GD, QualType RetTy,
787                     llvm::Function *Fn,
788                     const FunctionArgList &Args,
789                     SourceLocation StartLoc);
790
791  void EmitConstructorBody(FunctionArgList &Args);
792  void EmitDestructorBody(FunctionArgList &Args);
793  void EmitFunctionBody(FunctionArgList &Args);
794
795  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
796  /// emission when possible.
797  void EmitReturnBlock();
798
799  /// FinishFunction - Complete IR generation of the current function. It is
800  /// legal to call this function even if there is no current insertion point.
801  void FinishFunction(SourceLocation EndLoc=SourceLocation());
802
803  /// GenerateThunk - Generate a thunk for the given method.
804  void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
805
806  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
807                        FunctionArgList &Args);
808
809  /// InitializeVTablePointer - Initialize the vtable pointer of the given
810  /// subobject.
811  ///
812  void InitializeVTablePointer(BaseSubobject Base,
813                               const CXXRecordDecl *NearestVBase,
814                               uint64_t OffsetFromNearestVBase,
815                               llvm::Constant *VTable,
816                               const CXXRecordDecl *VTableClass);
817
818  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
819  void InitializeVTablePointers(BaseSubobject Base,
820                                const CXXRecordDecl *NearestVBase,
821                                uint64_t OffsetFromNearestVBase,
822                                bool BaseIsNonVirtualPrimaryBase,
823                                llvm::Constant *VTable,
824                                const CXXRecordDecl *VTableClass,
825                                VisitedVirtualBasesSetTy& VBases);
826
827  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
828
829
830  /// EnterDtorCleanups - Enter the cleanups necessary to complete the
831  /// given phase of destruction for a destructor.  The end result
832  /// should call destructors on members and base classes in reverse
833  /// order of their construction.
834  void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
835
836  /// ShouldInstrumentFunction - Return true if the current function should be
837  /// instrumented with __cyg_profile_func_* calls
838  bool ShouldInstrumentFunction();
839
840  /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
841  /// instrumentation function with the current function and the call site, if
842  /// function instrumentation is enabled.
843  void EmitFunctionInstrumentation(const char *Fn);
844
845  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
846  /// arguments for the given function. This is also responsible for naming the
847  /// LLVM function arguments.
848  void EmitFunctionProlog(const CGFunctionInfo &FI,
849                          llvm::Function *Fn,
850                          const FunctionArgList &Args);
851
852  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
853  /// given temporary.
854  void EmitFunctionEpilog(const CGFunctionInfo &FI);
855
856  /// EmitStartEHSpec - Emit the start of the exception spec.
857  void EmitStartEHSpec(const Decl *D);
858
859  /// EmitEndEHSpec - Emit the end of the exception spec.
860  void EmitEndEHSpec(const Decl *D);
861
862  /// getTerminateLandingPad - Return a landing pad that just calls terminate.
863  llvm::BasicBlock *getTerminateLandingPad();
864
865  /// getTerminateHandler - Return a handler (not a landing pad, just
866  /// a catch handler) that just calls terminate.  This is used when
867  /// a terminate scope encloses a try.
868  llvm::BasicBlock *getTerminateHandler();
869
870  const llvm::Type *ConvertTypeForMem(QualType T);
871  const llvm::Type *ConvertType(QualType T);
872  const llvm::Type *ConvertType(const TypeDecl *T) {
873    return ConvertType(getContext().getTypeDeclType(T));
874  }
875
876  /// LoadObjCSelf - Load the value of self. This function is only valid while
877  /// generating code for an Objective-C method.
878  llvm::Value *LoadObjCSelf();
879
880  /// TypeOfSelfObject - Return type of object that this self represents.
881  QualType TypeOfSelfObject();
882
883  /// hasAggregateLLVMType - Return true if the specified AST type will map into
884  /// an aggregate LLVM type or is void.
885  static bool hasAggregateLLVMType(QualType T);
886
887  /// createBasicBlock - Create an LLVM basic block.
888  llvm::BasicBlock *createBasicBlock(const char *Name="",
889                                     llvm::Function *Parent=0,
890                                     llvm::BasicBlock *InsertBefore=0) {
891#ifdef NDEBUG
892    return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
893#else
894    return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
895#endif
896  }
897
898  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
899  /// label maps to.
900  JumpDest getJumpDestForLabel(const LabelStmt *S);
901
902  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
903  /// another basic block, simplify it. This assumes that no other code could
904  /// potentially reference the basic block.
905  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
906
907  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
908  /// adding a fall-through branch from the current insert block if
909  /// necessary. It is legal to call this function even if there is no current
910  /// insertion point.
911  ///
912  /// IsFinished - If true, indicates that the caller has finished emitting
913  /// branches to the given block and does not expect to emit code into it. This
914  /// means the block can be ignored if it is unreachable.
915  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
916
917  /// EmitBranch - Emit a branch to the specified basic block from the current
918  /// insert block, taking care to avoid creation of branches from dummy
919  /// blocks. It is legal to call this function even if there is no current
920  /// insertion point.
921  ///
922  /// This function clears the current insertion point. The caller should follow
923  /// calls to this function with calls to Emit*Block prior to generation new
924  /// code.
925  void EmitBranch(llvm::BasicBlock *Block);
926
927  /// HaveInsertPoint - True if an insertion point is defined. If not, this
928  /// indicates that the current code being emitted is unreachable.
929  bool HaveInsertPoint() const {
930    return Builder.GetInsertBlock() != 0;
931  }
932
933  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
934  /// emitted IR has a place to go. Note that by definition, if this function
935  /// creates a block then that block is unreachable; callers may do better to
936  /// detect when no insertion point is defined and simply skip IR generation.
937  void EnsureInsertPoint() {
938    if (!HaveInsertPoint())
939      EmitBlock(createBasicBlock());
940  }
941
942  /// ErrorUnsupported - Print out an error that codegen doesn't support the
943  /// specified stmt yet.
944  void ErrorUnsupported(const Stmt *S, const char *Type,
945                        bool OmitOnError=false);
946
947  //===--------------------------------------------------------------------===//
948  //                                  Helpers
949  //===--------------------------------------------------------------------===//
950
951  Qualifiers MakeQualifiers(QualType T) {
952    Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
953    Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
954    return Quals;
955  }
956
957  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
958  /// block. The caller is responsible for setting an appropriate alignment on
959  /// the alloca.
960  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
961                                     const llvm::Twine &Name = "tmp");
962
963  /// InitTempAlloca - Provide an initial value for the given alloca.
964  void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
965
966  /// CreateIRTemp - Create a temporary IR object of the given type, with
967  /// appropriate alignment. This routine should only be used when an temporary
968  /// value needs to be stored into an alloca (for example, to avoid explicit
969  /// PHI construction), but the type is the IR type, not the type appropriate
970  /// for storing in memory.
971  llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
972
973  /// CreateMemTemp - Create a temporary memory object of the given type, with
974  /// appropriate alignment.
975  llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
976
977  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
978  /// expression and compare the result against zero, returning an Int1Ty value.
979  llvm::Value *EvaluateExprAsBool(const Expr *E);
980
981  /// EmitAnyExpr - Emit code to compute the specified expression which can have
982  /// any type.  The result is returned as an RValue struct.  If this is an
983  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
984  /// the result should be returned.
985  ///
986  /// \param IgnoreResult - True if the resulting value isn't used.
987  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
988                     bool IsAggLocVolatile = false, bool IgnoreResult = false,
989                     bool IsInitializer = false);
990
991  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
992  // or the value of the expression, depending on how va_list is defined.
993  llvm::Value *EmitVAListRef(const Expr *E);
994
995  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
996  /// always be accessible even if no aggregate location is provided.
997  RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
998                           bool IsInitializer = false);
999
1000  /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
1001  /// arbitrary expression into the given memory location.
1002  void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1003                        bool IsLocationVolatile = false,
1004                        bool IsInitializer = false);
1005
1006  /// EmitAggregateCopy - Emit an aggrate copy.
1007  ///
1008  /// \param isVolatile - True iff either the source or the destination is
1009  /// volatile.
1010  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1011                         QualType EltTy, bool isVolatile=false);
1012
1013  /// StartBlock - Start new block named N. If insert block is a dummy block
1014  /// then reuse it.
1015  void StartBlock(const char *N);
1016
1017  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
1018  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
1019
1020  /// GetAddrOfLocalVar - Return the address of a local variable.
1021  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
1022
1023  /// getAccessedFieldNo - Given an encoded value and a result number, return
1024  /// the input field number being accessed.
1025  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1026
1027  llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
1028  llvm::BasicBlock *GetIndirectGotoBlock();
1029
1030  /// EmitNullInitialization - Generate code to set a value of the given type to
1031  /// null, If the type contains data member pointers, they will be initialized
1032  /// to -1 in accordance with the Itanium C++ ABI.
1033  void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1034
1035  // EmitVAArg - Generate code to get an argument from the passed in pointer
1036  // and update it accordingly. The return value is a pointer to the argument.
1037  // FIXME: We should be able to get rid of this method and use the va_arg
1038  // instruction in LLVM instead once it works well enough.
1039  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1040
1041  /// EmitVLASize - Generate code for any VLA size expressions that might occur
1042  /// in a variably modified type. If Ty is a VLA, will return the value that
1043  /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
1044  ///
1045  /// This function can be called with a null (unreachable) insert point.
1046  llvm::Value *EmitVLASize(QualType Ty);
1047
1048  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
1049  // of a variable length array type.
1050  llvm::Value *GetVLASize(const VariableArrayType *);
1051
1052  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1053  /// generating code for an C++ member function.
1054  llvm::Value *LoadCXXThis() {
1055    assert(CXXThisValue && "no 'this' value for this function");
1056    return CXXThisValue;
1057  }
1058
1059  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1060  /// virtual bases.
1061  llvm::Value *LoadCXXVTT() {
1062    assert(CXXVTTValue && "no VTT value for this function");
1063    return CXXVTTValue;
1064  }
1065
1066  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1067  /// complete class to the given direct base.
1068  llvm::Value *
1069  GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1070                                        const CXXRecordDecl *Derived,
1071                                        const CXXRecordDecl *Base,
1072                                        bool BaseIsVirtual);
1073
1074  /// GetAddressOfBaseClass - This function will add the necessary delta to the
1075  /// load of 'this' and returns address of the base class.
1076  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1077                                     const CXXRecordDecl *Derived,
1078                                     CastExpr::path_const_iterator PathBegin,
1079                                     CastExpr::path_const_iterator PathEnd,
1080                                     bool NullCheckValue);
1081
1082  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1083                                        const CXXRecordDecl *Derived,
1084                                        CastExpr::path_const_iterator PathBegin,
1085                                        CastExpr::path_const_iterator PathEnd,
1086                                        bool NullCheckValue);
1087
1088  llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
1089                                         const CXXRecordDecl *ClassDecl,
1090                                         const CXXRecordDecl *BaseClassDecl);
1091
1092  void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1093                                      CXXCtorType CtorType,
1094                                      const FunctionArgList &Args);
1095  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1096                              bool ForVirtualBase, llvm::Value *This,
1097                              CallExpr::const_arg_iterator ArgBeg,
1098                              CallExpr::const_arg_iterator ArgEnd);
1099
1100  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1101                                  const ConstantArrayType *ArrayTy,
1102                                  llvm::Value *ArrayPtr,
1103                                  CallExpr::const_arg_iterator ArgBeg,
1104                                  CallExpr::const_arg_iterator ArgEnd,
1105                                  bool ZeroInitialization = false);
1106
1107  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1108                                  llvm::Value *NumElements,
1109                                  llvm::Value *ArrayPtr,
1110                                  CallExpr::const_arg_iterator ArgBeg,
1111                                  CallExpr::const_arg_iterator ArgEnd,
1112                                  bool ZeroInitialization = false);
1113
1114  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1115                                 const ArrayType *Array,
1116                                 llvm::Value *This);
1117
1118  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1119                                 llvm::Value *NumElements,
1120                                 llvm::Value *This);
1121
1122  llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1123                                                  const ArrayType *Array,
1124                                                  llvm::Value *This);
1125
1126  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1127                             bool ForVirtualBase, llvm::Value *This);
1128
1129  void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
1130                               llvm::Value *NumElements);
1131
1132  void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
1133
1134  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1135  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1136
1137  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1138                      QualType DeleteTy);
1139
1140  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1141  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1142
1143  void EmitCheck(llvm::Value *, unsigned Size);
1144
1145  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1146                                       bool isInc, bool isPre);
1147  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1148                                         bool isInc, bool isPre);
1149  //===--------------------------------------------------------------------===//
1150  //                            Declaration Emission
1151  //===--------------------------------------------------------------------===//
1152
1153  /// EmitDecl - Emit a declaration.
1154  ///
1155  /// This function can be called with a null (unreachable) insert point.
1156  void EmitDecl(const Decl &D);
1157
1158  /// EmitBlockVarDecl - Emit a block variable declaration.
1159  ///
1160  /// This function can be called with a null (unreachable) insert point.
1161  void EmitBlockVarDecl(const VarDecl &D);
1162
1163  typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1164                             llvm::Value *Address);
1165
1166  /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
1167  ///
1168  /// This function can be called with a null (unreachable) insert point.
1169  void EmitLocalBlockVarDecl(const VarDecl &D, SpecialInitFn *SpecialInit = 0);
1170
1171  void EmitStaticBlockVarDecl(const VarDecl &D,
1172                              llvm::GlobalValue::LinkageTypes Linkage);
1173
1174  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1175  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
1176
1177  //===--------------------------------------------------------------------===//
1178  //                             Statement Emission
1179  //===--------------------------------------------------------------------===//
1180
1181  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1182  void EmitStopPoint(const Stmt *S);
1183
1184  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1185  /// this function even if there is no current insertion point.
1186  ///
1187  /// This function may clear the current insertion point; callers should use
1188  /// EnsureInsertPoint if they wish to subsequently generate code without first
1189  /// calling EmitBlock, EmitBranch, or EmitStmt.
1190  void EmitStmt(const Stmt *S);
1191
1192  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1193  /// necessarily require an insertion point or debug information; typically
1194  /// because the statement amounts to a jump or a container of other
1195  /// statements.
1196  ///
1197  /// \return True if the statement was handled.
1198  bool EmitSimpleStmt(const Stmt *S);
1199
1200  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1201                          llvm::Value *AggLoc = 0, bool isAggVol = false);
1202
1203  /// EmitLabel - Emit the block for the given label. It is legal to call this
1204  /// function even if there is no current insertion point.
1205  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
1206
1207  void EmitLabelStmt(const LabelStmt &S);
1208  void EmitGotoStmt(const GotoStmt &S);
1209  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1210  void EmitIfStmt(const IfStmt &S);
1211  void EmitWhileStmt(const WhileStmt &S);
1212  void EmitDoStmt(const DoStmt &S);
1213  void EmitForStmt(const ForStmt &S);
1214  void EmitReturnStmt(const ReturnStmt &S);
1215  void EmitDeclStmt(const DeclStmt &S);
1216  void EmitBreakStmt(const BreakStmt &S);
1217  void EmitContinueStmt(const ContinueStmt &S);
1218  void EmitSwitchStmt(const SwitchStmt &S);
1219  void EmitDefaultStmt(const DefaultStmt &S);
1220  void EmitCaseStmt(const CaseStmt &S);
1221  void EmitCaseStmtRange(const CaseStmt &S);
1222  void EmitAsmStmt(const AsmStmt &S);
1223
1224  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1225  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1226  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1227  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1228
1229  llvm::Constant *getUnwindResumeOrRethrowFn();
1230  void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1231  void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1232
1233  void EmitCXXTryStmt(const CXXTryStmt &S);
1234
1235  //===--------------------------------------------------------------------===//
1236  //                         LValue Expression Emission
1237  //===--------------------------------------------------------------------===//
1238
1239  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1240  RValue GetUndefRValue(QualType Ty);
1241
1242  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1243  /// and issue an ErrorUnsupported style diagnostic (using the
1244  /// provided Name).
1245  RValue EmitUnsupportedRValue(const Expr *E,
1246                               const char *Name);
1247
1248  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1249  /// an ErrorUnsupported style diagnostic (using the provided Name).
1250  LValue EmitUnsupportedLValue(const Expr *E,
1251                               const char *Name);
1252
1253  /// EmitLValue - Emit code to compute a designator that specifies the location
1254  /// of the expression.
1255  ///
1256  /// This can return one of two things: a simple address or a bitfield
1257  /// reference.  In either case, the LLVM Value* in the LValue structure is
1258  /// guaranteed to be an LLVM pointer type.
1259  ///
1260  /// If this returns a bitfield reference, nothing about the pointee type of
1261  /// the LLVM value is known: For example, it may not be a pointer to an
1262  /// integer.
1263  ///
1264  /// If this returns a normal address, and if the lvalue's C type is fixed
1265  /// size, this method guarantees that the returned pointer type will point to
1266  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
1267  /// variable length type, this is not possible.
1268  ///
1269  LValue EmitLValue(const Expr *E);
1270
1271  /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1272  /// checking code to guard against undefined behavior.  This is only
1273  /// suitable when we know that the address will be used to access the
1274  /// object.
1275  LValue EmitCheckedLValue(const Expr *E);
1276
1277  /// EmitLoadOfScalar - Load a scalar value from an address, taking
1278  /// care to appropriately convert from the memory representation to
1279  /// the LLVM value representation.
1280  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1281                                QualType Ty);
1282
1283  /// EmitStoreOfScalar - Store a scalar value to an address, taking
1284  /// care to appropriately convert from the memory representation to
1285  /// the LLVM value representation.
1286  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1287                         bool Volatile, QualType Ty);
1288
1289  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1290  /// this method emits the address of the lvalue, then loads the result as an
1291  /// rvalue, returning the rvalue.
1292  RValue EmitLoadOfLValue(LValue V, QualType LVType);
1293  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1294  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1295  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1296  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1297
1298
1299  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1300  /// lvalue, where both are guaranteed to the have the same type, and that type
1301  /// is 'Ty'.
1302  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1303  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1304                                                QualType Ty);
1305  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1306  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1307
1308  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1309  /// EmitStoreThroughLValue.
1310  ///
1311  /// \param Result [out] - If non-null, this will be set to a Value* for the
1312  /// bit-field contents after the store, appropriate for use as the result of
1313  /// an assignment to the bit-field.
1314  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1315                                      llvm::Value **Result=0);
1316
1317  // Note: only availabe for agg return types
1318  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1319  LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1320  // Note: only available for agg return types
1321  LValue EmitCallExprLValue(const CallExpr *E);
1322  // Note: only available for agg return types
1323  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1324  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1325  LValue EmitStringLiteralLValue(const StringLiteral *E);
1326  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1327  LValue EmitPredefinedFunctionName(unsigned Type);
1328  LValue EmitPredefinedLValue(const PredefinedExpr *E);
1329  LValue EmitUnaryOpLValue(const UnaryOperator *E);
1330  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1331  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1332  LValue EmitMemberExpr(const MemberExpr *E);
1333  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1334  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1335  LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1336  LValue EmitCastLValue(const CastExpr *E);
1337  LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
1338
1339  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1340                              const ObjCIvarDecl *Ivar);
1341  LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1342                                      const FieldDecl* Field,
1343                                      unsigned CVRQualifiers);
1344  LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1345                            unsigned CVRQualifiers);
1346
1347  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1348  /// if the Field is a reference, this will return the address of the reference
1349  /// and not the address of the value stored in the reference.
1350  LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1351                                          const FieldDecl* Field,
1352                                          unsigned CVRQualifiers);
1353
1354  LValue EmitLValueForIvar(QualType ObjectTy,
1355                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
1356                           unsigned CVRQualifiers);
1357
1358  LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1359                                unsigned CVRQualifiers);
1360
1361  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1362
1363  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1364  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1365  LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1366  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1367
1368  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1369  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1370  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1371  LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1372  LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1373  LValue EmitStmtExprLValue(const StmtExpr *E);
1374  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1375  LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
1376  void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::ConstantInt *Init);
1377  //===--------------------------------------------------------------------===//
1378  //                         Scalar Expression Emission
1379  //===--------------------------------------------------------------------===//
1380
1381  /// EmitCall - Generate a call of the given function, expecting the given
1382  /// result type, and using the given argument list which specifies both the
1383  /// LLVM arguments and the types they were derived from.
1384  ///
1385  /// \param TargetDecl - If given, the decl of the function in a direct call;
1386  /// used to set attributes on the call (noreturn, etc.).
1387  RValue EmitCall(const CGFunctionInfo &FnInfo,
1388                  llvm::Value *Callee,
1389                  ReturnValueSlot ReturnValue,
1390                  const CallArgList &Args,
1391                  const Decl *TargetDecl = 0,
1392                  llvm::Instruction **callOrInvoke = 0);
1393
1394  RValue EmitCall(QualType FnType, llvm::Value *Callee,
1395                  ReturnValueSlot ReturnValue,
1396                  CallExpr::const_arg_iterator ArgBeg,
1397                  CallExpr::const_arg_iterator ArgEnd,
1398                  const Decl *TargetDecl = 0);
1399  RValue EmitCallExpr(const CallExpr *E,
1400                      ReturnValueSlot ReturnValue = ReturnValueSlot());
1401
1402  llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
1403                                  llvm::Value * const *ArgBegin,
1404                                  llvm::Value * const *ArgEnd,
1405                                  const llvm::Twine &Name = "");
1406
1407  llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1408                                const llvm::Type *Ty);
1409  llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1410                                llvm::Value *&This, const llvm::Type *Ty);
1411
1412  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1413                           llvm::Value *Callee,
1414                           ReturnValueSlot ReturnValue,
1415                           llvm::Value *This,
1416                           llvm::Value *VTT,
1417                           CallExpr::const_arg_iterator ArgBeg,
1418                           CallExpr::const_arg_iterator ArgEnd);
1419  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1420                               ReturnValueSlot ReturnValue);
1421  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1422                                      ReturnValueSlot ReturnValue);
1423
1424  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1425                                       const CXXMethodDecl *MD,
1426                                       ReturnValueSlot ReturnValue);
1427
1428
1429  RValue EmitBuiltinExpr(const FunctionDecl *FD,
1430                         unsigned BuiltinID, const CallExpr *E);
1431
1432  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1433
1434  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1435  /// is unhandled by the current target.
1436  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1437
1438  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1439  llvm::Value *EmitNeonCall(llvm::Function *F,
1440                            llvm::SmallVectorImpl<llvm::Value*> &O,
1441                            const char *name, bool splat = false,
1442                            unsigned shift = 0, bool rightshift = false);
1443  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
1444                             bool widen = false);
1445  llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
1446                                   bool negateForRightShift);
1447
1448  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1449  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1450
1451  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1452  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1453  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1454  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1455                             ReturnValueSlot Return = ReturnValueSlot());
1456  RValue EmitObjCPropertyGet(const Expr *E,
1457                             ReturnValueSlot Return = ReturnValueSlot());
1458  RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S,
1459                                  ReturnValueSlot Return = ReturnValueSlot());
1460  void EmitObjCPropertySet(const Expr *E, RValue Src);
1461  void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1462
1463
1464  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1465  /// expression. Will emit a temporary variable if E is not an LValue.
1466  RValue EmitReferenceBindingToExpr(const Expr* E,
1467                                    const NamedDecl *InitializedDecl);
1468
1469  //===--------------------------------------------------------------------===//
1470  //                           Expression Emission
1471  //===--------------------------------------------------------------------===//
1472
1473  // Expressions are broken into three classes: scalar, complex, aggregate.
1474
1475  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1476  /// scalar type, returning the result.
1477  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1478
1479  /// EmitScalarConversion - Emit a conversion from the specified type to the
1480  /// specified destination type, both of which are LLVM scalar types.
1481  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1482                                    QualType DstTy);
1483
1484  /// EmitComplexToScalarConversion - Emit a conversion from the specified
1485  /// complex type to the specified destination type, where the destination type
1486  /// is an LLVM scalar type.
1487  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1488                                             QualType DstTy);
1489
1490
1491  /// EmitAggExpr - Emit the computation of the specified expression of
1492  /// aggregate type.  The result is computed into DestPtr.  Note that if
1493  /// DestPtr is null, the value of the aggregate expression is not needed.
1494  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1495                   bool IgnoreResult = false, bool IsInitializer = false,
1496                   bool RequiresGCollection = false);
1497
1498  /// EmitAggExprToLValue - Emit the computation of the specified expression of
1499  /// aggregate type into a temporary LValue.
1500  LValue EmitAggExprToLValue(const Expr *E);
1501
1502  /// EmitGCMemmoveCollectable - Emit special API for structs with object
1503  /// pointers.
1504  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1505                                QualType Ty);
1506
1507  /// EmitComplexExpr - Emit the computation of the specified expression of
1508  /// complex type, returning the result.
1509  ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1510                                bool IgnoreImag = false,
1511                                bool IgnoreRealAssign = false,
1512                                bool IgnoreImagAssign = false);
1513
1514  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1515  /// of complex type, storing into the specified Value*.
1516  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1517                               bool DestIsVolatile);
1518
1519  /// StoreComplexToAddr - Store a complex number into the specified address.
1520  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1521                          bool DestIsVolatile);
1522  /// LoadComplexFromAddr - Load a complex number from the specified address.
1523  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1524
1525  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1526  /// static block var decl.
1527  llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1528                                                 const char *Separator,
1529                                       llvm::GlobalValue::LinkageTypes Linkage);
1530
1531  /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1532  /// global variable that has already been created for it.  If the initializer
1533  /// has a different type than GV does, this may free GV and return a different
1534  /// one.  Otherwise it just returns GV.
1535  llvm::GlobalVariable *
1536  AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1537                                     llvm::GlobalVariable *GV);
1538
1539
1540  /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1541  /// initialized static block var decl.
1542  void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1543                                     llvm::GlobalVariable *GV);
1544
1545  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1546  /// variable with global storage.
1547  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1548
1549  /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1550  /// with the C++ runtime so that its destructor will be called at exit.
1551  void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1552                                     llvm::Constant *DeclPtr);
1553
1554  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1555  /// variables.
1556  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1557                                 llvm::Constant **Decls,
1558                                 unsigned NumDecls);
1559
1560  /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1561  /// variables.
1562  void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1563                                 const std::vector<std::pair<llvm::WeakVH,
1564                                   llvm::Constant*> > &DtorsAndObjects);
1565
1566  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1567
1568  void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1569
1570  RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1571                                    llvm::Value *AggLoc = 0,
1572                                    bool IsAggLocVolatile = false,
1573                                    bool IsInitializer = false);
1574
1575  void EmitCXXThrowExpr(const CXXThrowExpr *E);
1576
1577  //===--------------------------------------------------------------------===//
1578  //                             Internal Helpers
1579  //===--------------------------------------------------------------------===//
1580
1581  /// ContainsLabel - Return true if the statement contains a label in it.  If
1582  /// this statement is not executed normally, it not containing a label means
1583  /// that we can just remove the code.
1584  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1585
1586  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1587  /// to a constant, or if it does but contains a label, return 0.  If it
1588  /// constant folds to 'true' and does not contain a label, return 1, if it
1589  /// constant folds to 'false' and does not contain a label, return -1.
1590  int ConstantFoldsToSimpleInteger(const Expr *Cond);
1591
1592  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1593  /// if statement) to the specified blocks.  Based on the condition, this might
1594  /// try to simplify the codegen of the conditional based on the branch.
1595  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1596                            llvm::BasicBlock *FalseBlock);
1597
1598  /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1599  /// generate a branch around the created basic block as necessary.
1600  llvm::BasicBlock *getTrapBB();
1601
1602  /// EmitCallArg - Emit a single call argument.
1603  RValue EmitCallArg(const Expr *E, QualType ArgType);
1604
1605  /// EmitDelegateCallArg - We are performing a delegate call; that
1606  /// is, the current function is delegating to another one.  Produce
1607  /// a r-value suitable for passing the given parameter.
1608  RValue EmitDelegateCallArg(const VarDecl *Param);
1609
1610private:
1611  void EmitReturnOfRValue(RValue RV, QualType Ty);
1612
1613  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1614  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1615  ///
1616  /// \param AI - The first function argument of the expansion.
1617  /// \return The argument following the last expanded function
1618  /// argument.
1619  llvm::Function::arg_iterator
1620  ExpandTypeFromArgs(QualType Ty, LValue Dst,
1621                     llvm::Function::arg_iterator AI);
1622
1623  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1624  /// Ty, into individual arguments on the provided vector \arg Args. See
1625  /// ABIArgInfo::Expand.
1626  void ExpandTypeToArgs(QualType Ty, RValue Src,
1627                        llvm::SmallVector<llvm::Value*, 16> &Args);
1628
1629  llvm::Value* EmitAsmInput(const AsmStmt &S,
1630                            const TargetInfo::ConstraintInfo &Info,
1631                            const Expr *InputExpr, std::string &ConstraintStr);
1632
1633  llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
1634                                  const TargetInfo::ConstraintInfo &Info,
1635                                  LValue InputValue, QualType InputType,
1636                                  std::string &ConstraintStr);
1637
1638  /// EmitCallArgs - Emit call arguments for a function.
1639  /// The CallArgTypeInfo parameter is used for iterating over the known
1640  /// argument types of the function being called.
1641  template<typename T>
1642  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1643                    CallExpr::const_arg_iterator ArgBeg,
1644                    CallExpr::const_arg_iterator ArgEnd) {
1645      CallExpr::const_arg_iterator Arg = ArgBeg;
1646
1647    // First, use the argument types that the type info knows about
1648    if (CallArgTypeInfo) {
1649      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1650           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1651        assert(Arg != ArgEnd && "Running over edge of argument list!");
1652        QualType ArgType = *I;
1653
1654        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1655               getTypePtr() ==
1656               getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1657               "type mismatch in call argument!");
1658
1659        Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1660                                      ArgType));
1661      }
1662
1663      // Either we've emitted all the call args, or we have a call to a
1664      // variadic function.
1665      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1666             "Extra arguments in non-variadic function!");
1667
1668    }
1669
1670    // If we still have any arguments, emit them using the type of the argument.
1671    for (; Arg != ArgEnd; ++Arg) {
1672      QualType ArgType = Arg->getType();
1673      Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1674                                    ArgType));
1675    }
1676  }
1677
1678  const TargetCodeGenInfo &getTargetHooks() const {
1679    return CGM.getTargetCodeGenInfo();
1680  }
1681
1682  void EmitDeclMetadata();
1683};
1684
1685/// CGBlockInfo - Information to generate a block literal.
1686class CGBlockInfo {
1687public:
1688  /// Name - The name of the block, kindof.
1689  const char *Name;
1690
1691  /// DeclRefs - Variables from parent scopes that have been
1692  /// imported into this block.
1693  llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
1694
1695  /// InnerBlocks - This block and the blocks it encloses.
1696  llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
1697
1698  /// CXXThisRef - Non-null if 'this' was required somewhere, in
1699  /// which case this is that expression.
1700  const CXXThisExpr *CXXThisRef;
1701
1702  /// NeedsObjCSelf - True if something in this block has an implicit
1703  /// reference to 'self'.
1704  bool NeedsObjCSelf;
1705
1706  /// These are initialized by GenerateBlockFunction.
1707  bool BlockHasCopyDispose;
1708  CharUnits BlockSize;
1709  CharUnits BlockAlign;
1710  llvm::SmallVector<const Expr*, 8> BlockLayout;
1711
1712  CGBlockInfo(const char *Name);
1713};
1714
1715}  // end namespace CodeGen
1716}  // end namespace clang
1717
1718#endif
1719