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