1 //===-- CGValue.h - LLVM CodeGen wrappers for llvm::Value* ------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // These classes implement wrappers around llvm::Value in order to
10 // fully represent the range of values for C L- and R- values.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Type.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/IR/Type.h"
22 #include "CodeGenTBAA.h"
32 class CodeGenFunction;
33 struct CGBitFieldInfo;
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.
40 enum Flavor { Scalar, Complex, Aggregate };
42 // The shift to make to an aggregate's alignment to make it look
44 enum { AggAlignShift = 4 };
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;
52 bool isScalar() const { return V1.getInt() == Scalar; }
53 bool isComplex() const { return V1.getInt() == Complex; }
54 bool isAggregate() const { return V1.getInt() == Aggregate; }
56 bool isVolatileQualified() const { return V2.getInt(); }
58 /// getScalarVal() - Return the Value* of this scalar value.
59 llvm::Value *getScalarVal() const {
60 assert(isScalar() && "Not a scalar!");
61 return V1.getPointer();
64 /// getComplexVal - Return the real/imag components of this complex value.
66 std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
67 return std::make_pair(V1.getPointer(), V2.getPointer());
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));
76 llvm::Value *getAggregatePointer() const {
77 assert(isAggregate() && "Not an aggregate!");
78 return V1.getPointer();
81 static RValue getIgnored() {
82 // FIXME: should we make this a more explicit state?
86 static RValue get(llvm::Value *V) {
93 static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
97 ER.V1.setInt(Complex);
101 static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
102 return getComplex(C.first, C.second);
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
107 static RValue getAggregate(Address addr, bool isVolatile = false) {
109 ER.V1.setPointer(addr.getPointer());
110 ER.V1.setInt(Aggregate);
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);
119 /// Does an ARC strong l-value have precise lifetime?
120 enum ARCPreciseLifetime_t {
121 ARCImpreciseLifetime, ARCPreciseLifetime
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.
132 /// The l-value was considered opaque, so the alignment was
133 /// determined from a type, but that type was an explicitly-aligned
137 /// The l-value was considered opaque, so the alignment was
138 /// determined from a type.
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;
150 class LValueBaseInfo {
151 AlignmentSource AlignSource;
154 explicit LValueBaseInfo(AlignmentSource Source = AlignmentSource::Type)
155 : AlignSource(Source) {}
156 AlignmentSource getAlignmentSource() const { return AlignSource; }
157 void setAlignmentSource(AlignmentSource Source) { AlignSource = Source; }
159 void mergeForCast(const LValueBaseInfo &Info) {
160 setAlignmentSource(Info.getAlignmentSource());
164 /// LValue - This represents an lvalue references. Because C/C++ allow
165 /// bitfields, this is not a simple LLVM pointer, it may be a pointer plus a
169 Simple, // This is a normal l-value, use getAddress().
170 VectorElt, // This is a vector element l-value (V[i]), use getVector*
171 BitField, // This is a bitfield l-value, use getBitfield*.
172 ExtVectorElt, // This is an extended vector subset, use getExtVectorComp
173 GlobalReg // This is a register l-value, use getGlobalReg()
179 // Index into a vector subscript: V[i]
180 llvm::Value *VectorIdx;
182 // ExtVector element subset: V.xyx
183 llvm::Constant *VectorElts;
185 // BitField start bit and size
186 const CGBitFieldInfo *BitFieldInfo;
191 // 'const' is unused here
194 // The alignment to use when accessing this lvalue. (For vector elements,
195 // this is the alignment of the whole vector.)
198 // objective-c's ivar
201 // objective-c's ivar is an array
204 // LValue is non-gc'able for any reason, including being a parameter or local
208 // Lvalue is a global reference of an objective-c object
209 bool GlobalObjCRef : 1;
211 // Lvalue is a thread local reference
212 bool ThreadLocalRef : 1;
214 // Lvalue has ARC imprecise lifetime. We store this inverted to try
215 // to make the default bitfield pattern all-zeroes.
216 bool ImpreciseLifetime : 1;
218 // This flag shows if a nontemporal load/stores should be used when accessing
220 bool Nontemporal : 1;
222 LValueBaseInfo BaseInfo;
223 TBAAAccessInfo TBAAInfo;
228 void Initialize(QualType Type, Qualifiers Quals, CharUnits Alignment,
229 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
230 assert((!Alignment.isZero() || Type->isIncompleteType()) &&
231 "initializing l-value with zero alignment!");
234 const unsigned MaxAlign = 1U << 31;
235 this->Alignment = Alignment.getQuantity() <= MaxAlign
236 ? Alignment.getQuantity()
238 assert(this->Alignment == Alignment.getQuantity() &&
239 "Alignment exceeds allowed max!");
240 this->BaseInfo = BaseInfo;
241 this->TBAAInfo = TBAAInfo;
243 // Initialize Objective-C flags.
244 this->Ivar = this->ObjIsArray = this->NonGC = this->GlobalObjCRef = false;
245 this->ImpreciseLifetime = false;
246 this->Nontemporal = false;
247 this->ThreadLocalRef = false;
248 this->BaseIvarExp = nullptr;
252 bool isSimple() const { return LVType == Simple; }
253 bool isVectorElt() const { return LVType == VectorElt; }
254 bool isBitField() const { return LVType == BitField; }
255 bool isExtVectorElt() const { return LVType == ExtVectorElt; }
256 bool isGlobalReg() const { return LVType == GlobalReg; }
258 bool isVolatileQualified() const { return Quals.hasVolatile(); }
259 bool isRestrictQualified() const { return Quals.hasRestrict(); }
260 unsigned getVRQualifiers() const {
261 return Quals.getCVRQualifiers() & ~Qualifiers::Const;
264 QualType getType() const { return Type; }
266 Qualifiers::ObjCLifetime getObjCLifetime() const {
267 return Quals.getObjCLifetime();
270 bool isObjCIvar() const { return Ivar; }
271 void setObjCIvar(bool Value) { Ivar = Value; }
273 bool isObjCArray() const { return ObjIsArray; }
274 void setObjCArray(bool Value) { ObjIsArray = Value; }
276 bool isNonGC () const { return NonGC; }
277 void setNonGC(bool Value) { NonGC = Value; }
279 bool isGlobalObjCRef() const { return GlobalObjCRef; }
280 void setGlobalObjCRef(bool Value) { GlobalObjCRef = Value; }
282 bool isThreadLocalRef() const { return ThreadLocalRef; }
283 void setThreadLocalRef(bool Value) { ThreadLocalRef = Value;}
285 ARCPreciseLifetime_t isARCPreciseLifetime() const {
286 return ARCPreciseLifetime_t(!ImpreciseLifetime);
288 void setARCPreciseLifetime(ARCPreciseLifetime_t value) {
289 ImpreciseLifetime = (value == ARCImpreciseLifetime);
291 bool isNontemporal() const { return Nontemporal; }
292 void setNontemporal(bool Value) { Nontemporal = Value; }
294 bool isObjCWeak() const {
295 return Quals.getObjCGCAttr() == Qualifiers::Weak;
297 bool isObjCStrong() const {
298 return Quals.getObjCGCAttr() == Qualifiers::Strong;
301 bool isVolatile() const {
302 return Quals.hasVolatile();
305 Expr *getBaseIvarExp() const { return BaseIvarExp; }
306 void setBaseIvarExp(Expr *V) { BaseIvarExp = V; }
308 TBAAAccessInfo getTBAAInfo() const { return TBAAInfo; }
309 void setTBAAInfo(TBAAAccessInfo Info) { TBAAInfo = Info; }
311 const Qualifiers &getQuals() const { return Quals; }
312 Qualifiers &getQuals() { return Quals; }
314 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
316 CharUnits getAlignment() const { return CharUnits::fromQuantity(Alignment); }
317 void setAlignment(CharUnits A) { Alignment = A.getQuantity(); }
319 LValueBaseInfo getBaseInfo() const { return BaseInfo; }
320 void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
323 llvm::Value *getPointer(CodeGenFunction &CGF) const {
327 Address getAddress(CodeGenFunction &CGF) const {
328 return Address(getPointer(CGF), getAlignment());
330 void setAddress(Address address) {
332 V = address.getPointer();
333 Alignment = address.getAlignment().getQuantity();
337 Address getVectorAddress() const {
338 return Address(getVectorPointer(), getAlignment());
340 llvm::Value *getVectorPointer() const { assert(isVectorElt()); return V; }
341 llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
343 // extended vector elements.
344 Address getExtVectorAddress() const {
345 return Address(getExtVectorPointer(), getAlignment());
347 llvm::Value *getExtVectorPointer() const {
348 assert(isExtVectorElt());
351 llvm::Constant *getExtVectorElts() const {
352 assert(isExtVectorElt());
357 Address getBitFieldAddress() const {
358 return Address(getBitFieldPointer(), getAlignment());
360 llvm::Value *getBitFieldPointer() const { assert(isBitField()); return V; }
361 const CGBitFieldInfo &getBitFieldInfo() const {
362 assert(isBitField());
363 return *BitFieldInfo;
366 // global register lvalue
367 llvm::Value *getGlobalReg() const { assert(isGlobalReg()); return V; }
369 static LValue MakeAddr(Address address, QualType type, ASTContext &Context,
370 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
371 Qualifiers qs = type.getQualifiers();
372 qs.setObjCGCAttr(Context.getObjCGCAttrKind(type));
376 assert(address.getPointer()->getType()->isPointerTy());
377 R.V = address.getPointer();
378 R.Initialize(type, qs, address.getAlignment(), BaseInfo, TBAAInfo);
382 static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx,
383 QualType type, LValueBaseInfo BaseInfo,
384 TBAAAccessInfo TBAAInfo) {
386 R.LVType = VectorElt;
387 R.V = vecAddress.getPointer();
389 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
394 static LValue MakeExtVectorElt(Address vecAddress, llvm::Constant *Elts,
395 QualType type, LValueBaseInfo BaseInfo,
396 TBAAAccessInfo TBAAInfo) {
398 R.LVType = ExtVectorElt;
399 R.V = vecAddress.getPointer();
401 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
406 /// Create a new object to represent a bit-field access.
408 /// \param Addr - The base address of the bit-field sequence this
409 /// bit-field refers to.
410 /// \param Info - The information describing how to perform the bit-field
412 static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info,
413 QualType type, LValueBaseInfo BaseInfo,
414 TBAAAccessInfo TBAAInfo) {
417 R.V = Addr.getPointer();
418 R.BitFieldInfo = &Info;
419 R.Initialize(type, type.getQualifiers(), Addr.getAlignment(), BaseInfo,
424 static LValue MakeGlobalReg(Address Reg, QualType type) {
426 R.LVType = GlobalReg;
427 R.V = Reg.getPointer();
428 R.Initialize(type, type.getQualifiers(), Reg.getAlignment(),
429 LValueBaseInfo(AlignmentSource::Decl), TBAAAccessInfo());
433 RValue asAggregateRValue(CodeGenFunction &CGF) const {
434 return RValue::getAggregate(getAddress(CGF), isVolatileQualified());
438 /// An aggregate value slot.
448 /// DestructedFlag - This is set to true if some external code is
449 /// responsible for setting up a destructor for the slot. Otherwise
450 /// the code which constructs it should push the appropriate cleanup.
451 bool DestructedFlag : 1;
453 /// ObjCGCFlag - This is set to true if writing to the memory in the
454 /// slot might require calling an appropriate Objective-C GC
455 /// barrier. The exact interaction here is unnecessarily mysterious.
458 /// ZeroedFlag - This is set to true if the memory in the slot is
459 /// known to be zero before the assignment into it. This means that
460 /// zero fields don't need to be set.
463 /// AliasedFlag - This is set to true if the slot might be aliased
464 /// and it's not undefined behavior to access it through such an
465 /// alias. Note that it's always undefined behavior to access a C++
466 /// object that's under construction through an alias derived from
467 /// outside the construction process.
469 /// This flag controls whether calls that produce the aggregate
470 /// value may be evaluated directly into the slot, or whether they
471 /// must be evaluated into an unaliased temporary and then memcpy'ed
472 /// over. Since it's invalid in general to memcpy a non-POD C++
473 /// object, it's important that this flag never be set when
474 /// evaluating an expression which constructs such an object.
475 bool AliasedFlag : 1;
477 /// This is set to true if the tail padding of this slot might overlap
478 /// another object that may have already been initialized (and whose
479 /// value must be preserved by this initialization). If so, we may only
480 /// store up to the dsize of the type. Otherwise we can widen stores to
481 /// the size of the type.
482 bool OverlapFlag : 1;
484 /// If is set to true, sanitizer checks are already generated for this address
485 /// or not required. For instance, if this address represents an object
486 /// created in 'new' expression, sanitizer checks for memory is made as a part
487 /// of 'operator new' emission and object constructor should not generate
489 bool SanitizerCheckedFlag : 1;
492 enum IsAliased_t { IsNotAliased, IsAliased };
493 enum IsDestructed_t { IsNotDestructed, IsDestructed };
494 enum IsZeroed_t { IsNotZeroed, IsZeroed };
495 enum Overlap_t { DoesNotOverlap, MayOverlap };
496 enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers };
497 enum IsSanitizerChecked_t { IsNotSanitizerChecked, IsSanitizerChecked };
499 /// ignored - Returns an aggregate value slot indicating that the
500 /// aggregate value is being ignored.
501 static AggValueSlot ignored() {
502 return forAddr(Address::invalid(), Qualifiers(), IsNotDestructed,
503 DoesNotNeedGCBarriers, IsNotAliased, DoesNotOverlap);
506 /// forAddr - Make a slot for an aggregate value.
508 /// \param quals - The qualifiers that dictate how the slot should
509 /// be initialied. Only 'volatile' and the Objective-C lifetime
510 /// qualifiers matter.
512 /// \param isDestructed - true if something else is responsible
513 /// for calling destructors on this object
514 /// \param needsGC - true if the slot is potentially located
515 /// somewhere that ObjC GC calls should be emitted for
516 static AggValueSlot forAddr(Address addr,
518 IsDestructed_t isDestructed,
519 NeedsGCBarriers_t needsGC,
520 IsAliased_t isAliased,
521 Overlap_t mayOverlap,
522 IsZeroed_t isZeroed = IsNotZeroed,
523 IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) {
525 if (addr.isValid()) {
526 AV.Addr = addr.getPointer();
527 AV.Alignment = addr.getAlignment().getQuantity();
533 AV.DestructedFlag = isDestructed;
534 AV.ObjCGCFlag = needsGC;
535 AV.ZeroedFlag = isZeroed;
536 AV.AliasedFlag = isAliased;
537 AV.OverlapFlag = mayOverlap;
538 AV.SanitizerCheckedFlag = isChecked;
543 forLValue(const LValue &LV, CodeGenFunction &CGF, IsDestructed_t isDestructed,
544 NeedsGCBarriers_t needsGC, IsAliased_t isAliased,
545 Overlap_t mayOverlap, IsZeroed_t isZeroed = IsNotZeroed,
546 IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) {
547 return forAddr(LV.getAddress(CGF), LV.getQuals(), isDestructed, needsGC,
548 isAliased, mayOverlap, isZeroed, isChecked);
551 IsDestructed_t isExternallyDestructed() const {
552 return IsDestructed_t(DestructedFlag);
554 void setExternallyDestructed(bool destructed = true) {
555 DestructedFlag = destructed;
558 Qualifiers getQualifiers() const { return Quals; }
560 bool isVolatile() const {
561 return Quals.hasVolatile();
564 void setVolatile(bool flag) {
568 Quals.removeVolatile();
571 Qualifiers::ObjCLifetime getObjCLifetime() const {
572 return Quals.getObjCLifetime();
575 NeedsGCBarriers_t requiresGCollection() const {
576 return NeedsGCBarriers_t(ObjCGCFlag);
579 llvm::Value *getPointer() const {
583 Address getAddress() const {
584 return Address(Addr, getAlignment());
587 bool isIgnored() const {
588 return Addr == nullptr;
591 CharUnits getAlignment() const {
592 return CharUnits::fromQuantity(Alignment);
595 IsAliased_t isPotentiallyAliased() const {
596 return IsAliased_t(AliasedFlag);
599 Overlap_t mayOverlap() const {
600 return Overlap_t(OverlapFlag);
603 bool isSanitizerChecked() const {
604 return SanitizerCheckedFlag;
607 RValue asRValue() const {
609 return RValue::getIgnored();
611 return RValue::getAggregate(getAddress(), isVolatile());
615 void setZeroed(bool V = true) { ZeroedFlag = V; }
616 IsZeroed_t isZeroed() const {
617 return IsZeroed_t(ZeroedFlag);
620 /// Get the preferred size to use when storing a value to this slot. This
621 /// is the type size unless that might overlap another object, in which
622 /// case it's the dsize.
623 CharUnits getPreferredSize(ASTContext &Ctx, QualType Type) const {
624 return mayOverlap() ? Ctx.getTypeInfoDataSizeInChars(Type).first
625 : Ctx.getTypeSizeInChars(Type);
629 } // end namespace CodeGen
630 } // end namespace clang