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