1 //===--- APValue.cpp - Union class for APFloat/APSInt/Complex -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the APValue class.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/APValue.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/Type.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
28 llvm::PointerIntPair<APValue::LValueBase, 1, bool> BaseAndIsOnePastTheEnd;
35 struct APValue::LV : LVBase {
36 static const unsigned InlinePathSpace =
37 (MaxSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
39 /// Path - The sequence of base classes, fields and array indices to follow to
40 /// walk from Base to the subobject. When performing GCC-style folding, there
41 /// may not be such a path.
43 LValuePathEntry Path[InlinePathSpace];
44 LValuePathEntry *PathPtr;
47 LV() { PathLength = (unsigned)-1; }
48 ~LV() { resizePath(0); }
50 void resizePath(unsigned Length) {
51 if (Length == PathLength)
57 PathPtr = new LValuePathEntry[Length];
60 bool hasPath() const { return PathLength != (unsigned)-1; }
61 bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; }
63 LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
64 const LValuePathEntry *getPath() const {
65 return hasPathPtr() ? PathPtr : Path;
70 struct MemberPointerBase {
71 llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMember;
76 struct APValue::MemberPointerData : MemberPointerBase {
77 static const unsigned InlinePathSpace =
78 (MaxSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
79 typedef const CXXRecordDecl *PathElem;
81 PathElem Path[InlinePathSpace];
85 MemberPointerData() { PathLength = 0; }
86 ~MemberPointerData() { resizePath(0); }
88 void resizePath(unsigned Length) {
89 if (Length == PathLength)
95 PathPtr = new PathElem[Length];
98 bool hasPathPtr() const { return PathLength > InlinePathSpace; }
100 PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
101 const PathElem *getPath() const {
102 return hasPathPtr() ? PathPtr : Path;
106 // FIXME: Reduce the malloc traffic here.
108 APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
109 Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]),
110 NumElts(NumElts), ArrSize(Size) {}
111 APValue::Arr::~Arr() { delete [] Elts; }
113 APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) :
114 Elts(new APValue[NumBases+NumFields]),
115 NumBases(NumBases), NumFields(NumFields) {}
116 APValue::StructData::~StructData() {
120 APValue::UnionData::UnionData() : Field(0), Value(new APValue) {}
121 APValue::UnionData::~UnionData () {
125 APValue::APValue(const APValue &RHS) : Kind(Uninitialized) {
126 switch (RHS.getKind()) {
131 setInt(RHS.getInt());
135 setFloat(RHS.getFloat());
139 setVector(((const Vec *)(const char *)RHS.Data)->Elts,
140 RHS.getVectorLength());
144 setComplexInt(RHS.getComplexIntReal(), RHS.getComplexIntImag());
148 setComplexFloat(RHS.getComplexFloatReal(), RHS.getComplexFloatImag());
152 if (RHS.hasLValuePath())
153 setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), RHS.getLValuePath(),
154 RHS.isLValueOnePastTheEnd(), RHS.getLValueCallIndex());
156 setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), NoLValuePath(),
157 RHS.getLValueCallIndex());
160 MakeArray(RHS.getArrayInitializedElts(), RHS.getArraySize());
161 for (unsigned I = 0, N = RHS.getArrayInitializedElts(); I != N; ++I)
162 getArrayInitializedElt(I) = RHS.getArrayInitializedElt(I);
163 if (RHS.hasArrayFiller())
164 getArrayFiller() = RHS.getArrayFiller();
167 MakeStruct(RHS.getStructNumBases(), RHS.getStructNumFields());
168 for (unsigned I = 0, N = RHS.getStructNumBases(); I != N; ++I)
169 getStructBase(I) = RHS.getStructBase(I);
170 for (unsigned I = 0, N = RHS.getStructNumFields(); I != N; ++I)
171 getStructField(I) = RHS.getStructField(I);
175 setUnion(RHS.getUnionField(), RHS.getUnionValue());
178 MakeMemberPointer(RHS.getMemberPointerDecl(),
179 RHS.isMemberPointerToDerivedMember(),
180 RHS.getMemberPointerPath());
184 setAddrLabelDiff(RHS.getAddrLabelDiffLHS(), RHS.getAddrLabelDiffRHS());
189 void APValue::DestroyDataAndMakeUninit() {
191 ((APSInt*)(char*)Data)->~APSInt();
192 else if (Kind == Float)
193 ((APFloat*)(char*)Data)->~APFloat();
194 else if (Kind == Vector)
195 ((Vec*)(char*)Data)->~Vec();
196 else if (Kind == ComplexInt)
197 ((ComplexAPSInt*)(char*)Data)->~ComplexAPSInt();
198 else if (Kind == ComplexFloat)
199 ((ComplexAPFloat*)(char*)Data)->~ComplexAPFloat();
200 else if (Kind == LValue)
201 ((LV*)(char*)Data)->~LV();
202 else if (Kind == Array)
203 ((Arr*)(char*)Data)->~Arr();
204 else if (Kind == Struct)
205 ((StructData*)(char*)Data)->~StructData();
206 else if (Kind == Union)
207 ((UnionData*)(char*)Data)->~UnionData();
208 else if (Kind == MemberPointer)
209 ((MemberPointerData*)(char*)Data)->~MemberPointerData();
210 else if (Kind == AddrLabelDiff)
211 ((AddrLabelDiffData*)(char*)Data)->~AddrLabelDiffData();
212 Kind = Uninitialized;
215 void APValue::swap(APValue &RHS) {
216 std::swap(Kind, RHS.Kind);
217 char TmpData[MaxSize];
218 memcpy(TmpData, Data, MaxSize);
219 memcpy(Data, RHS.Data, MaxSize);
220 memcpy(RHS.Data, TmpData, MaxSize);
223 void APValue::dump() const {
225 llvm::errs() << '\n';
228 static double GetApproxValue(const llvm::APFloat &F) {
231 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
233 return V.convertToDouble();
236 void APValue::dump(raw_ostream &OS) const {
239 OS << "Uninitialized";
242 OS << "Int: " << getInt();
245 OS << "Float: " << GetApproxValue(getFloat());
249 getVectorElt(0).dump(OS);
250 for (unsigned i = 1; i != getVectorLength(); ++i) {
252 getVectorElt(i).dump(OS);
256 OS << "ComplexInt: " << getComplexIntReal() << ", " << getComplexIntImag();
259 OS << "ComplexFloat: " << GetApproxValue(getComplexFloatReal())
260 << ", " << GetApproxValue(getComplexFloatImag());
263 OS << "LValue: <todo>";
267 for (unsigned I = 0, N = getArrayInitializedElts(); I != N; ++I) {
268 getArrayInitializedElt(I).dump(OS);
269 if (I != getArraySize() - 1) OS << ", ";
271 if (hasArrayFiller()) {
272 OS << getArraySize() - getArrayInitializedElts() << " x ";
273 getArrayFiller().dump(OS);
278 if (unsigned N = getStructNumBases()) {
280 getStructBase(0).dump(OS);
281 for (unsigned I = 1; I != N; ++I) {
283 getStructBase(I).dump(OS);
286 if (unsigned N = getStructNumFields()) {
288 getStructField(0).dump(OS);
289 for (unsigned I = 1; I != N; ++I) {
291 getStructField(I).dump(OS);
297 getUnionValue().dump(OS);
300 OS << "MemberPointer: <todo>";
303 OS << "AddrLabelDiff: <todo>";
306 llvm_unreachable("Unknown APValue kind!");
309 void APValue::printPretty(raw_ostream &Out, ASTContext &Ctx, QualType Ty) const{
311 case APValue::Uninitialized:
312 Out << "<uninitialized>";
315 if (Ty->isBooleanType())
316 Out << (getInt().getBoolValue() ? "true" : "false");
321 Out << GetApproxValue(getFloat());
323 case APValue::Vector: {
325 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
326 getVectorElt(0).printPretty(Out, Ctx, ElemTy);
327 for (unsigned i = 1; i != getVectorLength(); ++i) {
329 getVectorElt(i).printPretty(Out, Ctx, ElemTy);
334 case APValue::ComplexInt:
335 Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
337 case APValue::ComplexFloat:
338 Out << GetApproxValue(getComplexFloatReal()) << "+"
339 << GetApproxValue(getComplexFloatImag()) << "i";
341 case APValue::LValue: {
342 LValueBase Base = getLValueBase();
348 bool IsReference = Ty->isReferenceType();
350 = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
351 if (InnerTy.isNull())
354 if (!hasLValuePath()) {
355 // No lvalue path: just print the offset.
356 CharUnits O = getLValueOffset();
357 CharUnits S = Ctx.getTypeSizeInChars(InnerTy);
363 S = CharUnits::One();
366 } else if (!IsReference)
369 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
372 Base.get<const Expr*>()->printPretty(Out, 0, Ctx.getPrintingPolicy());
374 Out << " + " << (O / S);
381 // We have an lvalue path. Print it out nicely.
384 else if (isLValueOnePastTheEnd())
388 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
390 ElemTy = VD->getType();
392 const Expr *E = Base.get<const Expr*>();
393 E->printPretty(Out, 0, Ctx.getPrintingPolicy());
394 ElemTy = E->getType();
397 ArrayRef<LValuePathEntry> Path = getLValuePath();
398 const CXXRecordDecl *CastToBase = 0;
399 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
400 if (ElemTy->getAs<RecordType>()) {
401 // The lvalue refers to a class type, so the next path entry is a base
403 const Decl *BaseOrMember =
404 BaseOrMemberType::getFromOpaqueValue(Path[I].BaseOrMember).getPointer();
405 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
407 ElemTy = Ctx.getRecordType(RD);
409 const ValueDecl *VD = cast<ValueDecl>(BaseOrMember);
412 Out << *CastToBase << "::";
414 ElemTy = VD->getType();
417 // The lvalue must refer to an array.
418 Out << '[' << Path[I].ArrayIndex << ']';
419 ElemTy = Ctx.getAsArrayType(ElemTy)->getElementType();
423 // Handle formatting of one-past-the-end lvalues.
424 if (isLValueOnePastTheEnd()) {
425 // FIXME: If CastToBase is non-0, we should prefix the output with
433 case APValue::Array: {
434 const ArrayType *AT = Ctx.getAsArrayType(Ty);
435 QualType ElemTy = AT->getElementType();
437 if (unsigned N = getArrayInitializedElts()) {
438 getArrayInitializedElt(0).printPretty(Out, Ctx, ElemTy);
439 for (unsigned I = 1; I != N; ++I) {
442 // Avoid printing out the entire contents of large arrays.
446 getArrayInitializedElt(I).printPretty(Out, Ctx, ElemTy);
452 case APValue::Struct: {
454 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
456 if (unsigned N = getStructNumBases()) {
457 const CXXRecordDecl *CD = cast<CXXRecordDecl>(RD);
458 CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
459 for (unsigned I = 0; I != N; ++I, ++BI) {
460 assert(BI != CD->bases_end());
463 getStructBase(I).printPretty(Out, Ctx, BI->getType());
467 for (RecordDecl::field_iterator FI = RD->field_begin();
468 FI != RD->field_end(); ++FI) {
471 if (FI->isUnnamedBitfield()) continue;
472 getStructField(FI->getFieldIndex()).
473 printPretty(Out, Ctx, FI->getType());
481 if (const FieldDecl *FD = getUnionField()) {
482 Out << "." << *FD << " = ";
483 getUnionValue().printPretty(Out, Ctx, FD->getType());
487 case APValue::MemberPointer:
488 // FIXME: This is not enough to unambiguously identify the member in a
489 // multiple-inheritance scenario.
490 if (const ValueDecl *VD = getMemberPointerDecl()) {
491 Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << *VD;
496 case APValue::AddrLabelDiff:
497 Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
499 Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
502 llvm_unreachable("Unknown APValue kind!");
505 std::string APValue::getAsString(ASTContext &Ctx, QualType Ty) const {
507 llvm::raw_string_ostream Out(Result);
508 printPretty(Out, Ctx, Ty);
513 const APValue::LValueBase APValue::getLValueBase() const {
514 assert(isLValue() && "Invalid accessor");
515 return ((const LV*)(const void*)Data)->BaseAndIsOnePastTheEnd.getPointer();
518 bool APValue::isLValueOnePastTheEnd() const {
519 assert(isLValue() && "Invalid accessor");
520 return ((const LV*)(const void*)Data)->BaseAndIsOnePastTheEnd.getInt();
523 CharUnits &APValue::getLValueOffset() {
524 assert(isLValue() && "Invalid accessor");
525 return ((LV*)(void*)Data)->Offset;
528 bool APValue::hasLValuePath() const {
529 assert(isLValue() && "Invalid accessor");
530 return ((const LV*)(const char*)Data)->hasPath();
533 ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
534 assert(isLValue() && hasLValuePath() && "Invalid accessor");
535 const LV &LVal = *((const LV*)(const char*)Data);
536 return ArrayRef<LValuePathEntry>(LVal.getPath(), LVal.PathLength);
539 unsigned APValue::getLValueCallIndex() const {
540 assert(isLValue() && "Invalid accessor");
541 return ((const LV*)(const char*)Data)->CallIndex;
544 void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
545 unsigned CallIndex) {
546 assert(isLValue() && "Invalid accessor");
547 LV &LVal = *((LV*)(char*)Data);
548 LVal.BaseAndIsOnePastTheEnd.setPointer(B);
549 LVal.BaseAndIsOnePastTheEnd.setInt(false);
551 LVal.CallIndex = CallIndex;
552 LVal.resizePath((unsigned)-1);
555 void APValue::setLValue(LValueBase B, const CharUnits &O,
556 ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
557 unsigned CallIndex) {
558 assert(isLValue() && "Invalid accessor");
559 LV &LVal = *((LV*)(char*)Data);
560 LVal.BaseAndIsOnePastTheEnd.setPointer(B);
561 LVal.BaseAndIsOnePastTheEnd.setInt(IsOnePastTheEnd);
563 LVal.CallIndex = CallIndex;
564 LVal.resizePath(Path.size());
565 memcpy(LVal.getPath(), Path.data(), Path.size() * sizeof(LValuePathEntry));
568 const ValueDecl *APValue::getMemberPointerDecl() const {
569 assert(isMemberPointer() && "Invalid accessor");
570 const MemberPointerData &MPD = *((const MemberPointerData*)(const char*)Data);
571 return MPD.MemberAndIsDerivedMember.getPointer();
574 bool APValue::isMemberPointerToDerivedMember() const {
575 assert(isMemberPointer() && "Invalid accessor");
576 const MemberPointerData &MPD = *((const MemberPointerData*)(const char*)Data);
577 return MPD.MemberAndIsDerivedMember.getInt();
580 ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
581 assert(isMemberPointer() && "Invalid accessor");
582 const MemberPointerData &MPD = *((const MemberPointerData*)(const char*)Data);
583 return ArrayRef<const CXXRecordDecl*>(MPD.getPath(), MPD.PathLength);
586 void APValue::MakeLValue() {
587 assert(isUninit() && "Bad state change");
588 assert(sizeof(LV) <= MaxSize && "LV too big");
589 new ((void*)(char*)Data) LV();
593 void APValue::MakeArray(unsigned InitElts, unsigned Size) {
594 assert(isUninit() && "Bad state change");
595 new ((void*)(char*)Data) Arr(InitElts, Size);
599 void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
600 ArrayRef<const CXXRecordDecl*> Path) {
601 assert(isUninit() && "Bad state change");
602 MemberPointerData *MPD = new ((void*)(char*)Data) MemberPointerData;
603 Kind = MemberPointer;
604 MPD->MemberAndIsDerivedMember.setPointer(Member);
605 MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
606 MPD->resizePath(Path.size());
607 memcpy(MPD->getPath(), Path.data(), Path.size()*sizeof(const CXXRecordDecl*));