clang 22.0.0git
Pointer.cpp
Go to the documentation of this file.
1//===--- Pointer.cpp - Types for the constexpr VM ---------------*- C++ -*-===//
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#include "Pointer.h"
10#include "Boolean.h"
11#include "Context.h"
12#include "Floating.h"
13#include "Function.h"
14#include "Integral.h"
15#include "InterpBlock.h"
16#include "MemberPointer.h"
17#include "PrimType.h"
18#include "Record.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22
23using namespace clang;
24using namespace clang::interp;
25
27 : Pointer(Pointee, Pointee->getDescriptor()->getMetadataSize(),
28 Pointee->getDescriptor()->getMetadataSize()) {}
29
30Pointer::Pointer(Block *Pointee, uint64_t BaseAndOffset)
31 : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {}
32
33Pointer::Pointer(Block *Pointee, unsigned Base, uint64_t Offset)
34 : Offset(Offset), StorageKind(Storage::Block) {
35 assert((Base == RootPtrMark || Base % alignof(void *) == 0) && "wrong base");
36
37 BS = {Pointee, Base, nullptr, nullptr};
38
39 if (Pointee)
40 Pointee->addPointer(this);
41}
42
44 : Offset(P.Offset), StorageKind(P.StorageKind) {
45 switch (StorageKind) {
46 case Storage::Int:
47 Int = P.Int;
48 break;
49 case Storage::Block:
50 BS = P.BS;
51 if (BS.Pointee)
52 BS.Pointee->addPointer(this);
53 break;
54 case Storage::Fn:
55 Fn = P.Fn;
56 break;
57 case Storage::Typeid:
58 Typeid = P.Typeid;
59 break;
60 }
61}
62
63Pointer::Pointer(Pointer &&P) : Offset(P.Offset), StorageKind(P.StorageKind) {
64 switch (StorageKind) {
65 case Storage::Int:
66 Int = P.Int;
67 break;
68 case Storage::Block:
69 BS = P.BS;
70 if (BS.Pointee)
71 BS.Pointee->replacePointer(&P, this);
72 break;
73 case Storage::Fn:
74 Fn = P.Fn;
75 break;
76 case Storage::Typeid:
77 Typeid = P.Typeid;
78 break;
79 }
80}
81
83 if (!isBlockPointer())
84 return;
85
86 if (Block *Pointee = BS.Pointee) {
87 Pointee->removePointer(this);
88 BS.Pointee = nullptr;
89 Pointee->cleanup();
90 }
91}
92
94 // If the current storage type is Block, we need to remove
95 // this pointer from the block.
96 if (isBlockPointer()) {
97 if (P.isBlockPointer() && this->block() == P.block()) {
98 Offset = P.Offset;
99 BS.Base = P.BS.Base;
100 return *this;
101 }
102
103 if (Block *Pointee = BS.Pointee) {
104 Pointee->removePointer(this);
105 BS.Pointee = nullptr;
106 Pointee->cleanup();
107 }
108 }
109
110 StorageKind = P.StorageKind;
111 Offset = P.Offset;
112
113 if (P.isBlockPointer()) {
114 BS = P.BS;
115
116 if (BS.Pointee)
117 BS.Pointee->addPointer(this);
118 } else if (P.isIntegralPointer()) {
119 Int = P.Int;
120 } else if (P.isFunctionPointer()) {
121 Fn = P.Fn;
122 } else if (P.isTypeidPointer()) {
123 Typeid = P.Typeid;
124 } else {
125 assert(false && "Unhandled storage kind");
126 }
127 return *this;
128}
129
131 // If the current storage type is Block, we need to remove
132 // this pointer from the block.
133 if (isBlockPointer()) {
134 if (P.isBlockPointer() && this->block() == P.block()) {
135 Offset = P.Offset;
136 BS.Base = P.BS.Base;
137 return *this;
138 }
139
140 if (Block *Pointee = BS.Pointee) {
141 Pointee->removePointer(this);
142 BS.Pointee = nullptr;
143 Pointee->cleanup();
144 }
145 }
146
147 StorageKind = P.StorageKind;
148 Offset = P.Offset;
149
150 if (P.isBlockPointer()) {
151 BS = P.BS;
152
153 if (BS.Pointee)
154 BS.Pointee->addPointer(this);
155 } else if (P.isIntegralPointer()) {
156 Int = P.Int;
157 } else if (P.isFunctionPointer()) {
158 Fn = P.Fn;
159 } else if (P.isTypeidPointer()) {
160 Typeid = P.Typeid;
161 } else {
162 assert(false && "Unhandled storage kind");
163 }
164 return *this;
165}
166
169
170 if (isZero())
171 return APValue(static_cast<const Expr *>(nullptr), CharUnits::Zero(), Path,
172 /*IsOnePastEnd=*/false, /*IsNullPtr=*/true);
173 if (isIntegralPointer())
174 return APValue(static_cast<const Expr *>(nullptr),
176 Path,
177 /*IsOnePastEnd=*/false, /*IsNullPtr=*/false);
178 if (isFunctionPointer()) {
180 if (const FunctionDecl *FD = FP.getFunction()->getDecl())
181 return APValue(FD, CharUnits::fromQuantity(Offset), {},
182 /*OnePastTheEnd=*/false, /*IsNull=*/false);
183 return APValue(FP.getFunction()->getExpr(), CharUnits::fromQuantity(Offset),
184 {},
185 /*OnePastTheEnd=*/false, /*IsNull=*/false);
186 }
187
188 if (isTypeidPointer()) {
191 TypeInfo, QualType(Typeid.TypeInfoType, 0)),
192 CharUnits::Zero(), {},
193 /*OnePastTheEnd=*/false, /*IsNull=*/false);
194 }
195
196 // Build the lvalue base from the block.
197 const Descriptor *Desc = getDeclDesc();
199 if (const auto *VD = Desc->asValueDecl())
200 Base = VD;
201 else if (const auto *E = Desc->asExpr()) {
202 if (block()->isDynamic()) {
203 QualType AllocatedType = getDeclPtr().getFieldDesc()->getDataType(ASTCtx);
204 DynamicAllocLValue DA(*block()->DynAllocId);
205 Base = APValue::LValueBase::getDynamicAlloc(DA, AllocatedType);
206 } else {
207 Base = E;
208 }
209 } else
210 llvm_unreachable("Invalid allocation type");
211
212 if (isUnknownSizeArray())
213 return APValue(Base, CharUnits::Zero(), Path,
214 /*IsOnePastEnd=*/isOnePastEnd(), /*IsNullPtr=*/false);
215
216 CharUnits Offset = CharUnits::Zero();
217
218 auto getFieldOffset = [&](const FieldDecl *FD) -> CharUnits {
219 // This shouldn't happen, but if it does, don't crash inside
220 // getASTRecordLayout.
221 if (FD->getParent()->isInvalidDecl())
222 return CharUnits::Zero();
223 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
224 unsigned FieldIndex = FD->getFieldIndex();
225 return ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex));
226 };
227
228 bool UsePath = true;
229 if (const ValueDecl *VD = getDeclDesc()->asValueDecl();
230 VD && VD->getType()->isReferenceType())
231 UsePath = false;
232
233 // Build the path into the object.
234 bool OnePastEnd = isOnePastEnd() && !isZeroSizeArray();
235 Pointer Ptr = *this;
236 while (Ptr.isField() || Ptr.isArrayElement()) {
237
238 if (Ptr.isArrayRoot()) {
239 // An array root may still be an array element itself.
240 if (Ptr.isArrayElement()) {
241 Ptr = Ptr.expand();
242 const Descriptor *Desc = Ptr.getFieldDesc();
243 unsigned Index = Ptr.getIndex();
244 QualType ElemType = Desc->getElemQualType();
245 Offset += (Index * ASTCtx.getTypeSizeInChars(ElemType));
246 if (Ptr.getArray().getType()->isArrayType())
247 Path.push_back(APValue::LValuePathEntry::ArrayIndex(Index));
248 Ptr = Ptr.getArray();
249 } else {
250 const Descriptor *Desc = Ptr.getFieldDesc();
251 const auto *Dcl = Desc->asDecl();
252 Path.push_back(APValue::LValuePathEntry({Dcl, /*IsVirtual=*/false}));
253
254 if (const auto *FD = dyn_cast_if_present<FieldDecl>(Dcl))
255 Offset += getFieldOffset(FD);
256
257 Ptr = Ptr.getBase();
258 }
259 } else if (Ptr.isArrayElement()) {
260 Ptr = Ptr.expand();
261 const Descriptor *Desc = Ptr.getFieldDesc();
262 unsigned Index;
263 if (Ptr.isOnePastEnd()) {
264 Index = Ptr.getArray().getNumElems();
265 OnePastEnd = false;
266 } else
267 Index = Ptr.getIndex();
268
269 QualType ElemType = Desc->getElemQualType();
270 if (const auto *RD = ElemType->getAsRecordDecl();
271 RD && !RD->getDefinition()) {
272 // Ignore this for the offset.
273 } else {
274 Offset += (Index * ASTCtx.getTypeSizeInChars(ElemType));
275 }
276 if (Ptr.getArray().getType()->isArrayType())
277 Path.push_back(APValue::LValuePathEntry::ArrayIndex(Index));
278 Ptr = Ptr.getArray();
279 } else {
280 const Descriptor *Desc = Ptr.getFieldDesc();
281
282 // Create a path entry for the field.
283 if (const auto *BaseOrMember = Desc->asDecl()) {
284 bool IsVirtual = false;
285 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
286 Ptr = Ptr.getBase();
287 Offset += getFieldOffset(FD);
288 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
289 IsVirtual = Ptr.isVirtualBaseClass();
290 Ptr = Ptr.getBase();
291 const Record *BaseRecord = Ptr.getRecord();
292
293 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(
294 cast<CXXRecordDecl>(BaseRecord->getDecl()));
295 if (IsVirtual)
296 Offset += Layout.getVBaseClassOffset(RD);
297 else
298 Offset += Layout.getBaseClassOffset(RD);
299
300 } else {
301 Ptr = Ptr.getBase();
302 }
303 Path.push_back(APValue::LValuePathEntry({BaseOrMember, IsVirtual}));
304 continue;
305 }
306 llvm_unreachable("Invalid field type");
307 }
308 }
309
310 // We assemble the LValuePath starting from the innermost pointer to the
311 // outermost one. SO in a.b.c, the first element in Path will refer to
312 // the field 'c', while later code expects it to refer to 'a'.
313 // Just invert the order of the elements.
314 std::reverse(Path.begin(), Path.end());
315
316 if (UsePath)
317 return APValue(Base, Offset, Path, OnePastEnd);
318
319 return APValue(Base, Offset, APValue::NoLValuePath());
320}
321
322void Pointer::print(llvm::raw_ostream &OS) const {
323 switch (StorageKind) {
324 case Storage::Block: {
325 const Block *B = BS.Pointee;
326 OS << "(Block) " << B << " {";
327
328 if (isRoot())
329 OS << "rootptr(" << BS.Base << "), ";
330 else
331 OS << BS.Base << ", ";
332
333 if (isElementPastEnd())
334 OS << "pastend, ";
335 else
336 OS << Offset << ", ";
337
338 if (B)
339 OS << B->getSize();
340 else
341 OS << "nullptr";
342 OS << "}";
343 } break;
344 case Storage::Int:
345 OS << "(Int) {";
346 OS << Int.Value << " + " << Offset << ", " << Int.Desc;
347 OS << "}";
348 break;
349 case Storage::Fn:
350 OS << "(Fn) { " << asFunctionPointer().getFunction() << " + " << Offset
351 << " }";
352 break;
353 case Storage::Typeid:
354 OS << "(Typeid) { " << (const void *)asTypeidPointer().TypePtr << ", "
355 << (const void *)asTypeidPointer().TypeInfoType << " + " << Offset
356 << "}";
357 }
358}
359
361 if (isIntegralPointer())
362 return asIntPointer().Value + Offset;
363 if (isTypeidPointer())
364 return reinterpret_cast<uintptr_t>(asTypeidPointer().TypePtr) + Offset;
365
366 if (!isBlockPointer())
367 return Offset;
368
369 size_t Result = 0;
370 Pointer P = *this;
371 while (true) {
372
373 if (P.isVirtualBaseClass()) {
374 Result += getInlineDesc()->Offset;
375 P = P.getBase();
376 continue;
377 }
378
379 if (P.isBaseClass()) {
380 if (P.getRecord()->getNumVirtualBases() > 0)
381 Result += P.getInlineDesc()->Offset;
382 P = P.getBase();
383 continue;
384 }
385 if (P.isArrayElement()) {
386 P = P.expand();
387 Result += (P.getIndex() * P.elemSize());
388 P = P.getArray();
389 continue;
390 }
391
392 if (P.isRoot()) {
393 if (P.isOnePastEnd())
394 ++Result;
395 break;
396 }
397
398 if (const Record *R = P.getBase().getRecord(); R && R->isUnion()) {
399 if (P.isOnePastEnd())
400 ++Result;
401 // Direct child of a union - all have offset 0.
402 P = P.getBase();
403 continue;
404 }
405
406 // Fields, etc.
407 Result += P.getInlineDesc()->Offset;
408 if (P.isOnePastEnd())
409 ++Result;
410
411 P = P.getBase();
412 if (P.isRoot())
413 break;
414 }
415
416 return Result;
417}
418
419std::string Pointer::toDiagnosticString(const ASTContext &Ctx) const {
420 if (isZero())
421 return "nullptr";
422
423 if (isIntegralPointer())
424 return (Twine("&(") + Twine(asIntPointer().Value + Offset) + ")").str();
425
426 if (isFunctionPointer())
428
429 return toAPValue(Ctx).getAsString(Ctx, getType());
430}
431
433 if (!isBlockPointer())
434 return true;
435
436 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
437 Offset == BS.Base) {
438 const GlobalInlineDescriptor &GD =
439 *reinterpret_cast<const GlobalInlineDescriptor *>(block()->rawData());
441 }
442
443 assert(BS.Pointee && "Cannot check if null pointer was initialized");
444 const Descriptor *Desc = getFieldDesc();
445 assert(Desc);
446 if (Desc->isPrimitiveArray())
448
449 if (asBlockPointer().Base == 0)
450 return true;
451 // Field has its bit in an inline descriptor.
452 return getInlineDesc()->IsInitialized;
453}
454
455bool Pointer::isElementInitialized(unsigned Index) const {
456 if (!isBlockPointer())
457 return true;
458
459 const Descriptor *Desc = getFieldDesc();
460 assert(Desc);
461
462 if (isStatic() && BS.Base == 0)
463 return true;
464
465 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
466 Offset == BS.Base) {
467 const GlobalInlineDescriptor &GD =
468 *reinterpret_cast<const GlobalInlineDescriptor *>(block()->rawData());
470 }
471
472 if (Desc->isPrimitiveArray()) {
473 InitMapPtr &IM = getInitMap();
474 if (!IM)
475 return false;
476
477 if (IM->first)
478 return true;
479
480 return IM->second->isElementInitialized(Index);
481 }
482 return isInitialized();
483}
484
486 if (!isBlockPointer())
487 return;
488
489 assert(BS.Pointee && "Cannot initialize null pointer");
490
491 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
492 Offset == BS.Base) {
493 GlobalInlineDescriptor &GD = *reinterpret_cast<GlobalInlineDescriptor *>(
496 return;
497 }
498
499 const Descriptor *Desc = getFieldDesc();
500 assert(Desc);
501 if (Desc->isPrimitiveArray()) {
502 if (Desc->getNumElems() != 0)
504 return;
505 }
506
507 // Field has its bit in an inline descriptor.
508 assert(BS.Base != 0 && "Only composite fields can be initialised");
509 getInlineDesc()->IsInitialized = true;
510}
511
512void Pointer::initializeElement(unsigned Index) const {
513 // Primitive global arrays don't have an initmap.
514 if (isStatic() && BS.Base == 0)
515 return;
516
517 assert(Index < getFieldDesc()->getNumElems());
518
519 InitMapPtr &IM = getInitMap();
520 if (!IM) {
521 const Descriptor *Desc = getFieldDesc();
522 IM = std::make_pair(false, std::make_shared<InitMap>(Desc->getNumElems()));
523 }
524
525 assert(IM);
526
527 // All initialized.
528 if (IM->first)
529 return;
530
531 if (IM->second->initializeElement(Index)) {
532 IM->first = true;
533 IM->second.reset();
534 }
535}
536
538 assert(getFieldDesc()->isPrimitiveArray());
539 assert(isArrayRoot());
540
541 InitMapPtr &IM = getInitMap();
542 if (!IM) {
543 IM = std::make_pair(true, nullptr);
544 } else {
545 IM->first = true;
546 IM->second.reset();
547 }
548}
549
551 assert(getFieldDesc()->isPrimitiveArray());
552 assert(isArrayRoot());
553
554 if (isStatic() && BS.Base == 0)
555 return true;
556
557 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
558 Offset == BS.Base) {
559 const GlobalInlineDescriptor &GD =
560 *reinterpret_cast<const GlobalInlineDescriptor *>(block()->rawData());
562 }
563
564 InitMapPtr &IM = getInitMap();
565 return IM && IM->first;
566}
567
568void Pointer::activate() const {
569 // Field has its bit in an inline descriptor.
570 assert(BS.Base != 0 && "Only composite fields can be activated");
571
572 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor))
573 return;
574 if (!getInlineDesc()->InUnion)
575 return;
576
578 activate = [&activate](Pointer &P) -> void {
579 P.getInlineDesc()->IsActive = true;
580 if (const Record *R = P.getRecord(); R && !R->isUnion()) {
581 for (const Record::Field &F : R->fields()) {
582 Pointer FieldPtr = P.atField(F.Offset);
583 if (!FieldPtr.getInlineDesc()->IsActive)
584 activate(FieldPtr);
585 }
586 // FIXME: Bases?
587 }
588 };
589
591 deactivate = [&deactivate](Pointer &P) -> void {
592 P.getInlineDesc()->IsActive = false;
593
594 if (const Record *R = P.getRecord()) {
595 for (const Record::Field &F : R->fields()) {
596 Pointer FieldPtr = P.atField(F.Offset);
597 if (FieldPtr.getInlineDesc()->IsActive)
598 deactivate(FieldPtr);
599 }
600 // FIXME: Bases?
601 }
602 };
603
604 Pointer B = *this;
605 while (!B.isRoot() && B.inUnion()) {
606 activate(B);
607
608 // When walking up the pointer chain, deactivate
609 // all union child pointers that aren't on our path.
610 Pointer Cur = B;
611 B = B.getBase();
612 if (const Record *BR = B.getRecord(); BR && BR->isUnion()) {
613 for (const Record::Field &F : BR->fields()) {
614 Pointer FieldPtr = B.atField(F.Offset);
615 if (FieldPtr != Cur)
616 deactivate(FieldPtr);
617 }
618 }
619 }
620}
621
623 // TODO: this only appears in constructors, so nothing to deactivate.
624}
625
626bool Pointer::hasSameBase(const Pointer &A, const Pointer &B) {
627 // Two null pointers always have the same base.
628 if (A.isZero() && B.isZero())
629 return true;
630
632 return true;
634 return true;
635 if (A.isTypeidPointer() && B.isTypeidPointer())
636 return true;
637
638 if (A.StorageKind != B.StorageKind)
639 return false;
640
642}
643
644bool Pointer::pointToSameBlock(const Pointer &A, const Pointer &B) {
645 if (!A.isBlockPointer() || !B.isBlockPointer())
646 return false;
647 return A.block() == B.block();
648}
649
650bool Pointer::hasSameArray(const Pointer &A, const Pointer &B) {
651 return hasSameBase(A, B) && A.BS.Base == B.BS.Base &&
653}
654
656 if (isZero() || !isBlockPointer())
657 return false;
658
659 if (block()->isDynamic())
660 return false;
661
662 const Expr *E = block()->getDescriptor()->asExpr();
664}
665
667 if (isZero() || !isBlockPointer())
668 return false;
669
670 if (block()->isDynamic())
671 return false;
672
673 const Expr *E = block()->getDescriptor()->asExpr();
674 return isa_and_nonnull<StringLiteral>(E);
675}
676
677std::optional<std::pair<Pointer, Pointer>>
679 if (!A.isBlockPointer() || !B.isBlockPointer())
680 return std::nullopt;
681
683 return std::nullopt;
684 if (A.isRoot() && B.isRoot())
685 return std::nullopt;
686
687 if (A == B)
688 return std::make_pair(A, B);
689
690 auto getBase = [](const Pointer &P) -> Pointer {
691 if (P.isArrayElement())
692 return P.expand().getArray();
693 return P.getBase();
694 };
695
696 Pointer IterA = A;
697 Pointer IterB = B;
698 Pointer CurA = IterA;
699 Pointer CurB = IterB;
700 for (;;) {
701 if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
702 CurA = IterA;
703 IterA = getBase(IterA);
704 } else {
705 CurB = IterB;
706 IterB = getBase(IterB);
707 }
708
709 if (IterA == IterB)
710 return std::make_pair(CurA, CurB);
711
712 if (IterA.isRoot() && IterB.isRoot())
713 return std::nullopt;
714 }
715
716 llvm_unreachable("The loop above should've returned.");
717}
718
719std::optional<APValue> Pointer::toRValue(const Context &Ctx,
720 QualType ResultType) const {
721 const ASTContext &ASTCtx = Ctx.getASTContext();
722 assert(!ResultType.isNull());
723 // Method to recursively traverse composites.
724 std::function<bool(QualType, const Pointer &, APValue &)> Composite;
725 Composite = [&Composite, &Ctx, &ASTCtx](QualType Ty, const Pointer &Ptr,
726 APValue &R) {
727 if (const auto *AT = Ty->getAs<AtomicType>())
728 Ty = AT->getValueType();
729
730 // Invalid pointers.
731 if (Ptr.isDummy() || !Ptr.isLive() || !Ptr.isBlockPointer() ||
732 Ptr.isPastEnd())
733 return false;
734
735 // Primitive values.
736 if (OptPrimType T = Ctx.classify(Ty)) {
737 TYPE_SWITCH(*T, R = Ptr.deref<T>().toAPValue(ASTCtx));
738 return true;
739 }
740
741 if (const auto *RT = Ty->getAsCanonical<RecordType>()) {
742 const auto *Record = Ptr.getRecord();
743 assert(Record && "Missing record descriptor");
744
745 bool Ok = true;
746 if (RT->getOriginalDecl()->isUnion()) {
747 const FieldDecl *ActiveField = nullptr;
749 for (const auto &F : Record->fields()) {
750 const Pointer &FP = Ptr.atField(F.Offset);
751 QualType FieldTy = F.Decl->getType();
752 if (FP.isActive()) {
753 if (OptPrimType T = Ctx.classify(FieldTy)) {
754 TYPE_SWITCH(*T, Value = FP.deref<T>().toAPValue(ASTCtx));
755 } else {
756 Ok &= Composite(FieldTy, FP, Value);
757 }
758 ActiveField = FP.getFieldDesc()->asFieldDecl();
759 break;
760 }
761 }
762 R = APValue(ActiveField, Value);
763 } else {
764 unsigned NF = Record->getNumFields();
765 unsigned NB = Record->getNumBases();
766 unsigned NV = Ptr.isBaseClass() ? 0 : Record->getNumVirtualBases();
767
768 R = APValue(APValue::UninitStruct(), NB, NF);
769
770 for (unsigned I = 0; I < NF; ++I) {
771 const Record::Field *FD = Record->getField(I);
772 QualType FieldTy = FD->Decl->getType();
773 const Pointer &FP = Ptr.atField(FD->Offset);
774 APValue &Value = R.getStructField(I);
775
776 if (OptPrimType T = Ctx.classify(FieldTy)) {
777 TYPE_SWITCH(*T, Value = FP.deref<T>().toAPValue(ASTCtx));
778 } else {
779 Ok &= Composite(FieldTy, FP, Value);
780 }
781 }
782
783 for (unsigned I = 0; I < NB; ++I) {
784 const Record::Base *BD = Record->getBase(I);
785 QualType BaseTy = Ctx.getASTContext().getCanonicalTagType(BD->Decl);
786 const Pointer &BP = Ptr.atField(BD->Offset);
787 Ok &= Composite(BaseTy, BP, R.getStructBase(I));
788 }
789
790 for (unsigned I = 0; I < NV; ++I) {
791 const Record::Base *VD = Record->getVirtualBase(I);
792 QualType VirtBaseTy =
793 Ctx.getASTContext().getCanonicalTagType(VD->Decl);
794 const Pointer &VP = Ptr.atField(VD->Offset);
795 Ok &= Composite(VirtBaseTy, VP, R.getStructBase(NB + I));
796 }
797 }
798 return Ok;
799 }
800
801 if (Ty->isIncompleteArrayType()) {
802 R = APValue(APValue::UninitArray(), 0, 0);
803 return true;
804 }
805
806 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
807 const size_t NumElems = Ptr.getNumElems();
808 QualType ElemTy = AT->getElementType();
809 R = APValue(APValue::UninitArray{}, NumElems, NumElems);
810
811 bool Ok = true;
812 OptPrimType ElemT = Ctx.classify(ElemTy);
813 for (unsigned I = 0; I != NumElems; ++I) {
814 APValue &Slot = R.getArrayInitializedElt(I);
815 if (ElemT) {
816 TYPE_SWITCH(*ElemT, Slot = Ptr.elem<T>(I).toAPValue(ASTCtx));
817 } else {
818 Ok &= Composite(ElemTy, Ptr.atIndex(I).narrow(), Slot);
819 }
820 }
821 return Ok;
822 }
823
824 // Complex types.
825 if (const auto *CT = Ty->getAs<ComplexType>()) {
826 // Can happen via C casts.
827 if (!Ptr.getFieldDesc()->isPrimitiveArray())
828 return false;
829
830 QualType ElemTy = CT->getElementType();
831 if (ElemTy->isIntegerType()) {
832 OptPrimType ElemT = Ctx.classify(ElemTy);
833 assert(ElemT);
834 INT_TYPE_SWITCH(*ElemT, {
835 auto V1 = Ptr.elem<T>(0);
836 auto V2 = Ptr.elem<T>(1);
837 R = APValue(V1.toAPSInt(), V2.toAPSInt());
838 return true;
839 });
840 } else if (ElemTy->isFloatingType()) {
841 R = APValue(Ptr.elem<Floating>(0).getAPFloat(),
842 Ptr.elem<Floating>(1).getAPFloat());
843 return true;
844 }
845 return false;
846 }
847
848 // Vector types.
849 if (const auto *VT = Ty->getAs<VectorType>()) {
850 assert(Ptr.getFieldDesc()->isPrimitiveArray());
851 QualType ElemTy = VT->getElementType();
852 PrimType ElemT = *Ctx.classify(ElemTy);
853
855 Values.reserve(VT->getNumElements());
856 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
857 TYPE_SWITCH(ElemT,
858 { Values.push_back(Ptr.elem<T>(I).toAPValue(ASTCtx)); });
859 }
860
861 assert(Values.size() == VT->getNumElements());
862 R = APValue(Values.data(), Values.size());
863 return true;
864 }
865
866 llvm_unreachable("invalid value to return");
867 };
868
869 // Invalid to read from.
870 if (isDummy() || !isLive() || isPastEnd())
871 return std::nullopt;
872
873 // We can return these as rvalues, but we can't deref() them.
874 if (isZero() || isIntegralPointer())
875 return toAPValue(ASTCtx);
876
877 // Just load primitive types.
878 if (OptPrimType T = Ctx.classify(ResultType)) {
879 TYPE_SWITCH(*T, return this->deref<T>().toAPValue(ASTCtx));
880 }
881
882 // Return the composite type.
884 if (!Composite(ResultType, *this, Result))
885 return std::nullopt;
886 return Result;
887}
888
890 unsigned Offset) const {
891 if (!this->Desc)
892 return *this;
893 const Record *R = this->Desc->ElemRecord;
894 if (!R)
895 return *this;
896
897 const Record::Field *F = nullptr;
898 for (auto &It : R->fields()) {
899 if (It.Offset == Offset) {
900 F = &It;
901 break;
902 }
903 }
904 if (!F)
905 return *this;
906
907 const FieldDecl *FD = F->Decl;
908 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
909 unsigned FieldIndex = FD->getFieldIndex();
910 uint64_t FieldOffset =
911 ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex))
912 .getQuantity();
913 return IntPointer{F->Desc, this->Value + FieldOffset};
914}
915
917 unsigned BaseOffset) const {
918 if (!Desc) {
919 assert(Value == 0);
920 return *this;
921 }
922 const Record *R = Desc->ElemRecord;
923 const Descriptor *BaseDesc = nullptr;
924
925 // This iterates over bases and checks for the proper offset. That's
926 // potentially slow but this case really shouldn't happen a lot.
927 for (const Record::Base &B : R->bases()) {
928 if (B.Offset == BaseOffset) {
929 BaseDesc = B.Desc;
930 break;
931 }
932 }
933 assert(BaseDesc);
934
935 // Adjust the offset value based on the information from the record layout.
936 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(R->getDecl());
937 CharUnits BaseLayoutOffset =
938 Layout.getBaseClassOffset(cast<CXXRecordDecl>(BaseDesc->asDecl()));
939
940 return {BaseDesc, Value + BaseLayoutOffset.getQuantity()};
941}
Defines the clang::Expr interface and subclasses for C++ expressions.
#define INT_TYPE_SWITCH(Expr, B)
Definition PrimType.h:228
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:207
static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD)
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:207
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
Decl()=delete
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3157
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
Represents a function declaration or definition.
Definition Decl.h:1999
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8621
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
bool isFloatingType() const
Definition Type.cpp:2304
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getSize() const
Returns the size of the block.
Definition InterpBlock.h:87
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition InterpBlock.h:73
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:75
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:310
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
APFloat getAPFloat() const
Definition Floating.h:63
const Function * getFunction() const
std::string toDiagnosticString(const ASTContext &Ctx) const
const BlockExpr * getExpr() const
Definition Function.h:112
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition Function.h:109
static bool hasSameBase(const Pointer &A, const Pointer &B)
Checks if two pointers are comparable.
Definition Pointer.cpp:626
void deactivate() const
Deactivates an entire strurcutre.
Definition Pointer.cpp:622
bool isInitialized() const
Checks if an object was initialized.
Definition Pointer.cpp:432
bool isStatic() const
Checks if the storage is static.
Definition Pointer.h:491
bool isDynamic() const
Checks if the storage has been dynamically allocated.
Definition Pointer.h:506
bool inUnion() const
Definition Pointer.h:399
bool isZeroSizeArray() const
Checks if the pointer is pointing to a zero-size array.
Definition Pointer.h:651
bool isElementInitialized(unsigned Index) const
Like isInitialized(), but for primitive arrays.
Definition Pointer.cpp:455
FunctionPointer Fn
Definition Pointer.h:823
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition Pointer.h:544
void print(llvm::raw_ostream &OS) const
Prints the pointer.
Definition Pointer.cpp:322
int64_t getIndex() const
Returns the index into an array.
Definition Pointer.h:609
bool isActive() const
Checks if the object is active.
Definition Pointer.h:533
Pointer atField(unsigned Off) const
Creates a pointer to a field.
Definition Pointer.h:173
T & deref() const
Dereferences the pointer, if it's live.
Definition Pointer.h:660
unsigned getNumElems() const
Returns the number of elements.
Definition Pointer.h:593
Pointer getArray() const
Returns the parent array.
Definition Pointer.h:313
bool isUnknownSizeArray() const
Checks if the structure is an array of unknown size.
Definition Pointer.h:412
void activate() const
Activats a field.
Definition Pointer.cpp:568
static std::optional< std::pair< Pointer, Pointer > > computeSplitPoint(const Pointer &A, const Pointer &B)
Definition Pointer.cpp:678
const TypeidPointer & asTypeidPointer() const
Definition Pointer.h:460
bool isIntegralPointer() const
Definition Pointer.h:466
QualType getType() const
Returns the type of the innermost field.
Definition Pointer.h:333
bool isArrayElement() const
Checks if the pointer points to an array.
Definition Pointer.h:418
void initializeAllElements() const
Initialize all elements of a primitive array at once.
Definition Pointer.cpp:537
bool pointsToStringLiteral() const
Definition Pointer.cpp:666
bool isArrayRoot() const
Whether this array refers to an array, but not to the first element.
Definition Pointer.h:391
bool isLive() const
Checks if the pointer is live.
Definition Pointer.h:265
bool pointsToLiteral() const
Whether this points to a block that's been created for a "literal lvalue", i.e.
Definition Pointer.cpp:655
Pointer getBase() const
Returns a pointer to the object of which this pointer is a field.
Definition Pointer.h:304
bool isTypeidPointer() const
Definition Pointer.h:468
std::string toDiagnosticString(const ASTContext &Ctx) const
Converts the pointer to a string usable in diagnostics.
Definition Pointer.cpp:419
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:254
Pointer & operator=(const Pointer &P)
Definition Pointer.cpp:93
const IntPointer & asIntPointer() const
Definition Pointer.h:452
bool isRoot() const
Pointer points directly to a block.
Definition Pointer.h:434
const Descriptor * getDeclDesc() const
Accessor for information about the declaration site.
Definition Pointer.h:279
static bool pointToSameBlock(const Pointer &A, const Pointer &B)
Checks if both given pointers point to the same block.
Definition Pointer.cpp:644
APValue toAPValue(const ASTContext &ASTCtx) const
Converts the pointer to an APValue.
Definition Pointer.cpp:167
bool isOnePastEnd() const
Checks if the index is one past end.
Definition Pointer.h:626
static bool hasSameArray(const Pointer &A, const Pointer &B)
Checks if two pointers can be subtracted.
Definition Pointer.cpp:650
bool isPastEnd() const
Checks if the pointer points past the end of the object.
Definition Pointer.h:640
Pointer expand() const
Expands a pointer to the containing array, undoing narrowing.
Definition Pointer.h:221
friend class Block
Definition Pointer.h:782
bool isElementPastEnd() const
Checks if the pointer is an out-of-bounds element pointer.
Definition Pointer.h:648
bool isBlockPointer() const
Definition Pointer.h:465
BlockPointer BS
Definition Pointer.h:822
TypeidPointer Typeid
Definition Pointer.h:824
std::optional< APValue > toRValue(const Context &Ctx, QualType ResultType) const
Converts the pointer to an APValue that is an rvalue.
Definition Pointer.cpp:719
const FunctionPointer & asFunctionPointer() const
Definition Pointer.h:456
bool allElementsInitialized() const
Definition Pointer.cpp:550
const Block * block() const
Definition Pointer.h:599
bool isFunctionPointer() const
Definition Pointer.h:467
Pointer getDeclPtr() const
Definition Pointer.h:352
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition Pointer.h:323
bool isVirtualBaseClass() const
Definition Pointer.h:540
bool isBaseClass() const
Checks if a structure is a base class.
Definition Pointer.h:539
size_t elemSize() const
Returns the element size of the innermost field.
Definition Pointer.h:355
size_t computeOffsetForComparison() const
Compute an integer that can be used to compare this pointer to another one.
Definition Pointer.cpp:360
const BlockPointer & asBlockPointer() const
Definition Pointer.h:448
void initialize() const
Initializes a field.
Definition Pointer.cpp:485
bool isField() const
Checks if the item is a field in an object.
Definition Pointer.h:271
void initializeElement(unsigned Index) const
Initialized the given element of a primitive array.
Definition Pointer.cpp:512
const Record * getRecord() const
Returns the record descriptor of a class.
Definition Pointer.h:471
Structure/Class descriptor.
Definition Record.h:25
const RecordDecl * getDecl() const
Returns the underlying declaration.
Definition Record.h:53
bool isUnion() const
Checks if the record is a union.
Definition Record.h:57
unsigned getNumBases() const
Definition Record.h:96
const Field * getField(const FieldDecl *FD) const
Returns a field.
Definition Record.cpp:47
llvm::iterator_range< const_base_iter > bases() const
Definition Record.h:92
const Base * getVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition Record.cpp:65
unsigned getNumFields() const
Definition Record.h:88
unsigned getNumVirtualBases() const
Definition Record.h:107
llvm::iterator_range< const_field_iter > fields() const
Definition Record.h:84
const Base * getBase(const RecordDecl *FD) const
Returns a base descriptor.
Definition Record.cpp:53
#define bool
Definition gpuintrin.h:32
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
std::optional< std::pair< bool, std::shared_ptr< InitMap > > > InitMapPtr
Definition Descriptor.h:30
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
unsigned Base
Start of the current subfield.
Definition Pointer.h:39
Block * Pointee
The block the pointer is pointing to.
Definition Pointer.h:37
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:249
QualType getElemQualType() const
const ValueDecl * asValueDecl() const
Definition Descriptor.h:214
QualType getType() const
const Decl * asDecl() const
Definition Descriptor.h:210
QualType getDataType(const ASTContext &Ctx) const
const bool IsArray
Flag indicating if the block is an array.
Definition Descriptor.h:168
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:254
const FieldDecl * asFieldDecl() const
Definition Descriptor.h:222
const Expr * asExpr() const
Definition Descriptor.h:211
Descriptor used for global variables.
Definition Descriptor.h:51
unsigned IsActive
Flag indicating if the field is the active member of a union.
Definition Descriptor.h:89
unsigned Offset
Offset inside the structure/array.
Definition Descriptor.h:69
IntPointer baseCast(const ASTContext &ASTCtx, unsigned BaseOffset) const
Definition Pointer.cpp:916
IntPointer atOffset(const ASTContext &ASTCtx, unsigned Offset) const
Definition Pointer.cpp:889
const Descriptor * Desc
Definition Pointer.h:47
const Type * TypeInfoType
Definition Pointer.h:56