CodeGenFunction.h revision 203955
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
386  /// CXXVTTDecl - When generating code for a base object constructor or
387  /// base object destructor with virtual bases, this will hold the implicit
388  /// VTT parameter.
389  ImplicitParamDecl *CXXVTTDecl;
390
391  /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
392  struct CXXLiveTemporaryInfo {
393    /// Temporary - The live temporary.
394    const CXXTemporary *Temporary;
395
396    /// ThisPtr - The pointer to the temporary.
397    llvm::Value *ThisPtr;
398
399    /// DtorBlock - The destructor block.
400    llvm::BasicBlock *DtorBlock;
401
402    /// CondPtr - If this is a conditional temporary, this is the pointer to the
403    /// condition variable that states whether the destructor should be called
404    /// or not.
405    llvm::Value *CondPtr;
406
407    CXXLiveTemporaryInfo(const CXXTemporary *temporary,
408                         llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
409                         llvm::Value *condptr)
410      : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
411      CondPtr(condptr) { }
412  };
413
414  llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
415
416  /// ConditionalBranchLevel - Contains the nesting level of the current
417  /// conditional branch. This is used so that we know if a temporary should be
418  /// destroyed conditionally.
419  unsigned ConditionalBranchLevel;
420
421
422  /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
423  /// type as well as the field number that contains the actual data.
424  llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
425                                              unsigned> > ByRefValueInfo;
426
427  /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
428  /// number that holds the value.
429  unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
430
431  llvm::BasicBlock *TerminateHandler;
432  llvm::BasicBlock *TrapBB;
433
434  int UniqueAggrDestructorCount;
435public:
436  CodeGenFunction(CodeGenModule &cgm);
437
438  ASTContext &getContext() const;
439  CGDebugInfo *getDebugInfo() { return DebugInfo; }
440
441  llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
442  void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
443
444  llvm::LLVMContext &getLLVMContext() { return VMContext; }
445
446  //===--------------------------------------------------------------------===//
447  //                                  Objective-C
448  //===--------------------------------------------------------------------===//
449
450  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
451
452  void StartObjCMethod(const ObjCMethodDecl *MD,
453                       const ObjCContainerDecl *CD);
454
455  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
456  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
457                          const ObjCPropertyImplDecl *PID);
458
459  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
460  /// for the given property.
461  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
462                          const ObjCPropertyImplDecl *PID);
463
464  //===--------------------------------------------------------------------===//
465  //                                  Block Bits
466  //===--------------------------------------------------------------------===//
467
468  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
469  llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose,
470                                           CharUnits Size,
471                                           const llvm::StructType *,
472                                           std::vector<HelperInfo> *);
473
474  llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
475                                        const BlockInfo& Info,
476                                        const Decl *OuterFuncDecl,
477                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm,
478                                        CharUnits &Size, CharUnits &Align,
479                      llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
480                                        bool &subBlockHasCopyDispose);
481
482  void BlockForwardSelf();
483  llvm::Value *LoadBlockStruct();
484
485  CharUnits AllocateBlockDecl(const BlockDeclRefExpr *E);
486  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E);
487  const llvm::Type *BuildByRefType(const ValueDecl *D);
488
489  void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
490  void StartFunction(GlobalDecl GD, QualType RetTy,
491                     llvm::Function *Fn,
492                     const FunctionArgList &Args,
493                     SourceLocation StartLoc);
494
495  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
496  /// emission when possible.
497  void EmitReturnBlock();
498
499  /// FinishFunction - Complete IR generation of the current function. It is
500  /// legal to call this function even if there is no current insertion point.
501  void FinishFunction(SourceLocation EndLoc=SourceLocation());
502
503  /// DynamicTypeAdjust - Do the non-virtual and virtual adjustments on an
504  /// object pointer to alter the dynamic type of the pointer.  Used by
505  /// GenerateCovariantThunk for building thunks.
506  llvm::Value *DynamicTypeAdjust(llvm::Value *V,
507                                 const ThunkAdjustment &Adjustment);
508
509  /// GenerateThunk - Generate a thunk for the given method
510  llvm::Constant *GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
511                                bool Extern,
512                                const ThunkAdjustment &ThisAdjustment);
513  llvm::Constant *
514  GenerateCovariantThunk(llvm::Function *Fn, GlobalDecl GD,
515                         bool Extern,
516                         const CovariantThunkAdjustment &Adjustment);
517
518  void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type);
519
520  void InitializeVtablePtrs(const CXXRecordDecl *ClassDecl);
521
522  void InitializeVtablePtrsRecursive(const CXXRecordDecl *ClassDecl,
523                                     llvm::Constant *Vtable,
524                                     CGVtableInfo::AddrSubMap_t& AddressPoints,
525                                     llvm::Value *ThisPtr,
526                                     uint64_t Offset);
527
528  void SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
529                                    CXXCtorType Type,
530                                    llvm::Function *Fn,
531                                    const FunctionArgList &Args);
532
533  void SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
534                                   llvm::Function *Fn,
535                                   const FunctionArgList &Args);
536
537  void SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
538                                    CXXCtorType Type,
539                                    llvm::Function *Fn,
540                                    const FunctionArgList &Args);
541
542  void SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
543                                   CXXDtorType Type,
544                                   llvm::Function *Fn,
545                                   const FunctionArgList &Args);
546
547  /// EmitDtorEpilogue - Emit all code that comes at the end of class's
548  /// destructor. This is to call destructors on members and base classes in
549  /// reverse order of their construction.
550  void EmitDtorEpilogue(const CXXDestructorDecl *Dtor,
551                        CXXDtorType Type);
552
553  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
554  /// arguments for the given function. This is also responsible for naming the
555  /// LLVM function arguments.
556  void EmitFunctionProlog(const CGFunctionInfo &FI,
557                          llvm::Function *Fn,
558                          const FunctionArgList &Args);
559
560  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
561  /// given temporary.
562  void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
563
564  /// EmitStartEHSpec - Emit the start of the exception spec.
565  void EmitStartEHSpec(const Decl *D);
566
567  /// EmitEndEHSpec - Emit the end of the exception spec.
568  void EmitEndEHSpec(const Decl *D);
569
570  /// getTerminateHandler - Return a handler that just calls terminate.
571  llvm::BasicBlock *getTerminateHandler();
572
573  const llvm::Type *ConvertTypeForMem(QualType T);
574  const llvm::Type *ConvertType(QualType T);
575  const llvm::Type *ConvertType(const TypeDecl *T) {
576    return ConvertType(getContext().getTypeDeclType(T));
577  }
578
579  /// LoadObjCSelf - Load the value of self. This function is only valid while
580  /// generating code for an Objective-C method.
581  llvm::Value *LoadObjCSelf();
582
583  /// TypeOfSelfObject - Return type of object that this self represents.
584  QualType TypeOfSelfObject();
585
586  /// hasAggregateLLVMType - Return true if the specified AST type will map into
587  /// an aggregate LLVM type or is void.
588  static bool hasAggregateLLVMType(QualType T);
589
590  /// createBasicBlock - Create an LLVM basic block.
591  llvm::BasicBlock *createBasicBlock(const char *Name="",
592                                     llvm::Function *Parent=0,
593                                     llvm::BasicBlock *InsertBefore=0) {
594#ifdef NDEBUG
595    return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
596#else
597    return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
598#endif
599  }
600
601  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
602  /// label maps to.
603  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
604
605  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
606  /// another basic block, simplify it. This assumes that no other code could
607  /// potentially reference the basic block.
608  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
609
610  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
611  /// adding a fall-through branch from the current insert block if
612  /// necessary. It is legal to call this function even if there is no current
613  /// insertion point.
614  ///
615  /// IsFinished - If true, indicates that the caller has finished emitting
616  /// branches to the given block and does not expect to emit code into it. This
617  /// means the block can be ignored if it is unreachable.
618  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
619
620  /// EmitBranch - Emit a branch to the specified basic block from the current
621  /// insert block, taking care to avoid creation of branches from dummy
622  /// blocks. It is legal to call this function even if there is no current
623  /// insertion point.
624  ///
625  /// This function clears the current insertion point. The caller should follow
626  /// calls to this function with calls to Emit*Block prior to generation new
627  /// code.
628  void EmitBranch(llvm::BasicBlock *Block);
629
630  /// HaveInsertPoint - True if an insertion point is defined. If not, this
631  /// indicates that the current code being emitted is unreachable.
632  bool HaveInsertPoint() const {
633    return Builder.GetInsertBlock() != 0;
634  }
635
636  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
637  /// emitted IR has a place to go. Note that by definition, if this function
638  /// creates a block then that block is unreachable; callers may do better to
639  /// detect when no insertion point is defined and simply skip IR generation.
640  void EnsureInsertPoint() {
641    if (!HaveInsertPoint())
642      EmitBlock(createBasicBlock());
643  }
644
645  /// ErrorUnsupported - Print out an error that codegen doesn't support the
646  /// specified stmt yet.
647  void ErrorUnsupported(const Stmt *S, const char *Type,
648                        bool OmitOnError=false);
649
650  //===--------------------------------------------------------------------===//
651  //                                  Helpers
652  //===--------------------------------------------------------------------===//
653
654  Qualifiers MakeQualifiers(QualType T) {
655    Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
656    Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
657    return Quals;
658  }
659
660  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
661  /// block. The caller is responsible for setting an appropriate alignment on
662  /// the alloca.
663  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
664                                     const llvm::Twine &Name = "tmp");
665
666  /// CreateMemTemp - Create a temporary memory object of the given type, with
667  /// appropriate alignment.
668  llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
669
670  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
671  /// expression and compare the result against zero, returning an Int1Ty value.
672  llvm::Value *EvaluateExprAsBool(const Expr *E);
673
674  /// EmitAnyExpr - Emit code to compute the specified expression which can have
675  /// any type.  The result is returned as an RValue struct.  If this is an
676  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
677  /// the result should be returned.
678  ///
679  /// \param IgnoreResult - True if the resulting value isn't used.
680  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
681                     bool IsAggLocVolatile = false, bool IgnoreResult = false,
682                     bool IsInitializer = false);
683
684  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
685  // or the value of the expression, depending on how va_list is defined.
686  llvm::Value *EmitVAListRef(const Expr *E);
687
688  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
689  /// always be accessible even if no aggregate location is provided.
690  RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
691                           bool IsInitializer = false);
692
693  /// EmitAggregateCopy - Emit an aggrate copy.
694  ///
695  /// \param isVolatile - True iff either the source or the destination is
696  /// volatile.
697  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
698                         QualType EltTy, bool isVolatile=false);
699
700  void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
701
702  /// StartBlock - Start new block named N. If insert block is a dummy block
703  /// then reuse it.
704  void StartBlock(const char *N);
705
706  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
707  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
708
709  /// GetAddrOfLocalVar - Return the address of a local variable.
710  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
711
712  /// getAccessedFieldNo - Given an encoded value and a result number, return
713  /// the input field number being accessed.
714  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
715
716  llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
717  llvm::BasicBlock *GetIndirectGotoBlock();
718
719  /// EmitMemSetToZero - Generate code to memset a value of the given type to 0.
720  void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty);
721
722  // EmitVAArg - Generate code to get an argument from the passed in pointer
723  // and update it accordingly. The return value is a pointer to the argument.
724  // FIXME: We should be able to get rid of this method and use the va_arg
725  // instruction in LLVM instead once it works well enough.
726  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
727
728  /// EmitVLASize - Generate code for any VLA size expressions that might occur
729  /// in a variably modified type. If Ty is a VLA, will return the value that
730  /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
731  ///
732  /// This function can be called with a null (unreachable) insert point.
733  llvm::Value *EmitVLASize(QualType Ty);
734
735  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
736  // of a variable length array type.
737  llvm::Value *GetVLASize(const VariableArrayType *);
738
739  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
740  /// generating code for an C++ member function.
741  llvm::Value *LoadCXXThis();
742
743  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
744  /// virtual bases.
745  llvm::Value *LoadCXXVTT();
746
747  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
748  /// complete class down to one of its virtual bases.
749  llvm::Value *GetAddressOfBaseOfCompleteClass(llvm::Value *Value,
750                                               bool IsVirtual,
751                                               const CXXRecordDecl *Derived,
752                                               const CXXRecordDecl *Base);
753
754  /// GetAddressOfBaseClass - This function will add the necessary delta to the
755  /// load of 'this' and returns address of the base class.
756  llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
757                                     const CXXRecordDecl *ClassDecl,
758                                     const CXXRecordDecl *BaseClassDecl,
759                                     bool NullCheckValue);
760
761  llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
762                                        const CXXRecordDecl *ClassDecl,
763                                        const CXXRecordDecl *DerivedClassDecl,
764                                        bool NullCheckValue);
765
766  llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
767                                         const CXXRecordDecl *ClassDecl,
768                                         const CXXRecordDecl *BaseClassDecl);
769
770  void EmitClassAggrMemberwiseCopy(llvm::Value *DestValue,
771                                   llvm::Value *SrcValue,
772                                   const ArrayType *Array,
773                                   const CXXRecordDecl *BaseClassDecl,
774                                   QualType Ty);
775
776  void EmitClassAggrCopyAssignment(llvm::Value *DestValue,
777                                   llvm::Value *SrcValue,
778                                   const ArrayType *Array,
779                                   const CXXRecordDecl *BaseClassDecl,
780                                   QualType Ty);
781
782  void EmitClassMemberwiseCopy(llvm::Value *DestValue, llvm::Value *SrcValue,
783                               const CXXRecordDecl *ClassDecl,
784                               const CXXRecordDecl *BaseClassDecl,
785                               QualType Ty);
786
787  void EmitClassCopyAssignment(llvm::Value *DestValue, llvm::Value *SrcValue,
788                               const CXXRecordDecl *ClassDecl,
789                               const CXXRecordDecl *BaseClassDecl,
790                               QualType Ty);
791
792  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
793                              llvm::Value *This,
794                              CallExpr::const_arg_iterator ArgBeg,
795                              CallExpr::const_arg_iterator ArgEnd);
796
797  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
798                                  const ConstantArrayType *ArrayTy,
799                                  llvm::Value *ArrayPtr,
800                                  CallExpr::const_arg_iterator ArgBeg,
801                                  CallExpr::const_arg_iterator ArgEnd);
802
803  void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
804                                  llvm::Value *NumElements,
805                                  llvm::Value *ArrayPtr,
806                                  CallExpr::const_arg_iterator ArgBeg,
807                                  CallExpr::const_arg_iterator ArgEnd);
808
809  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
810                                 const ArrayType *Array,
811                                 llvm::Value *This);
812
813  void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
814                                 llvm::Value *NumElements,
815                                 llvm::Value *This);
816
817  llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
818                                                const ArrayType *Array,
819                                                llvm::Value *This);
820
821  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
822                             llvm::Value *This);
823
824  void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
825  void PopCXXTemporary();
826
827  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
828  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
829
830  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
831                      QualType DeleteTy);
832
833  llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
834  llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
835
836  void EmitCheck(llvm::Value *, unsigned Size);
837
838  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
839                                       bool isInc, bool isPre);
840  ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
841                                         bool isInc, bool isPre);
842  //===--------------------------------------------------------------------===//
843  //                            Declaration Emission
844  //===--------------------------------------------------------------------===//
845
846  /// EmitDecl - Emit a declaration.
847  ///
848  /// This function can be called with a null (unreachable) insert point.
849  void EmitDecl(const Decl &D);
850
851  /// EmitBlockVarDecl - Emit a block variable declaration.
852  ///
853  /// This function can be called with a null (unreachable) insert point.
854  void EmitBlockVarDecl(const VarDecl &D);
855
856  /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
857  ///
858  /// This function can be called with a null (unreachable) insert point.
859  void EmitLocalBlockVarDecl(const VarDecl &D);
860
861  void EmitStaticBlockVarDecl(const VarDecl &D,
862                              llvm::GlobalValue::LinkageTypes Linkage);
863
864  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
865  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
866
867  //===--------------------------------------------------------------------===//
868  //                             Statement Emission
869  //===--------------------------------------------------------------------===//
870
871  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
872  void EmitStopPoint(const Stmt *S);
873
874  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
875  /// this function even if there is no current insertion point.
876  ///
877  /// This function may clear the current insertion point; callers should use
878  /// EnsureInsertPoint if they wish to subsequently generate code without first
879  /// calling EmitBlock, EmitBranch, or EmitStmt.
880  void EmitStmt(const Stmt *S);
881
882  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
883  /// necessarily require an insertion point or debug information; typically
884  /// because the statement amounts to a jump or a container of other
885  /// statements.
886  ///
887  /// \return True if the statement was handled.
888  bool EmitSimpleStmt(const Stmt *S);
889
890  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
891                          llvm::Value *AggLoc = 0, bool isAggVol = false);
892
893  /// EmitLabel - Emit the block for the given label. It is legal to call this
894  /// function even if there is no current insertion point.
895  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
896
897  void EmitLabelStmt(const LabelStmt &S);
898  void EmitGotoStmt(const GotoStmt &S);
899  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
900  void EmitIfStmt(const IfStmt &S);
901  void EmitWhileStmt(const WhileStmt &S);
902  void EmitDoStmt(const DoStmt &S);
903  void EmitForStmt(const ForStmt &S);
904  void EmitReturnStmt(const ReturnStmt &S);
905  void EmitDeclStmt(const DeclStmt &S);
906  void EmitBreakStmt(const BreakStmt &S);
907  void EmitContinueStmt(const ContinueStmt &S);
908  void EmitSwitchStmt(const SwitchStmt &S);
909  void EmitDefaultStmt(const DefaultStmt &S);
910  void EmitCaseStmt(const CaseStmt &S);
911  void EmitCaseStmtRange(const CaseStmt &S);
912  void EmitAsmStmt(const AsmStmt &S);
913
914  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
915  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
916  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
917  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
918
919  void EmitCXXTryStmt(const CXXTryStmt &S);
920
921  //===--------------------------------------------------------------------===//
922  //                         LValue Expression Emission
923  //===--------------------------------------------------------------------===//
924
925  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
926  RValue GetUndefRValue(QualType Ty);
927
928  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
929  /// and issue an ErrorUnsupported style diagnostic (using the
930  /// provided Name).
931  RValue EmitUnsupportedRValue(const Expr *E,
932                               const char *Name);
933
934  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
935  /// an ErrorUnsupported style diagnostic (using the provided Name).
936  LValue EmitUnsupportedLValue(const Expr *E,
937                               const char *Name);
938
939  /// EmitLValue - Emit code to compute a designator that specifies the location
940  /// of the expression.
941  ///
942  /// This can return one of two things: a simple address or a bitfield
943  /// reference.  In either case, the LLVM Value* in the LValue structure is
944  /// guaranteed to be an LLVM pointer type.
945  ///
946  /// If this returns a bitfield reference, nothing about the pointee type of
947  /// the LLVM value is known: For example, it may not be a pointer to an
948  /// integer.
949  ///
950  /// If this returns a normal address, and if the lvalue's C type is fixed
951  /// size, this method guarantees that the returned pointer type will point to
952  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
953  /// variable length type, this is not possible.
954  ///
955  LValue EmitLValue(const Expr *E);
956
957  /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
958  /// checking code to guard against undefined behavior.  This is only
959  /// suitable when we know that the address will be used to access the
960  /// object.
961  LValue EmitCheckedLValue(const Expr *E);
962
963  /// EmitLoadOfScalar - Load a scalar value from an address, taking
964  /// care to appropriately convert from the memory representation to
965  /// the LLVM value representation.
966  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
967                                QualType Ty);
968
969  /// EmitStoreOfScalar - Store a scalar value to an address, taking
970  /// care to appropriately convert from the memory representation to
971  /// the LLVM value representation.
972  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
973                         bool Volatile, QualType Ty);
974
975  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
976  /// this method emits the address of the lvalue, then loads the result as an
977  /// rvalue, returning the rvalue.
978  RValue EmitLoadOfLValue(LValue V, QualType LVType);
979  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
980  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
981  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
982  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
983
984
985  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
986  /// lvalue, where both are guaranteed to the have the same type, and that type
987  /// is 'Ty'.
988  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
989  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
990                                                QualType Ty);
991  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
992  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
993
994  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
995  /// EmitStoreThroughLValue.
996  ///
997  /// \param Result [out] - If non-null, this will be set to a Value* for the
998  /// bit-field contents after the store, appropriate for use as the result of
999  /// an assignment to the bit-field.
1000  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1001                                      llvm::Value **Result=0);
1002
1003  // Note: only availabe for agg return types
1004  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1005  // Note: only available for agg return types
1006  LValue EmitCallExprLValue(const CallExpr *E);
1007  // Note: only available for agg return types
1008  LValue EmitVAArgExprLValue(const VAArgExpr *E);
1009  LValue EmitDeclRefLValue(const DeclRefExpr *E);
1010  LValue EmitStringLiteralLValue(const StringLiteral *E);
1011  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1012  LValue EmitPredefinedFunctionName(unsigned Type);
1013  LValue EmitPredefinedLValue(const PredefinedExpr *E);
1014  LValue EmitUnaryOpLValue(const UnaryOperator *E);
1015  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1016  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1017  LValue EmitMemberExpr(const MemberExpr *E);
1018  LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1019  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1020  LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1021  LValue EmitCastLValue(const CastExpr *E);
1022  LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1023
1024  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1025                              const ObjCIvarDecl *Ivar);
1026  LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1027                            unsigned CVRQualifiers);
1028
1029  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1030  /// if the Field is a reference, this will return the address of the reference
1031  /// and not the address of the value stored in the reference.
1032  LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1033                                          const FieldDecl* Field,
1034                                          unsigned CVRQualifiers);
1035
1036  LValue EmitLValueForIvar(QualType ObjectTy,
1037                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
1038                           unsigned CVRQualifiers);
1039
1040  LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1041                                unsigned CVRQualifiers);
1042
1043  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1044
1045  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1046  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1047  LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1048  LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1049
1050  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1051  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1052  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1053  LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1054  LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1055  LValue EmitStmtExprLValue(const StmtExpr *E);
1056  LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1057
1058  //===--------------------------------------------------------------------===//
1059  //                         Scalar Expression Emission
1060  //===--------------------------------------------------------------------===//
1061
1062  /// EmitCall - Generate a call of the given function, expecting the given
1063  /// result type, and using the given argument list which specifies both the
1064  /// LLVM arguments and the types they were derived from.
1065  ///
1066  /// \param TargetDecl - If given, the decl of the function in a direct call;
1067  /// used to set attributes on the call (noreturn, etc.).
1068  RValue EmitCall(const CGFunctionInfo &FnInfo,
1069                  llvm::Value *Callee,
1070                  ReturnValueSlot ReturnValue,
1071                  const CallArgList &Args,
1072                  const Decl *TargetDecl = 0);
1073
1074  RValue EmitCall(QualType FnType, llvm::Value *Callee,
1075                  ReturnValueSlot ReturnValue,
1076                  CallExpr::const_arg_iterator ArgBeg,
1077                  CallExpr::const_arg_iterator ArgEnd,
1078                  const Decl *TargetDecl = 0);
1079  RValue EmitCallExpr(const CallExpr *E,
1080                      ReturnValueSlot ReturnValue = ReturnValueSlot());
1081
1082  llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1083                                const llvm::Type *Ty);
1084  llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1085                                llvm::Value *&This, const llvm::Type *Ty);
1086
1087  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1088                           llvm::Value *Callee,
1089                           ReturnValueSlot ReturnValue,
1090                           llvm::Value *This,
1091                           llvm::Value *VTT,
1092                           CallExpr::const_arg_iterator ArgBeg,
1093                           CallExpr::const_arg_iterator ArgEnd);
1094  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1095                               ReturnValueSlot ReturnValue);
1096  RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1097                                      ReturnValueSlot ReturnValue);
1098
1099  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1100                                       const CXXMethodDecl *MD,
1101                                       ReturnValueSlot ReturnValue);
1102
1103
1104  RValue EmitBuiltinExpr(const FunctionDecl *FD,
1105                         unsigned BuiltinID, const CallExpr *E);
1106
1107  RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1108
1109  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1110  /// is unhandled by the current target.
1111  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1112
1113  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1114  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1115
1116  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1117  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1118  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1119  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
1120  RValue EmitObjCPropertyGet(const Expr *E);
1121  RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S);
1122  void EmitObjCPropertySet(const Expr *E, RValue Src);
1123  void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1124
1125
1126  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1127  /// expression. Will emit a temporary variable if E is not an LValue.
1128  RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false);
1129
1130  //===--------------------------------------------------------------------===//
1131  //                           Expression Emission
1132  //===--------------------------------------------------------------------===//
1133
1134  // Expressions are broken into three classes: scalar, complex, aggregate.
1135
1136  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1137  /// scalar type, returning the result.
1138  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1139
1140  /// EmitScalarConversion - Emit a conversion from the specified type to the
1141  /// specified destination type, both of which are LLVM scalar types.
1142  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1143                                    QualType DstTy);
1144
1145  /// EmitComplexToScalarConversion - Emit a conversion from the specified
1146  /// complex type to the specified destination type, where the destination type
1147  /// is an LLVM scalar type.
1148  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1149                                             QualType DstTy);
1150
1151
1152  /// EmitAggExpr - Emit the computation of the specified expression of
1153  /// aggregate type.  The result is computed into DestPtr.  Note that if
1154  /// DestPtr is null, the value of the aggregate expression is not needed.
1155  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1156                   bool IgnoreResult = false, bool IsInitializer = false,
1157                   bool RequiresGCollection = false);
1158
1159  /// EmitAggExprToLValue - Emit the computation of the specified expression of
1160  /// aggregate type into a temporary LValue.
1161  LValue EmitAggExprToLValue(const Expr *E);
1162
1163  /// EmitGCMemmoveCollectable - Emit special API for structs with object
1164  /// pointers.
1165  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1166                                QualType Ty);
1167
1168  /// EmitComplexExpr - Emit the computation of the specified expression of
1169  /// complex type, returning the result.
1170  ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1171                                bool IgnoreImag = false,
1172                                bool IgnoreRealAssign = false,
1173                                bool IgnoreImagAssign = false);
1174
1175  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1176  /// of complex type, storing into the specified Value*.
1177  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1178                               bool DestIsVolatile);
1179
1180  /// StoreComplexToAddr - Store a complex number into the specified address.
1181  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1182                          bool DestIsVolatile);
1183  /// LoadComplexFromAddr - Load a complex number from the specified address.
1184  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1185
1186  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1187  /// static block var decl.
1188  llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1189                                                 const char *Separator,
1190                                       llvm::GlobalValue::LinkageTypes Linkage);
1191
1192  /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1193  /// global variable that has already been created for it.  If the initializer
1194  /// has a different type than GV does, this may free GV and return a different
1195  /// one.  Otherwise it just returns GV.
1196  llvm::GlobalVariable *
1197  AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1198                                     llvm::GlobalVariable *GV);
1199
1200
1201  /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1202  /// initialized static block var decl.
1203  void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1204                                     llvm::GlobalVariable *GV);
1205
1206  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1207  /// variable with global storage.
1208  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1209
1210  /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1211  /// with the C++ runtime so that its destructor will be called at exit.
1212  void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1213                                     llvm::Constant *DeclPtr);
1214
1215  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1216  /// variables.
1217  void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1218                                 llvm::Constant **Decls,
1219                                 unsigned NumDecls);
1220
1221  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1222
1223  void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1224
1225  RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1226                                    llvm::Value *AggLoc = 0,
1227                                    bool IsAggLocVolatile = false,
1228                                    bool IsInitializer = false);
1229
1230  void EmitCXXThrowExpr(const CXXThrowExpr *E);
1231
1232  //===--------------------------------------------------------------------===//
1233  //                             Internal Helpers
1234  //===--------------------------------------------------------------------===//
1235
1236  /// ContainsLabel - Return true if the statement contains a label in it.  If
1237  /// this statement is not executed normally, it not containing a label means
1238  /// that we can just remove the code.
1239  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1240
1241  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1242  /// to a constant, or if it does but contains a label, return 0.  If it
1243  /// constant folds to 'true' and does not contain a label, return 1, if it
1244  /// constant folds to 'false' and does not contain a label, return -1.
1245  int ConstantFoldsToSimpleInteger(const Expr *Cond);
1246
1247  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1248  /// if statement) to the specified blocks.  Based on the condition, this might
1249  /// try to simplify the codegen of the conditional based on the branch.
1250  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1251                            llvm::BasicBlock *FalseBlock);
1252
1253  /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1254  /// generate a branch around the created basic block as necessary.
1255  llvm::BasicBlock* getTrapBB();
1256private:
1257
1258  void EmitReturnOfRValue(RValue RV, QualType Ty);
1259
1260  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1261  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1262  ///
1263  /// \param AI - The first function argument of the expansion.
1264  /// \return The argument following the last expanded function
1265  /// argument.
1266  llvm::Function::arg_iterator
1267  ExpandTypeFromArgs(QualType Ty, LValue Dst,
1268                     llvm::Function::arg_iterator AI);
1269
1270  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1271  /// Ty, into individual arguments on the provided vector \arg Args. See
1272  /// ABIArgInfo::Expand.
1273  void ExpandTypeToArgs(QualType Ty, RValue Src,
1274                        llvm::SmallVector<llvm::Value*, 16> &Args);
1275
1276  llvm::Value* EmitAsmInput(const AsmStmt &S,
1277                            const TargetInfo::ConstraintInfo &Info,
1278                            const Expr *InputExpr, std::string &ConstraintStr);
1279
1280  /// EmitCleanupBlock - emits a single cleanup block.
1281  void EmitCleanupBlock();
1282
1283  /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1284  /// current cleanup scope.
1285  void AddBranchFixup(llvm::BranchInst *BI);
1286
1287  /// EmitCallArg - Emit a single call argument.
1288  RValue EmitCallArg(const Expr *E, QualType ArgType);
1289
1290  /// EmitCallArgs - Emit call arguments for a function.
1291  /// The CallArgTypeInfo parameter is used for iterating over the known
1292  /// argument types of the function being called.
1293  template<typename T>
1294  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1295                    CallExpr::const_arg_iterator ArgBeg,
1296                    CallExpr::const_arg_iterator ArgEnd) {
1297      CallExpr::const_arg_iterator Arg = ArgBeg;
1298
1299    // First, use the argument types that the type info knows about
1300    if (CallArgTypeInfo) {
1301      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1302           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1303        assert(Arg != ArgEnd && "Running over edge of argument list!");
1304        QualType ArgType = *I;
1305
1306        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1307               getTypePtr() ==
1308               getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1309               "type mismatch in call argument!");
1310
1311        Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1312                                      ArgType));
1313      }
1314
1315      // Either we've emitted all the call args, or we have a call to a
1316      // variadic function.
1317      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1318             "Extra arguments in non-variadic function!");
1319
1320    }
1321
1322    // If we still have any arguments, emit them using the type of the argument.
1323    for (; Arg != ArgEnd; ++Arg) {
1324      QualType ArgType = Arg->getType();
1325      Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1326                                    ArgType));
1327    }
1328  }
1329};
1330
1331
1332}  // end namespace CodeGen
1333}  // end namespace clang
1334
1335#endif
1336