Home | History | Annotate | Download | only in CodeGen
      1 //===-- CGValue.h - LLVM CodeGen wrappers for llvm::Value* ------*- 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 // These classes implement wrappers around llvm::Value in order to
     11 // fully represent the range of values for C L- and R- values.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
     16 #define LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
     17 
     18 #include "clang/AST/ASTContext.h"
     19 #include "clang/AST/Type.h"
     20 #include "llvm/IR/Value.h"
     21 #include "llvm/IR/Type.h"
     22 #include "Address.h"
     23 
     24 namespace llvm {
     25   class Constant;
     26   class MDNode;
     27 }
     28 
     29 namespace clang {
     30 namespace CodeGen {
     31   class AggValueSlot;
     32   struct CGBitFieldInfo;
     33 
     34 /// RValue - This trivial value class is used to represent the result of an
     35 /// expression that is evaluated.  It can be one of three things: either a
     36 /// simple LLVM SSA value, a pair of SSA values for complex numbers, or the
     37 /// address of an aggregate value in memory.
     38 class RValue {
     39   enum Flavor { Scalar, Complex, Aggregate };
     40 
     41   // The shift to make to an aggregate's alignment to make it look
     42   // like a pointer.
     43   enum { AggAlignShift = 4 };
     44 
     45   // Stores first value and flavor.
     46   llvm::PointerIntPair<llvm::Value *, 2, Flavor> V1;
     47   // Stores second value and volatility.
     48   llvm::PointerIntPair<llvm::Value *, 1, bool> V2;
     49 
     50 public:
     51   bool isScalar() const { return V1.getInt() == Scalar; }
     52   bool isComplex() const { return V1.getInt() == Complex; }
     53   bool isAggregate() const { return V1.getInt() == Aggregate; }
     54 
     55   bool isVolatileQualified() const { return V2.getInt(); }
     56 
     57   /// getScalarVal() - Return the Value* of this scalar value.
     58   llvm::Value *getScalarVal() const {
     59     assert(isScalar() && "Not a scalar!");
     60     return V1.getPointer();
     61   }
     62 
     63   /// getComplexVal - Return the real/imag components of this complex value.
     64   ///
     65   std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
     66     return std::make_pair(V1.getPointer(), V2.getPointer());
     67   }
     68 
     69   /// getAggregateAddr() - Return the Value* of the address of the aggregate.
     70   Address getAggregateAddress() const {
     71     assert(isAggregate() && "Not an aggregate!");
     72     auto align = reinterpret_cast<uintptr_t>(V2.getPointer()) >> AggAlignShift;
     73     return Address(V1.getPointer(), CharUnits::fromQuantity(align));
     74   }
     75   llvm::Value *getAggregatePointer() const {
     76     assert(isAggregate() && "Not an aggregate!");
     77     return V1.getPointer();
     78   }
     79 
     80   static RValue getIgnored() {
     81     // FIXME: should we make this a more explicit state?
     82     return get(nullptr);
     83   }
     84 
     85   static RValue get(llvm::Value *V) {
     86     RValue ER;
     87     ER.V1.setPointer(V);
     88     ER.V1.setInt(Scalar);
     89     ER.V2.setInt(false);
     90     return ER;
     91   }
     92   static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
     93     RValue ER;
     94     ER.V1.setPointer(V1);
     95     ER.V2.setPointer(V2);
     96     ER.V1.setInt(Complex);
     97     ER.V2.setInt(false);
     98     return ER;
     99   }
    100   static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
    101     return getComplex(C.first, C.second);
    102   }
    103   // FIXME: Aggregate rvalues need to retain information about whether they are
    104   // volatile or not.  Remove default to find all places that probably get this
    105   // wrong.
    106   static RValue getAggregate(Address addr, bool isVolatile = false) {
    107     RValue ER;
    108     ER.V1.setPointer(addr.getPointer());
    109     ER.V1.setInt(Aggregate);
    110 
    111     auto align = static_cast<uintptr_t>(addr.getAlignment().getQuantity());
    112     ER.V2.setPointer(reinterpret_cast<llvm::Value*>(align << AggAlignShift));
    113     ER.V2.setInt(isVolatile);
    114     return ER;
    115   }
    116 };
    117 
    118 /// Does an ARC strong l-value have precise lifetime?
    119 enum ARCPreciseLifetime_t {
    120   ARCImpreciseLifetime, ARCPreciseLifetime
    121 };
    122 
    123 /// The source of the alignment of an l-value; an expression of
    124 /// confidence in the alignment actually matching the estimate.
    125 enum class AlignmentSource {
    126   /// The l-value was an access to a declared entity or something
    127   /// equivalently strong, like the address of an array allocated by a
    128   /// language runtime.
    129   Decl,
    130 
    131   /// The l-value was considered opaque, so the alignment was
    132   /// determined from a type, but that type was an explicitly-aligned
    133   /// typedef.
    134   AttributedType,
    135 
    136   /// The l-value was considered opaque, so the alignment was
    137   /// determined from a type.
    138   Type
    139 };
    140 
    141 /// Given that the base address has the given alignment source, what's
    142 /// our confidence in the alignment of the field?
    143 static inline AlignmentSource getFieldAlignmentSource(AlignmentSource Source) {
    144   // For now, we don't distinguish fields of opaque pointers from
    145   // top-level declarations, but maybe we should.
    146   return AlignmentSource::Decl;
    147 }
    148 
    149 /// LValue - This represents an lvalue references.  Because C/C++ allow
    150 /// bitfields, this is not a simple LLVM pointer, it may be a pointer plus a
    151 /// bitrange.
    152 class LValue {
    153   enum {
    154     Simple,       // This is a normal l-value, use getAddress().
    155     VectorElt,    // This is a vector element l-value (V[i]), use getVector*
    156     BitField,     // This is a bitfield l-value, use getBitfield*.
    157     ExtVectorElt, // This is an extended vector subset, use getExtVectorComp
    158     GlobalReg     // This is a register l-value, use getGlobalReg()
    159   } LVType;
    160 
    161   llvm::Value *V;
    162 
    163   union {
    164     // Index into a vector subscript: V[i]
    165     llvm::Value *VectorIdx;
    166 
    167     // ExtVector element subset: V.xyx
    168     llvm::Constant *VectorElts;
    169 
    170     // BitField start bit and size
    171     const CGBitFieldInfo *BitFieldInfo;
    172   };
    173 
    174   QualType Type;
    175 
    176   // 'const' is unused here
    177   Qualifiers Quals;
    178 
    179   // The alignment to use when accessing this lvalue.  (For vector elements,
    180   // this is the alignment of the whole vector.)
    181   int64_t Alignment;
    182 
    183   // objective-c's ivar
    184   bool Ivar:1;
    185 
    186   // objective-c's ivar is an array
    187   bool ObjIsArray:1;
    188 
    189   // LValue is non-gc'able for any reason, including being a parameter or local
    190   // variable.
    191   bool NonGC: 1;
    192 
    193   // Lvalue is a global reference of an objective-c object
    194   bool GlobalObjCRef : 1;
    195 
    196   // Lvalue is a thread local reference
    197   bool ThreadLocalRef : 1;
    198 
    199   // Lvalue has ARC imprecise lifetime.  We store this inverted to try
    200   // to make the default bitfield pattern all-zeroes.
    201   bool ImpreciseLifetime : 1;
    202 
    203   unsigned AlignSource : 2;
    204 
    205   // This flag shows if a nontemporal load/stores should be used when accessing
    206   // this lvalue.
    207   bool Nontemporal : 1;
    208 
    209   Expr *BaseIvarExp;
    210 
    211   /// Used by struct-path-aware TBAA.
    212   QualType TBAABaseType;
    213   /// Offset relative to the base type.
    214   uint64_t TBAAOffset;
    215 
    216   /// TBAAInfo - TBAA information to attach to dereferences of this LValue.
    217   llvm::MDNode *TBAAInfo;
    218 
    219 private:
    220   void Initialize(QualType Type, Qualifiers Quals,
    221                   CharUnits Alignment, AlignmentSource AlignSource,
    222                   llvm::MDNode *TBAAInfo = nullptr) {
    223     assert((!Alignment.isZero() || Type->isIncompleteType()) &&
    224            "initializing l-value with zero alignment!");
    225     this->Type = Type;
    226     this->Quals = Quals;
    227     this->Alignment = Alignment.getQuantity();
    228     assert(this->Alignment == Alignment.getQuantity() &&
    229            "Alignment exceeds allowed max!");
    230     this->AlignSource = unsigned(AlignSource);
    231 
    232     // Initialize Objective-C flags.
    233     this->Ivar = this->ObjIsArray = this->NonGC = this->GlobalObjCRef = false;
    234     this->ImpreciseLifetime = false;
    235     this->Nontemporal = false;
    236     this->ThreadLocalRef = false;
    237     this->BaseIvarExp = nullptr;
    238 
    239     // Initialize fields for TBAA.
    240     this->TBAABaseType = Type;
    241     this->TBAAOffset = 0;
    242     this->TBAAInfo = TBAAInfo;
    243   }
    244 
    245 public:
    246   bool isSimple() const { return LVType == Simple; }
    247   bool isVectorElt() const { return LVType == VectorElt; }
    248   bool isBitField() const { return LVType == BitField; }
    249   bool isExtVectorElt() const { return LVType == ExtVectorElt; }
    250   bool isGlobalReg() const { return LVType == GlobalReg; }
    251 
    252   bool isVolatileQualified() const { return Quals.hasVolatile(); }
    253   bool isRestrictQualified() const { return Quals.hasRestrict(); }
    254   unsigned getVRQualifiers() const {
    255     return Quals.getCVRQualifiers() & ~Qualifiers::Const;
    256   }
    257 
    258   QualType getType() const { return Type; }
    259 
    260   Qualifiers::ObjCLifetime getObjCLifetime() const {
    261     return Quals.getObjCLifetime();
    262   }
    263 
    264   bool isObjCIvar() const { return Ivar; }
    265   void setObjCIvar(bool Value) { Ivar = Value; }
    266 
    267   bool isObjCArray() const { return ObjIsArray; }
    268   void setObjCArray(bool Value) { ObjIsArray = Value; }
    269 
    270   bool isNonGC () const { return NonGC; }
    271   void setNonGC(bool Value) { NonGC = Value; }
    272 
    273   bool isGlobalObjCRef() const { return GlobalObjCRef; }
    274   void setGlobalObjCRef(bool Value) { GlobalObjCRef = Value; }
    275 
    276   bool isThreadLocalRef() const { return ThreadLocalRef; }
    277   void setThreadLocalRef(bool Value) { ThreadLocalRef = Value;}
    278 
    279   ARCPreciseLifetime_t isARCPreciseLifetime() const {
    280     return ARCPreciseLifetime_t(!ImpreciseLifetime);
    281   }
    282   void setARCPreciseLifetime(ARCPreciseLifetime_t value) {
    283     ImpreciseLifetime = (value == ARCImpreciseLifetime);
    284   }
    285   bool isNontemporal() const { return Nontemporal; }
    286   void setNontemporal(bool Value) { Nontemporal = Value; }
    287 
    288   bool isObjCWeak() const {
    289     return Quals.getObjCGCAttr() == Qualifiers::Weak;
    290   }
    291   bool isObjCStrong() const {
    292     return Quals.getObjCGCAttr() == Qualifiers::Strong;
    293   }
    294 
    295   bool isVolatile() const {
    296     return Quals.hasVolatile();
    297   }
    298 
    299   Expr *getBaseIvarExp() const { return BaseIvarExp; }
    300   void setBaseIvarExp(Expr *V) { BaseIvarExp = V; }
    301 
    302   QualType getTBAABaseType() const { return TBAABaseType; }
    303   void setTBAABaseType(QualType T) { TBAABaseType = T; }
    304 
    305   uint64_t getTBAAOffset() const { return TBAAOffset; }
    306   void setTBAAOffset(uint64_t O) { TBAAOffset = O; }
    307 
    308   llvm::MDNode *getTBAAInfo() const { return TBAAInfo; }
    309   void setTBAAInfo(llvm::MDNode *N) { TBAAInfo = N; }
    310 
    311   const Qualifiers &getQuals() const { return Quals; }
    312   Qualifiers &getQuals() { return Quals; }
    313 
    314   unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
    315 
    316   CharUnits getAlignment() const { return CharUnits::fromQuantity(Alignment); }
    317   void setAlignment(CharUnits A) { Alignment = A.getQuantity(); }
    318 
    319   AlignmentSource getAlignmentSource() const {
    320     return AlignmentSource(AlignSource);
    321   }
    322   void setAlignmentSource(AlignmentSource Source) {
    323     AlignSource = unsigned(Source);
    324   }
    325 
    326   // simple lvalue
    327   llvm::Value *getPointer() const {
    328     assert(isSimple());
    329     return V;
    330   }
    331   Address getAddress() const { return Address(getPointer(), getAlignment()); }
    332   void setAddress(Address address) {
    333     assert(isSimple());
    334     V = address.getPointer();
    335     Alignment = address.getAlignment().getQuantity();
    336   }
    337 
    338   // vector elt lvalue
    339   Address getVectorAddress() const {
    340     return Address(getVectorPointer(), getAlignment());
    341   }
    342   llvm::Value *getVectorPointer() const { assert(isVectorElt()); return V; }
    343   llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
    344 
    345   // extended vector elements.
    346   Address getExtVectorAddress() const {
    347     return Address(getExtVectorPointer(), getAlignment());
    348   }
    349   llvm::Value *getExtVectorPointer() const {
    350     assert(isExtVectorElt());
    351     return V;
    352   }
    353   llvm::Constant *getExtVectorElts() const {
    354     assert(isExtVectorElt());
    355     return VectorElts;
    356   }
    357 
    358   // bitfield lvalue
    359   Address getBitFieldAddress() const {
    360     return Address(getBitFieldPointer(), getAlignment());
    361   }
    362   llvm::Value *getBitFieldPointer() const { assert(isBitField()); return V; }
    363   const CGBitFieldInfo &getBitFieldInfo() const {
    364     assert(isBitField());
    365     return *BitFieldInfo;
    366   }
    367 
    368   // global register lvalue
    369   llvm::Value *getGlobalReg() const { assert(isGlobalReg()); return V; }
    370 
    371   static LValue MakeAddr(Address address, QualType type,
    372                          ASTContext &Context,
    373                          AlignmentSource alignSource,
    374                          llvm::MDNode *TBAAInfo = nullptr) {
    375     Qualifiers qs = type.getQualifiers();
    376     qs.setObjCGCAttr(Context.getObjCGCAttrKind(type));
    377 
    378     LValue R;
    379     R.LVType = Simple;
    380     assert(address.getPointer()->getType()->isPointerTy());
    381     R.V = address.getPointer();
    382     R.Initialize(type, qs, address.getAlignment(), alignSource, TBAAInfo);
    383     return R;
    384   }
    385 
    386   static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx,
    387                               QualType type, AlignmentSource alignSource) {
    388     LValue R;
    389     R.LVType = VectorElt;
    390     R.V = vecAddress.getPointer();
    391     R.VectorIdx = Idx;
    392     R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
    393                  alignSource);
    394     return R;
    395   }
    396 
    397   static LValue MakeExtVectorElt(Address vecAddress, llvm::Constant *Elts,
    398                                  QualType type, AlignmentSource alignSource) {
    399     LValue R;
    400     R.LVType = ExtVectorElt;
    401     R.V = vecAddress.getPointer();
    402     R.VectorElts = Elts;
    403     R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
    404                  alignSource);
    405     return R;
    406   }
    407 
    408   /// \brief Create a new object to represent a bit-field access.
    409   ///
    410   /// \param Addr - The base address of the bit-field sequence this
    411   /// bit-field refers to.
    412   /// \param Info - The information describing how to perform the bit-field
    413   /// access.
    414   static LValue MakeBitfield(Address Addr,
    415                              const CGBitFieldInfo &Info,
    416                              QualType type,
    417                              AlignmentSource alignSource) {
    418     LValue R;
    419     R.LVType = BitField;
    420     R.V = Addr.getPointer();
    421     R.BitFieldInfo = &Info;
    422     R.Initialize(type, type.getQualifiers(), Addr.getAlignment(), alignSource);
    423     return R;
    424   }
    425 
    426   static LValue MakeGlobalReg(Address Reg, QualType type) {
    427     LValue R;
    428     R.LVType = GlobalReg;
    429     R.V = Reg.getPointer();
    430     R.Initialize(type, type.getQualifiers(), Reg.getAlignment(),
    431                  AlignmentSource::Decl);
    432     return R;
    433   }
    434 
    435   RValue asAggregateRValue() const {
    436     return RValue::getAggregate(getAddress(), isVolatileQualified());
    437   }
    438 };
    439 
    440 /// An aggregate value slot.
    441 class AggValueSlot {
    442   /// The address.
    443   llvm::Value *Addr;
    444 
    445   // Qualifiers
    446   Qualifiers Quals;
    447 
    448   unsigned short Alignment;
    449 
    450   /// DestructedFlag - This is set to true if some external code is
    451   /// responsible for setting up a destructor for the slot.  Otherwise
    452   /// the code which constructs it should push the appropriate cleanup.
    453   bool DestructedFlag : 1;
    454 
    455   /// ObjCGCFlag - This is set to true if writing to the memory in the
    456   /// slot might require calling an appropriate Objective-C GC
    457   /// barrier.  The exact interaction here is unnecessarily mysterious.
    458   bool ObjCGCFlag : 1;
    459 
    460   /// ZeroedFlag - This is set to true if the memory in the slot is
    461   /// known to be zero before the assignment into it.  This means that
    462   /// zero fields don't need to be set.
    463   bool ZeroedFlag : 1;
    464 
    465   /// AliasedFlag - This is set to true if the slot might be aliased
    466   /// and it's not undefined behavior to access it through such an
    467   /// alias.  Note that it's always undefined behavior to access a C++
    468   /// object that's under construction through an alias derived from
    469   /// outside the construction process.
    470   ///
    471   /// This flag controls whether calls that produce the aggregate
    472   /// value may be evaluated directly into the slot, or whether they
    473   /// must be evaluated into an unaliased temporary and then memcpy'ed
    474   /// over.  Since it's invalid in general to memcpy a non-POD C++
    475   /// object, it's important that this flag never be set when
    476   /// evaluating an expression which constructs such an object.
    477   bool AliasedFlag : 1;
    478 
    479 public:
    480   enum IsAliased_t { IsNotAliased, IsAliased };
    481   enum IsDestructed_t { IsNotDestructed, IsDestructed };
    482   enum IsZeroed_t { IsNotZeroed, IsZeroed };
    483   enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers };
    484 
    485   /// ignored - Returns an aggregate value slot indicating that the
    486   /// aggregate value is being ignored.
    487   static AggValueSlot ignored() {
    488     return forAddr(Address::invalid(), Qualifiers(), IsNotDestructed,
    489                    DoesNotNeedGCBarriers, IsNotAliased);
    490   }
    491 
    492   /// forAddr - Make a slot for an aggregate value.
    493   ///
    494   /// \param quals - The qualifiers that dictate how the slot should
    495   /// be initialied. Only 'volatile' and the Objective-C lifetime
    496   /// qualifiers matter.
    497   ///
    498   /// \param isDestructed - true if something else is responsible
    499   ///   for calling destructors on this object
    500   /// \param needsGC - true if the slot is potentially located
    501   ///   somewhere that ObjC GC calls should be emitted for
    502   static AggValueSlot forAddr(Address addr,
    503                               Qualifiers quals,
    504                               IsDestructed_t isDestructed,
    505                               NeedsGCBarriers_t needsGC,
    506                               IsAliased_t isAliased,
    507                               IsZeroed_t isZeroed = IsNotZeroed) {
    508     AggValueSlot AV;
    509     if (addr.isValid()) {
    510       AV.Addr = addr.getPointer();
    511       AV.Alignment = addr.getAlignment().getQuantity();
    512     } else {
    513       AV.Addr = nullptr;
    514       AV.Alignment = 0;
    515     }
    516     AV.Quals = quals;
    517     AV.DestructedFlag = isDestructed;
    518     AV.ObjCGCFlag = needsGC;
    519     AV.ZeroedFlag = isZeroed;
    520     AV.AliasedFlag = isAliased;
    521     return AV;
    522   }
    523 
    524   static AggValueSlot forLValue(const LValue &LV,
    525                                 IsDestructed_t isDestructed,
    526                                 NeedsGCBarriers_t needsGC,
    527                                 IsAliased_t isAliased,
    528                                 IsZeroed_t isZeroed = IsNotZeroed) {
    529     return forAddr(LV.getAddress(),
    530                    LV.getQuals(), isDestructed, needsGC, isAliased, isZeroed);
    531   }
    532 
    533   IsDestructed_t isExternallyDestructed() const {
    534     return IsDestructed_t(DestructedFlag);
    535   }
    536   void setExternallyDestructed(bool destructed = true) {
    537     DestructedFlag = destructed;
    538   }
    539 
    540   Qualifiers getQualifiers() const { return Quals; }
    541 
    542   bool isVolatile() const {
    543     return Quals.hasVolatile();
    544   }
    545 
    546   void setVolatile(bool flag) {
    547     Quals.setVolatile(flag);
    548   }
    549 
    550   Qualifiers::ObjCLifetime getObjCLifetime() const {
    551     return Quals.getObjCLifetime();
    552   }
    553 
    554   NeedsGCBarriers_t requiresGCollection() const {
    555     return NeedsGCBarriers_t(ObjCGCFlag);
    556   }
    557 
    558   llvm::Value *getPointer() const {
    559     return Addr;
    560   }
    561 
    562   Address getAddress() const {
    563     return Address(Addr, getAlignment());
    564   }
    565 
    566   bool isIgnored() const {
    567     return Addr == nullptr;
    568   }
    569 
    570   CharUnits getAlignment() const {
    571     return CharUnits::fromQuantity(Alignment);
    572   }
    573 
    574   IsAliased_t isPotentiallyAliased() const {
    575     return IsAliased_t(AliasedFlag);
    576   }
    577 
    578   RValue asRValue() const {
    579     if (isIgnored()) {
    580       return RValue::getIgnored();
    581     } else {
    582       return RValue::getAggregate(getAddress(), isVolatile());
    583     }
    584   }
    585 
    586   void setZeroed(bool V = true) { ZeroedFlag = V; }
    587   IsZeroed_t isZeroed() const {
    588     return IsZeroed_t(ZeroedFlag);
    589   }
    590 };
    591 
    592 }  // end namespace CodeGen
    593 }  // end namespace clang
    594 
    595 #endif
    596