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