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