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 bool APValue::needsCleanup() const {
226 return getInt().needsCleanup();
228 return getFloat().needsCleanup();
230 assert(getComplexFloatImag().needsCleanup() ==
231 getComplexFloatReal().needsCleanup() &&
232 "In _Complex float types, real and imaginary values always have the "
234 return getComplexFloatReal().needsCleanup();
236 assert(getComplexIntImag().needsCleanup() ==
237 getComplexIntReal().needsCleanup() &&
238 "In _Complex int types, real and imaginary values must have the "
240 return getComplexIntReal().needsCleanup();
242 return reinterpret_cast<const LV *>(Data)->hasPathPtr();
244 return reinterpret_cast<const MemberPointerData *>(Data)->hasPathPtr();
246 llvm_unreachable("Unknown APValue kind!");
249 void APValue::swap(APValue &RHS) {
250 std::swap(Kind, RHS.Kind);
251 char TmpData[MaxSize];
252 memcpy(TmpData, Data, MaxSize);
253 memcpy(Data, RHS.Data, MaxSize);
254 memcpy(RHS.Data, TmpData, MaxSize);
257 void APValue::dump() const {
259 llvm::errs() << '\n';
262 static double GetApproxValue(const llvm::APFloat &F) {
265 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
267 return V.convertToDouble();
270 void APValue::dump(raw_ostream &OS) const {
273 OS << "Uninitialized";
276 OS << "Int: " << getInt();
279 OS << "Float: " << GetApproxValue(getFloat());
283 getVectorElt(0).dump(OS);
284 for (unsigned i = 1; i != getVectorLength(); ++i) {
286 getVectorElt(i).dump(OS);
290 OS << "ComplexInt: " << getComplexIntReal() << ", " << getComplexIntImag();
293 OS << "ComplexFloat: " << GetApproxValue(getComplexFloatReal())
294 << ", " << GetApproxValue(getComplexFloatImag());
297 OS << "LValue: <todo>";
301 for (unsigned I = 0, N = getArrayInitializedElts(); I != N; ++I) {
302 getArrayInitializedElt(I).dump(OS);
303 if (I != getArraySize() - 1) OS << ", ";
305 if (hasArrayFiller()) {
306 OS << getArraySize() - getArrayInitializedElts() << " x ";
307 getArrayFiller().dump(OS);
312 if (unsigned N = getStructNumBases()) {
314 getStructBase(0).dump(OS);
315 for (unsigned I = 1; I != N; ++I) {
317 getStructBase(I).dump(OS);
320 if (unsigned N = getStructNumFields()) {
322 getStructField(0).dump(OS);
323 for (unsigned I = 1; I != N; ++I) {
325 getStructField(I).dump(OS);
331 getUnionValue().dump(OS);
334 OS << "MemberPointer: <todo>";
337 OS << "AddrLabelDiff: <todo>";
340 llvm_unreachable("Unknown APValue kind!");
343 void APValue::printPretty(raw_ostream &Out, ASTContext &Ctx, QualType Ty) const{
345 case APValue::Uninitialized:
346 Out << "<uninitialized>";
349 if (Ty->isBooleanType())
350 Out << (getInt().getBoolValue() ? "true" : "false");
355 Out << GetApproxValue(getFloat());
357 case APValue::Vector: {
359 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
360 getVectorElt(0).printPretty(Out, Ctx, ElemTy);
361 for (unsigned i = 1; i != getVectorLength(); ++i) {
363 getVectorElt(i).printPretty(Out, Ctx, ElemTy);
368 case APValue::ComplexInt:
369 Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
371 case APValue::ComplexFloat:
372 Out << GetApproxValue(getComplexFloatReal()) << "+"
373 << GetApproxValue(getComplexFloatImag()) << "i";
375 case APValue::LValue: {
376 LValueBase Base = getLValueBase();
382 bool IsReference = Ty->isReferenceType();
384 = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
385 if (InnerTy.isNull())
388 if (!hasLValuePath()) {
389 // No lvalue path: just print the offset.
390 CharUnits O = getLValueOffset();
391 CharUnits S = Ctx.getTypeSizeInChars(InnerTy);
397 S = CharUnits::One();
400 } else if (!IsReference)
403 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
406 Base.get<const Expr*>()->printPretty(Out, 0, Ctx.getPrintingPolicy());
408 Out << " + " << (O / S);
415 // We have an lvalue path. Print it out nicely.
418 else if (isLValueOnePastTheEnd())
422 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
424 ElemTy = VD->getType();
426 const Expr *E = Base.get<const Expr*>();
427 E->printPretty(Out, 0, Ctx.getPrintingPolicy());
428 ElemTy = E->getType();
431 ArrayRef<LValuePathEntry> Path = getLValuePath();
432 const CXXRecordDecl *CastToBase = 0;
433 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
434 if (ElemTy->getAs<RecordType>()) {
435 // The lvalue refers to a class type, so the next path entry is a base
437 const Decl *BaseOrMember =
438 BaseOrMemberType::getFromOpaqueValue(Path[I].BaseOrMember).getPointer();
439 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
441 ElemTy = Ctx.getRecordType(RD);
443 const ValueDecl *VD = cast<ValueDecl>(BaseOrMember);
446 Out << *CastToBase << "::";
448 ElemTy = VD->getType();
451 // The lvalue must refer to an array.
452 Out << '[' << Path[I].ArrayIndex << ']';
453 ElemTy = Ctx.getAsArrayType(ElemTy)->getElementType();
457 // Handle formatting of one-past-the-end lvalues.
458 if (isLValueOnePastTheEnd()) {
459 // FIXME: If CastToBase is non-0, we should prefix the output with
467 case APValue::Array: {
468 const ArrayType *AT = Ctx.getAsArrayType(Ty);
469 QualType ElemTy = AT->getElementType();
471 if (unsigned N = getArrayInitializedElts()) {
472 getArrayInitializedElt(0).printPretty(Out, Ctx, ElemTy);
473 for (unsigned I = 1; I != N; ++I) {
476 // Avoid printing out the entire contents of large arrays.
480 getArrayInitializedElt(I).printPretty(Out, Ctx, ElemTy);
486 case APValue::Struct: {
488 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
490 if (unsigned N = getStructNumBases()) {
491 const CXXRecordDecl *CD = cast<CXXRecordDecl>(RD);
492 CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
493 for (unsigned I = 0; I != N; ++I, ++BI) {
494 assert(BI != CD->bases_end());
497 getStructBase(I).printPretty(Out, Ctx, BI->getType());
501 for (RecordDecl::field_iterator FI = RD->field_begin();
502 FI != RD->field_end(); ++FI) {
505 if (FI->isUnnamedBitfield()) continue;
506 getStructField(FI->getFieldIndex()).
507 printPretty(Out, Ctx, FI->getType());
515 if (const FieldDecl *FD = getUnionField()) {
516 Out << "." << *FD << " = ";
517 getUnionValue().printPretty(Out, Ctx, FD->getType());
521 case APValue::MemberPointer:
522 // FIXME: This is not enough to unambiguously identify the member in a
523 // multiple-inheritance scenario.
524 if (const ValueDecl *VD = getMemberPointerDecl()) {
525 Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << *VD;
530 case APValue::AddrLabelDiff:
531 Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
533 Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
536 llvm_unreachable("Unknown APValue kind!");
539 std::string APValue::getAsString(ASTContext &Ctx, QualType Ty) const {
541 llvm::raw_string_ostream Out(Result);
542 printPretty(Out, Ctx, Ty);
547 const APValue::LValueBase APValue::getLValueBase() const {
548 assert(isLValue() && "Invalid accessor");
549 return ((const LV*)(const void*)Data)->BaseAndIsOnePastTheEnd.getPointer();
552 bool APValue::isLValueOnePastTheEnd() const {
553 assert(isLValue() && "Invalid accessor");
554 return ((const LV*)(const void*)Data)->BaseAndIsOnePastTheEnd.getInt();
557 CharUnits &APValue::getLValueOffset() {
558 assert(isLValue() && "Invalid accessor");
559 return ((LV*)(void*)Data)->Offset;
562 bool APValue::hasLValuePath() const {
563 assert(isLValue() && "Invalid accessor");
564 return ((const LV*)(const char*)Data)->hasPath();
567 ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
568 assert(isLValue() && hasLValuePath() && "Invalid accessor");
569 const LV &LVal = *((const LV*)(const char*)Data);
570 return ArrayRef<LValuePathEntry>(LVal.getPath(), LVal.PathLength);
573 unsigned APValue::getLValueCallIndex() const {
574 assert(isLValue() && "Invalid accessor");
575 return ((const LV*)(const char*)Data)->CallIndex;
578 void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
579 unsigned CallIndex) {
580 assert(isLValue() && "Invalid accessor");
581 LV &LVal = *((LV*)(char*)Data);
582 LVal.BaseAndIsOnePastTheEnd.setPointer(B);
583 LVal.BaseAndIsOnePastTheEnd.setInt(false);
585 LVal.CallIndex = CallIndex;
586 LVal.resizePath((unsigned)-1);
589 void APValue::setLValue(LValueBase B, const CharUnits &O,
590 ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
591 unsigned CallIndex) {
592 assert(isLValue() && "Invalid accessor");
593 LV &LVal = *((LV*)(char*)Data);
594 LVal.BaseAndIsOnePastTheEnd.setPointer(B);
595 LVal.BaseAndIsOnePastTheEnd.setInt(IsOnePastTheEnd);
597 LVal.CallIndex = CallIndex;
598 LVal.resizePath(Path.size());
599 memcpy(LVal.getPath(), Path.data(), Path.size() * sizeof(LValuePathEntry));
602 const ValueDecl *APValue::getMemberPointerDecl() const {
603 assert(isMemberPointer() && "Invalid accessor");
604 const MemberPointerData &MPD = *((const MemberPointerData*)(const char*)Data);
605 return MPD.MemberAndIsDerivedMember.getPointer();
608 bool APValue::isMemberPointerToDerivedMember() const {
609 assert(isMemberPointer() && "Invalid accessor");
610 const MemberPointerData &MPD = *((const MemberPointerData*)(const char*)Data);
611 return MPD.MemberAndIsDerivedMember.getInt();
614 ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
615 assert(isMemberPointer() && "Invalid accessor");
616 const MemberPointerData &MPD = *((const MemberPointerData*)(const char*)Data);
617 return ArrayRef<const CXXRecordDecl*>(MPD.getPath(), MPD.PathLength);
620 void APValue::MakeLValue() {
621 assert(isUninit() && "Bad state change");
622 assert(sizeof(LV) <= MaxSize && "LV too big");
623 new ((void*)(char*)Data) LV();
627 void APValue::MakeArray(unsigned InitElts, unsigned Size) {
628 assert(isUninit() && "Bad state change");
629 new ((void*)(char*)Data) Arr(InitElts, Size);
633 void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
634 ArrayRef<const CXXRecordDecl*> Path) {
635 assert(isUninit() && "Bad state change");
636 MemberPointerData *MPD = new ((void*)(char*)Data) MemberPointerData;
637 Kind = MemberPointer;
638 MPD->MemberAndIsDerivedMember.setPointer(Member);
639 MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
640 MPD->resizePath(Path.size());
641 memcpy(MPD->getPath(), Path.data(), Path.size()*sizeof(const CXXRecordDecl*));