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