1//===--- APValue.cpp - Union class for APFloat/APSInt/Complex -------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the APValue class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/APValue.h"
14#include "Linkage.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CharUnits.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/Type.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/raw_ostream.h"
23using namespace clang;
24
25/// The identity of a type_info object depends on the canonical unqualified
26/// type only.
27TypeInfoLValue::TypeInfoLValue(const Type *T)
28 : T(T->getCanonicalTypeUnqualified().getTypePtr()) {}
29
30void TypeInfoLValue::print(llvm::raw_ostream &Out,
31 const PrintingPolicy &Policy) const {
32 Out << "typeid(";
33 QualType(getType(), 0).print(OS&: Out, Policy);
34 Out << ")";
35}
36
37static_assert(
38 1 << llvm::PointerLikeTypeTraits<TypeInfoLValue>::NumLowBitsAvailable <=
39 alignof(Type),
40 "Type is insufficiently aligned");
41
42APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V)
43 : Ptr(P ? cast<ValueDecl>(P->getCanonicalDecl()) : nullptr), Local{.CallIndex: I, .Version: V} {}
44APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
45 : Ptr(P), Local{.CallIndex: I, .Version: V} {}
46
47APValue::LValueBase APValue::LValueBase::getDynamicAlloc(DynamicAllocLValue LV,
48 QualType Type) {
49 LValueBase Base;
50 Base.Ptr = LV;
51 Base.DynamicAllocType = Type.getAsOpaquePtr();
52 return Base;
53}
54
55APValue::LValueBase APValue::LValueBase::getTypeInfo(TypeInfoLValue LV,
56 QualType TypeInfo) {
57 LValueBase Base;
58 Base.Ptr = LV;
59 Base.TypeInfoType = TypeInfo.getAsOpaquePtr();
60 return Base;
61}
62
63QualType APValue::LValueBase::getType() const {
64 if (!*this) return QualType();
65 if (const ValueDecl *D = dyn_cast<const ValueDecl*>()) {
66 // FIXME: It's unclear where we're supposed to take the type from, and
67 // this actually matters for arrays of unknown bound. Eg:
68 //
69 // extern int arr[]; void f() { extern int arr[3]; };
70 // constexpr int *p = &arr[1]; // valid?
71 //
72 // For now, we take the most complete type we can find.
73 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
74 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
75 QualType T = Redecl->getType();
76 if (!T->isIncompleteArrayType())
77 return T;
78 }
79 return D->getType();
80 }
81
82 if (is<TypeInfoLValue>())
83 return getTypeInfoType();
84
85 if (is<DynamicAllocLValue>())
86 return getDynamicAllocType();
87
88 const Expr *Base = get<const Expr*>();
89
90 // For a materialized temporary, the type of the temporary we materialized
91 // may not be the type of the expression.
92 if (const MaterializeTemporaryExpr *MTE =
93 clang::dyn_cast<MaterializeTemporaryExpr>(Val: Base)) {
94 SmallVector<const Expr *, 2> CommaLHSs;
95 SmallVector<SubobjectAdjustment, 2> Adjustments;
96 const Expr *Temp = MTE->getSubExpr();
97 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs,
98 Adjustments);
99 // Keep any cv-qualifiers from the reference if we generated a temporary
100 // for it directly. Otherwise use the type after adjustment.
101 if (!Adjustments.empty())
102 return Inner->getType();
103 }
104
105 return Base->getType();
106}
107
108unsigned APValue::LValueBase::getCallIndex() const {
109 return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0
110 : Local.CallIndex;
111}
112
113unsigned APValue::LValueBase::getVersion() const {
114 return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0 : Local.Version;
115}
116
117QualType APValue::LValueBase::getTypeInfoType() const {
118 assert(is<TypeInfoLValue>() && "not a type_info lvalue");
119 return QualType::getFromOpaquePtr(Ptr: TypeInfoType);
120}
121
122QualType APValue::LValueBase::getDynamicAllocType() const {
123 assert(is<DynamicAllocLValue>() && "not a dynamic allocation lvalue");
124 return QualType::getFromOpaquePtr(Ptr: DynamicAllocType);
125}
126
127void APValue::LValueBase::Profile(llvm::FoldingSetNodeID &ID) const {
128 ID.AddPointer(Ptr: Ptr.getOpaqueValue());
129 if (is<TypeInfoLValue>() || is<DynamicAllocLValue>())
130 return;
131 ID.AddInteger(I: Local.CallIndex);
132 ID.AddInteger(I: Local.Version);
133}
134
135namespace clang {
136bool operator==(const APValue::LValueBase &LHS,
137 const APValue::LValueBase &RHS) {
138 if (LHS.Ptr != RHS.Ptr)
139 return false;
140 if (LHS.is<TypeInfoLValue>() || LHS.is<DynamicAllocLValue>())
141 return true;
142 return LHS.Local.CallIndex == RHS.Local.CallIndex &&
143 LHS.Local.Version == RHS.Local.Version;
144}
145}
146
147APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) {
148 if (const Decl *D = BaseOrMember.getPointer())
149 BaseOrMember.setPointer(D->getCanonicalDecl());
150 Value = reinterpret_cast<uintptr_t>(BaseOrMember.getOpaqueValue());
151}
152
153void APValue::LValuePathEntry::Profile(llvm::FoldingSetNodeID &ID) const {
154 ID.AddInteger(I: Value);
155}
156
157APValue::LValuePathSerializationHelper::LValuePathSerializationHelper(
158 ArrayRef<LValuePathEntry> Path, QualType ElemTy)
159 : Ty((const void *)ElemTy.getTypePtrOrNull()), Path(Path) {}
160
161QualType APValue::LValuePathSerializationHelper::getType() {
162 return QualType::getFromOpaquePtr(Ptr: Ty);
163}
164
165namespace {
166 struct LVBase {
167 APValue::LValueBase Base;
168 CharUnits Offset;
169 unsigned PathLength;
170 bool IsNullPtr : 1;
171 bool IsOnePastTheEnd : 1;
172 };
173}
174
175void *APValue::LValueBase::getOpaqueValue() const {
176 return Ptr.getOpaqueValue();
177}
178
179bool APValue::LValueBase::isNull() const {
180 return Ptr.isNull();
181}
182
183APValue::LValueBase::operator bool () const {
184 return static_cast<bool>(Ptr);
185}
186
187clang::APValue::LValueBase
188llvm::DenseMapInfo<clang::APValue::LValueBase>::getEmptyKey() {
189 clang::APValue::LValueBase B;
190 B.Ptr = DenseMapInfo<const ValueDecl*>::getEmptyKey();
191 return B;
192}
193
194clang::APValue::LValueBase
195llvm::DenseMapInfo<clang::APValue::LValueBase>::getTombstoneKey() {
196 clang::APValue::LValueBase B;
197 B.Ptr = DenseMapInfo<const ValueDecl*>::getTombstoneKey();
198 return B;
199}
200
201namespace clang {
202llvm::hash_code hash_value(const APValue::LValueBase &Base) {
203 if (Base.is<TypeInfoLValue>() || Base.is<DynamicAllocLValue>())
204 return llvm::hash_value(ptr: Base.getOpaqueValue());
205 return llvm::hash_combine(args: Base.getOpaqueValue(), args: Base.getCallIndex(),
206 args: Base.getVersion());
207}
208}
209
210unsigned llvm::DenseMapInfo<clang::APValue::LValueBase>::getHashValue(
211 const clang::APValue::LValueBase &Base) {
212 return hash_value(Base);
213}
214
215bool llvm::DenseMapInfo<clang::APValue::LValueBase>::isEqual(
216 const clang::APValue::LValueBase &LHS,
217 const clang::APValue::LValueBase &RHS) {
218 return LHS == RHS;
219}
220
221struct APValue::LV : LVBase {
222 static const unsigned InlinePathSpace =
223 (DataSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
224
225 /// Path - The sequence of base classes, fields and array indices to follow to
226 /// walk from Base to the subobject. When performing GCC-style folding, there
227 /// may not be such a path.
228 union {
229 LValuePathEntry Path[InlinePathSpace];
230 LValuePathEntry *PathPtr;
231 };
232
233 LV() { PathLength = (unsigned)-1; }
234 ~LV() { resizePath(Length: 0); }
235
236 void resizePath(unsigned Length) {
237 if (Length == PathLength)
238 return;
239 if (hasPathPtr())
240 delete [] PathPtr;
241 PathLength = Length;
242 if (hasPathPtr())
243 PathPtr = new LValuePathEntry[Length];
244 }
245
246 bool hasPath() const { return PathLength != (unsigned)-1; }
247 bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; }
248
249 LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
250 const LValuePathEntry *getPath() const {
251 return hasPathPtr() ? PathPtr : Path;
252 }
253};
254
255namespace {
256 struct MemberPointerBase {
257 llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMember;
258 unsigned PathLength;
259 };
260}
261
262struct APValue::MemberPointerData : MemberPointerBase {
263 static const unsigned InlinePathSpace =
264 (DataSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
265 typedef const CXXRecordDecl *PathElem;
266 union {
267 PathElem Path[InlinePathSpace];
268 PathElem *PathPtr;
269 };
270
271 MemberPointerData() { PathLength = 0; }
272 ~MemberPointerData() { resizePath(Length: 0); }
273
274 void resizePath(unsigned Length) {
275 if (Length == PathLength)
276 return;
277 if (hasPathPtr())
278 delete [] PathPtr;
279 PathLength = Length;
280 if (hasPathPtr())
281 PathPtr = new PathElem[Length];
282 }
283
284 bool hasPathPtr() const { return PathLength > InlinePathSpace; }
285
286 PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
287 const PathElem *getPath() const {
288 return hasPathPtr() ? PathPtr : Path;
289 }
290};
291
292// FIXME: Reduce the malloc traffic here.
293
294APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
295 Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]),
296 NumElts(NumElts), ArrSize(Size) {}
297APValue::Arr::~Arr() { delete [] Elts; }
298
299APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) :
300 Elts(new APValue[NumBases+NumFields]),
301 NumBases(NumBases), NumFields(NumFields) {}
302APValue::StructData::~StructData() {
303 delete [] Elts;
304}
305
306APValue::UnionData::UnionData() : Field(nullptr), Value(new APValue) {}
307APValue::UnionData::~UnionData () {
308 delete Value;
309}
310
311APValue::APValue(const APValue &RHS) : Kind(None) {
312 switch (RHS.getKind()) {
313 case None:
314 case Indeterminate:
315 Kind = RHS.getKind();
316 break;
317 case Int:
318 MakeInt();
319 setInt(RHS.getInt());
320 break;
321 case Float:
322 MakeFloat();
323 setFloat(RHS.getFloat());
324 break;
325 case FixedPoint: {
326 APFixedPoint FXCopy = RHS.getFixedPoint();
327 MakeFixedPoint(FX: std::move(FXCopy));
328 break;
329 }
330 case Vector:
331 MakeVector();
332 setVector(E: ((const Vec *)(const char *)&RHS.Data)->Elts,
333 N: RHS.getVectorLength());
334 break;
335 case ComplexInt:
336 MakeComplexInt();
337 setComplexInt(R: RHS.getComplexIntReal(), I: RHS.getComplexIntImag());
338 break;
339 case ComplexFloat:
340 MakeComplexFloat();
341 setComplexFloat(R: RHS.getComplexFloatReal(), I: RHS.getComplexFloatImag());
342 break;
343 case LValue:
344 MakeLValue();
345 if (RHS.hasLValuePath())
346 setLValue(B: RHS.getLValueBase(), O: RHS.getLValueOffset(), Path: RHS.getLValuePath(),
347 OnePastTheEnd: RHS.isLValueOnePastTheEnd(), IsNullPtr: RHS.isNullPointer());
348 else
349 setLValue(B: RHS.getLValueBase(), O: RHS.getLValueOffset(), NoLValuePath(),
350 IsNullPtr: RHS.isNullPointer());
351 break;
352 case Array:
353 MakeArray(InitElts: RHS.getArrayInitializedElts(), Size: RHS.getArraySize());
354 for (unsigned I = 0, N = RHS.getArrayInitializedElts(); I != N; ++I)
355 getArrayInitializedElt(I) = RHS.getArrayInitializedElt(I);
356 if (RHS.hasArrayFiller())
357 getArrayFiller() = RHS.getArrayFiller();
358 break;
359 case Struct:
360 MakeStruct(B: RHS.getStructNumBases(), M: RHS.getStructNumFields());
361 for (unsigned I = 0, N = RHS.getStructNumBases(); I != N; ++I)
362 getStructBase(i: I) = RHS.getStructBase(i: I);
363 for (unsigned I = 0, N = RHS.getStructNumFields(); I != N; ++I)
364 getStructField(i: I) = RHS.getStructField(i: I);
365 break;
366 case Union:
367 MakeUnion();
368 setUnion(Field: RHS.getUnionField(), Value: RHS.getUnionValue());
369 break;
370 case MemberPointer:
371 MakeMemberPointer(Member: RHS.getMemberPointerDecl(),
372 IsDerivedMember: RHS.isMemberPointerToDerivedMember(),
373 Path: RHS.getMemberPointerPath());
374 break;
375 case AddrLabelDiff:
376 MakeAddrLabelDiff();
377 setAddrLabelDiff(LHSExpr: RHS.getAddrLabelDiffLHS(), RHSExpr: RHS.getAddrLabelDiffRHS());
378 break;
379 }
380}
381
382APValue::APValue(APValue &&RHS) : Kind(RHS.Kind), Data(RHS.Data) {
383 RHS.Kind = None;
384}
385
386APValue &APValue::operator=(const APValue &RHS) {
387 if (this != &RHS)
388 *this = APValue(RHS);
389 return *this;
390}
391
392APValue &APValue::operator=(APValue &&RHS) {
393 if (this != &RHS) {
394 if (Kind != None && Kind != Indeterminate)
395 DestroyDataAndMakeUninit();
396 Kind = RHS.Kind;
397 Data = RHS.Data;
398 RHS.Kind = None;
399 }
400 return *this;
401}
402
403void APValue::DestroyDataAndMakeUninit() {
404 if (Kind == Int)
405 ((APSInt *)(char *)&Data)->~APSInt();
406 else if (Kind == Float)
407 ((APFloat *)(char *)&Data)->~APFloat();
408 else if (Kind == FixedPoint)
409 ((APFixedPoint *)(char *)&Data)->~APFixedPoint();
410 else if (Kind == Vector)
411 ((Vec *)(char *)&Data)->~Vec();
412 else if (Kind == ComplexInt)
413 ((ComplexAPSInt *)(char *)&Data)->~ComplexAPSInt();
414 else if (Kind == ComplexFloat)
415 ((ComplexAPFloat *)(char *)&Data)->~ComplexAPFloat();
416 else if (Kind == LValue)
417 ((LV *)(char *)&Data)->~LV();
418 else if (Kind == Array)
419 ((Arr *)(char *)&Data)->~Arr();
420 else if (Kind == Struct)
421 ((StructData *)(char *)&Data)->~StructData();
422 else if (Kind == Union)
423 ((UnionData *)(char *)&Data)->~UnionData();
424 else if (Kind == MemberPointer)
425 ((MemberPointerData *)(char *)&Data)->~MemberPointerData();
426 else if (Kind == AddrLabelDiff)
427 ((AddrLabelDiffData *)(char *)&Data)->~AddrLabelDiffData();
428 Kind = None;
429}
430
431bool APValue::needsCleanup() const {
432 switch (getKind()) {
433 case None:
434 case Indeterminate:
435 case AddrLabelDiff:
436 return false;
437 case Struct:
438 case Union:
439 case Array:
440 case Vector:
441 return true;
442 case Int:
443 return getInt().needsCleanup();
444 case Float:
445 return getFloat().needsCleanup();
446 case FixedPoint:
447 return getFixedPoint().getValue().needsCleanup();
448 case ComplexFloat:
449 assert(getComplexFloatImag().needsCleanup() ==
450 getComplexFloatReal().needsCleanup() &&
451 "In _Complex float types, real and imaginary values always have the "
452 "same size.");
453 return getComplexFloatReal().needsCleanup();
454 case ComplexInt:
455 assert(getComplexIntImag().needsCleanup() ==
456 getComplexIntReal().needsCleanup() &&
457 "In _Complex int types, real and imaginary values must have the "
458 "same size.");
459 return getComplexIntReal().needsCleanup();
460 case LValue:
461 return reinterpret_cast<const LV *>(&Data)->hasPathPtr();
462 case MemberPointer:
463 return reinterpret_cast<const MemberPointerData *>(&Data)->hasPathPtr();
464 }
465 llvm_unreachable("Unknown APValue kind!");
466}
467
468void APValue::swap(APValue &RHS) {
469 std::swap(a&: Kind, b&: RHS.Kind);
470 std::swap(a&: Data, b&: RHS.Data);
471}
472
473/// Profile the value of an APInt, excluding its bit-width.
474static void profileIntValue(llvm::FoldingSetNodeID &ID, const llvm::APInt &V) {
475 for (unsigned I = 0, N = V.getBitWidth(); I < N; I += 32)
476 ID.AddInteger(I: (uint32_t)V.extractBitsAsZExtValue(numBits: std::min(a: 32u, b: N - I), bitPosition: I));
477}
478
479void APValue::Profile(llvm::FoldingSetNodeID &ID) const {
480 // Note that our profiling assumes that only APValues of the same type are
481 // ever compared. As a result, we don't consider collisions that could only
482 // happen if the types are different. (For example, structs with different
483 // numbers of members could profile the same.)
484
485 ID.AddInteger(I: Kind);
486
487 switch (Kind) {
488 case None:
489 case Indeterminate:
490 return;
491
492 case AddrLabelDiff:
493 ID.AddPointer(Ptr: getAddrLabelDiffLHS()->getLabel()->getCanonicalDecl());
494 ID.AddPointer(Ptr: getAddrLabelDiffRHS()->getLabel()->getCanonicalDecl());
495 return;
496
497 case Struct:
498 for (unsigned I = 0, N = getStructNumBases(); I != N; ++I)
499 getStructBase(i: I).Profile(ID);
500 for (unsigned I = 0, N = getStructNumFields(); I != N; ++I)
501 getStructField(i: I).Profile(ID);
502 return;
503
504 case Union:
505 if (!getUnionField()) {
506 ID.AddInteger(I: 0);
507 return;
508 }
509 ID.AddInteger(I: getUnionField()->getFieldIndex() + 1);
510 getUnionValue().Profile(ID);
511 return;
512
513 case Array: {
514 if (getArraySize() == 0)
515 return;
516
517 // The profile should not depend on whether the array is expanded or
518 // not, but we don't want to profile the array filler many times for
519 // a large array. So treat all equal trailing elements as the filler.
520 // Elements are profiled in reverse order to support this, and the
521 // first profiled element is followed by a count. For example:
522 //
523 // ['a', 'c', 'x', 'x', 'x'] is profiled as
524 // [5, 'x', 3, 'c', 'a']
525 llvm::FoldingSetNodeID FillerID;
526 (hasArrayFiller() ? getArrayFiller()
527 : getArrayInitializedElt(I: getArrayInitializedElts() - 1))
528 .Profile(ID&: FillerID);
529 ID.AddNodeID(ID: FillerID);
530 unsigned NumFillers = getArraySize() - getArrayInitializedElts();
531 unsigned N = getArrayInitializedElts();
532
533 // Count the number of elements equal to the last one. This loop ends
534 // by adding an integer indicating the number of such elements, with
535 // N set to the number of elements left to profile.
536 while (true) {
537 if (N == 0) {
538 // All elements are fillers.
539 assert(NumFillers == getArraySize());
540 ID.AddInteger(I: NumFillers);
541 break;
542 }
543
544 // No need to check if the last element is equal to the last
545 // element.
546 if (N != getArraySize()) {
547 llvm::FoldingSetNodeID ElemID;
548 getArrayInitializedElt(I: N - 1).Profile(ID&: ElemID);
549 if (ElemID != FillerID) {
550 ID.AddInteger(I: NumFillers);
551 ID.AddNodeID(ID: ElemID);
552 --N;
553 break;
554 }
555 }
556
557 // This is a filler.
558 ++NumFillers;
559 --N;
560 }
561
562 // Emit the remaining elements.
563 for (; N != 0; --N)
564 getArrayInitializedElt(I: N - 1).Profile(ID);
565 return;
566 }
567
568 case Vector:
569 for (unsigned I = 0, N = getVectorLength(); I != N; ++I)
570 getVectorElt(I).Profile(ID);
571 return;
572
573 case Int:
574 profileIntValue(ID, V: getInt());
575 return;
576
577 case Float:
578 profileIntValue(ID, V: getFloat().bitcastToAPInt());
579 return;
580
581 case FixedPoint:
582 profileIntValue(ID, V: getFixedPoint().getValue());
583 return;
584
585 case ComplexFloat:
586 profileIntValue(ID, V: getComplexFloatReal().bitcastToAPInt());
587 profileIntValue(ID, V: getComplexFloatImag().bitcastToAPInt());
588 return;
589
590 case ComplexInt:
591 profileIntValue(ID, V: getComplexIntReal());
592 profileIntValue(ID, V: getComplexIntImag());
593 return;
594
595 case LValue:
596 getLValueBase().Profile(ID);
597 ID.AddInteger(I: getLValueOffset().getQuantity());
598 ID.AddInteger(I: (isNullPointer() ? 1 : 0) |
599 (isLValueOnePastTheEnd() ? 2 : 0) |
600 (hasLValuePath() ? 4 : 0));
601 if (hasLValuePath()) {
602 ID.AddInteger(I: getLValuePath().size());
603 // For uniqueness, we only need to profile the entries corresponding
604 // to union members, but we don't have the type here so we don't know
605 // how to interpret the entries.
606 for (LValuePathEntry E : getLValuePath())
607 E.Profile(ID);
608 }
609 return;
610
611 case MemberPointer:
612 ID.AddPointer(Ptr: getMemberPointerDecl());
613 ID.AddInteger(I: isMemberPointerToDerivedMember());
614 for (const CXXRecordDecl *D : getMemberPointerPath())
615 ID.AddPointer(Ptr: D);
616 return;
617 }
618
619 llvm_unreachable("Unknown APValue kind!");
620}
621
622static double GetApproxValue(const llvm::APFloat &F) {
623 llvm::APFloat V = F;
624 bool ignored;
625 V.convert(ToSemantics: llvm::APFloat::IEEEdouble(), RM: llvm::APFloat::rmNearestTiesToEven,
626 losesInfo: &ignored);
627 return V.convertToDouble();
628}
629
630static bool TryPrintAsStringLiteral(raw_ostream &Out,
631 const PrintingPolicy &Policy,
632 const ArrayType *ATy,
633 ArrayRef<APValue> Inits) {
634 if (Inits.empty())
635 return false;
636
637 QualType Ty = ATy->getElementType();
638 if (!Ty->isAnyCharacterType())
639 return false;
640
641 // Nothing we can do about a sequence that is not null-terminated
642 if (!Inits.back().isInt() || !Inits.back().getInt().isZero())
643 return false;
644
645 Inits = Inits.drop_back();
646
647 llvm::SmallString<40> Buf;
648 Buf.push_back(Elt: '"');
649
650 // Better than printing a two-digit sequence of 10 integers.
651 constexpr size_t MaxN = 36;
652 StringRef Ellipsis;
653 if (Inits.size() > MaxN && !Policy.EntireContentsOfLargeArray) {
654 Ellipsis = "[...]";
655 Inits =
656 Inits.take_front(N: std::min(a: MaxN - Ellipsis.size() / 2, b: Inits.size()));
657 }
658
659 for (auto &Val : Inits) {
660 if (!Val.isInt())
661 return false;
662 int64_t Char64 = Val.getInt().getExtValue();
663 if (!isASCII(c: Char64))
664 return false; // Bye bye, see you in integers.
665 auto Ch = static_cast<unsigned char>(Char64);
666 // The diagnostic message is 'quoted'
667 StringRef Escaped = escapeCStyle<EscapeChar::SingleAndDouble>(Ch);
668 if (Escaped.empty()) {
669 if (!isPrintable(c: Ch))
670 return false;
671 Buf.emplace_back(Args&: Ch);
672 } else {
673 Buf.append(RHS: Escaped);
674 }
675 }
676
677 Buf.append(RHS: Ellipsis);
678 Buf.push_back(Elt: '"');
679
680 if (Ty->isWideCharType())
681 Out << 'L';
682 else if (Ty->isChar8Type())
683 Out << "u8";
684 else if (Ty->isChar16Type())
685 Out << 'u';
686 else if (Ty->isChar32Type())
687 Out << 'U';
688
689 Out << Buf;
690 return true;
691}
692
693void APValue::printPretty(raw_ostream &Out, const ASTContext &Ctx,
694 QualType Ty) const {
695 printPretty(OS&: Out, Policy: Ctx.getPrintingPolicy(), Ty, Ctx: &Ctx);
696}
697
698void APValue::printPretty(raw_ostream &Out, const PrintingPolicy &Policy,
699 QualType Ty, const ASTContext *Ctx) const {
700 // There are no objects of type 'void', but values of this type can be
701 // returned from functions.
702 if (Ty->isVoidType()) {
703 Out << "void()";
704 return;
705 }
706
707 switch (getKind()) {
708 case APValue::None:
709 Out << "<out of lifetime>";
710 return;
711 case APValue::Indeterminate:
712 Out << "<uninitialized>";
713 return;
714 case APValue::Int:
715 if (Ty->isBooleanType())
716 Out << (getInt().getBoolValue() ? "true" : "false");
717 else
718 Out << getInt();
719 return;
720 case APValue::Float:
721 Out << GetApproxValue(F: getFloat());
722 return;
723 case APValue::FixedPoint:
724 Out << getFixedPoint();
725 return;
726 case APValue::Vector: {
727 Out << '{';
728 QualType ElemTy = Ty->castAs<VectorType>()->getElementType();
729 getVectorElt(I: 0).printPretty(Out, Policy, Ty: ElemTy, Ctx);
730 for (unsigned i = 1; i != getVectorLength(); ++i) {
731 Out << ", ";
732 getVectorElt(I: i).printPretty(Out, Policy, Ty: ElemTy, Ctx);
733 }
734 Out << '}';
735 return;
736 }
737 case APValue::ComplexInt:
738 Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
739 return;
740 case APValue::ComplexFloat:
741 Out << GetApproxValue(F: getComplexFloatReal()) << "+"
742 << GetApproxValue(F: getComplexFloatImag()) << "i";
743 return;
744 case APValue::LValue: {
745 bool IsReference = Ty->isReferenceType();
746 QualType InnerTy
747 = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
748 if (InnerTy.isNull())
749 InnerTy = Ty;
750
751 LValueBase Base = getLValueBase();
752 if (!Base) {
753 if (isNullPointer()) {
754 Out << (Policy.Nullptr ? "nullptr" : "0");
755 } else if (IsReference) {
756 Out << "*(" << InnerTy.stream(Policy) << "*)"
757 << getLValueOffset().getQuantity();
758 } else {
759 Out << "(" << Ty.stream(Policy) << ")"
760 << getLValueOffset().getQuantity();
761 }
762 return;
763 }
764
765 if (!hasLValuePath()) {
766 // No lvalue path: just print the offset.
767 CharUnits O = getLValueOffset();
768 CharUnits S = Ctx ? Ctx->getTypeSizeInCharsIfKnown(Ty: InnerTy).value_or(
769 u: CharUnits::Zero())
770 : CharUnits::Zero();
771 if (!O.isZero()) {
772 if (IsReference)
773 Out << "*(";
774 if (S.isZero() || O % S) {
775 Out << "(char*)";
776 S = CharUnits::One();
777 }
778 Out << '&';
779 } else if (!IsReference) {
780 Out << '&';
781 }
782
783 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
784 Out << *VD;
785 else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
786 TI.print(Out, Policy);
787 } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
788 Out << "{*new "
789 << Base.getDynamicAllocType().stream(Policy) << "#"
790 << DA.getIndex() << "}";
791 } else {
792 assert(Base.get<const Expr *>() != nullptr &&
793 "Expecting non-null Expr");
794 Base.get<const Expr*>()->printPretty(Out, nullptr, Policy);
795 }
796
797 if (!O.isZero()) {
798 Out << " + " << (O / S);
799 if (IsReference)
800 Out << ')';
801 }
802 return;
803 }
804
805 // We have an lvalue path. Print it out nicely.
806 if (!IsReference)
807 Out << '&';
808 else if (isLValueOnePastTheEnd())
809 Out << "*(&";
810
811 QualType ElemTy = Base.getType();
812 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
813 Out << *VD;
814 } else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
815 TI.print(Out, Policy);
816 } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
817 Out << "{*new " << Base.getDynamicAllocType().stream(Policy) << "#"
818 << DA.getIndex() << "}";
819 } else {
820 const Expr *E = Base.get<const Expr*>();
821 assert(E != nullptr && "Expecting non-null Expr");
822 E->printPretty(Out, nullptr, Policy);
823 }
824
825 ArrayRef<LValuePathEntry> Path = getLValuePath();
826 const CXXRecordDecl *CastToBase = nullptr;
827 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
828 if (ElemTy->isRecordType()) {
829 // The lvalue refers to a class type, so the next path entry is a base
830 // or member.
831 const Decl *BaseOrMember = Path[I].getAsBaseOrMember().getPointer();
832 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: BaseOrMember)) {
833 CastToBase = RD;
834 // Leave ElemTy referring to the most-derived class. The actual type
835 // doesn't matter except for array types.
836 } else {
837 const ValueDecl *VD = cast<ValueDecl>(Val: BaseOrMember);
838 Out << ".";
839 if (CastToBase)
840 Out << *CastToBase << "::";
841 Out << *VD;
842 ElemTy = VD->getType();
843 }
844 } else if (ElemTy->isAnyComplexType()) {
845 // The lvalue refers to a complex type
846 Out << (Path[I].getAsArrayIndex() == 0 ? ".real" : ".imag");
847 ElemTy = ElemTy->castAs<ComplexType>()->getElementType();
848 } else {
849 // The lvalue must refer to an array.
850 Out << '[' << Path[I].getAsArrayIndex() << ']';
851 ElemTy = ElemTy->castAsArrayTypeUnsafe()->getElementType();
852 }
853 }
854
855 // Handle formatting of one-past-the-end lvalues.
856 if (isLValueOnePastTheEnd()) {
857 // FIXME: If CastToBase is non-0, we should prefix the output with
858 // "(CastToBase*)".
859 Out << " + 1";
860 if (IsReference)
861 Out << ')';
862 }
863 return;
864 }
865 case APValue::Array: {
866 const ArrayType *AT = Ty->castAsArrayTypeUnsafe();
867 unsigned N = getArrayInitializedElts();
868 if (N != 0 && TryPrintAsStringLiteral(Out, Policy, ATy: AT,
869 Inits: {&getArrayInitializedElt(I: 0), N}))
870 return;
871 QualType ElemTy = AT->getElementType();
872 Out << '{';
873 unsigned I = 0;
874 switch (N) {
875 case 0:
876 for (; I != N; ++I) {
877 Out << ", ";
878 if (I == 10 && !Policy.EntireContentsOfLargeArray) {
879 Out << "...}";
880 return;
881 }
882 [[fallthrough]];
883 default:
884 getArrayInitializedElt(I).printPretty(Out, Policy, Ty: ElemTy, Ctx);
885 }
886 }
887 Out << '}';
888 return;
889 }
890 case APValue::Struct: {
891 Out << '{';
892 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
893 bool First = true;
894 if (unsigned N = getStructNumBases()) {
895 const CXXRecordDecl *CD = cast<CXXRecordDecl>(Val: RD);
896 CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
897 for (unsigned I = 0; I != N; ++I, ++BI) {
898 assert(BI != CD->bases_end());
899 if (!First)
900 Out << ", ";
901 getStructBase(i: I).printPretty(Out, Policy, Ty: BI->getType(), Ctx);
902 First = false;
903 }
904 }
905 for (const auto *FI : RD->fields()) {
906 if (!First)
907 Out << ", ";
908 if (FI->isUnnamedBitfield()) continue;
909 getStructField(i: FI->getFieldIndex()).
910 printPretty(Out, Policy, FI->getType(), Ctx);
911 First = false;
912 }
913 Out << '}';
914 return;
915 }
916 case APValue::Union:
917 Out << '{';
918 if (const FieldDecl *FD = getUnionField()) {
919 Out << "." << *FD << " = ";
920 getUnionValue().printPretty(Out, Policy, FD->getType(), Ctx);
921 }
922 Out << '}';
923 return;
924 case APValue::MemberPointer:
925 // FIXME: This is not enough to unambiguously identify the member in a
926 // multiple-inheritance scenario.
927 if (const ValueDecl *VD = getMemberPointerDecl()) {
928 Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << *VD;
929 return;
930 }
931 Out << "0";
932 return;
933 case APValue::AddrLabelDiff:
934 Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
935 Out << " - ";
936 Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
937 return;
938 }
939 llvm_unreachable("Unknown APValue kind!");
940}
941
942std::string APValue::getAsString(const ASTContext &Ctx, QualType Ty) const {
943 std::string Result;
944 llvm::raw_string_ostream Out(Result);
945 printPretty(Out, Ctx, Ty);
946 Out.flush();
947 return Result;
948}
949
950bool APValue::toIntegralConstant(APSInt &Result, QualType SrcTy,
951 const ASTContext &Ctx) const {
952 if (isInt()) {
953 Result = getInt();
954 return true;
955 }
956
957 if (isLValue() && isNullPointer()) {
958 Result = Ctx.MakeIntValue(Value: Ctx.getTargetNullPointerValue(QT: SrcTy), Type: SrcTy);
959 return true;
960 }
961
962 if (isLValue() && !getLValueBase()) {
963 Result = Ctx.MakeIntValue(Value: getLValueOffset().getQuantity(), Type: SrcTy);
964 return true;
965 }
966
967 return false;
968}
969
970const APValue::LValueBase APValue::getLValueBase() const {
971 assert(isLValue() && "Invalid accessor");
972 return ((const LV *)(const void *)&Data)->Base;
973}
974
975bool APValue::isLValueOnePastTheEnd() const {
976 assert(isLValue() && "Invalid accessor");
977 return ((const LV *)(const void *)&Data)->IsOnePastTheEnd;
978}
979
980CharUnits &APValue::getLValueOffset() {
981 assert(isLValue() && "Invalid accessor");
982 return ((LV *)(void *)&Data)->Offset;
983}
984
985bool APValue::hasLValuePath() const {
986 assert(isLValue() && "Invalid accessor");
987 return ((const LV *)(const char *)&Data)->hasPath();
988}
989
990ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
991 assert(isLValue() && hasLValuePath() && "Invalid accessor");
992 const LV &LVal = *((const LV *)(const char *)&Data);
993 return llvm::ArrayRef(LVal.getPath(), LVal.PathLength);
994}
995
996unsigned APValue::getLValueCallIndex() const {
997 assert(isLValue() && "Invalid accessor");
998 return ((const LV *)(const char *)&Data)->Base.getCallIndex();
999}
1000
1001unsigned APValue::getLValueVersion() const {
1002 assert(isLValue() && "Invalid accessor");
1003 return ((const LV *)(const char *)&Data)->Base.getVersion();
1004}
1005
1006bool APValue::isNullPointer() const {
1007 assert(isLValue() && "Invalid usage");
1008 return ((const LV *)(const char *)&Data)->IsNullPtr;
1009}
1010
1011void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
1012 bool IsNullPtr) {
1013 assert(isLValue() && "Invalid accessor");
1014 LV &LVal = *((LV *)(char *)&Data);
1015 LVal.Base = B;
1016 LVal.IsOnePastTheEnd = false;
1017 LVal.Offset = O;
1018 LVal.resizePath(Length: (unsigned)-1);
1019 LVal.IsNullPtr = IsNullPtr;
1020}
1021
1022MutableArrayRef<APValue::LValuePathEntry>
1023APValue::setLValueUninit(LValueBase B, const CharUnits &O, unsigned Size,
1024 bool IsOnePastTheEnd, bool IsNullPtr) {
1025 assert(isLValue() && "Invalid accessor");
1026 LV &LVal = *((LV *)(char *)&Data);
1027 LVal.Base = B;
1028 LVal.IsOnePastTheEnd = IsOnePastTheEnd;
1029 LVal.Offset = O;
1030 LVal.IsNullPtr = IsNullPtr;
1031 LVal.resizePath(Length: Size);
1032 return {LVal.getPath(), Size};
1033}
1034
1035void APValue::setLValue(LValueBase B, const CharUnits &O,
1036 ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
1037 bool IsNullPtr) {
1038 MutableArrayRef<APValue::LValuePathEntry> InternalPath =
1039 setLValueUninit(B, O, Size: Path.size(), IsOnePastTheEnd, IsNullPtr);
1040 if (Path.size()) {
1041 memcpy(dest: InternalPath.data(), src: Path.data(),
1042 n: Path.size() * sizeof(LValuePathEntry));
1043 }
1044}
1045
1046void APValue::setUnion(const FieldDecl *Field, const APValue &Value) {
1047 assert(isUnion() && "Invalid accessor");
1048 ((UnionData *)(char *)&Data)->Field =
1049 Field ? Field->getCanonicalDecl() : nullptr;
1050 *((UnionData *)(char *)&Data)->Value = Value;
1051}
1052
1053const ValueDecl *APValue::getMemberPointerDecl() const {
1054 assert(isMemberPointer() && "Invalid accessor");
1055 const MemberPointerData &MPD =
1056 *((const MemberPointerData *)(const char *)&Data);
1057 return MPD.MemberAndIsDerivedMember.getPointer();
1058}
1059
1060bool APValue::isMemberPointerToDerivedMember() const {
1061 assert(isMemberPointer() && "Invalid accessor");
1062 const MemberPointerData &MPD =
1063 *((const MemberPointerData *)(const char *)&Data);
1064 return MPD.MemberAndIsDerivedMember.getInt();
1065}
1066
1067ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
1068 assert(isMemberPointer() && "Invalid accessor");
1069 const MemberPointerData &MPD =
1070 *((const MemberPointerData *)(const char *)&Data);
1071 return llvm::ArrayRef(MPD.getPath(), MPD.PathLength);
1072}
1073
1074void APValue::MakeLValue() {
1075 assert(isAbsent() && "Bad state change");
1076 static_assert(sizeof(LV) <= DataSize, "LV too big");
1077 new ((void *)(char *)&Data) LV();
1078 Kind = LValue;
1079}
1080
1081void APValue::MakeArray(unsigned InitElts, unsigned Size) {
1082 assert(isAbsent() && "Bad state change");
1083 new ((void *)(char *)&Data) Arr(InitElts, Size);
1084 Kind = Array;
1085}
1086
1087MutableArrayRef<APValue::LValuePathEntry>
1088setLValueUninit(APValue::LValueBase B, const CharUnits &O, unsigned Size,
1089 bool OnePastTheEnd, bool IsNullPtr);
1090
1091MutableArrayRef<const CXXRecordDecl *>
1092APValue::setMemberPointerUninit(const ValueDecl *Member, bool IsDerivedMember,
1093 unsigned Size) {
1094 assert(isAbsent() && "Bad state change");
1095 MemberPointerData *MPD = new ((void *)(char *)&Data) MemberPointerData;
1096 Kind = MemberPointer;
1097 MPD->MemberAndIsDerivedMember.setPointer(
1098 Member ? cast<ValueDecl>(Member->getCanonicalDecl()) : nullptr);
1099 MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
1100 MPD->resizePath(Length: Size);
1101 return {MPD->getPath(), MPD->PathLength};
1102}
1103
1104void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
1105 ArrayRef<const CXXRecordDecl *> Path) {
1106 MutableArrayRef<const CXXRecordDecl *> InternalPath =
1107 setMemberPointerUninit(Member, IsDerivedMember, Size: Path.size());
1108 for (unsigned I = 0; I != Path.size(); ++I)
1109 InternalPath[I] = Path[I]->getCanonicalDecl();
1110}
1111
1112LinkageInfo LinkageComputer::getLVForValue(const APValue &V,
1113 LVComputationKind computation) {
1114 LinkageInfo LV = LinkageInfo::external();
1115
1116 auto MergeLV = [&](LinkageInfo MergeLV) {
1117 LV.merge(other: MergeLV);
1118 return LV.getLinkage() == Linkage::Internal;
1119 };
1120 auto Merge = [&](const APValue &V) {
1121 return MergeLV(getLVForValue(V, computation));
1122 };
1123
1124 switch (V.getKind()) {
1125 case APValue::None:
1126 case APValue::Indeterminate:
1127 case APValue::Int:
1128 case APValue::Float:
1129 case APValue::FixedPoint:
1130 case APValue::ComplexInt:
1131 case APValue::ComplexFloat:
1132 case APValue::Vector:
1133 break;
1134
1135 case APValue::AddrLabelDiff:
1136 // Even for an inline function, it's not reasonable to treat a difference
1137 // between the addresses of labels as an external value.
1138 return LinkageInfo::internal();
1139
1140 case APValue::Struct: {
1141 for (unsigned I = 0, N = V.getStructNumBases(); I != N; ++I)
1142 if (Merge(V.getStructBase(i: I)))
1143 break;
1144 for (unsigned I = 0, N = V.getStructNumFields(); I != N; ++I)
1145 if (Merge(V.getStructField(i: I)))
1146 break;
1147 break;
1148 }
1149
1150 case APValue::Union:
1151 if (V.getUnionField())
1152 Merge(V.getUnionValue());
1153 break;
1154
1155 case APValue::Array: {
1156 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
1157 if (Merge(V.getArrayInitializedElt(I)))
1158 break;
1159 if (V.hasArrayFiller())
1160 Merge(V.getArrayFiller());
1161 break;
1162 }
1163
1164 case APValue::LValue: {
1165 if (!V.getLValueBase()) {
1166 // Null or absolute address: this is external.
1167 } else if (const auto *VD =
1168 V.getLValueBase().dyn_cast<const ValueDecl *>()) {
1169 if (VD && MergeLV(getLVForDecl(VD, computation)))
1170 break;
1171 } else if (const auto TI = V.getLValueBase().dyn_cast<TypeInfoLValue>()) {
1172 if (MergeLV(getLVForType(T: *TI.getType(), computation)))
1173 break;
1174 } else if (const Expr *E = V.getLValueBase().dyn_cast<const Expr *>()) {
1175 // Almost all expression bases are internal. The exception is
1176 // lifetime-extended temporaries.
1177 // FIXME: These should be modeled as having the
1178 // LifetimeExtendedTemporaryDecl itself as the base.
1179 // FIXME: If we permit Objective-C object literals in template arguments,
1180 // they should not imply internal linkage.
1181 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
1182 if (!MTE || MTE->getStorageDuration() == SD_FullExpression)
1183 return LinkageInfo::internal();
1184 if (MergeLV(getLVForDecl(MTE->getExtendingDecl(), computation)))
1185 break;
1186 } else {
1187 assert(V.getLValueBase().is<DynamicAllocLValue>() &&
1188 "unexpected LValueBase kind");
1189 return LinkageInfo::internal();
1190 }
1191 // The lvalue path doesn't matter: pointers to all subobjects always have
1192 // the same visibility as pointers to the complete object.
1193 break;
1194 }
1195
1196 case APValue::MemberPointer:
1197 if (const NamedDecl *D = V.getMemberPointerDecl())
1198 MergeLV(getLVForDecl(D, computation));
1199 // Note that we could have a base-to-derived conversion here to a member of
1200 // a derived class with less linkage/visibility. That's covered by the
1201 // linkage and visibility of the value's type.
1202 break;
1203 }
1204
1205 return LV;
1206}
1207

source code of clang/lib/AST/APValue.cpp