CodeGenFunction.h revision 2504941793b549323f9d29c62507cf21d865fade
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 <map>
26#include "CodeGenModule.h"
27#include "CGBlocks.h"
28#include "CGBuilder.h"
29#include "CGCall.h"
30#include "CGCXX.h"
31#include "CGValue.h"
32
33namespace llvm {
34  class BasicBlock;
35  class LLVMContext;
36  class Module;
37  class SwitchInst;
38  class Twine;
39  class Value;
40}
41
42namespace clang {
43  class ASTContext;
44  class CXXDestructorDecl;
45  class CXXTryStmt;
46  class Decl;
47  class EnumConstantDecl;
48  class FunctionDecl;
49  class FunctionProtoType;
50  class LabelStmt;
51  class ObjCContainerDecl;
52  class ObjCInterfaceDecl;
53  class ObjCIvarDecl;
54  class ObjCMethodDecl;
55  class ObjCImplementationDecl;
56  class ObjCPropertyImplDecl;
57  class TargetInfo;
58  class VarDecl;
59  class ObjCForCollectionStmt;
60  class ObjCAtTryStmt;
61  class ObjCAtThrowStmt;
62  class ObjCAtSynchronizedStmt;
63
64namespace CodeGen {
65  class CodeGenModule;
66  class CodeGenTypes;
67  class CGDebugInfo;
68  class CGFunctionInfo;
69  class CGRecordLayout;
70
71/// CodeGenFunction - This class organizes the per-function state that is used
72/// while generating LLVM code.
73class CodeGenFunction : public BlockFunction {
74  CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
75  void operator=(const CodeGenFunction&);  // DO NOT IMPLEMENT
76public:
77  CodeGenModule &CGM;  // Per-module state.
78  const TargetInfo &Target;
79
80  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
81  CGBuilderTy Builder;
82
83  /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
84  /// This excludes BlockDecls.
85  const Decl *CurFuncDecl;
86  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
87  const Decl *CurCodeDecl;
88  const CGFunctionInfo *CurFnInfo;
89  QualType FnRetTy;
90  llvm::Function *CurFn;
91
92  /// CurGD - The GlobalDecl for the current function being compiled.
93  GlobalDecl CurGD;
94  /// OuterTryBlock - This is the address of the outter most try block, 0
95  /// otherwise.
96  const Stmt *OuterTryBlock;
97
98  /// ReturnBlock - Unified return block.
99  llvm::BasicBlock *ReturnBlock;
100  /// ReturnValue - The temporary alloca to hold the return value. This is null
101  /// iff the function has no return value.
102  llvm::Value *ReturnValue;
103
104  /// AllocaInsertPoint - This is an instruction in the entry block before which
105  /// we prefer to insert allocas.
106  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
107
108  const llvm::Type *LLVMIntTy;
109  uint32_t LLVMPointerWidth;
110
111  bool Exceptions;
112  bool CatchUndefined;
113public:
114  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
115  /// rethrows.
116  llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
117
118  /// PushCleanupBlock - Push a new cleanup entry on the stack and set the
119  /// passed in block as the cleanup block.
120  void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
121                        llvm::BasicBlock *CleanupExitBlock,
122                        llvm::BasicBlock *PreviousInvokeDest,
123                        bool EHOnly = false);
124  void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock) {
125    PushCleanupBlock(CleanupEntryBlock, 0, getInvokeDest(), false);
126  }
127
128  /// CleanupBlockInfo - A struct representing a popped cleanup block.
129  struct CleanupBlockInfo {
130    /// CleanupEntryBlock - the cleanup entry block
131    llvm::BasicBlock *CleanupBlock;
132
133    /// SwitchBlock - the block (if any) containing the switch instruction used
134    /// for jumping to the final destination.
135    llvm::BasicBlock *SwitchBlock;
136
137    /// EndBlock - the default destination for the switch instruction.
138    llvm::BasicBlock *EndBlock;
139
140    /// EHOnly - True iff this cleanup should only be performed on the
141    /// exceptional edge.
142    bool EHOnly;
143
144    CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb,
145                     llvm::BasicBlock *eb, bool ehonly = false)
146      : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb), EHOnly(ehonly) {}
147  };
148
149  /// EHCleanupBlock - RAII object that will create a cleanup block for the
150  /// exceptional edge and set the insert point to that block.  When destroyed,
151  /// it creates the cleanup edge and sets the insert point to the previous
152  /// block.
153  class EHCleanupBlock {
154    CodeGenFunction& CGF;
155    llvm::BasicBlock *Cont;
156    llvm::BasicBlock *CleanupHandler;
157    llvm::BasicBlock *CleanupEntryBB;
158    llvm::BasicBlock *PreviousInvokeDest;
159  public:
160    EHCleanupBlock(CodeGenFunction &cgf)
161      : CGF(cgf), Cont(CGF.createBasicBlock("cont")),
162        CleanupHandler(CGF.createBasicBlock("ehcleanup")),
163        CleanupEntryBB(CGF.createBasicBlock("ehcleanup.rest")),
164        PreviousInvokeDest(CGF.getInvokeDest()) {
165      CGF.EmitBranch(Cont);
166      llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler();
167      CGF.Builder.SetInsertPoint(CleanupEntryBB);
168      CGF.setInvokeDest(TerminateHandler);
169    }
170    ~EHCleanupBlock();
171  };
172
173  /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all
174  /// branch fixups and return a block info struct with the switch block and end
175  /// block.  This will also reset the invoke handler to the previous value
176  /// from when the cleanup block was created.
177  CleanupBlockInfo PopCleanupBlock();
178
179  /// DelayedCleanupBlock - RAII object that will create a cleanup block and set
180  /// the insert point to that block. When destructed, it sets the insert point
181  /// to the previous block and pushes a new cleanup entry on the stack.
182  class DelayedCleanupBlock {
183    CodeGenFunction& CGF;
184    llvm::BasicBlock *CurBB;
185    llvm::BasicBlock *CleanupEntryBB;
186    llvm::BasicBlock *CleanupExitBB;
187    llvm::BasicBlock *CurInvokeDest;
188    bool EHOnly;
189
190  public:
191    DelayedCleanupBlock(CodeGenFunction &cgf, bool ehonly = false)
192      : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()),
193        CleanupEntryBB(CGF.createBasicBlock("cleanup")), CleanupExitBB(0),
194        CurInvokeDest(CGF.getInvokeDest()),
195        EHOnly(ehonly) {
196      CGF.Builder.SetInsertPoint(CleanupEntryBB);
197    }
198
199    llvm::BasicBlock *getCleanupExitBlock() {
200      if (!CleanupExitBB)
201        CleanupExitBB = CGF.createBasicBlock("cleanup.exit");
202      return CleanupExitBB;
203    }
204
205    ~DelayedCleanupBlock() {
206      CGF.PushCleanupBlock(CleanupEntryBB, CleanupExitBB, CurInvokeDest,
207                           EHOnly);
208      // FIXME: This is silly, move this into the builder.
209      if (CurBB)
210        CGF.Builder.SetInsertPoint(CurBB);
211      else
212        CGF.Builder.ClearInsertionPoint();
213    }
214  };
215
216  /// \brief Enters a new scope for capturing cleanups, all of which will be
217  /// executed once the scope is exited.
218  class CleanupScope {
219    CodeGenFunction& CGF;
220    size_t CleanupStackDepth;
221    bool OldDidCallStackSave;
222    bool PerformCleanup;
223
224    CleanupScope(const CleanupScope &); // DO NOT IMPLEMENT
225    CleanupScope &operator=(const CleanupScope &); // DO NOT IMPLEMENT
226
227  public:
228    /// \brief Enter a new cleanup scope.
229    explicit CleanupScope(CodeGenFunction &CGF)
230      : CGF(CGF), PerformCleanup(true)
231    {
232      CleanupStackDepth = CGF.CleanupEntries.size();
233      OldDidCallStackSave = CGF.DidCallStackSave;
234    }
235
236    /// \brief Exit this cleanup scope, emitting any accumulated
237    /// cleanups.
238    ~CleanupScope() {
239      if (PerformCleanup) {
240        CGF.DidCallStackSave = OldDidCallStackSave;
241        CGF.EmitCleanupBlocks(CleanupStackDepth);
242      }
243    }
244
245    /// \brief Determine whether this scope requires any cleanups.
246    bool requiresCleanups() const {
247      return CGF.CleanupEntries.size() > CleanupStackDepth;
248    }
249
250    /// \brief Force the emission of cleanups now, instead of waiting
251    /// until this object is destroyed.
252    void ForceCleanup() {
253      assert(PerformCleanup && "Already forced cleanup");
254      CGF.DidCallStackSave = OldDidCallStackSave;
255      CGF.EmitCleanupBlocks(CleanupStackDepth);
256      PerformCleanup = false;
257    }
258  };
259
260  /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup
261  /// blocks that have been added.
262  void EmitCleanupBlocks(size_t OldCleanupStackSize);
263
264  /// EmitBranchThroughCleanup - Emit a branch from the current insert block
265  /// through the cleanup handling code (if any) and then on to \arg Dest.
266  ///
267  /// FIXME: Maybe this should really be in EmitBranch? Don't we always want
268  /// this behavior for branches?
269  void EmitBranchThroughCleanup(llvm::BasicBlock *Dest);
270
271  /// BeginConditionalBranch - Should be called before a conditional part of an
272  /// expression is emitted. For example, before the RHS of the expression below
273  /// is emitted:
274  ///
275  /// b && f(T());
276  ///
277  /// This is used to make sure that any temporaries created in the conditional
278  /// branch are only destroyed if the branch is taken.
279  void BeginConditionalBranch() {
280    ++ConditionalBranchLevel;
281  }
282
283  /// EndConditionalBranch - Should be called after a conditional part of an
284  /// expression has been emitted.
285  void EndConditionalBranch() {
286    assert(ConditionalBranchLevel != 0 &&
287           "Conditional branch mismatch!");
288
289    --ConditionalBranchLevel;
290  }
291
292private:
293  CGDebugInfo *DebugInfo;
294
295  /// IndirectBranch - The first time an indirect goto is seen we create a block
296  /// with an indirect branch.  Every time we see the address of a label taken,
297  /// we add the label to the indirect goto.  Every subsequent indirect goto is
298  /// codegen'd as a jump to the IndirectBranch's basic block.
299  llvm::IndirectBrInst *IndirectBranch;
300
301  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
302  /// decls.
303  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
304
305  /// LabelMap - This keeps track of the LLVM basic block for each C label.
306  llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
307
308  // BreakContinueStack - This keeps track of where break and continue
309  // statements should jump to.
310  struct BreakContinue {
311    BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
312      : BreakBlock(bb), ContinueBlock(cb) {}
313
314    llvm::BasicBlock *BreakBlock;
315    llvm::BasicBlock *ContinueBlock;
316  };
317  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
318
319  /// SwitchInsn - This is nearest current switch instruction. It is null if if
320  /// current context is not in a switch.
321  llvm::SwitchInst *SwitchInsn;
322
323  /// CaseRangeBlock - This block holds if condition check for last case
324  /// statement range in current switch instruction.
325  llvm::BasicBlock *CaseRangeBlock;
326
327  /// InvokeDest - This is the nearest exception target for calls
328  /// which can unwind, when exceptions are being used.
329  llvm::BasicBlock *InvokeDest;
330
331  // VLASizeMap - This keeps track of the associated size for each VLA type.
332  // We track this by the size expression rather than the type itself because
333  // in certain situations, like a const qualifier applied to an VLA typedef,
334  // multiple VLA types can share the same size expression.
335  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
336  // enter/leave scopes.
337  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
338
339  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
340  /// calling llvm.stacksave for multiple VLAs in the same scope.
341  bool DidCallStackSave;
342
343  struct CleanupEntry {
344    /// CleanupEntryBlock - The block of code that does the actual cleanup.
345    llvm::BasicBlock *CleanupEntryBlock;
346
347    /// CleanupExitBlock - The cleanup exit block.
348    llvm::BasicBlock *CleanupExitBlock;
349
350    /// Blocks - Basic blocks that were emitted in the current cleanup scope.
351    std::vector<llvm::BasicBlock *> Blocks;
352
353    /// BranchFixups - Branch instructions to basic blocks that haven't been
354    /// inserted into the current function yet.
355    std::vector<llvm::BranchInst *> BranchFixups;
356
357    /// PreviousInvokeDest - The invoke handler from the start of the cleanup
358    /// region.
359    llvm::BasicBlock *PreviousInvokeDest;
360
361    /// EHOnly - Perform this only on the exceptional edge, not the main edge.
362    bool EHOnly;
363
364    explicit CleanupEntry(llvm::BasicBlock *CleanupEntryBlock,
365                          llvm::BasicBlock *CleanupExitBlock,
366                          llvm::BasicBlock *PreviousInvokeDest,
367                          bool ehonly)
368      : CleanupEntryBlock(CleanupEntryBlock),
369        CleanupExitBlock(CleanupExitBlock),
370        PreviousInvokeDest(PreviousInvokeDest),
371        EHOnly(ehonly) {}
372  };
373
374  /// CleanupEntries - Stack of cleanup entries.
375  llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
376
377  typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
378
379  /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
380  BlockScopeMap BlockScopes;
381
382  /// CXXThisDecl - When generating code for a C++ member function,
383  /// this will hold the implicit 'this' declaration.
384  ImplicitParamDecl *CXXThisDecl;
385  llvm::Value *CXXThisValue;
386
387  /// CXXVTTDecl - When generating code for a base object constructor or
388  /// base object destructor with virtual bases, this will hold the implicit
389  /// VTT parameter.
390  ImplicitParamDecl *CXXVTTDecl;
391  llvm::Value *CXXVTTValue;
392
393  /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
394  struct CXXLiveTemporaryInfo {
395    /// Temporary - The live temporary.
396    const CXXTemporary *Temporary;
397
398    /// ThisPtr - The pointer to the temporary.
399    llvm::Value *ThisPtr;
400
401    /// DtorBlock - The destructor block.
402    llvm::BasicBlock *DtorBlock;
403
404    /// CondPtr - If this is a conditional temporary, this is the pointer to the
405    /// condition variable that states whether the destructor should be called
406    /// or not.
407    llvm::Value *CondPtr;
408
409    CXXLiveTemporaryInfo(const CXXTemporary *temporary,
410                         llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
411                         llvm::Value *condptr)
412      : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
413      CondPtr(condptr) { }
414  };
415
416  llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
417
418  /// ConditionalBranchLevel - Contains the nesting level of the current
419  /// conditional branch. This is used so that we know if a temporary should be
420  /// destroyed conditionally.
421  unsigned ConditionalBranchLevel;
422
423
424  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
425  /// type as well as the field number that contains the actual data.
426  llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
427                                              unsigned> > ByRefValueInfo;
428
429  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
430  /// number that holds the value.
431  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
432
433  llvm::BasicBlock *TerminateHandler;
434  llvm::BasicBlock *TrapBB;
435
436  int UniqueAggrDestructorCount;
437public:
438  CodeGenFunction(CodeGenModule &cgm);
439
440  ASTContext &getContext() const;
441  CGDebugInfo *getDebugInfo() { return DebugInfo; }
442
443  llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
444  void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
445
446  llvm::LLVMContext &getLLVMContext() { return VMContext; }
447
448  //===--------------------------------------------------------------------===//
449  //                                  Objective-C
450  //===--------------------------------------------------------------------===//
451
452  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
453
454  void StartObjCMethod(const ObjCMethodDecl *MD,
455                       const ObjCContainerDecl *CD);
456
457  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
458  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
459                          const ObjCPropertyImplDecl *PID);
460
461  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
462  /// for the given property.
463  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
464                          const ObjCPropertyImplDecl *PID);
465
466  //===--------------------------------------------------------------------===//
467  //                                  Block Bits
468  //===--------------------------------------------------------------------===//
469
470  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
471  llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose,
472                                           CharUnits Size,
473                                           const llvm::StructType *,
474                                           std::vector<HelperInfo> *);
475
476  llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
477                                        const BlockInfo& Info,
478                                        const Decl *OuterFuncDecl,
479                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm,
480                                        CharUnits &Size, CharUnits &Align,
481                      llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
482                                        bool &subBlockHasCopyDispose);
483
484  void BlockForwardSelf();
485  llvm::Value *LoadBlockStruct();
486
487  CharUnits AllocateBlockDecl(const BlockDeclRefExpr *E);
488  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E);
489  const llvm::Type *BuildByRefType(const ValueDecl *D);
490
491  void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
492  void StartFunction(GlobalDecl GD, QualType RetTy,
493                     llvm::Function *Fn,
494                     const FunctionArgList &Args,
495                     SourceLocation StartLoc);
496
497  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
498  /// emission when possible.
499  void EmitReturnBlock();
500
501  /// FinishFunction - Complete IR generation of the current function. It is
502  /// legal to call this function even if there is no current insertion point.
503  void FinishFunction(SourceLocation EndLoc=SourceLocation());
504
505  /// DynamicTypeAdjust - Do the non-virtual and virtual adjustments on an
506  /// object pointer to alter the dynamic type of the pointer.  Used by
507  /// GenerateCovariantThunk for building thunks.
508  llvm::Value *DynamicTypeAdjust(llvm::Value *V,
509                                 const ThunkAdjustment &Adjustment);
510
511  /// GenerateThunk - Generate a thunk for the given method
512  llvm::Constant *GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
513                                bool Extern,
514                                const ThunkAdjustment &ThisAdjustment);
515  llvm::Constant *
516  GenerateCovariantThunk(llvm::Function *Fn, GlobalDecl GD,
517                         bool Extern,
518                         const CovariantThunkAdjustment &Adjustment);
519
520  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type);
521
522  void InitializeVtablePtrs(const CXXRecordDecl *ClassDecl);
523
524  void InitializeVtablePtrsRecursive(const CXXRecordDecl *ClassDecl,
525                                     llvm::Constant *Vtable,
526                                     CGVtableInfo::AddrSubMap_t& AddressPoints,
527                                     llvm::Value *ThisPtr,
528                                     uint64_t Offset);
529
530  void SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
531                                    CXXCtorType Type,
532                                    llvm::Function *Fn,
533                                    const FunctionArgList &Args);
534
535  void SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
536                                   llvm::Function *Fn,
537                                   const FunctionArgList &Args);
538
539  void SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
540                                    CXXCtorType Type,
541                                    llvm::Function *Fn,
542                                    const FunctionArgList &Args);
543
544  void SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
545                                   CXXDtorType Type,
546                                   llvm::Function *Fn,
547                                   const FunctionArgList &Args);
548
549  /// EmitDtorEpilogue - Emit all code that comes at the end of class's
550  /// destructor. This is to call destructors on members and base classes in
551  /// reverse order of their construction.
552  void EmitDtorEpilogue(const CXXDestructorDecl *Dtor,
553                        CXXDtorType Type);
554
555  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
556  /// arguments for the given function. This is also responsible for naming the
557  /// LLVM function arguments.
558  void EmitFunctionProlog(const CGFunctionInfo &FI,
559                          llvm::Function *Fn,
560                          const FunctionArgList &Args);
561
562  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
563  /// given temporary.
564  void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
565
566  /// EmitStartEHSpec - Emit the start of the exception spec.
567  void EmitStartEHSpec(const Decl *D);
568
569  /// EmitEndEHSpec - Emit the end of the exception spec.
570  void EmitEndEHSpec(const Decl *D);
571
572  /// getTerminateHandler - Return a handler that just calls terminate.
573  llvm::BasicBlock *getTerminateHandler();
574
575  const llvm::Type *ConvertTypeForMem(QualType T);
576  const llvm::Type *ConvertType(QualType T);
577  const llvm::Type *ConvertType(const TypeDecl *T) {
578    return ConvertType(getContext().getTypeDeclType(T));
579  }
580
581  /// LoadObjCSelf - Load the value of self. This function is only valid while
582  /// generating code for an Objective-C method.
583  llvm::Value *LoadObjCSelf();
584
585  /// TypeOfSelfObject - Return type of object that this self represents.
586  QualType TypeOfSelfObject();
587
588  /// hasAggregateLLVMType - Return true if the specified AST type will map into
589  /// an aggregate LLVM type or is void.
590  static bool hasAggregateLLVMType(QualType T);
591
592  /// createBasicBlock - Create an LLVM basic block.
593  llvm::BasicBlock *createBasicBlock(const char *Name="",
594                                     llvm::Function *Parent=0,
595                                     llvm::BasicBlock *InsertBefore=0) {
596#ifdef NDEBUG
597    return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
598#else
599    return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
600#endif
601  }
602
603  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
604  /// label maps to.
605  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
606
607  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
608  /// another basic block, simplify it. This assumes that no other code could
609  /// potentially reference the basic block.
610  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
611
612  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
613  /// adding a fall-through branch from the current insert block if
614  /// necessary. It is legal to call this function even if there is no current
615  /// insertion point.
616  ///
617  /// IsFinished - If true, indicates that the caller has finished emitting
618  /// branches to the given block and does not expect to emit code into it. This
619  /// means the block can be ignored if it is unreachable.
620  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
621
622  /// EmitBranch - Emit a branch to the specified basic block from the current
623  /// insert block, taking care to avoid creation of branches from dummy
624  /// blocks. It is legal to call this function even if there is no current
625  /// insertion point.
626  ///
627  /// This function clears the current insertion point. The caller should follow
628  /// calls to this function with calls to Emit*Block prior to generation new
629  /// code.
630  void EmitBranch(llvm::BasicBlock *Block);
631
632  /// HaveInsertPoint - True if an insertion point is defined. If not, this
633  /// indicates that the current code being emitted is unreachable.
634  bool HaveInsertPoint() const {
635    return Builder.GetInsertBlock() != 0;
636  }
637
638  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
639  /// emitted IR has a place to go. Note that by definition, if this function
640  /// creates a block then that block is unreachable; callers may do better to
641  /// detect when no insertion point is defined and simply skip IR generation.
642  void EnsureInsertPoint() {
643    if (!HaveInsertPoint())
644      EmitBlock(createBasicBlock());
645  }
646
647  /// ErrorUnsupported - Print out an error that codegen doesn't support the
648  /// specified stmt yet.
649  void ErrorUnsupported(const Stmt *S, const char *Type,
650                        bool OmitOnError=false);
651
652  //===--------------------------------------------------------------------===//
653  //                                  Helpers
654  //===--------------------------------------------------------------------===//
655
656  Qualifiers MakeQualifiers(QualType T) {
657    Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
658    Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
659    return Quals;
660  }
661
662  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
663  /// block. The caller is responsible for setting an appropriate alignment on
664  /// the alloca.
665  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
666                                     const llvm::Twine &Name = "tmp");
667
668  /// CreateIRTemp - Create a temporary IR object of the given type, with
669  /// appropriate alignment. This routine should only be used when an temporary
670  /// value needs to be stored into an alloca (for example, to avoid explicit
671  /// PHI construction), but the type is the IR type, not the type appropriate
672  /// for storing in memory.
673  llvm::Value *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
674
675  /// CreateMemTemp - Create a temporary memory object of the given type, with
676  /// appropriate alignment.
677  llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
678
679  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
680  /// expression and compare the result against zero, returning an Int1Ty value.
681  llvm::Value *EvaluateExprAsBool(const Expr *E);
682
683  /// EmitAnyExpr - Emit code to compute the specified expression which can have
684  /// any type.  The result is returned as an RValue struct.  If this is an
685  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
686  /// the result should be returned.
687  ///
688  /// \param IgnoreResult - True if the resulting value isn't used.
689  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
690                     bool IsAggLocVolatile = false, bool IgnoreResult = false,
691                     bool IsInitializer = false);
692
693  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
694  // or the value of the expression, depending on how va_list is defined.
695  llvm::Value *EmitVAListRef(const Expr *E);
696
697  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
698  /// always be accessible even if no aggregate location is provided.
699  RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
700                           bool IsInitializer = false);
701
702  /// EmitAggregateCopy - Emit an aggrate copy.
703  ///
704  /// \param isVolatile - True iff either the source or the destination is
705  /// volatile.
706  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
707                         QualType EltTy, bool isVolatile=false);
708
709  void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
710
711  /// StartBlock - Start new block named N. If insert block is a dummy block
712  /// then reuse it.
713  void StartBlock(const char *N);
714
715  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
716  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
717
718  /// GetAddrOfLocalVar - Return the address of a local variable.
719  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
720
721  /// getAccessedFieldNo - Given an encoded value and a result number, return
722  /// the input field number being accessed.
723  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
724
725  llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
726  llvm::BasicBlock *GetIndirectGotoBlock();
727
728  /// EmitMemSetToZero - Generate code to memset a value of the given type to 0.
729  void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty);
730
731  // EmitVAArg - Generate code to get an argument from the passed in pointer
732  // and update it accordingly. The return value is a pointer to the argument.
733  // FIXME: We should be able to get rid of this method and use the va_arg
734  // instruction in LLVM instead once it works well enough.
735  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
736
737  /// EmitVLASize - Generate code for any VLA size expressions that might occur
738  /// in a variably modified type. If Ty is a VLA, will return the value that
739  /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
740  ///
741  /// This function can be called with a null (unreachable) insert point.
742  llvm::Value *EmitVLASize(QualType Ty);
743
744  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
745  // of a variable length array type.
746  llvm::Value *GetVLASize(const VariableArrayType *);
747
748  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
749  /// generating code for an C++ member function.
750  llvm::Value *LoadCXXThis() {
751    assert(CXXThisValue && "no 'this' value for this function");
752    return CXXThisValue;
753  }
754
755  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
756  /// virtual bases.
757  llvm::Value *LoadCXXVTT() {
758    assert(CXXVTTValue && "no VTT value for this function");
759    return CXXVTTValue;
760  }
761
762  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
763  /// complete class down to one of its virtual bases.
764  llvm::Value *GetAddressOfBaseOfCompleteClass(llvm::Value *Value,
765                                               bool IsVirtual,
766                                               const CXXRecordDecl *Derived,
767                                               const CXXRecordDecl *Base);
768
769  /// GetAddressOfBaseClass - This function will add the necessary delta to the
770  /// load of 'this' and returns address of the base class.
771  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
772                                     const CXXRecordDecl *ClassDecl,
773                                     const CXXRecordDecl *BaseClassDecl,
774                                     bool NullCheckValue);
775
776  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
777                                        const CXXRecordDecl *ClassDecl,
778                                        const CXXRecordDecl *DerivedClassDecl,
779                                        bool NullCheckValue);
780
781  llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
782                                         const CXXRecordDecl *ClassDecl,
783                                         const CXXRecordDecl *BaseClassDecl);
784
785  void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue,
786                                   llvm::Value *SrcValue,
787                                   const ArrayType *Array,
788                                   const CXXRecordDecl *BaseClassDecl,
789                                   QualType Ty);
790
791  void EmitClassAggrCopyAssignment(llvm::Value *DestValue,
792                                   llvm::Value *SrcValue,
793                                   const ArrayType *Array,
794                                   const CXXRecordDecl *BaseClassDecl,
795                                   QualType Ty);
796
797  void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue,
798                               const CXXRecordDecl *ClassDecl,
799                               const CXXRecordDecl *BaseClassDecl,
800                               QualType Ty);
801
802  void EmitClassCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue,
803                               const CXXRecordDecl *ClassDecl,
804                               const CXXRecordDecl *BaseClassDecl,
805                               QualType Ty);
806
807  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
808                              llvm::Value *This,
809                              CallExpr::const_arg_iterator ArgBeg,
810                              CallExpr::const_arg_iterator ArgEnd);
811
812  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
813                                  const ConstantArrayType *ArrayTy,
814                                  llvm::Value *ArrayPtr,
815                                  CallExpr::const_arg_iterator ArgBeg,
816                                  CallExpr::const_arg_iterator ArgEnd);
817
818  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
819                                  llvm::Value *NumElements,
820                                  llvm::Value *ArrayPtr,
821                                  CallExpr::const_arg_iterator ArgBeg,
822                                  CallExpr::const_arg_iterator ArgEnd);
823
824  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
825                                 const ArrayType *Array,
826                                 llvm::Value *This);
827
828  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
829                                 llvm::Value *NumElements,
830                                 llvm::Value *This);
831
832  llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
833                                                const ArrayType *Array,
834                                                llvm::Value *This);
835
836  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
837                             llvm::Value *This);
838
839  void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
840  void PopCXXTemporary();
841
842  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
843  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
844
845  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
846                      QualType DeleteTy);
847
848  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
849  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
850
851  void EmitCheck(llvm::Value *, unsigned Size);
852
853  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
854                                       bool isInc, bool isPre);
855  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
856                                         bool isInc, bool isPre);
857  //===--------------------------------------------------------------------===//
858  //                            Declaration Emission
859  //===--------------------------------------------------------------------===//
860
861  /// EmitDecl - Emit a declaration.
862  ///
863  /// This function can be called with a null (unreachable) insert point.
864  void EmitDecl(const Decl &D);
865
866  /// EmitBlockVarDecl - Emit a block variable declaration.
867  ///
868  /// This function can be called with a null (unreachable) insert point.
869  void EmitBlockVarDecl(const VarDecl &D);
870
871  /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
872  ///
873  /// This function can be called with a null (unreachable) insert point.
874  void EmitLocalBlockVarDecl(const VarDecl &D);
875
876  void EmitStaticBlockVarDecl(const VarDecl &D,
877                              llvm::GlobalValue::LinkageTypes Linkage);
878
879  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
880  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
881
882  //===--------------------------------------------------------------------===//
883  //                             Statement Emission
884  //===--------------------------------------------------------------------===//
885
886  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
887  void EmitStopPoint(const Stmt *S);
888
889  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
890  /// this function even if there is no current insertion point.
891  ///
892  /// This function may clear the current insertion point; callers should use
893  /// EnsureInsertPoint if they wish to subsequently generate code without first
894  /// calling EmitBlock, EmitBranch, or EmitStmt.
895  void EmitStmt(const Stmt *S);
896
897  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
898  /// necessarily require an insertion point or debug information; typically
899  /// because the statement amounts to a jump or a container of other
900  /// statements.
901  ///
902  /// \return True if the statement was handled.
903  bool EmitSimpleStmt(const Stmt *S);
904
905  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
906                          llvm::Value *AggLoc = 0, bool isAggVol = false);
907
908  /// EmitLabel - Emit the block for the given label. It is legal to call this
909  /// function even if there is no current insertion point.
910  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
911
912  void EmitLabelStmt(const LabelStmt &S);
913  void EmitGotoStmt(const GotoStmt &S);
914  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
915  void EmitIfStmt(const IfStmt &S);
916  void EmitWhileStmt(const WhileStmt &S);
917  void EmitDoStmt(const DoStmt &S);
918  void EmitForStmt(const ForStmt &S);
919  void EmitReturnStmt(const ReturnStmt &S);
920  void EmitDeclStmt(const DeclStmt &S);
921  void EmitBreakStmt(const BreakStmt &S);
922  void EmitContinueStmt(const ContinueStmt &S);
923  void EmitSwitchStmt(const SwitchStmt &S);
924  void EmitDefaultStmt(const DefaultStmt &S);
925  void EmitCaseStmt(const CaseStmt &S);
926  void EmitCaseStmtRange(const CaseStmt &S);
927  void EmitAsmStmt(const AsmStmt &S);
928
929  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
930  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
931  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
932  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
933
934  void EmitCXXTryStmt(const CXXTryStmt &S);
935
936  //===--------------------------------------------------------------------===//
937  //                         LValue Expression Emission
938  //===--------------------------------------------------------------------===//
939
940  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
941  RValue GetUndefRValue(QualType Ty);
942
943  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
944  /// and issue an ErrorUnsupported style diagnostic (using the
945  /// provided Name).
946  RValue EmitUnsupportedRValue(const Expr *E,
947                               const char *Name);
948
949  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
950  /// an ErrorUnsupported style diagnostic (using the provided Name).
951  LValue EmitUnsupportedLValue(const Expr *E,
952                               const char *Name);
953
954  /// EmitLValue - Emit code to compute a designator that specifies the location
955  /// of the expression.
956  ///
957  /// This can return one of two things: a simple address or a bitfield
958  /// reference.  In either case, the LLVM Value* in the LValue structure is
959  /// guaranteed to be an LLVM pointer type.
960  ///
961  /// If this returns a bitfield reference, nothing about the pointee type of
962  /// the LLVM value is known: For example, it may not be a pointer to an
963  /// integer.
964  ///
965  /// If this returns a normal address, and if the lvalue's C type is fixed
966  /// size, this method guarantees that the returned pointer type will point to
967  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
968  /// variable length type, this is not possible.
969  ///
970  LValue EmitLValue(const Expr *E);
971
972  /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
973  /// checking code to guard against undefined behavior.  This is only
974  /// suitable when we know that the address will be used to access the
975  /// object.
976  LValue EmitCheckedLValue(const Expr *E);
977
978  /// EmitLoadOfScalar - Load a scalar value from an address, taking
979  /// care to appropriately convert from the memory representation to
980  /// the LLVM value representation.
981  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
982                                QualType Ty);
983
984  /// EmitStoreOfScalar - Store a scalar value to an address, taking
985  /// care to appropriately convert from the memory representation to
986  /// the LLVM value representation.
987  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
988                         bool Volatile, QualType Ty);
989
990  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
991  /// this method emits the address of the lvalue, then loads the result as an
992  /// rvalue, returning the rvalue.
993  RValue EmitLoadOfLValue(LValue V, QualType LVType);
994  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
995  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
996  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
997  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
998
999
1000  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1001  /// lvalue, where both are guaranteed to the have the same type, and that type
1002  /// is 'Ty'.
1003  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1004  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1005                                                QualType Ty);
1006  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1007  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1008
1009  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1010  /// EmitStoreThroughLValue.
1011  ///
1012  /// \param Result [out] - If non-null, this will be set to a Value* for the
1013  /// bit-field contents after the store, appropriate for use as the result of
1014  /// an assignment to the bit-field.
1015  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1016                                      llvm::Value **Result=0);
1017
1018  // Note: only availabe for agg return types
1019  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1020  // Note: only available for agg return types
1021  LValue EmitCallExprLValue(const CallExpr *E);
1022  // Note: only available for agg return types
1023  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1024  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1025  LValue EmitStringLiteralLValue(const StringLiteral *E);
1026  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1027  LValue EmitPredefinedFunctionName(unsigned Type);
1028  LValue EmitPredefinedLValue(const PredefinedExpr *E);
1029  LValue EmitUnaryOpLValue(const UnaryOperator *E);
1030  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1031  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1032  LValue EmitMemberExpr(const MemberExpr *E);
1033  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1034  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1035  LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1036  LValue EmitCastLValue(const CastExpr *E);
1037  LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1038
1039  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1040                              const ObjCIvarDecl *Ivar);
1041  LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1042                            unsigned CVRQualifiers);
1043
1044  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1045  /// if the Field is a reference, this will return the address of the reference
1046  /// and not the address of the value stored in the reference.
1047  LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1048                                          const FieldDecl* Field,
1049                                          unsigned CVRQualifiers);
1050
1051  LValue EmitLValueForIvar(QualType ObjectTy,
1052                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
1053                           unsigned CVRQualifiers);
1054
1055  LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1056                                unsigned CVRQualifiers);
1057
1058  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1059
1060  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1061  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1062  LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1063  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1064
1065  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1066  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1067  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1068  LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1069  LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1070  LValue EmitStmtExprLValue(const StmtExpr *E);
1071  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1072
1073  //===--------------------------------------------------------------------===//
1074  //                         Scalar Expression Emission
1075  //===--------------------------------------------------------------------===//
1076
1077  /// EmitCall - Generate a call of the given function, expecting the given
1078  /// result type, and using the given argument list which specifies both the
1079  /// LLVM arguments and the types they were derived from.
1080  ///
1081  /// \param TargetDecl - If given, the decl of the function in a direct call;
1082  /// used to set attributes on the call (noreturn, etc.).
1083  RValue EmitCall(const CGFunctionInfo &FnInfo,
1084                  llvm::Value *Callee,
1085                  ReturnValueSlot ReturnValue,
1086                  const CallArgList &Args,
1087                  const Decl *TargetDecl = 0);
1088
1089  RValue EmitCall(QualType FnType, llvm::Value *Callee,
1090                  ReturnValueSlot ReturnValue,
1091                  CallExpr::const_arg_iterator ArgBeg,
1092                  CallExpr::const_arg_iterator ArgEnd,
1093                  const Decl *TargetDecl = 0);
1094  RValue EmitCallExpr(const CallExpr *E,
1095                      ReturnValueSlot ReturnValue = ReturnValueSlot());
1096
1097  llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1098                                const llvm::Type *Ty);
1099  llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1100                                llvm::Value *&This, const llvm::Type *Ty);
1101
1102  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1103                           llvm::Value *Callee,
1104                           ReturnValueSlot ReturnValue,
1105                           llvm::Value *This,
1106                           llvm::Value *VTT,
1107                           CallExpr::const_arg_iterator ArgBeg,
1108                           CallExpr::const_arg_iterator ArgEnd);
1109  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1110                               ReturnValueSlot ReturnValue);
1111  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1112                                      ReturnValueSlot ReturnValue);
1113
1114  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1115                                       const CXXMethodDecl *MD,
1116                                       ReturnValueSlot ReturnValue);
1117
1118
1119  RValue EmitBuiltinExpr(const FunctionDecl *FD,
1120                         unsigned BuiltinID, const CallExpr *E);
1121
1122  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1123
1124  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1125  /// is unhandled by the current target.
1126  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1127
1128  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1129  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1130
1131  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1132  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1133  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1134  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
1135  RValue EmitObjCPropertyGet(const Expr *E);
1136  RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S);
1137  void EmitObjCPropertySet(const Expr *E, RValue Src);
1138  void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1139
1140
1141  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1142  /// expression. Will emit a temporary variable if E is not an LValue.
1143  RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false);
1144
1145  //===--------------------------------------------------------------------===//
1146  //                           Expression Emission
1147  //===--------------------------------------------------------------------===//
1148
1149  // Expressions are broken into three classes: scalar, complex, aggregate.
1150
1151  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1152  /// scalar type, returning the result.
1153  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1154
1155  /// EmitScalarConversion - Emit a conversion from the specified type to the
1156  /// specified destination type, both of which are LLVM scalar types.
1157  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1158                                    QualType DstTy);
1159
1160  /// EmitComplexToScalarConversion - Emit a conversion from the specified
1161  /// complex type to the specified destination type, where the destination type
1162  /// is an LLVM scalar type.
1163  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1164                                             QualType DstTy);
1165
1166
1167  /// EmitAggExpr - Emit the computation of the specified expression of
1168  /// aggregate type.  The result is computed into DestPtr.  Note that if
1169  /// DestPtr is null, the value of the aggregate expression is not needed.
1170  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1171                   bool IgnoreResult = false, bool IsInitializer = false,
1172                   bool RequiresGCollection = false);
1173
1174  /// EmitAggExprToLValue - Emit the computation of the specified expression of
1175  /// aggregate type into a temporary LValue.
1176  LValue EmitAggExprToLValue(const Expr *E);
1177
1178  /// EmitGCMemmoveCollectable - Emit special API for structs with object
1179  /// pointers.
1180  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1181                                QualType Ty);
1182
1183  /// EmitComplexExpr - Emit the computation of the specified expression of
1184  /// complex type, returning the result.
1185  ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1186                                bool IgnoreImag = false,
1187                                bool IgnoreRealAssign = false,
1188                                bool IgnoreImagAssign = false);
1189
1190  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1191  /// of complex type, storing into the specified Value*.
1192  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1193                               bool DestIsVolatile);
1194
1195  /// StoreComplexToAddr - Store a complex number into the specified address.
1196  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1197                          bool DestIsVolatile);
1198  /// LoadComplexFromAddr - Load a complex number from the specified address.
1199  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1200
1201  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1202  /// static block var decl.
1203  llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1204                                                 const char *Separator,
1205                                       llvm::GlobalValue::LinkageTypes Linkage);
1206
1207  /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1208  /// global variable that has already been created for it.  If the initializer
1209  /// has a different type than GV does, this may free GV and return a different
1210  /// one.  Otherwise it just returns GV.
1211  llvm::GlobalVariable *
1212  AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1213                                     llvm::GlobalVariable *GV);
1214
1215
1216  /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1217  /// initialized static block var decl.
1218  void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1219                                     llvm::GlobalVariable *GV);
1220
1221  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1222  /// variable with global storage.
1223  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1224
1225  /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1226  /// with the C++ runtime so that its destructor will be called at exit.
1227  void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1228                                     llvm::Constant *DeclPtr);
1229
1230  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1231  /// variables.
1232  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1233                                 llvm::Constant **Decls,
1234                                 unsigned NumDecls);
1235
1236  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1237
1238  void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1239
1240  RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1241                                    llvm::Value *AggLoc = 0,
1242                                    bool IsAggLocVolatile = false,
1243                                    bool IsInitializer = false);
1244
1245  void EmitCXXThrowExpr(const CXXThrowExpr *E);
1246
1247  //===--------------------------------------------------------------------===//
1248  //                             Internal Helpers
1249  //===--------------------------------------------------------------------===//
1250
1251  /// ContainsLabel - Return true if the statement contains a label in it.  If
1252  /// this statement is not executed normally, it not containing a label means
1253  /// that we can just remove the code.
1254  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1255
1256  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1257  /// to a constant, or if it does but contains a label, return 0.  If it
1258  /// constant folds to 'true' and does not contain a label, return 1, if it
1259  /// constant folds to 'false' and does not contain a label, return -1.
1260  int ConstantFoldsToSimpleInteger(const Expr *Cond);
1261
1262  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1263  /// if statement) to the specified blocks.  Based on the condition, this might
1264  /// try to simplify the codegen of the conditional based on the branch.
1265  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1266                            llvm::BasicBlock *FalseBlock);
1267
1268  /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1269  /// generate a branch around the created basic block as necessary.
1270  llvm::BasicBlock* getTrapBB();
1271private:
1272
1273  void EmitReturnOfRValue(RValue RV, QualType Ty);
1274
1275  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1276  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1277  ///
1278  /// \param AI - The first function argument of the expansion.
1279  /// \return The argument following the last expanded function
1280  /// argument.
1281  llvm::Function::arg_iterator
1282  ExpandTypeFromArgs(QualType Ty, LValue Dst,
1283                     llvm::Function::arg_iterator AI);
1284
1285  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1286  /// Ty, into individual arguments on the provided vector \arg Args. See
1287  /// ABIArgInfo::Expand.
1288  void ExpandTypeToArgs(QualType Ty, RValue Src,
1289                        llvm::SmallVector<llvm::Value*, 16> &Args);
1290
1291  llvm::Value* EmitAsmInput(const AsmStmt &S,
1292                            const TargetInfo::ConstraintInfo &Info,
1293                            const Expr *InputExpr, std::string &ConstraintStr);
1294
1295  /// EmitCleanupBlock - emits a single cleanup block.
1296  void EmitCleanupBlock();
1297
1298  /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1299  /// current cleanup scope.
1300  void AddBranchFixup(llvm::BranchInst *BI);
1301
1302  /// EmitCallArg - Emit a single call argument.
1303  RValue EmitCallArg(const Expr *E, QualType ArgType);
1304
1305  /// EmitCallArgs - Emit call arguments for a function.
1306  /// The CallArgTypeInfo parameter is used for iterating over the known
1307  /// argument types of the function being called.
1308  template<typename T>
1309  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1310                    CallExpr::const_arg_iterator ArgBeg,
1311                    CallExpr::const_arg_iterator ArgEnd) {
1312      CallExpr::const_arg_iterator Arg = ArgBeg;
1313
1314    // First, use the argument types that the type info knows about
1315    if (CallArgTypeInfo) {
1316      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1317           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1318        assert(Arg != ArgEnd && "Running over edge of argument list!");
1319        QualType ArgType = *I;
1320
1321        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1322               getTypePtr() ==
1323               getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1324               "type mismatch in call argument!");
1325
1326        Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1327                                      ArgType));
1328      }
1329
1330      // Either we've emitted all the call args, or we have a call to a
1331      // variadic function.
1332      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1333             "Extra arguments in non-variadic function!");
1334
1335    }
1336
1337    // If we still have any arguments, emit them using the type of the argument.
1338    for (; Arg != ArgEnd; ++Arg) {
1339      QualType ArgType = Arg->getType();
1340      Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1341                                    ArgType));
1342    }
1343  }
1344};
1345
1346
1347}  // end namespace CodeGen
1348}  // end namespace clang
1349
1350#endif
1351