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