CodeGenFunction.h revision 4111024be81e7c0525e42dadcc126d27e5bf2425
1//===--- CodeGenFunction.h - Per-Function state for LLVM CodeGen ----------===//
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 "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/IRBuilder.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprObjC.h"
23
24#include <vector>
25
26namespace llvm {
27  class Module;
28}
29
30namespace clang {
31  class ASTContext;
32  class Decl;
33  class FunctionDecl;
34  class ObjCMethodDecl;
35  class TargetInfo;
36  class FunctionTypeProto;
37
38namespace CodeGen {
39  class CodeGenModule;
40  class CodeGenTypes;
41  class CGRecordLayout;
42
43/// RValue - This trivial value class is used to represent the result of an
44/// expression that is evaluated.  It can be one of three things: either a
45/// simple LLVM SSA value, a pair of SSA values for complex numbers, or the
46/// address of an aggregate value in memory.
47class RValue {
48  llvm::Value *V1, *V2;
49  // TODO: Encode this into the low bit of pointer for more efficient
50  // return-by-value.
51  enum { Scalar, Complex, Aggregate } Flavor;
52
53  // FIXME: Aggregate rvalues need to retain information about whether they are
54  // volatile or not.
55public:
56
57  bool isScalar() const { return Flavor == Scalar; }
58  bool isComplex() const { return Flavor == Complex; }
59  bool isAggregate() const { return Flavor == Aggregate; }
60
61  /// getScalar() - Return the Value* of this scalar value.
62  llvm::Value *getScalarVal() const {
63    assert(isScalar() && "Not a scalar!");
64    return V1;
65  }
66
67  /// getComplexVal - Return the real/imag components of this complex value.
68  ///
69  std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
70    return std::pair<llvm::Value *, llvm::Value *>(V1, V2);
71  }
72
73  /// getAggregateAddr() - Return the Value* of the address of the aggregate.
74  llvm::Value *getAggregateAddr() const {
75    assert(isAggregate() && "Not an aggregate!");
76    return V1;
77  }
78
79  static RValue get(llvm::Value *V) {
80    RValue ER;
81    ER.V1 = V;
82    ER.Flavor = Scalar;
83    return ER;
84  }
85  static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
86    RValue ER;
87    ER.V1 = V1;
88    ER.V2 = V2;
89    ER.Flavor = Complex;
90    return ER;
91  }
92  static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
93    RValue ER;
94    ER.V1 = C.first;
95    ER.V2 = C.second;
96    ER.Flavor = Complex;
97    return ER;
98  }
99  static RValue getAggregate(llvm::Value *V) {
100    RValue ER;
101    ER.V1 = V;
102    ER.Flavor = Aggregate;
103    return ER;
104  }
105};
106
107
108/// LValue - This represents an lvalue references.  Because C/C++ allow
109/// bitfields, this is not a simple LLVM pointer, it may be a pointer plus a
110/// bitrange.
111class LValue {
112  // FIXME: alignment?
113
114  enum {
115    Simple,       // This is a normal l-value, use getAddress().
116    VectorElt,    // This is a vector element l-value (V[i]), use getVector*
117    BitField,     // This is a bitfield l-value, use getBitfield*.
118    ExtVectorElt  // This is an extended vector subset, use getExtVectorComp
119  } LVType;
120
121  llvm::Value *V;
122
123  union {
124    // Index into a vector subscript: V[i]
125    llvm::Value *VectorIdx;
126
127    // ExtVector element subset: V.xyx
128    llvm::Constant *VectorElts;
129
130    struct {
131      unsigned short StartBit;
132      unsigned short Size;
133      bool IsSigned;
134    } BitfieldData;           // BitField start bit and size
135  };
136
137  bool Volatile:1;
138  // FIXME: set but never used, what effect should it have?
139  bool Restrict:1;
140
141private:
142  static void SetQualifiers(unsigned Qualifiers, LValue& R) {
143    R.Volatile = (Qualifiers&QualType::Volatile)!=0;
144    R.Restrict = (Qualifiers&QualType::Restrict)!=0;
145  }
146
147public:
148  bool isSimple() const { return LVType == Simple; }
149  bool isVectorElt() const { return LVType == VectorElt; }
150  bool isBitfield() const { return LVType == BitField; }
151  bool isExtVectorElt() const { return LVType == ExtVectorElt; }
152
153  bool isVolatileQualified() const { return Volatile; }
154  bool isRestrictQualified() const { return Restrict; }
155
156  // simple lvalue
157  llvm::Value *getAddress() const { assert(isSimple()); return V; }
158  // vector elt lvalue
159  llvm::Value *getVectorAddr() const { assert(isVectorElt()); return V; }
160  llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
161  // extended vector elements.
162  llvm::Value *getExtVectorAddr() const { assert(isExtVectorElt()); return V; }
163  llvm::Constant *getExtVectorElts() const {
164    assert(isExtVectorElt());
165    return VectorElts;
166  }
167  // bitfield lvalue
168  llvm::Value *getBitfieldAddr() const { assert(isBitfield()); return V; }
169  unsigned short getBitfieldStartBit() const {
170    assert(isBitfield());
171    return BitfieldData.StartBit;
172  }
173  unsigned short getBitfieldSize() const {
174    assert(isBitfield());
175    return BitfieldData.Size;
176  }
177  bool isBitfieldSigned() const {
178    assert(isBitfield());
179    return BitfieldData.IsSigned;
180  }
181
182  static LValue MakeAddr(llvm::Value *V, unsigned Qualifiers) {
183    LValue R;
184    R.LVType = Simple;
185    R.V = V;
186    SetQualifiers(Qualifiers,R);
187    return R;
188  }
189
190  static LValue MakeVectorElt(llvm::Value *Vec, llvm::Value *Idx,
191                              unsigned Qualifiers) {
192    LValue R;
193    R.LVType = VectorElt;
194    R.V = Vec;
195    R.VectorIdx = Idx;
196    SetQualifiers(Qualifiers,R);
197    return R;
198  }
199
200  static LValue MakeExtVectorElt(llvm::Value *Vec, llvm::Constant *Elts,
201                                 unsigned Qualifiers) {
202    LValue R;
203    R.LVType = ExtVectorElt;
204    R.V = Vec;
205    R.VectorElts = Elts;
206    SetQualifiers(Qualifiers,R);
207    return R;
208  }
209
210  static LValue MakeBitfield(llvm::Value *V, unsigned short StartBit,
211                             unsigned short Size, bool IsSigned,
212                             unsigned Qualifiers) {
213    LValue R;
214    R.LVType = BitField;
215    R.V = V;
216    R.BitfieldData.StartBit = StartBit;
217    R.BitfieldData.Size = Size;
218    R.BitfieldData.IsSigned = IsSigned;
219    SetQualifiers(Qualifiers,R);
220    return R;
221  }
222};
223
224/// CodeGenFunction - This class organizes the per-function state that is used
225/// while generating LLVM code.
226class CodeGenFunction {
227public:
228  CodeGenModule &CGM;  // Per-module state.
229  TargetInfo &Target;
230
231  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
232  llvm::IRBuilder Builder;
233
234  // Holds the Decl for the current function or method
235  const Decl *CurFuncDecl;
236  QualType FnRetTy;
237  llvm::Function *CurFn;
238
239  /// AllocaInsertPoint - This is an instruction in the entry block before which
240  /// we prefer to insert allocas.
241  llvm::Instruction *AllocaInsertPt;
242
243  const llvm::Type *LLVMIntTy;
244  uint32_t LLVMPointerWidth;
245
246private:
247  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
248  /// decls.
249  llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
250
251  /// LabelMap - This keeps track of the LLVM basic block for each C label.
252  llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
253
254  // BreakContinueStack - This keeps track of where break and continue
255  // statements should jump to.
256  struct BreakContinue {
257    BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
258      : BreakBlock(bb), ContinueBlock(cb) {}
259
260    llvm::BasicBlock *BreakBlock;
261    llvm::BasicBlock *ContinueBlock;
262  };
263  llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
264
265  /// SwitchInsn - This is nearest current switch instruction. It is null if
266  /// if current context is not in a switch.
267  llvm::SwitchInst *SwitchInsn;
268
269  /// CaseRangeBlock - This block holds if condition check for last case
270  /// statement range in current switch instruction.
271  llvm::BasicBlock *CaseRangeBlock;
272
273public:
274  CodeGenFunction(CodeGenModule &cgm);
275
276  ASTContext &getContext() const;
277
278  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
279  void GenerateCode(const FunctionDecl *FD);
280  void GenerateFunction(const Stmt *Body);
281
282  const llvm::Type *ConvertType(QualType T);
283
284  llvm::Value *LoadObjCSelf();
285
286  /// isObjCPointerType - Return true if the specificed AST type will map onto
287  /// some Objective-C pointer type.
288  static bool isObjCPointerType(QualType T);
289
290  /// hasAggregateLLVMType - Return true if the specified AST type will map into
291  /// an aggregate LLVM type or is void.
292  static bool hasAggregateLLVMType(QualType T);
293
294  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
295  /// label maps to.
296  llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
297
298
299  void EmitBlock(llvm::BasicBlock *BB);
300
301  /// WarnUnsupported - Print out a warning that codegen doesn't support the
302  /// specified stmt yet.
303  void WarnUnsupported(const Stmt *S, const char *Type);
304
305  //===--------------------------------------------------------------------===//
306  //                                  Helpers
307  //===--------------------------------------------------------------------===//
308
309  /// CreateTempAlloca - This creates a alloca and inserts it into the entry
310  /// block.
311  llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
312                                     const char *Name = "tmp");
313
314  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
315  /// expression and compare the result against zero, returning an Int1Ty value.
316  llvm::Value *EvaluateExprAsBool(const Expr *E);
317
318  /// EmitAnyExpr - Emit code to compute the specified expression which can have
319  /// any type.  The result is returned as an RValue struct.  If this is an
320  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
321  /// the result should be returned.
322  RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
323                     bool isAggLocVolatile = false);
324
325  /// isDummyBlock - Return true if BB is an empty basic block
326  /// with no predecessors.
327  static bool isDummyBlock(const llvm::BasicBlock *BB);
328
329  /// StartBlock - Start new block named N. If insert block is a dummy block
330  /// then reuse it.
331  void StartBlock(const char *N);
332
333  /// getCGRecordLayout - Return record layout info.
334  const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy);
335
336  /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
337  llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
338
339  /// getAccessedFieldNo - Given an encoded value and a result number, return
340  /// the input field number being accessed.
341  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
342
343  //===--------------------------------------------------------------------===//
344  //                            Declaration Emission
345  //===--------------------------------------------------------------------===//
346
347  void EmitDecl(const Decl &D);
348  void EmitEnumConstantDecl(const EnumConstantDecl &D);
349  void EmitBlockVarDecl(const VarDecl &D);
350  void EmitLocalBlockVarDecl(const VarDecl &D);
351  void EmitStaticBlockVarDecl(const VarDecl &D);
352  void EmitParmDecl(const ParmVarDecl &D, llvm::Value *Arg);
353
354  //===--------------------------------------------------------------------===//
355  //                             Statement Emission
356  //===--------------------------------------------------------------------===//
357
358  void EmitStmt(const Stmt *S);
359  RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
360                          llvm::Value *AggLoc = 0, bool isAggVol = false);
361  void EmitLabelStmt(const LabelStmt &S);
362  void EmitGotoStmt(const GotoStmt &S);
363  void EmitIfStmt(const IfStmt &S);
364  void EmitWhileStmt(const WhileStmt &S);
365  void EmitDoStmt(const DoStmt &S);
366  void EmitForStmt(const ForStmt &S);
367  void EmitReturnStmt(const ReturnStmt &S);
368  void EmitDeclStmt(const DeclStmt &S);
369  void EmitBreakStmt();
370  void EmitContinueStmt();
371  void EmitSwitchStmt(const SwitchStmt &S);
372  void EmitDefaultStmt(const DefaultStmt &S);
373  void EmitCaseStmt(const CaseStmt &S);
374  void EmitCaseStmtRange(const CaseStmt &S);
375  void EmitAsmStmt(const AsmStmt &S);
376
377  //===--------------------------------------------------------------------===//
378  //                         LValue Expression Emission
379  //===--------------------------------------------------------------------===//
380
381  /// EmitLValue - Emit code to compute a designator that specifies the location
382  /// of the expression.
383  ///
384  /// This can return one of two things: a simple address or a bitfield
385  /// reference.  In either case, the LLVM Value* in the LValue structure is
386  /// guaranteed to be an LLVM pointer type.
387  ///
388  /// If this returns a bitfield reference, nothing about the pointee type of
389  /// the LLVM value is known: For example, it may not be a pointer to an
390  /// integer.
391  ///
392  /// If this returns a normal address, and if the lvalue's C type is fixed
393  /// size, this method guarantees that the returned pointer type will point to
394  /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
395  /// variable length type, this is not possible.
396  ///
397  LValue EmitLValue(const Expr *E);
398
399  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
400  /// this method emits the address of the lvalue, then loads the result as an
401  /// rvalue, returning the rvalue.
402  RValue EmitLoadOfLValue(LValue V, QualType LVType);
403  RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
404  RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
405
406
407  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
408  /// lvalue, where both are guaranteed to the have the same type, and that type
409  /// is 'Ty'.
410  void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
411  void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
412                                                QualType Ty);
413  void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty);
414
415  // Note: only availabe for agg return types
416  LValue EmitCallExprLValue(const CallExpr *E);
417
418  LValue EmitDeclRefLValue(const DeclRefExpr *E);
419  LValue EmitStringLiteralLValue(const StringLiteral *E);
420  LValue EmitPreDefinedLValue(const PreDefinedExpr *E);
421  LValue EmitUnaryOpLValue(const UnaryOperator *E);
422  LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
423  LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
424  LValue EmitMemberExpr(const MemberExpr *E);
425  LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
426
427  LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field,
428                            bool isUnion, unsigned CVRQualifiers);
429
430  LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
431  //===--------------------------------------------------------------------===//
432  //                         Scalar Expression Emission
433  //===--------------------------------------------------------------------===//
434
435  RValue EmitCallExpr(const CallExpr *E);
436
437  RValue EmitCallExpr(Expr *FnExpr, CallExpr::const_arg_iterator ArgBeg,
438                      CallExpr::const_arg_iterator ArgEnd);
439
440  RValue EmitCallExpr(llvm::Value *Callee, QualType FnType,
441                      CallExpr::const_arg_iterator ArgBeg,
442                      CallExpr::const_arg_iterator ArgEnd);
443
444  RValue EmitBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
445
446  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
447  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
448
449  llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...);
450  llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals,
451                          bool isSplat = false);
452
453  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
454
455  //===--------------------------------------------------------------------===//
456  //                           Expression Emission
457  //===--------------------------------------------------------------------===//
458
459  // Expressions are broken into three classes: scalar, complex, aggregate.
460
461  /// EmitScalarExpr - Emit the computation of the specified expression of
462  /// LLVM scalar type, returning the result.
463  llvm::Value *EmitScalarExpr(const Expr *E);
464
465  /// EmitScalarConversion - Emit a conversion from the specified type to the
466  /// specified destination type, both of which are LLVM scalar types.
467  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
468                                    QualType DstTy);
469
470  /// EmitComplexToScalarConversion - Emit a conversion from the specified
471  /// complex type to the specified destination type, where the destination
472  /// type is an LLVM scalar type.
473  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
474                                             QualType DstTy);
475
476
477  /// EmitAggExpr - Emit the computation of the specified expression of
478  /// aggregate type.  The result is computed into DestPtr.  Note that if
479  /// DestPtr is null, the value of the aggregate expression is not needed.
480  void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest);
481
482  /// EmitComplexExpr - Emit the computation of the specified expression of
483  /// complex type, returning the result.
484  ComplexPairTy EmitComplexExpr(const Expr *E);
485
486  /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
487  /// of complex type, storing into the specified Value*.
488  void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
489                               bool DestIsVolatile);
490  /// LoadComplexFromAddr - Load a complex number from the specified address.
491  ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
492
493  /// GenerateStaticBlockVarDecl - return the the static
494  /// declaration of local variable.
495  llvm::GlobalValue *GenerateStaticBlockVarDecl(const VarDecl &D,
496                                                bool NoInit,
497                                                const char *Separator);
498};
499}  // end namespace CodeGen
500}  // end namespace clang
501
502#endif
503