CodeGenFunction.h revision 6d0bdaa68989bee60c85274e82a8f9c982587f26
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  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
228  // enter/leave scopes.
229  llvm::DenseMap<const VariableArrayType*, llvm::Value*> VLASizeMap;
230
231  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
232  /// calling llvm.stacksave for multiple VLAs in the same scope.
233  bool DidCallStackSave;
234
235  struct CleanupEntry {
236    /// CleanupBlock - The block of code that does the actual cleanup.
237    llvm::BasicBlock *CleanupBlock;
238
239    /// Blocks - Basic blocks that were emitted in the current cleanup scope.
240    std::vector<llvm::BasicBlock *> Blocks;
241
242    /// BranchFixups - Branch instructions to basic blocks that haven't been
243    /// inserted into the current function yet.
244    std::vector<llvm::BranchInst *> BranchFixups;
245
246    explicit CleanupEntry(llvm::BasicBlock *cb)
247      : CleanupBlock(cb) {}
248  };
249
250  /// CleanupEntries - Stack of cleanup entries.
251  llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
252
253  typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
254
255  /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
256  BlockScopeMap BlockScopes;
257
258  /// CXXThisDecl - When parsing an C++ function, this will hold the implicit
259  /// 'this' declaration.
260  ImplicitParamDecl *CXXThisDecl;
261
262  /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
263  struct CXXLiveTemporaryInfo {
264    /// Temporary - The live temporary.
265    const CXXTemporary *Temporary;
266
267    /// ThisPtr - The pointer to the temporary.
268    llvm::Value *ThisPtr;
269
270    /// DtorBlock - The destructor block.
271    llvm::BasicBlock *DtorBlock;
272
273    /// CondPtr - If this is a conditional temporary, this is the pointer to
274    /// the condition variable that states whether the destructor should be
275    /// called or not.
276    llvm::Value *CondPtr;
277
278    CXXLiveTemporaryInfo(const CXXTemporary *temporary,
279                         llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
280                         llvm::Value *condptr)
281      : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
282      CondPtr(condptr) { }
283  };
284
285  llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
286
287  /// ConditionalTempDestructionStack - Contains the number of live temporaries
288  /// when PushConditionalTempDestruction was called. This is used so that
289  /// we know how many temporaries were created by a certain expression.
290  llvm::SmallVector<size_t, 4> ConditionalTempDestructionStack;
291
292public:
293  CodeGenFunction(CodeGenModule &cgm);
294
295  ASTContext &getContext() const;
296  CGDebugInfo *getDebugInfo() { return DebugInfo; }
297
298  llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
299  void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
300
301  llvm::LLVMContext &getLLVMContext() { return VMContext; }
302
303  //===--------------------------------------------------------------------===//
304  //                                  Objective-C
305  //===--------------------------------------------------------------------===//
306
307  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
308
309  void StartObjCMethod(const ObjCMethodDecl *MD,
310                       const ObjCContainerDecl *CD);
311
312  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
313  void GenerateObjCGetter(ObjCImplementationDecl *IMP,
314                          const ObjCPropertyImplDecl *PID);
315
316  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
317  /// for the given property.
318  void GenerateObjCSetter(ObjCImplementationDecl *IMP,
319                          const ObjCPropertyImplDecl *PID);
320
321  //===--------------------------------------------------------------------===//
322  //                                  Block Bits
323  //===--------------------------------------------------------------------===//
324
325  llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
326  llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose,
327                                           uint64_t Size,
328                                           const llvm::StructType *,
329                                           std::vector<HelperInfo> *);
330
331  llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
332                                        const BlockInfo& Info,
333                                        const Decl *OuterFuncDecl,
334                                  llvm::DenseMap<const Decl*, llvm::Value*> ldm,
335                                        uint64_t &Size, uint64_t &Align,
336                      llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
337                                        bool &subBlockHasCopyDispose);
338
339  void BlockForwardSelf();
340  llvm::Value *LoadBlockStruct();
341
342  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E);
343
344  const llvm::Type *BuildByRefType(QualType Ty, uint64_t Align);
345
346  void GenerateCode(const FunctionDecl *FD,
347                    llvm::Function *Fn);
348  void StartFunction(const Decl *D, QualType RetTy,
349                     llvm::Function *Fn,
350                     const FunctionArgList &Args,
351                     SourceLocation StartLoc);
352
353  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
354  /// emission when possible.
355  void EmitReturnBlock();
356
357  /// FinishFunction - Complete IR generation of the current function. It is
358  /// legal to call this function even if there is no current insertion point.
359  void FinishFunction(SourceLocation EndLoc=SourceLocation());
360
361  void EmitCtorPrologue(const CXXConstructorDecl *CD);
362
363  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
364  /// arguments for the given function. This is also responsible for naming the
365  /// LLVM function arguments.
366  void EmitFunctionProlog(const CGFunctionInfo &FI,
367                          llvm::Function *Fn,
368                          const FunctionArgList &Args);
369
370  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
371  /// given temporary.
372  void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
373
374  const llvm::Type *ConvertTypeForMem(QualType T);
375  const llvm::Type *ConvertType(QualType T);
376
377  /// LoadObjCSelf - Load the value of self. This function is only valid while
378  /// generating code for an Objective-C method.
379  llvm::Value *LoadObjCSelf();
380
381  /// TypeOfSelfObject - Return type of object that this self represents.
382  QualType TypeOfSelfObject();
383
384  /// hasAggregateLLVMType - Return true if the specified AST type will map into
385  /// an aggregate LLVM type or is void.
386  static bool hasAggregateLLVMType(QualType T);
387
388  /// createBasicBlock - Create an LLVM basic block.
389  llvm::BasicBlock *createBasicBlock(const char *Name="",
390                                     llvm::Function *Parent=0,
391                                     llvm::BasicBlock *InsertBefore=0) {
392#ifdef NDEBUG
393    return llvm::BasicBlock::Create("", Parent, InsertBefore);
394#else
395    return llvm::BasicBlock::Create(Name, Parent, InsertBefore);
396#endif
397  }
398
399  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
400  /// label maps to.
401  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
402
403  /// SimplifyForwardingBlocks - If the given basic block is only a
404  /// branch to another basic block, simplify it. This assumes that no
405  /// other code could potentially reference the basic block.
406  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
407
408  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
409  /// adding a fall-through branch from the current insert block if
410  /// necessary. It is legal to call this function even if there is no current
411  /// insertion point.
412  ///
413  /// IsFinished - If true, indicates that the caller has finished emitting
414  /// branches to the given block and does not expect to emit code into it. This
415  /// means the block can be ignored if it is unreachable.
416  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
417
418  /// EmitBranch - Emit a branch to the specified basic block from the current
419  /// insert block, taking care to avoid creation of branches from dummy
420  /// blocks. It is legal to call this function even if there is no current
421  /// insertion point.
422  ///
423  /// This function clears the current insertion point. The caller should follow
424  /// calls to this function with calls to Emit*Block prior to generation new
425  /// code.
426  void EmitBranch(llvm::BasicBlock *Block);
427
428  /// HaveInsertPoint - True if an insertion point is defined. If not, this
429  /// indicates that the current code being emitted is unreachable.
430  bool HaveInsertPoint() const {
431    return Builder.GetInsertBlock() != 0;
432  }
433
434  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
435  /// emitted IR has a place to go. Note that by definition, if this function
436  /// creates a block then that block is unreachable; callers may do better to
437  /// detect when no insertion point is defined and simply skip IR generation.
438  void EnsureInsertPoint() {
439    if (!HaveInsertPoint())
440      EmitBlock(createBasicBlock());
441  }
442
443  /// ErrorUnsupported - Print out an error that codegen doesn't support the
444  /// specified stmt yet.
445  void ErrorUnsupported(const Stmt *S, const char *Type,
446                        bool OmitOnError=false);
447
448  //===--------------------------------------------------------------------===//
449  //                                  Helpers
450  //===--------------------------------------------------------------------===//
451
452  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
453  /// block.
454  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
455                                     const char *Name = "tmp");
456
457  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
458  /// expression and compare the result against zero, returning an Int1Ty value.
459  llvm::Value *EvaluateExprAsBool(const Expr *E);
460
461  /// EmitAnyExpr - Emit code to compute the specified expression which can have
462  /// any type.  The result is returned as an RValue struct.  If this is an
463  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
464  /// the result should be returned.
465  ///
466  /// \param IgnoreResult - True if the resulting value isn't used.
467  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
468                     bool isAggLocVolatile = false, bool IgnoreResult = false);
469
470  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
471  // or the value of the expression, depending on how va_list is defined.
472  llvm::Value *EmitVAListRef(const Expr *E);
473
474  /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
475  /// always be accessible even if no aggregate location is provided.
476  RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0,
477                           bool isAggLocVolatile = false);
478
479  /// EmitAggregateCopy - Emit an aggrate copy.
480  ///
481  /// \param isVolatile - True iff either the source or the destination is
482  /// volatile.
483  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
484                         QualType EltTy, bool isVolatile=false);
485
486  void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
487
488  /// StartBlock - Start new block named N. If insert block is a dummy block
489  /// then reuse it.
490  void StartBlock(const char *N);
491
492  /// getCGRecordLayout - Return record layout info.
493  const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy);
494
495  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
496  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
497
498  /// GetAddrOfLocalVar - Return the address of a local variable.
499  llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
500
501  /// getAccessedFieldNo - Given an encoded value and a result number, return
502  /// the input field number being accessed.
503  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
504
505  unsigned GetIDForAddrOfLabel(const LabelStmt *L);
506
507  /// EmitMemSetToZero - Generate code to memset a value of the given type to 0.
508  void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty);
509
510  // EmitVAArg - Generate code to get an argument from the passed in pointer
511  // and update it accordingly. The return value is a pointer to the argument.
512  // FIXME: We should be able to get rid of this method and use the va_arg
513  // instruction in LLVM instead once it works well enough.
514  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
515
516  // EmitVLASize - Generate code for any VLA size expressions that might occur
517  // in a variably modified type. If Ty is a VLA, will return the value that
518  // corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
519  ///
520  /// This function can be called with a null (unreachable) insert point.
521  llvm::Value *EmitVLASize(QualType Ty);
522
523  // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
524  // of a variable length array type.
525  llvm::Value *GetVLASize(const VariableArrayType *);
526
527  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
528  /// generating code for an C++ member function.
529  llvm::Value *LoadCXXThis();
530
531  /// AddressCXXOfBaseClass - This function will add the necessary delta
532  /// to the load of 'this' and returns address of the base class.
533  // FIXME. This currently only does a derived to non-virtual base conversion.
534  // Other kinds of conversions will come later.
535  llvm::Value *AddressCXXOfBaseClass(llvm::Value *ThisValue,
536                                     const CXXRecordDecl *ClassDecl,
537                                     const CXXRecordDecl *BaseClassDecl);
538
539  void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
540                              llvm::Value *This,
541                              CallExpr::const_arg_iterator ArgBeg,
542                              CallExpr::const_arg_iterator ArgEnd);
543
544  void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
545                             llvm::Value *This);
546
547  void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
548  void PopCXXTemporary();
549
550  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
551
552  //===--------------------------------------------------------------------===//
553  //                            Declaration Emission
554  //===--------------------------------------------------------------------===//
555
556  /// EmitDecl - Emit a declaration.
557  ///
558  /// This function can be called with a null (unreachable) insert point.
559  void EmitDecl(const Decl &D);
560
561  /// EmitBlockVarDecl - Emit a block variable declaration.
562  ///
563  /// This function can be called with a null (unreachable) insert point.
564  void EmitBlockVarDecl(const VarDecl &D);
565
566  /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
567  ///
568  /// This function can be called with a null (unreachable) insert point.
569  void EmitLocalBlockVarDecl(const VarDecl &D);
570
571  void EmitStaticBlockVarDecl(const VarDecl &D);
572
573  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
574  void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
575
576  //===--------------------------------------------------------------------===//
577  //                             Statement Emission
578  //===--------------------------------------------------------------------===//
579
580  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
581  void EmitStopPoint(const Stmt *S);
582
583  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
584  /// this function even if there is no current insertion point.
585  ///
586  /// This function may clear the current insertion point; callers should use
587  /// EnsureInsertPoint if they wish to subsequently generate code without first
588  /// calling EmitBlock, EmitBranch, or EmitStmt.
589  void EmitStmt(const Stmt *S);
590
591  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
592  /// necessarily require an insertion point or debug information; typically
593  /// because the statement amounts to a jump or a container of other
594  /// statements.
595  ///
596  /// \return True if the statement was handled.
597  bool EmitSimpleStmt(const Stmt *S);
598
599  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
600                          llvm::Value *AggLoc = 0, bool isAggVol = false);
601
602  /// EmitLabel - Emit the block for the given label. It is legal to call this
603  /// function even if there is no current insertion point.
604  void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
605
606  void EmitLabelStmt(const LabelStmt &S);
607  void EmitGotoStmt(const GotoStmt &S);
608  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
609  void EmitIfStmt(const IfStmt &S);
610  void EmitWhileStmt(const WhileStmt &S);
611  void EmitDoStmt(const DoStmt &S);
612  void EmitForStmt(const ForStmt &S);
613  void EmitReturnStmt(const ReturnStmt &S);
614  void EmitDeclStmt(const DeclStmt &S);
615  void EmitBreakStmt(const BreakStmt &S);
616  void EmitContinueStmt(const ContinueStmt &S);
617  void EmitSwitchStmt(const SwitchStmt &S);
618  void EmitDefaultStmt(const DefaultStmt &S);
619  void EmitCaseStmt(const CaseStmt &S);
620  void EmitCaseStmtRange(const CaseStmt &S);
621  void EmitAsmStmt(const AsmStmt &S);
622
623  void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
624  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
625  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
626  void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
627
628  //===--------------------------------------------------------------------===//
629  //                         LValue Expression Emission
630  //===--------------------------------------------------------------------===//
631
632  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
633  RValue GetUndefRValue(QualType Ty);
634
635  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
636  /// and issue an ErrorUnsupported style diagnostic (using the
637  /// provided Name).
638  RValue EmitUnsupportedRValue(const Expr *E,
639                               const char *Name);
640
641  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
642  /// an ErrorUnsupported style diagnostic (using the provided Name).
643  LValue EmitUnsupportedLValue(const Expr *E,
644                               const char *Name);
645
646  /// EmitLValue - Emit code to compute a designator that specifies the location
647  /// of the expression.
648  ///
649  /// This can return one of two things: a simple address or a bitfield
650  /// reference.  In either case, the LLVM Value* in the LValue structure is
651  /// guaranteed to be an LLVM pointer type.
652  ///
653  /// If this returns a bitfield reference, nothing about the pointee type of
654  /// the LLVM value is known: For example, it may not be a pointer to an
655  /// integer.
656  ///
657  /// If this returns a normal address, and if the lvalue's C type is fixed
658  /// size, this method guarantees that the returned pointer type will point to
659  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
660  /// variable length type, this is not possible.
661  ///
662  LValue EmitLValue(const Expr *E);
663
664  /// EmitLoadOfScalar - Load a scalar value from an address, taking
665  /// care to appropriately convert from the memory representation to
666  /// the LLVM value representation.
667  llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
668                                QualType Ty);
669
670  /// EmitStoreOfScalar - Store a scalar value to an address, taking
671  /// care to appropriately convert from the memory representation to
672  /// the LLVM value representation.
673  void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
674                         bool Volatile, QualType Ty);
675
676  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
677  /// this method emits the address of the lvalue, then loads the result as an
678  /// rvalue, returning the rvalue.
679  RValue EmitLoadOfLValue(LValue V, QualType LVType);
680  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
681  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
682  RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
683  RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
684
685
686  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
687  /// lvalue, where both are guaranteed to the have the same type, and that type
688  /// is 'Ty'.
689  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
690  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
691                                                QualType Ty);
692  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
693  void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
694
695  /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
696  /// EmitStoreThroughLValue.
697  ///
698  /// \param Result [out] - If non-null, this will be set to a Value* for the
699  /// bit-field contents after the store, appropriate for use as the result of
700  /// an assignment to the bit-field.
701  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
702                                      llvm::Value **Result=0);
703
704  // Note: only availabe for agg return types
705  LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
706  // Note: only available for agg return types
707  LValue EmitCallExprLValue(const CallExpr *E);
708  // Note: only available for agg return types
709  LValue EmitVAArgExprLValue(const VAArgExpr *E);
710  LValue EmitDeclRefLValue(const DeclRefExpr *E);
711  LValue EmitStringLiteralLValue(const StringLiteral *E);
712  LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
713  LValue EmitPredefinedFunctionName(unsigned Type);
714  LValue EmitPredefinedLValue(const PredefinedExpr *E);
715  LValue EmitUnaryOpLValue(const UnaryOperator *E);
716  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
717  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
718  LValue EmitMemberExpr(const MemberExpr *E);
719  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
720  LValue EmitConditionalOperator(const ConditionalOperator *E);
721  LValue EmitCastLValue(const CastExpr *E);
722
723  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
724                              const ObjCIvarDecl *Ivar);
725  LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field,
726                            bool isUnion, unsigned CVRQualifiers);
727  LValue EmitLValueForIvar(QualType ObjectTy,
728                           llvm::Value* Base, const ObjCIvarDecl *Ivar,
729                           unsigned CVRQualifiers);
730
731  LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field,
732                                unsigned CVRQualifiers);
733
734  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
735
736  LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E);
737  LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
738  LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
739
740  LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
741  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
742  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
743  LValue EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E);
744  LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
745  LValue EmitStmtExprLValue(const StmtExpr *E);
746
747  //===--------------------------------------------------------------------===//
748  //                         Scalar Expression Emission
749  //===--------------------------------------------------------------------===//
750
751  /// EmitCall - Generate a call of the given function, expecting the given
752  /// result type, and using the given argument list which specifies both the
753  /// LLVM arguments and the types they were derived from.
754  ///
755  /// \param TargetDecl - If given, the decl of the function in a
756  /// direct call; used to set attributes on the call (noreturn,
757  /// etc.).
758  RValue EmitCall(const CGFunctionInfo &FnInfo,
759                  llvm::Value *Callee,
760                  const CallArgList &Args,
761                  const Decl *TargetDecl = 0);
762
763  RValue EmitCall(llvm::Value *Callee, QualType FnType,
764                  CallExpr::const_arg_iterator ArgBeg,
765                  CallExpr::const_arg_iterator ArgEnd,
766                  const Decl *TargetDecl = 0);
767  RValue EmitCallExpr(const CallExpr *E);
768
769  RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
770                           llvm::Value *Callee,
771                           llvm::Value *This,
772                           CallExpr::const_arg_iterator ArgBeg,
773                           CallExpr::const_arg_iterator ArgEnd);
774  RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E);
775
776  RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
777                                       const CXXMethodDecl *MD);
778
779  RValue EmitBuiltinExpr(const FunctionDecl *FD,
780                         unsigned BuiltinID, const CallExpr *E);
781
782  RValue EmitBlockCallExpr(const CallExpr *E);
783
784  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
785  /// is unhandled by the current target.
786  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
787
788  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
789  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
790
791  llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...);
792  llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals,
793                          bool isSplat = false);
794
795  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
796  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
797  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
798  RValue EmitObjCMessageExpr(const ObjCMessageExpr *E);
799  RValue EmitObjCPropertyGet(const Expr *E);
800  RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S);
801  void EmitObjCPropertySet(const Expr *E, RValue Src);
802  void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
803
804
805  /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
806  /// expression. Will emit a temporary variable if E is not an LValue.
807  RValue EmitReferenceBindingToExpr(const Expr* E, QualType DestType);
808
809  //===--------------------------------------------------------------------===//
810  //                           Expression Emission
811  //===--------------------------------------------------------------------===//
812
813  // Expressions are broken into three classes: scalar, complex, aggregate.
814
815  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
816  /// scalar type, returning the result.
817  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign=false);
818
819  /// EmitScalarConversion - Emit a conversion from the specified type to the
820  /// specified destination type, both of which are LLVM scalar types.
821  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
822                                    QualType DstTy);
823
824  /// EmitComplexToScalarConversion - Emit a conversion from the specified
825  /// complex type to the specified destination type, where the destination type
826  /// is an LLVM scalar type.
827  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
828                                             QualType DstTy);
829
830
831  /// EmitAggExpr - Emit the computation of the specified expression of
832  /// aggregate type.  The result is computed into DestPtr.  Note that if
833  /// DestPtr is null, the value of the aggregate expression is not needed.
834  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
835                   bool IgnoreResult = false);
836
837  /// EmitGCMemmoveCollectable - Emit special API for structs with object
838  /// pointers.
839  void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
840                                unsigned long);
841
842  /// EmitComplexExpr - Emit the computation of the specified expression of
843  /// complex type, returning the result.
844  ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
845                                bool IgnoreImag = false,
846                                bool IgnoreRealAssign = false,
847                                bool IgnoreImagAssign = false);
848
849  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
850  /// of complex type, storing into the specified Value*.
851  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
852                               bool DestIsVolatile);
853
854  /// StoreComplexToAddr - Store a complex number into the specified address.
855  void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
856                          bool DestIsVolatile);
857  /// LoadComplexFromAddr - Load a complex number from the specified address.
858  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
859
860  /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global
861  /// for a static block var decl.
862  llvm::GlobalVariable * CreateStaticBlockVarDecl(const VarDecl &D,
863                                                  const char *Separator,
864                                                  llvm::GlobalValue::LinkageTypes
865                                                  Linkage);
866
867  /// GenerateStaticCXXBlockVarDecl - Create the initializer for a C++
868  /// runtime initialized static block var decl.
869  void GenerateStaticCXXBlockVarDeclInit(const VarDecl &D,
870                                         llvm::GlobalVariable *GV);
871
872  void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
873
874  RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
875                                    llvm::Value *AggLoc = 0,
876                                    bool isAggLocVolatile = false);
877
878  //===--------------------------------------------------------------------===//
879  //                             Internal Helpers
880  //===--------------------------------------------------------------------===//
881
882  /// ContainsLabel - Return true if the statement contains a label in it.  If
883  /// this statement is not executed normally, it not containing a label means
884  /// that we can just remove the code.
885  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
886
887  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
888  /// to a constant, or if it does but contains a label, return 0.  If it
889  /// constant folds to 'true' and does not contain a label, return 1, if it
890  /// constant folds to 'false' and does not contain a label, return -1.
891  int ConstantFoldsToSimpleInteger(const Expr *Cond);
892
893  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
894  /// if statement) to the specified blocks.  Based on the condition, this might
895  /// try to simplify the codegen of the conditional based on the branch.
896  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
897                            llvm::BasicBlock *FalseBlock);
898private:
899
900  /// EmitIndirectSwitches - Emit code for all of the switch
901  /// instructions in IndirectSwitches.
902  void EmitIndirectSwitches();
903
904  void EmitReturnOfRValue(RValue RV, QualType Ty);
905
906  /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
907  /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
908  ///
909  /// \param AI - The first function argument of the expansion.
910  /// \return The argument following the last expanded function
911  /// argument.
912  llvm::Function::arg_iterator
913  ExpandTypeFromArgs(QualType Ty, LValue Dst,
914                     llvm::Function::arg_iterator AI);
915
916  /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
917  /// Ty, into individual arguments on the provided vector \arg Args. See
918  /// ABIArgInfo::Expand.
919  void ExpandTypeToArgs(QualType Ty, RValue Src,
920                        llvm::SmallVector<llvm::Value*, 16> &Args);
921
922  llvm::Value* EmitAsmInput(const AsmStmt &S,
923                            const TargetInfo::ConstraintInfo &Info,
924                            const Expr *InputExpr, std::string &ConstraintStr);
925
926  /// EmitCleanupBlock - emits a single cleanup block.
927  void EmitCleanupBlock();
928
929  /// AddBranchFixup - adds a branch instruction to the list of fixups for the
930  /// current cleanup scope.
931  void AddBranchFixup(llvm::BranchInst *BI);
932
933  /// EmitCallArg - Emit a single call argument.
934  RValue EmitCallArg(const Expr *E, QualType ArgType);
935
936  /// EmitCallArgs - Emit call arguments for a function.
937  /// The CallArgTypeInfo parameter is used for iterating over the known
938  /// argument types of the function being called.
939  template<typename T>
940  void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
941                    CallExpr::const_arg_iterator ArgBeg,
942                    CallExpr::const_arg_iterator ArgEnd) {
943      CallExpr::const_arg_iterator Arg = ArgBeg;
944
945    // First, use the argument types that the type info knows about
946    if (CallArgTypeInfo) {
947      for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
948           E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
949        QualType ArgType = *I;
950
951        assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
952               getTypePtr() ==
953               getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
954               "type mismatch in call argument!");
955
956        Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
957                                      ArgType));
958      }
959
960      // Either we've emitted all the call args, or we have a call to a
961      // variadic function.
962      assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
963             "Extra arguments in non-variadic function!");
964
965    }
966
967    // If we still have any arguments, emit them using the type of the argument.
968    for (; Arg != ArgEnd; ++Arg) {
969      QualType ArgType = Arg->getType();
970      Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
971                                    ArgType));
972    }
973  }
974};
975
976
977}  // end namespace CodeGen
978}  // end namespace clang
979
980#endif
981