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 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   //===--------------------------------------------------------------------===//
811   //                            Declaration Emission
812   //===--------------------------------------------------------------------===//
813 
814   /// EmitDecl - Emit a declaration.
815   ///
816   /// This function can be called with a null (unreachable) insert point.
817   void EmitDecl(const Decl &D);
818 
819   /// EmitBlockVarDecl - Emit a block variable declaration.
820   ///
821   /// This function can be called with a null (unreachable) insert point.
822   void EmitBlockVarDecl(const VarDecl &D);
823 
824   /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
825   ///
826   /// This function can be called with a null (unreachable) insert point.
827   void EmitLocalBlockVarDecl(const VarDecl &D);
828 
829   void EmitStaticBlockVarDecl(const VarDecl &D);
830 
831   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
832   void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
833 
834   //===--------------------------------------------------------------------===//
835   //                             Statement Emission
836   //===--------------------------------------------------------------------===//
837 
838   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
839   void EmitStopPoint(const Stmt *S);
840 
841   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
842   /// this function even if there is no current insertion point.
843   ///
844   /// This function may clear the current insertion point; callers should use
845   /// EnsureInsertPoint if they wish to subsequently generate code without first
846   /// calling EmitBlock, EmitBranch, or EmitStmt.
847   void EmitStmt(const Stmt *S);
848 
849   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
850   /// necessarily require an insertion point or debug information; typically
851   /// because the statement amounts to a jump or a container of other
852   /// statements.
853   ///
854   /// \return True if the statement was handled.
855   bool EmitSimpleStmt(const Stmt *S);
856 
857   RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
858                           llvm::Value *AggLoc = 0, bool isAggVol = false);
859 
860   /// EmitLabel - Emit the block for the given label. It is legal to call this
861   /// function even if there is no current insertion point.
862   void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
863 
864   void EmitLabelStmt(const LabelStmt &S);
865   void EmitGotoStmt(const GotoStmt &S);
866   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
867   void EmitIfStmt(const IfStmt &S);
868   void EmitWhileStmt(const WhileStmt &S);
869   void EmitDoStmt(const DoStmt &S);
870   void EmitForStmt(const ForStmt &S);
871   void EmitReturnStmt(const ReturnStmt &S);
872   void EmitDeclStmt(const DeclStmt &S);
873   void EmitBreakStmt(const BreakStmt &S);
874   void EmitContinueStmt(const ContinueStmt &S);
875   void EmitSwitchStmt(const SwitchStmt &S);
876   void EmitDefaultStmt(const DefaultStmt &S);
877   void EmitCaseStmt(const CaseStmt &S);
878   void EmitCaseStmtRange(const CaseStmt &S);
879   void EmitAsmStmt(const AsmStmt &S);
880 
881   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
882   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
883   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
884   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
885 
886   void EmitCXXTryStmt(const CXXTryStmt &S);
887 
888   //===--------------------------------------------------------------------===//
889   //                         LValue Expression Emission
890   //===--------------------------------------------------------------------===//
891 
892   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
893   RValue GetUndefRValue(QualType Ty);
894 
895   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
896   /// and issue an ErrorUnsupported style diagnostic (using the
897   /// provided Name).
898   RValue EmitUnsupportedRValue(const Expr *E,
899                                const char *Name);
900 
901   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
902   /// an ErrorUnsupported style diagnostic (using the provided Name).
903   LValue EmitUnsupportedLValue(const Expr *E,
904                                const char *Name);
905 
906   /// EmitLValue - Emit code to compute a designator that specifies the location
907   /// of the expression.
908   ///
909   /// This can return one of two things: a simple address or a bitfield
910   /// reference.  In either case, the LLVM Value* in the LValue structure is
911   /// guaranteed to be an LLVM pointer type.
912   ///
913   /// If this returns a bitfield reference, nothing about the pointee type of
914   /// the LLVM value is known: For example, it may not be a pointer to an
915   /// integer.
916   ///
917   /// If this returns a normal address, and if the lvalue's C type is fixed
918   /// size, this method guarantees that the returned pointer type will point to
919   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
920   /// variable length type, this is not possible.
921   ///
922   LValue EmitLValue(const Expr *E);
923 
924   /// EmitLoadOfScalar - Load a scalar value from an address, taking
925   /// care to appropriately convert from the memory representation to
926   /// the LLVM value representation.
927   llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
928                                 QualType Ty);
929 
930   /// EmitStoreOfScalar - Store a scalar value to an address, taking
931   /// care to appropriately convert from the memory representation to
932   /// the LLVM value representation.
933   void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
934                          bool Volatile, QualType Ty);
935 
936   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
937   /// this method emits the address of the lvalue, then loads the result as an
938   /// rvalue, returning the rvalue.
939   RValue EmitLoadOfLValue(LValue V, QualType LVType);
940   RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
941   RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
942   RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
943   RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
944 
945 
946   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
947   /// lvalue, where both are guaranteed to the have the same type, and that type
948   /// is 'Ty'.
949   void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
950   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
951                                                 QualType Ty);
952   void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
953   void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
954 
955   /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
956   /// EmitStoreThroughLValue.
957   ///
958   /// \param Result [out] - If non-null, this will be set to a Value* for the
959   /// bit-field contents after the store, appropriate for use as the result of
960   /// an assignment to the bit-field.
961   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
962                                       llvm::Value **Result=0);
963 
964   // Note: only availabe for agg return types
965   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
966   // Note: only available for agg return types
967   LValue EmitCallExprLValue(const CallExpr *E);
968   // Note: only available for agg return types
969   LValue EmitVAArgExprLValue(const VAArgExpr *E);
970   LValue EmitDeclRefLValue(const DeclRefExpr *E);
971   LValue EmitStringLiteralLValue(const StringLiteral *E);
972   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
973   LValue EmitPredefinedFunctionName(unsigned Type);
974   LValue EmitPredefinedLValue(const PredefinedExpr *E);
975   LValue EmitUnaryOpLValue(const UnaryOperator *E);
976   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
977   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
978   LValue EmitMemberExpr(const MemberExpr *E);
979   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
980   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
981   LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
982   LValue EmitCastLValue(const CastExpr *E);
983   LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
984 
985   LValue EmitPointerToDataMemberLValue(const FieldDecl *Field);
986 
987   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
988                               const ObjCIvarDecl *Ivar);
989   LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
990                             bool isUnion, unsigned CVRQualifiers);
991   LValue EmitLValueForIvar(QualType ObjectTy,
992                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
993                            unsigned CVRQualifiers);
994 
995   LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
996                                 unsigned CVRQualifiers);
997 
998   LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
999 
1000   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1001   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1002   LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1003   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1004 
1005   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1006   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1007   LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1008   LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1009   LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1010   LValue EmitStmtExprLValue(const StmtExpr *E);
1011   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1012 
1013   //===--------------------------------------------------------------------===//
1014   //                         Scalar Expression Emission
1015   //===--------------------------------------------------------------------===//
1016 
1017   /// EmitCall - Generate a call of the given function, expecting the given
1018   /// result type, and using the given argument list which specifies both the
1019   /// LLVM arguments and the types they were derived from.
1020   ///
1021   /// \param TargetDecl - If given, the decl of the function in a direct call;
1022   /// used to set attributes on the call (noreturn, etc.).
1023   RValue EmitCall(const CGFunctionInfo &FnInfo,
1024                   llvm::Value *Callee,
1025                   const CallArgList &Args,
1026                   const Decl *TargetDecl = 0);
1027 
1028   RValue EmitCall(llvm::Value *Callee, QualType FnType,
1029                   CallExpr::const_arg_iterator ArgBeg,
1030                   CallExpr::const_arg_iterator ArgEnd,
1031                   const Decl *TargetDecl = 0);
1032   RValue EmitCallExpr(const CallExpr *E);
1033 
1034   llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1035                                 const llvm::Type *Ty);
1036   llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1037                                 llvm::Value *&This, const llvm::Type *Ty);
1038 
1039   RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1040                            llvm::Value *Callee,
1041                            llvm::Value *This,
1042                            CallExpr::const_arg_iterator ArgBeg,
1043                            CallExpr::const_arg_iterator ArgEnd);
1044   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E);
1045   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E);
1046 
1047   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1048                                        const CXXMethodDecl *MD);
1049 
1050 
1051   RValue EmitBuiltinExpr(const FunctionDecl *FD,
1052                          unsigned BuiltinID, const CallExpr *E);
1053 
1054   RValue EmitBlockCallExpr(const CallExpr *E);
1055 
1056   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1057   /// is unhandled by the current target.
1058   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1059 
1060   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1061   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1062 
1063   llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...);
1064   llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals,
1065                           bool isSplat = false);
1066 
1067   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1068   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1069   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1070   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
1071   RValue EmitObjCPropertyGet(const Expr *E);
1072   RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S);
1073   void EmitObjCPropertySet(const Expr *E, RValue Src);
1074   void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1075 
1076 
1077   /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1078   /// expression. Will emit a temporary variable if E is not an LValue.
1079   RValue EmitReferenceBindingToExpr(const Expr* E, QualType DestType,
1080                                     bool IsInitializer = false);
1081 
1082   //===--------------------------------------------------------------------===//
1083   //                           Expression Emission
1084   //===--------------------------------------------------------------------===//
1085 
1086   // Expressions are broken into three classes: scalar, complex, aggregate.
1087 
1088   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1089   /// scalar type, returning the result.
1090   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1091 
1092   /// EmitScalarConversion - Emit a conversion from the specified type to the
1093   /// specified destination type, both of which are LLVM scalar types.
1094   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1095                                     QualType DstTy);
1096 
1097   /// EmitComplexToScalarConversion - Emit a conversion from the specified
1098   /// complex type to the specified destination type, where the destination type
1099   /// is an LLVM scalar type.
1100   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1101                                              QualType DstTy);
1102 
1103 
1104   /// EmitAggExpr - Emit the computation of the specified expression of
1105   /// aggregate type.  The result is computed into DestPtr.  Note that if
1106   /// DestPtr is null, the value of the aggregate expression is not needed.
1107   void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1108                    bool IgnoreResult = false, bool IsInitializer = false,
1109                    bool RequiresGCollection = false);
1110 
1111   /// EmitGCMemmoveCollectable - Emit special API for structs with object
1112   /// pointers.
1113   void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1114                                 QualType Ty);
1115 
1116   /// EmitComplexExpr - Emit the computation of the specified expression of
1117   /// complex type, returning the result.
1118   ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1119                                 bool IgnoreImag = false,
1120                                 bool IgnoreRealAssign = false,
1121                                 bool IgnoreImagAssign = false);
1122 
1123   /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1124   /// of complex type, storing into the specified Value*.
1125   void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1126                                bool DestIsVolatile);
1127 
1128   /// StoreComplexToAddr - Store a complex number into the specified address.
1129   void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1130                           bool DestIsVolatile);
1131   /// LoadComplexFromAddr - Load a complex number from the specified address.
1132   ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1133 
1134   /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1135   /// static block var decl.
1136   llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1137                                                  const char *Separator,
1138                                        llvm::GlobalValue::LinkageTypes Linkage);
1139 
1140   /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1141   /// global variable that has already been created for it.  If the initializer
1142   /// has a different type than GV does, this may free GV and return a different
1143   /// one.  Otherwise it just returns GV.
1144   llvm::GlobalVariable *
1145   AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1146                                      llvm::GlobalVariable *GV);
1147 
1148 
1149   /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1150   /// initialized static block var decl.
1151   void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1152                                      llvm::GlobalVariable *GV);
1153 
1154   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1155   /// variable with global storage.
1156   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1157 
1158   /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1159   /// with the C++ runtime so that its destructor will be called at exit.
1160   void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1161                                      llvm::Constant *DeclPtr);
1162 
1163   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1164   /// variables.
1165   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1166                                  const VarDecl **Decls,
1167                                  unsigned NumDecls);
1168 
1169   void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1170 
1171   RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1172                                     llvm::Value *AggLoc = 0,
1173                                     bool IsAggLocVolatile = false,
1174                                     bool IsInitializer = false);
1175 
1176   void EmitCXXThrowExpr(const CXXThrowExpr *E);
1177 
1178   //===--------------------------------------------------------------------===//
1179   //                             Internal Helpers
1180   //===--------------------------------------------------------------------===//
1181 
1182   /// ContainsLabel - Return true if the statement contains a label in it.  If
1183   /// this statement is not executed normally, it not containing a label means
1184   /// that we can just remove the code.
1185   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1186 
1187   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1188   /// to a constant, or if it does but contains a label, return 0.  If it
1189   /// constant folds to 'true' and does not contain a label, return 1, if it
1190   /// constant folds to 'false' and does not contain a label, return -1.
1191   int ConstantFoldsToSimpleInteger(const Expr *Cond);
1192 
1193   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1194   /// if statement) to the specified blocks.  Based on the condition, this might
1195   /// try to simplify the codegen of the conditional based on the branch.
1196   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1197                             llvm::BasicBlock *FalseBlock);
1198 
1199   /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1200   /// generate a branch around the created basic block as necessary.
1201   llvm::BasicBlock* getTrapBB();
1202 private:
1203 
1204   void EmitReturnOfRValue(RValue RV, QualType Ty);
1205 
1206   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1207   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1208   ///
1209   /// \param AI - The first function argument of the expansion.
1210   /// \return The argument following the last expanded function
1211   /// argument.
1212   llvm::Function::arg_iterator
1213   ExpandTypeFromArgs(QualType Ty, LValue Dst,
1214                      llvm::Function::arg_iterator AI);
1215 
1216   /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1217   /// Ty, into individual arguments on the provided vector \arg Args. See
1218   /// ABIArgInfo::Expand.
1219   void ExpandTypeToArgs(QualType Ty, RValue Src,
1220                         llvm::SmallVector<llvm::Value*, 16> &Args);
1221 
1222   llvm::Value* EmitAsmInput(const AsmStmt &S,
1223                             const TargetInfo::ConstraintInfo &Info,
1224                             const Expr *InputExpr, std::string &ConstraintStr);
1225 
1226   /// EmitCleanupBlock - emits a single cleanup block.
1227   void EmitCleanupBlock();
1228 
1229   /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1230   /// current cleanup scope.
1231   void AddBranchFixup(llvm::BranchInst *BI);
1232 
1233   /// EmitCallArg - Emit a single call argument.
1234   RValue EmitCallArg(const Expr *E, QualType ArgType);
1235 
1236   /// EmitCallArgs - Emit call arguments for a function.
1237   /// The CallArgTypeInfo parameter is used for iterating over the known
1238   /// argument types of the function being called.
1239   template<typename T>
1240   void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1241                     CallExpr::const_arg_iterator ArgBeg,
1242                     CallExpr::const_arg_iterator ArgEnd) {
1243       CallExpr::const_arg_iterator Arg = ArgBeg;
1244 
1245     // First, use the argument types that the type info knows about
1246     if (CallArgTypeInfo) {
1247       for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1248            E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1249         assert(Arg != ArgEnd && "Running over edge of argument list!");
1250         QualType ArgType = *I;
1251 
1252         assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1253                getTypePtr() ==
1254                getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1255                "type mismatch in call argument!");
1256 
1257         Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1258                                       ArgType));
1259       }
1260 
1261       // Either we've emitted all the call args, or we have a call to a
1262       // variadic function.
1263       assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1264              "Extra arguments in non-variadic function!");
1265 
1266     }
1267 
1268     // If we still have any arguments, emit them using the type of the argument.
1269     for (; Arg != ArgEnd; ++Arg) {
1270       QualType ArgType = Arg->getType();
1271       Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1272                                     ArgType));
1273     }
1274   }
1275 };
1276 
1277 
1278 }  // end namespace CodeGen
1279 }  // end namespace clang
1280 
1281 #endif
1282