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