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 "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/Type.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
22 
23 /// The identity of a type_info object depends on the canonical unqualified
24 /// type only.
25 TypeInfoLValue::TypeInfoLValue(const Type *T)
26     : T(T->getCanonicalTypeUnqualified().getTypePtr()) {}
27 
28 void TypeInfoLValue::print(llvm::raw_ostream &Out,
29                            const PrintingPolicy &Policy) const {
30   Out << "typeid(";
31   QualType(getType(), 0).print(Out, Policy);
32   Out << ")";
33 }
34 
35 static_assert(
36     1 << llvm::PointerLikeTypeTraits<TypeInfoLValue>::NumLowBitsAvailable <=
37         alignof(Type),
38     "Type is insufficiently aligned");
39 
40 APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V)
41     : Ptr(P), Local{I, V} {}
42 APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
43     : Ptr(P), Local{I, V} {}
44 
45 APValue::LValueBase APValue::LValueBase::getTypeInfo(TypeInfoLValue LV,
46                                                      QualType TypeInfo) {
47   LValueBase Base;
48   Base.Ptr = LV;
49   Base.TypeInfoType = TypeInfo.getAsOpaquePtr();
50   return Base;
51 }
52 
53 unsigned APValue::LValueBase::getCallIndex() const {
54   return is<TypeInfoLValue>() ? 0 : Local.CallIndex;
55 }
56 
57 unsigned APValue::LValueBase::getVersion() const {
58   return is<TypeInfoLValue>() ? 0 : Local.Version;
59 }
60 
61 QualType APValue::LValueBase::getTypeInfoType() const {
62   assert(is<TypeInfoLValue>() && "not a type_info lvalue");
63   return QualType::getFromOpaquePtr(TypeInfoType);
64 }
65 
66 namespace clang {
67 bool operator==(const APValue::LValueBase &LHS,
68                 const APValue::LValueBase &RHS) {
69   if (LHS.Ptr != RHS.Ptr)
70     return false;
71   if (LHS.is<TypeInfoLValue>())
72     return true;
73   return LHS.Local.CallIndex == RHS.Local.CallIndex &&
74          LHS.Local.Version == RHS.Local.Version;
75 }
76 }
77 
78 namespace {
79   struct LVBase {
80     APValue::LValueBase Base;
81     CharUnits Offset;
82     unsigned PathLength;
83     bool IsNullPtr : 1;
84     bool IsOnePastTheEnd : 1;
85   };
86 }
87 
88 void *APValue::LValueBase::getOpaqueValue() const {
89   return Ptr.getOpaqueValue();
90 }
91 
92 bool APValue::LValueBase::isNull() const {
93   return Ptr.isNull();
94 }
95 
96 APValue::LValueBase::operator bool () const {
97   return static_cast<bool>(Ptr);
98 }
99 
100 clang::APValue::LValueBase
101 llvm::DenseMapInfo<clang::APValue::LValueBase>::getEmptyKey() {
102   return clang::APValue::LValueBase(
103       DenseMapInfo<const ValueDecl*>::getEmptyKey());
104 }
105 
106 clang::APValue::LValueBase
107 llvm::DenseMapInfo<clang::APValue::LValueBase>::getTombstoneKey() {
108   return clang::APValue::LValueBase(
109       DenseMapInfo<const ValueDecl*>::getTombstoneKey());
110 }
111 
112 namespace clang {
113 llvm::hash_code hash_value(const APValue::LValueBase &Base) {
114   if (Base.is<TypeInfoLValue>())
115     return llvm::hash_value(Base.getOpaqueValue());
116   return llvm::hash_combine(Base.getOpaqueValue(), Base.getCallIndex(),
117                             Base.getVersion());
118 }
119 }
120 
121 unsigned llvm::DenseMapInfo<clang::APValue::LValueBase>::getHashValue(
122     const clang::APValue::LValueBase &Base) {
123   return hash_value(Base);
124 }
125 
126 bool llvm::DenseMapInfo<clang::APValue::LValueBase>::isEqual(
127     const clang::APValue::LValueBase &LHS,
128     const clang::APValue::LValueBase &RHS) {
129   return LHS == RHS;
130 }
131 
132 struct APValue::LV : LVBase {
133   static const unsigned InlinePathSpace =
134       (DataSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
135 
136   /// Path - The sequence of base classes, fields and array indices to follow to
137   /// walk from Base to the subobject. When performing GCC-style folding, there
138   /// may not be such a path.
139   union {
140     LValuePathEntry Path[InlinePathSpace];
141     LValuePathEntry *PathPtr;
142   };
143 
144   LV() { PathLength = (unsigned)-1; }
145   ~LV() { resizePath(0); }
146 
147   void resizePath(unsigned Length) {
148     if (Length == PathLength)
149       return;
150     if (hasPathPtr())
151       delete [] PathPtr;
152     PathLength = Length;
153     if (hasPathPtr())
154       PathPtr = new LValuePathEntry[Length];
155   }
156 
157   bool hasPath() const { return PathLength != (unsigned)-1; }
158   bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; }
159 
160   LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
161   const LValuePathEntry *getPath() const {
162     return hasPathPtr() ? PathPtr : Path;
163   }
164 };
165 
166 namespace {
167   struct MemberPointerBase {
168     llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMember;
169     unsigned PathLength;
170   };
171 }
172 
173 struct APValue::MemberPointerData : MemberPointerBase {
174   static const unsigned InlinePathSpace =
175       (DataSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
176   typedef const CXXRecordDecl *PathElem;
177   union {
178     PathElem Path[InlinePathSpace];
179     PathElem *PathPtr;
180   };
181 
182   MemberPointerData() { PathLength = 0; }
183   ~MemberPointerData() { resizePath(0); }
184 
185   void resizePath(unsigned Length) {
186     if (Length == PathLength)
187       return;
188     if (hasPathPtr())
189       delete [] PathPtr;
190     PathLength = Length;
191     if (hasPathPtr())
192       PathPtr = new PathElem[Length];
193   }
194 
195   bool hasPathPtr() const { return PathLength > InlinePathSpace; }
196 
197   PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
198   const PathElem *getPath() const {
199     return hasPathPtr() ? PathPtr : Path;
200   }
201 };
202 
203 // FIXME: Reduce the malloc traffic here.
204 
205 APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
206   Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]),
207   NumElts(NumElts), ArrSize(Size) {}
208 APValue::Arr::~Arr() { delete [] Elts; }
209 
210 APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) :
211   Elts(new APValue[NumBases+NumFields]),
212   NumBases(NumBases), NumFields(NumFields) {}
213 APValue::StructData::~StructData() {
214   delete [] Elts;
215 }
216 
217 APValue::UnionData::UnionData() : Field(nullptr), Value(new APValue) {}
218 APValue::UnionData::~UnionData () {
219   delete Value;
220 }
221 
222 APValue::APValue(const APValue &RHS) : Kind(None) {
223   switch (RHS.getKind()) {
224   case None:
225   case Indeterminate:
226     Kind = RHS.getKind();
227     break;
228   case Int:
229     MakeInt();
230     setInt(RHS.getInt());
231     break;
232   case Float:
233     MakeFloat();
234     setFloat(RHS.getFloat());
235     break;
236   case FixedPoint: {
237     APFixedPoint FXCopy = RHS.getFixedPoint();
238     MakeFixedPoint(std::move(FXCopy));
239     break;
240   }
241   case Vector:
242     MakeVector();
243     setVector(((const Vec *)(const char *)RHS.Data.buffer)->Elts,
244               RHS.getVectorLength());
245     break;
246   case ComplexInt:
247     MakeComplexInt();
248     setComplexInt(RHS.getComplexIntReal(), RHS.getComplexIntImag());
249     break;
250   case ComplexFloat:
251     MakeComplexFloat();
252     setComplexFloat(RHS.getComplexFloatReal(), RHS.getComplexFloatImag());
253     break;
254   case LValue:
255     MakeLValue();
256     if (RHS.hasLValuePath())
257       setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), RHS.getLValuePath(),
258                 RHS.isLValueOnePastTheEnd(), RHS.isNullPointer());
259     else
260       setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), NoLValuePath(),
261                 RHS.isNullPointer());
262     break;
263   case Array:
264     MakeArray(RHS.getArrayInitializedElts(), RHS.getArraySize());
265     for (unsigned I = 0, N = RHS.getArrayInitializedElts(); I != N; ++I)
266       getArrayInitializedElt(I) = RHS.getArrayInitializedElt(I);
267     if (RHS.hasArrayFiller())
268       getArrayFiller() = RHS.getArrayFiller();
269     break;
270   case Struct:
271     MakeStruct(RHS.getStructNumBases(), RHS.getStructNumFields());
272     for (unsigned I = 0, N = RHS.getStructNumBases(); I != N; ++I)
273       getStructBase(I) = RHS.getStructBase(I);
274     for (unsigned I = 0, N = RHS.getStructNumFields(); I != N; ++I)
275       getStructField(I) = RHS.getStructField(I);
276     break;
277   case Union:
278     MakeUnion();
279     setUnion(RHS.getUnionField(), RHS.getUnionValue());
280     break;
281   case MemberPointer:
282     MakeMemberPointer(RHS.getMemberPointerDecl(),
283                       RHS.isMemberPointerToDerivedMember(),
284                       RHS.getMemberPointerPath());
285     break;
286   case AddrLabelDiff:
287     MakeAddrLabelDiff();
288     setAddrLabelDiff(RHS.getAddrLabelDiffLHS(), RHS.getAddrLabelDiffRHS());
289     break;
290   }
291 }
292 
293 void APValue::DestroyDataAndMakeUninit() {
294   if (Kind == Int)
295     ((APSInt*)(char*)Data.buffer)->~APSInt();
296   else if (Kind == Float)
297     ((APFloat*)(char*)Data.buffer)->~APFloat();
298   else if (Kind == FixedPoint)
299     ((APFixedPoint *)(char *)Data.buffer)->~APFixedPoint();
300   else if (Kind == Vector)
301     ((Vec*)(char*)Data.buffer)->~Vec();
302   else if (Kind == ComplexInt)
303     ((ComplexAPSInt*)(char*)Data.buffer)->~ComplexAPSInt();
304   else if (Kind == ComplexFloat)
305     ((ComplexAPFloat*)(char*)Data.buffer)->~ComplexAPFloat();
306   else if (Kind == LValue)
307     ((LV*)(char*)Data.buffer)->~LV();
308   else if (Kind == Array)
309     ((Arr*)(char*)Data.buffer)->~Arr();
310   else if (Kind == Struct)
311     ((StructData*)(char*)Data.buffer)->~StructData();
312   else if (Kind == Union)
313     ((UnionData*)(char*)Data.buffer)->~UnionData();
314   else if (Kind == MemberPointer)
315     ((MemberPointerData*)(char*)Data.buffer)->~MemberPointerData();
316   else if (Kind == AddrLabelDiff)
317     ((AddrLabelDiffData*)(char*)Data.buffer)->~AddrLabelDiffData();
318   Kind = None;
319 }
320 
321 bool APValue::needsCleanup() const {
322   switch (getKind()) {
323   case None:
324   case Indeterminate:
325   case AddrLabelDiff:
326     return false;
327   case Struct:
328   case Union:
329   case Array:
330   case Vector:
331     return true;
332   case Int:
333     return getInt().needsCleanup();
334   case Float:
335     return getFloat().needsCleanup();
336   case FixedPoint:
337     return getFixedPoint().getValue().needsCleanup();
338   case ComplexFloat:
339     assert(getComplexFloatImag().needsCleanup() ==
340                getComplexFloatReal().needsCleanup() &&
341            "In _Complex float types, real and imaginary values always have the "
342            "same size.");
343     return getComplexFloatReal().needsCleanup();
344   case ComplexInt:
345     assert(getComplexIntImag().needsCleanup() ==
346                getComplexIntReal().needsCleanup() &&
347            "In _Complex int types, real and imaginary values must have the "
348            "same size.");
349     return getComplexIntReal().needsCleanup();
350   case LValue:
351     return reinterpret_cast<const LV *>(Data.buffer)->hasPathPtr();
352   case MemberPointer:
353     return reinterpret_cast<const MemberPointerData *>(Data.buffer)
354         ->hasPathPtr();
355   }
356   llvm_unreachable("Unknown APValue kind!");
357 }
358 
359 void APValue::swap(APValue &RHS) {
360   std::swap(Kind, RHS.Kind);
361   char TmpData[DataSize];
362   memcpy(TmpData, Data.buffer, DataSize);
363   memcpy(Data.buffer, RHS.Data.buffer, DataSize);
364   memcpy(RHS.Data.buffer, TmpData, DataSize);
365 }
366 
367 LLVM_DUMP_METHOD void APValue::dump() const {
368   dump(llvm::errs());
369   llvm::errs() << '\n';
370 }
371 
372 static double GetApproxValue(const llvm::APFloat &F) {
373   llvm::APFloat V = F;
374   bool ignored;
375   V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
376             &ignored);
377   return V.convertToDouble();
378 }
379 
380 void APValue::dump(raw_ostream &OS) const {
381   switch (getKind()) {
382   case None:
383     OS << "None";
384     return;
385   case Indeterminate:
386     OS << "Indeterminate";
387     return;
388   case Int:
389     OS << "Int: " << getInt();
390     return;
391   case Float:
392     OS << "Float: " << GetApproxValue(getFloat());
393     return;
394   case FixedPoint:
395     OS << "FixedPoint : " << getFixedPoint();
396     return;
397   case Vector:
398     OS << "Vector: ";
399     getVectorElt(0).dump(OS);
400     for (unsigned i = 1; i != getVectorLength(); ++i) {
401       OS << ", ";
402       getVectorElt(i).dump(OS);
403     }
404     return;
405   case ComplexInt:
406     OS << "ComplexInt: " << getComplexIntReal() << ", " << getComplexIntImag();
407     return;
408   case ComplexFloat:
409     OS << "ComplexFloat: " << GetApproxValue(getComplexFloatReal())
410        << ", " << GetApproxValue(getComplexFloatImag());
411     return;
412   case LValue:
413     OS << "LValue: <todo>";
414     return;
415   case Array:
416     OS << "Array: ";
417     for (unsigned I = 0, N = getArrayInitializedElts(); I != N; ++I) {
418       getArrayInitializedElt(I).dump(OS);
419       if (I != getArraySize() - 1) OS << ", ";
420     }
421     if (hasArrayFiller()) {
422       OS << getArraySize() - getArrayInitializedElts() << " x ";
423       getArrayFiller().dump(OS);
424     }
425     return;
426   case Struct:
427     OS << "Struct ";
428     if (unsigned N = getStructNumBases()) {
429       OS << " bases: ";
430       getStructBase(0).dump(OS);
431       for (unsigned I = 1; I != N; ++I) {
432         OS << ", ";
433         getStructBase(I).dump(OS);
434       }
435     }
436     if (unsigned N = getStructNumFields()) {
437       OS << " fields: ";
438       getStructField(0).dump(OS);
439       for (unsigned I = 1; I != N; ++I) {
440         OS << ", ";
441         getStructField(I).dump(OS);
442       }
443     }
444     return;
445   case Union:
446     OS << "Union: ";
447     getUnionValue().dump(OS);
448     return;
449   case MemberPointer:
450     OS << "MemberPointer: <todo>";
451     return;
452   case AddrLabelDiff:
453     OS << "AddrLabelDiff: <todo>";
454     return;
455   }
456   llvm_unreachable("Unknown APValue kind!");
457 }
458 
459 void APValue::printPretty(raw_ostream &Out, ASTContext &Ctx, QualType Ty) const{
460   switch (getKind()) {
461   case APValue::None:
462     Out << "<out of lifetime>";
463     return;
464   case APValue::Indeterminate:
465     Out << "<uninitialized>";
466     return;
467   case APValue::Int:
468     if (Ty->isBooleanType())
469       Out << (getInt().getBoolValue() ? "true" : "false");
470     else
471       Out << getInt();
472     return;
473   case APValue::Float:
474     Out << GetApproxValue(getFloat());
475     return;
476   case APValue::FixedPoint:
477     Out << getFixedPoint();
478     return;
479   case APValue::Vector: {
480     Out << '{';
481     QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
482     getVectorElt(0).printPretty(Out, Ctx, ElemTy);
483     for (unsigned i = 1; i != getVectorLength(); ++i) {
484       Out << ", ";
485       getVectorElt(i).printPretty(Out, Ctx, ElemTy);
486     }
487     Out << '}';
488     return;
489   }
490   case APValue::ComplexInt:
491     Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
492     return;
493   case APValue::ComplexFloat:
494     Out << GetApproxValue(getComplexFloatReal()) << "+"
495         << GetApproxValue(getComplexFloatImag()) << "i";
496     return;
497   case APValue::LValue: {
498     bool IsReference = Ty->isReferenceType();
499     QualType InnerTy
500       = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
501     if (InnerTy.isNull())
502       InnerTy = Ty;
503 
504     LValueBase Base = getLValueBase();
505     if (!Base) {
506       if (isNullPointer()) {
507         Out << (Ctx.getLangOpts().CPlusPlus11 ? "nullptr" : "0");
508       } else if (IsReference) {
509         Out << "*(" << InnerTy.stream(Ctx.getPrintingPolicy()) << "*)"
510             << getLValueOffset().getQuantity();
511       } else {
512         Out << "(" << Ty.stream(Ctx.getPrintingPolicy()) << ")"
513             << getLValueOffset().getQuantity();
514       }
515       return;
516     }
517 
518     if (!hasLValuePath()) {
519       // No lvalue path: just print the offset.
520       CharUnits O = getLValueOffset();
521       CharUnits S = Ctx.getTypeSizeInChars(InnerTy);
522       if (!O.isZero()) {
523         if (IsReference)
524           Out << "*(";
525         if (O % S) {
526           Out << "(char*)";
527           S = CharUnits::One();
528         }
529         Out << '&';
530       } else if (!IsReference)
531         Out << '&';
532 
533       if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
534         Out << *VD;
535       else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
536         TI.print(Out, Ctx.getPrintingPolicy());
537       } else {
538         assert(Base.get<const Expr *>() != nullptr &&
539                "Expecting non-null Expr");
540         Base.get<const Expr*>()->printPretty(Out, nullptr,
541                                              Ctx.getPrintingPolicy());
542       }
543 
544       if (!O.isZero()) {
545         Out << " + " << (O / S);
546         if (IsReference)
547           Out << ')';
548       }
549       return;
550     }
551 
552     // We have an lvalue path. Print it out nicely.
553     if (!IsReference)
554       Out << '&';
555     else if (isLValueOnePastTheEnd())
556       Out << "*(&";
557 
558     QualType ElemTy;
559     if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
560       Out << *VD;
561       ElemTy = VD->getType();
562     } else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
563       TI.print(Out, Ctx.getPrintingPolicy());
564       ElemTy = Base.getTypeInfoType();
565     } else {
566       const Expr *E = Base.get<const Expr*>();
567       assert(E != nullptr && "Expecting non-null Expr");
568       E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
569       ElemTy = E->getType();
570     }
571 
572     ArrayRef<LValuePathEntry> Path = getLValuePath();
573     const CXXRecordDecl *CastToBase = nullptr;
574     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
575       if (ElemTy->getAs<RecordType>()) {
576         // The lvalue refers to a class type, so the next path entry is a base
577         // or member.
578         const Decl *BaseOrMember = Path[I].getAsBaseOrMember().getPointer();
579         if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
580           CastToBase = RD;
581           ElemTy = Ctx.getRecordType(RD);
582         } else {
583           const ValueDecl *VD = cast<ValueDecl>(BaseOrMember);
584           Out << ".";
585           if (CastToBase)
586             Out << *CastToBase << "::";
587           Out << *VD;
588           ElemTy = VD->getType();
589         }
590       } else {
591         // The lvalue must refer to an array.
592         Out << '[' << Path[I].getAsArrayIndex() << ']';
593         ElemTy = Ctx.getAsArrayType(ElemTy)->getElementType();
594       }
595     }
596 
597     // Handle formatting of one-past-the-end lvalues.
598     if (isLValueOnePastTheEnd()) {
599       // FIXME: If CastToBase is non-0, we should prefix the output with
600       // "(CastToBase*)".
601       Out << " + 1";
602       if (IsReference)
603         Out << ')';
604     }
605     return;
606   }
607   case APValue::Array: {
608     const ArrayType *AT = Ctx.getAsArrayType(Ty);
609     QualType ElemTy = AT->getElementType();
610     Out << '{';
611     if (unsigned N = getArrayInitializedElts()) {
612       getArrayInitializedElt(0).printPretty(Out, Ctx, ElemTy);
613       for (unsigned I = 1; I != N; ++I) {
614         Out << ", ";
615         if (I == 10) {
616           // Avoid printing out the entire contents of large arrays.
617           Out << "...";
618           break;
619         }
620         getArrayInitializedElt(I).printPretty(Out, Ctx, ElemTy);
621       }
622     }
623     Out << '}';
624     return;
625   }
626   case APValue::Struct: {
627     Out << '{';
628     const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
629     bool First = true;
630     if (unsigned N = getStructNumBases()) {
631       const CXXRecordDecl *CD = cast<CXXRecordDecl>(RD);
632       CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
633       for (unsigned I = 0; I != N; ++I, ++BI) {
634         assert(BI != CD->bases_end());
635         if (!First)
636           Out << ", ";
637         getStructBase(I).printPretty(Out, Ctx, BI->getType());
638         First = false;
639       }
640     }
641     for (const auto *FI : RD->fields()) {
642       if (!First)
643         Out << ", ";
644       if (FI->isUnnamedBitfield()) continue;
645       getStructField(FI->getFieldIndex()).
646         printPretty(Out, Ctx, FI->getType());
647       First = false;
648     }
649     Out << '}';
650     return;
651   }
652   case APValue::Union:
653     Out << '{';
654     if (const FieldDecl *FD = getUnionField()) {
655       Out << "." << *FD << " = ";
656       getUnionValue().printPretty(Out, Ctx, FD->getType());
657     }
658     Out << '}';
659     return;
660   case APValue::MemberPointer:
661     // FIXME: This is not enough to unambiguously identify the member in a
662     // multiple-inheritance scenario.
663     if (const ValueDecl *VD = getMemberPointerDecl()) {
664       Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << *VD;
665       return;
666     }
667     Out << "0";
668     return;
669   case APValue::AddrLabelDiff:
670     Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
671     Out << " - ";
672     Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
673     return;
674   }
675   llvm_unreachable("Unknown APValue kind!");
676 }
677 
678 std::string APValue::getAsString(ASTContext &Ctx, QualType Ty) const {
679   std::string Result;
680   llvm::raw_string_ostream Out(Result);
681   printPretty(Out, Ctx, Ty);
682   Out.flush();
683   return Result;
684 }
685 
686 bool APValue::toIntegralConstant(APSInt &Result, QualType SrcTy,
687                                  const ASTContext &Ctx) const {
688   if (isInt()) {
689     Result = getInt();
690     return true;
691   }
692 
693   if (isLValue() && isNullPointer()) {
694     Result = Ctx.MakeIntValue(Ctx.getTargetNullPointerValue(SrcTy), SrcTy);
695     return true;
696   }
697 
698   if (isLValue() && !getLValueBase()) {
699     Result = Ctx.MakeIntValue(getLValueOffset().getQuantity(), SrcTy);
700     return true;
701   }
702 
703   return false;
704 }
705 
706 const APValue::LValueBase APValue::getLValueBase() const {
707   assert(isLValue() && "Invalid accessor");
708   return ((const LV*)(const void*)Data.buffer)->Base;
709 }
710 
711 bool APValue::isLValueOnePastTheEnd() const {
712   assert(isLValue() && "Invalid accessor");
713   return ((const LV*)(const void*)Data.buffer)->IsOnePastTheEnd;
714 }
715 
716 CharUnits &APValue::getLValueOffset() {
717   assert(isLValue() && "Invalid accessor");
718   return ((LV*)(void*)Data.buffer)->Offset;
719 }
720 
721 bool APValue::hasLValuePath() const {
722   assert(isLValue() && "Invalid accessor");
723   return ((const LV*)(const char*)Data.buffer)->hasPath();
724 }
725 
726 ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
727   assert(isLValue() && hasLValuePath() && "Invalid accessor");
728   const LV &LVal = *((const LV*)(const char*)Data.buffer);
729   return llvm::makeArrayRef(LVal.getPath(), LVal.PathLength);
730 }
731 
732 unsigned APValue::getLValueCallIndex() const {
733   assert(isLValue() && "Invalid accessor");
734   return ((const LV*)(const char*)Data.buffer)->Base.getCallIndex();
735 }
736 
737 unsigned APValue::getLValueVersion() const {
738   assert(isLValue() && "Invalid accessor");
739   return ((const LV*)(const char*)Data.buffer)->Base.getVersion();
740 }
741 
742 bool APValue::isNullPointer() const {
743   assert(isLValue() && "Invalid usage");
744   return ((const LV*)(const char*)Data.buffer)->IsNullPtr;
745 }
746 
747 void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
748                         bool IsNullPtr) {
749   assert(isLValue() && "Invalid accessor");
750   LV &LVal = *((LV*)(char*)Data.buffer);
751   LVal.Base = B;
752   LVal.IsOnePastTheEnd = false;
753   LVal.Offset = O;
754   LVal.resizePath((unsigned)-1);
755   LVal.IsNullPtr = IsNullPtr;
756 }
757 
758 void APValue::setLValue(LValueBase B, const CharUnits &O,
759                         ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
760                         bool IsNullPtr) {
761   assert(isLValue() && "Invalid accessor");
762   LV &LVal = *((LV*)(char*)Data.buffer);
763   LVal.Base = B;
764   LVal.IsOnePastTheEnd = IsOnePastTheEnd;
765   LVal.Offset = O;
766   LVal.resizePath(Path.size());
767   memcpy(LVal.getPath(), Path.data(), Path.size() * sizeof(LValuePathEntry));
768   LVal.IsNullPtr = IsNullPtr;
769 }
770 
771 const ValueDecl *APValue::getMemberPointerDecl() const {
772   assert(isMemberPointer() && "Invalid accessor");
773   const MemberPointerData &MPD =
774       *((const MemberPointerData *)(const char *)Data.buffer);
775   return MPD.MemberAndIsDerivedMember.getPointer();
776 }
777 
778 bool APValue::isMemberPointerToDerivedMember() const {
779   assert(isMemberPointer() && "Invalid accessor");
780   const MemberPointerData &MPD =
781       *((const MemberPointerData *)(const char *)Data.buffer);
782   return MPD.MemberAndIsDerivedMember.getInt();
783 }
784 
785 ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
786   assert(isMemberPointer() && "Invalid accessor");
787   const MemberPointerData &MPD =
788       *((const MemberPointerData *)(const char *)Data.buffer);
789   return llvm::makeArrayRef(MPD.getPath(), MPD.PathLength);
790 }
791 
792 void APValue::MakeLValue() {
793   assert(isAbsent() && "Bad state change");
794   static_assert(sizeof(LV) <= DataSize, "LV too big");
795   new ((void*)(char*)Data.buffer) LV();
796   Kind = LValue;
797 }
798 
799 void APValue::MakeArray(unsigned InitElts, unsigned Size) {
800   assert(isAbsent() && "Bad state change");
801   new ((void*)(char*)Data.buffer) Arr(InitElts, Size);
802   Kind = Array;
803 }
804 
805 void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
806                                 ArrayRef<const CXXRecordDecl*> Path) {
807   assert(isAbsent() && "Bad state change");
808   MemberPointerData *MPD = new ((void*)(char*)Data.buffer) MemberPointerData;
809   Kind = MemberPointer;
810   MPD->MemberAndIsDerivedMember.setPointer(Member);
811   MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
812   MPD->resizePath(Path.size());
813   memcpy(MPD->getPath(), Path.data(), Path.size()*sizeof(const CXXRecordDecl*));
814 }
815