clang 24.0.0git
CodeGenTBAA.cpp
Go to the documentation of this file.
1//===-- CodeGenTBAA.cpp - TBAA information for LLVM CodeGen ---------------===//
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 is the code that manages TBAA information and defines the TBAA policy
10// for the optimizer to use. Relevant standards text includes:
11//
12// C99 6.5p7
13// C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
14//
15//===----------------------------------------------------------------------===//
16
17#include "CodeGenTBAA.h"
18#include "ABIInfoImpl.h"
19#include "CGCXXABI.h"
20#include "CGRecordLayout.h"
21#include "CodeGenTypes.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/Mangle.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/Support/Debug.h"
35using namespace clang;
36using namespace CodeGen;
37
39 llvm::Module &M, const CodeGenOptions &CGO,
40 const LangOptions &Features)
41 : Context(Ctx), CGTypes(CGTypes), Module(M), CodeGenOpts(CGO),
42 Features(Features),
43 MangleCtx(ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics())),
44 MDHelper(M.getContext()), Root(nullptr), Char(nullptr) {}
45
48
49llvm::MDNode *CodeGenTBAA::getRoot() {
50 // Define the root of the tree. This identifies the tree, so that
51 // if our LLVM IR is linked with LLVM IR from a different front-end
52 // (or a different version of this front-end), their TBAA trees will
53 // remain distinct, and the optimizer will treat them conservatively.
54 if (!Root) {
55 if (Features.CPlusPlus)
56 Root = MDHelper.createTBAARoot("Simple C++ TBAA");
57 else
58 Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
59 }
60
61 return Root;
62}
63
64llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name,
65 llvm::MDNode *Parent,
66 uint64_t Size) {
67 if (CodeGenOpts.NewStructPathTBAA) {
68 llvm::Metadata *Id = MDHelper.createString(Name);
69 return MDHelper.createTBAATypeNode(Parent, Size, Id);
70 }
71 return MDHelper.createTBAAScalarTypeNode(Name, Parent);
72}
73
74llvm::MDNode *CodeGenTBAA::getChar() {
75 // Define the root of the tree for user-accessible memory. C and C++
76 // give special powers to char and certain similar types. However,
77 // these special powers only cover user-accessible memory, and doesn't
78 // include things like vtables.
79 if (!Char)
80 Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1);
81
82 return Char;
83}
84
85llvm::MDNode *CodeGenTBAA::getAnyPtr(unsigned PtrDepth) {
86 assert(PtrDepth >= 1 && "Pointer must have some depth");
87
88 // Populate at least PtrDepth elements in AnyPtrs. These are the type nodes
89 // for "any" pointers of increasing pointer depth, and are organized in the
90 // hierarchy: any pointer <- any p2 pointer <- any p3 pointer <- ...
91 //
92 // Note that AnyPtrs[Idx] is actually the node for pointer depth (Idx+1),
93 // since there is no node for pointer depth 0.
94 //
95 // These "any" pointer type nodes are used in pointer TBAA. The type node of
96 // a concrete pointer type has the "any" pointer type node of appropriate
97 // pointer depth as its parent. The "any" pointer type nodes are also used
98 // directly for accesses to void pointers, or to specific pointers that we
99 // conservatively do not distinguish in pointer TBAA (e.g. pointers to
100 // members). Essentially, this establishes that e.g. void** can alias with
101 // any type that can unify with T**, ignoring things like qualifiers. Here, T
102 // is a variable that represents an arbitrary type, including pointer types.
103 // As such, each depth is naturally a subtype of the previous depth, and thus
104 // transitively of all previous depths.
105 if (AnyPtrs.size() < PtrDepth) {
106 AnyPtrs.reserve(PtrDepth);
107 auto Size = Module.getDataLayout().getPointerSize();
108 // Populate first element.
109 if (AnyPtrs.empty())
110 AnyPtrs.push_back(createScalarTypeNode("any pointer", getChar(), Size));
111 // Populate further elements.
112 for (size_t Idx = AnyPtrs.size(); Idx < PtrDepth; ++Idx) {
113 auto Name = ("any p" + llvm::Twine(Idx + 1) + " pointer").str();
114 AnyPtrs.push_back(createScalarTypeNode(Name, AnyPtrs[Idx - 1], Size));
115 }
116 }
117
118 return AnyPtrs[PtrDepth - 1];
119}
120
121llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type *Ty) {
122 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
123
124 // Handle builtin types.
125 if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
126 switch (BTy->getKind()) {
127 // Character types are special and can alias anything.
128 // In C++, this technically only includes "char" and "unsigned char",
129 // and not "signed char". In C, it includes all three. For now,
130 // the risk of exploiting this detail in C++ seems likely to outweigh
131 // the benefit.
132 case BuiltinType::Char_U:
133 case BuiltinType::Char_S:
134 case BuiltinType::UChar:
135 case BuiltinType::SChar:
136 return getChar();
137
138 default:
139 break;
140 }
141
142 // Unsigned types can alias their corresponding signed types.
143 QualType SignedTy = CodeGenUtils::getTBAASignedCounterpart(Context, BTy);
144 if (!SignedTy.isNull())
145 return getTypeInfo(SignedTy);
146
147 // Treat all other builtin types as distinct types. This includes
148 // treating wchar_t, char16_t, and char32_t as distinct from their
149 // "underlying types".
150 return createScalarTypeNode(BTy->getName(Features), getChar(), Size);
151 }
152
153 // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
154 // an object through a glvalue of other than one of the following types the
155 // behavior is undefined: [...] a char, unsigned char, or std::byte type."
156 if (Ty->isStdByteType())
157 return getChar();
158
159 // Handle pointers and references.
160 //
161 // C has a very strict rule for pointer aliasing. C23 6.7.6.1p2:
162 // For two pointer types to be compatible, both shall be identically
163 // qualified and both shall be pointers to compatible types.
164 //
165 // This rule is impractically strict; we want to at least ignore CVR
166 // qualifiers. Distinguishing by CVR qualifiers would make it UB to
167 // e.g. cast a `char **` to `const char * const *` and dereference it,
168 // which is too common and useful to invalidate. C++'s similar types
169 // rule permits qualifier differences in these nested positions; in fact,
170 // C++ even allows that cast as an implicit conversion.
171 //
172 // Other qualifiers could theoretically be distinguished, especially if
173 // they involve a significant representation difference. We don't
174 // currently do so, however.
175 if (Ty->isPointerType() || Ty->isReferenceType()) {
176 if (!CodeGenOpts.PointerTBAA)
177 return getAnyPtr();
178 // C++ [basic.lval]p11 permits objects to accessed through an l-value of
179 // similar type. Two types are similar under C++ [conv.qual]p2 if the
180 // decomposition of the types into pointers, member pointers, and arrays has
181 // the same structure when ignoring cv-qualifiers at each level of the
182 // decomposition. Meanwhile, C makes T(*)[] and T(*)[N] compatible, which
183 // would really complicate any attempt to distinguish pointers to arrays by
184 // their bounds. It's simpler, and much easier to explain to users, to
185 // simply treat all pointers to arrays as pointers to their element type for
186 // aliasing purposes. So when creating a TBAA tag for a pointer type, we
187 // recursively ignore both qualifiers and array types when decomposing the
188 // pointee type. The only meaningful remaining structure is the number of
189 // pointer types we encountered along the way, so we just produce the tag
190 // "p<depth> <base type tag>". If we do find a member pointer type, for now
191 // we just conservatively bail out with AnyPtr (below) rather than trying to
192 // create a tag that honors the similar-type rules while still
193 // distinguishing different kinds of member pointer.
194 unsigned PtrDepth = 0;
195 do {
196 PtrDepth++;
198 } while (Ty->isPointerType());
199
200 // While there are no special rules in the standards regarding void pointers
201 // and strict aliasing, emitting distinct tags for void pointers break some
202 // common idioms and there is no good alternative to re-write the code
203 // without strict-aliasing violations.
204 if (Ty->isVoidType())
205 return getAnyPtr(PtrDepth);
206
207 assert(!isa<VariableArrayType>(Ty));
208 // When the underlying type is a builtin type, we compute the pointee type
209 // string recursively, which is implicitly more forgiving than the standards
210 // require. Effectively, we are turning the question "are these types
211 // compatible/similar" into "are accesses to these types allowed to alias".
212 // In both C and C++, the latter question has special carve-outs for
213 // signedness mismatches that only apply at the top level. As a result, we
214 // are allowing e.g. `int *` l-values to access `unsigned *` objects.
215 SmallString<256> TyName;
216 if (isa<BuiltinType>(Ty)) {
217 llvm::MDNode *ScalarMD = getTypeInfoHelper(Ty);
218 StringRef Name =
220 ScalarMD->getOperand(CodeGenOpts.NewStructPathTBAA ? 2 : 0))
221 ->getString();
222 TyName = Name;
223 } else {
224 // Be conservative if the type isn't a RecordType. We are specifically
225 // required to do this for member pointers until we implement the
226 // similar-types rule.
227 const auto *RT = Ty->getAsCanonical<RecordType>();
228 if (!RT)
229 return getAnyPtr(PtrDepth);
230
231 // For unnamed structs or unions C's compatible types rule applies. Two
232 // compatible types in different compilation units can have different
233 // mangled names, meaning the metadata emitted below would incorrectly
234 // mark them as no-alias. Use AnyPtr for such types in both C and C++, as
235 // C and C++ types may be visible when doing LTO.
236 //
237 // Note that using AnyPtr is overly conservative. We could summarize the
238 // members of the type, as per the C compatibility rule in the future.
239 // This also covers anonymous structs and unions, which have a different
240 // compatibility rule, but it doesn't matter because you can never have a
241 // pointer to an anonymous struct or union.
242 if (!RT->getDecl()->getDeclName())
243 return getAnyPtr(PtrDepth);
244
245 // For non-builtin types use the mangled name of the canonical type.
246 llvm::raw_svector_ostream TyOut(TyName);
247 MangleCtx->mangleCanonicalTypeName(QualType(Ty, 0), TyOut);
248 }
249
250 SmallString<256> OutName("p");
251 OutName += std::to_string(PtrDepth);
252 OutName += " ";
253 OutName += TyName;
254 return createScalarTypeNode(OutName, getAnyPtr(PtrDepth), Size);
255 }
256
257 // Accesses to arrays are accesses to objects of their element types.
258 if (CodeGenOpts.NewStructPathTBAA && Ty->isArrayType())
259 return getTypeInfo(cast<ArrayType>(Ty)->getElementType());
260
261 // Accesses to matrix types are accesses to objects of their element types.
262 if (const auto *MTy = dyn_cast<MatrixType>(Ty)) {
263 assert(isa<ConstantMatrixType>(Ty) &&
264 "only ConstantMatrixType should reach CodeGen");
265 return getTypeInfo(MTy->getElementType());
266 }
267
268 if (const auto *CMTy = dyn_cast<CooperativeMatrixType>(Ty))
269 return getTypeInfo(CMTy->getElementType());
270
271 // Accesses to complex types are accesses to objects of their element types.
272 if (const auto *CTy = dyn_cast<ComplexType>(Ty))
273 return getTypeInfo(CTy->getElementType());
274
275 // Enum types are distinct types. In C++ they have "underlying types",
276 // however they aren't related for TBAA.
277 if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
278 const EnumDecl *ED = ETy->getDecl()->getDefinitionOrSelf();
279 if (!Features.CPlusPlus)
280 return getTypeInfo(ED->getIntegerType());
281
282 // In C++ mode, types have linkage, so we can rely on the ODR and
283 // on their mangled names, if they're external.
284 // TODO: Is there a way to get a program-wide unique name for a
285 // decl with local linkage or no linkage?
286 if (!ED->isExternallyVisible())
287 return getChar();
288
289 SmallString<256> OutName;
290 llvm::raw_svector_ostream Out(OutName);
291 CGTypes.getCXXABI().getMangleContext().mangleCanonicalTypeName(
292 QualType(ETy, 0), Out);
293 return createScalarTypeNode(OutName, getChar(), Size);
294 }
295
296 if (const auto *EIT = dyn_cast<BitIntType>(Ty)) {
297 SmallString<256> OutName;
298 llvm::raw_svector_ostream Out(OutName);
299 // Don't specify signed/unsigned since integer types can alias despite sign
300 // differences.
301 Out << "_BitInt(" << EIT->getNumBits() << ')';
302 return createScalarTypeNode(OutName, getChar(), Size);
303 }
304
305 // For now, handle any other kind of type conservatively.
306 return getChar();
307}
308
310 // At -O0 or relaxed aliasing, TBAA is not emitted for regular types (unless
311 // we're running TypeSanitizer).
312 if (!Features.Sanitize.has(SanitizerKind::Type) &&
313 (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing))
314 return nullptr;
315
316 // If the type has the may_alias attribute (even on a typedef), it is
317 // effectively in the general char alias class.
319 return getChar();
320
321 // We need this function to not fall back to returning the "omnipotent char"
322 // type node for aggregate and union types. Otherwise, any dereference of an
323 // aggregate will result into the may-alias access descriptor, meaning all
324 // subsequent accesses to direct and indirect members of that aggregate will
325 // be considered may-alias too.
326 // TODO: Combine getTypeInfo() and getValidBaseTypeInfo() into a single
327 // function.
329 return getValidBaseTypeInfo(QTy);
330
331 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
332 if (llvm::MDNode *N = MetadataCache[Ty])
333 return N;
334
335 // Note that the following helper call is allowed to add new nodes to the
336 // cache, which invalidates all its previously obtained iterators. So we
337 // first generate the node for the type and then add that node to the cache.
338 llvm::MDNode *TypeNode = getTypeInfoHelper(Ty);
339 return MetadataCache[Ty] = TypeNode;
340}
341
343 // Pointee values may have incomplete types, but they shall never be
344 // dereferenced.
345 if (AccessType->isIncompleteType())
347
348 if (CodeGenUtils::typeHasMayAlias(AccessType))
350
351 uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
352 return TBAAAccessInfo(getTypeInfo(AccessType), Size);
353}
354
356 const llvm::DataLayout &DL = Module.getDataLayout();
357 unsigned Size = DL.getPointerTypeSize(VTablePtrType);
358 return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size),
359 Size);
360}
361
362bool
363CodeGenTBAA::CollectFields(uint64_t BaseOffset,
364 QualType QTy,
366 Fields,
367 bool MayAlias) {
368 /* Things not handled yet include: C++ base classes, bitfields, */
369
370 if (const auto *TTy = QTy->getAsCanonical<RecordType>()) {
371 if (TTy->isUnionType()) {
372 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
373 llvm::MDNode *TBAAType = getChar();
374 llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
375 Fields.push_back(
376 llvm::MDBuilder::TBAAStructField(BaseOffset, Size, TBAATag));
377 return true;
378 }
379 const RecordDecl *RD = TTy->getDecl()->getDefinition();
380 if (RD->hasFlexibleArrayMember())
381 return false;
382
383 // TODO: Handle C++ base classes.
384 if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
385 if (!Decl->bases().empty())
386 return false;
387
388 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
389 const CGRecordLayout &CGRL = CGTypes.getCGRecordLayout(RD);
390
391 unsigned idx = 0;
392 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
393 i != e; ++i, ++idx) {
395 continue;
396
397 uint64_t Offset =
398 BaseOffset + Layout.getFieldOffset(idx) / Context.getCharWidth();
399
400 // Create a single field for consecutive named bitfields using char as
401 // base type.
402 if ((*i)->isBitField()) {
403 const CGBitFieldInfo &Info = CGRL.getBitFieldInfo(*i);
404 // For big endian targets the first bitfield in the consecutive run is
405 // at the most-significant end; see CGRecordLowering::setBitFieldInfo
406 // for more information.
407 bool IsBE = Context.getTargetInfo().isBigEndian();
408 bool IsFirst = IsBE ? Info.StorageSize - (Info.Offset + Info.Size) == 0
409 : Info.Offset == 0;
410 if (!IsFirst)
411 continue;
412 unsigned CurrentBitFieldSize = Info.StorageSize;
413 uint64_t Size =
414 llvm::divideCeil(CurrentBitFieldSize, Context.getCharWidth());
415 llvm::MDNode *TBAAType = getChar();
416 llvm::MDNode *TBAATag =
417 getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
418 Fields.push_back(
419 llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
420 continue;
421 }
422
423 QualType FieldQTy = i->getType();
424 if (!CollectFields(Offset, FieldQTy, Fields,
426 return false;
427 }
428 return true;
429 }
430
431 if (const auto *CTy = QTy->getAsCanonical<ComplexType>()) {
432 QualType ElemQTy = CTy->getElementType();
433 uint64_t Size = Context.getTypeSizeInChars(ElemQTy).getQuantity();
434 llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(ElemQTy);
435 llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
436 Fields.push_back(
437 llvm::MDBuilder::TBAAStructField(BaseOffset, Size, TBAATag));
438 Fields.push_back(
439 llvm::MDBuilder::TBAAStructField(BaseOffset + Size, Size, TBAATag));
440 return true;
441 }
442
443 /* Otherwise, treat whatever it is as a field. */
444 uint64_t Offset = BaseOffset;
445 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
446 llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy);
447 llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
448 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
449 return true;
450}
451
452llvm::MDNode *
454 if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
455 return nullptr;
456
457 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
458
459 if (llvm::MDNode *N = StructMetadataCache[Ty])
460 return N;
461
463 if (CollectFields(0, QTy, Fields, CodeGenUtils::typeHasMayAlias(QTy)))
464 return MDHelper.createTBAAStructNode(Fields);
465
466 // For now, handle any other kind of type conservatively.
467 return StructMetadataCache[Ty] = nullptr;
468}
469
470llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) {
471 if (auto *TTy = dyn_cast<RecordType>(Ty)) {
472 const RecordDecl *RD = TTy->getDecl()->getDefinition();
473 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
474 using TBAAStructField = llvm::MDBuilder::TBAAStructField;
476 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
477 // Handle C++ base classes. Non-virtual bases can treated a kind of
478 // field. Virtual bases are more complex and omitted, but avoid an
479 // incomplete view for NewStructPathTBAA.
480 if (CodeGenOpts.NewStructPathTBAA && CXXRD->getNumVBases() != 0)
481 return nullptr;
482 for (const CXXBaseSpecifier &B : CXXRD->bases()) {
483 if (B.isVirtual())
484 continue;
485 QualType BaseQTy = B.getType();
486 const CXXRecordDecl *BaseRD = BaseQTy->getAsCXXRecordDecl();
487 if (BaseRD->isEmpty())
488 continue;
489 llvm::MDNode *TypeNode = CodeGenUtils::isValidTBAABaseType(BaseQTy)
490 ? getValidBaseTypeInfo(BaseQTy)
491 : getTypeInfo(BaseQTy);
492 if (!TypeNode)
493 return nullptr;
494 uint64_t Offset = Layout.getBaseClassOffset(BaseRD).getQuantity();
495 uint64_t Size =
496 Context.getASTRecordLayout(BaseRD).getDataSize().getQuantity();
497 Fields.push_back(
498 llvm::MDBuilder::TBAAStructField(Offset, Size, TypeNode));
499 }
500 // The order in which base class subobjects are allocated is unspecified,
501 // so may differ from declaration order. In particular, Itanium ABI will
502 // allocate a primary base first.
503 // Since we exclude empty subobjects, the objects are not overlapping and
504 // their offsets are unique.
505 llvm::sort(Fields,
506 [](const TBAAStructField &A, const TBAAStructField &B) {
507 return A.Offset < B.Offset;
508 });
509 }
510 for (FieldDecl *Field : RD->fields()) {
511 if (Field->isZeroSize(Context) || Field->isUnnamedBitField())
512 continue;
513 QualType FieldQTy = Field->getType();
514 llvm::MDNode *TypeNode = CodeGenUtils::isValidTBAABaseType(FieldQTy)
515 ? getValidBaseTypeInfo(FieldQTy)
516 : getTypeInfo(FieldQTy);
517 if (!TypeNode)
518 return nullptr;
519
520 uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex());
521 uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity();
522 uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity();
523 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size,
524 TypeNode));
525 }
526
527 SmallString<256> OutName;
528 if (Features.CPlusPlus) {
529 // Don't use the mangler for C code.
530 llvm::raw_svector_ostream Out(OutName);
531 CGTypes.getCXXABI().getMangleContext().mangleCanonicalTypeName(
532 QualType(Ty, 0), Out);
533 } else {
534 OutName = RD->getName();
535 }
536
537 if (CodeGenOpts.NewStructPathTBAA) {
538 llvm::MDNode *Parent = getChar();
539 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
540 llvm::Metadata *Id = MDHelper.createString(OutName);
541 return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields);
542 }
543
544 // Create the struct type node with a vector of pairs (offset, type).
545 SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes;
546 for (const auto &Field : Fields)
547 OffsetsAndTypes.push_back(std::make_pair(Field.Type, Field.Offset));
548 return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes);
549 }
550
551 return nullptr;
552}
553
554llvm::MDNode *CodeGenTBAA::getValidBaseTypeInfo(QualType QTy) {
555 assert(CodeGenUtils::isValidTBAABaseType(QTy) && "Must be a valid base type");
556
557 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
558
559 // nullptr is a valid value in the cache, so use find rather than []
560 auto I = BaseTypeMetadataCache.find(Ty);
561 if (I != BaseTypeMetadataCache.end())
562 return I->second;
563
564 // First calculate the metadata, before recomputing the insertion point, as
565 // the helper can recursively call us.
566 llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
567 [[maybe_unused]] auto inserted = BaseTypeMetadataCache.insert({Ty, TypeNode});
568 assert(inserted.second && "BaseType metadata was already inserted");
569
570 return TypeNode;
571}
572
574 return CodeGenUtils::isValidTBAABaseType(QTy) ? getValidBaseTypeInfo(QTy)
575 : nullptr;
576}
577
579 assert(!Info.isIncomplete() && "Access to an object of an incomplete type!");
580
581 if (Info.isMayAlias())
582 Info = TBAAAccessInfo(getChar(), Info.Size);
583
584 if (!Info.AccessType)
585 return nullptr;
586
587 if (!CodeGenOpts.StructPathTBAA)
588 Info = TBAAAccessInfo(Info.AccessType, Info.Size);
589
590 llvm::MDNode *&N = AccessTagMetadataCache[Info];
591 if (N)
592 return N;
593
594 if (!Info.BaseType) {
595 Info.BaseType = Info.AccessType;
596 assert(!Info.Offset && "Nonzero offset for an access with no base type!");
597 }
598 if (CodeGenOpts.NewStructPathTBAA) {
599 return N = MDHelper.createTBAAAccessTag(Info.BaseType, Info.AccessType,
600 Info.Offset, Info.Size);
601 }
602 return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
603 Info.Offset);
604}
605
612
615 TBAAAccessInfo InfoB) {
616 if (InfoA == InfoB)
617 return InfoA;
618
619 if (!InfoA || !InfoB)
620 return TBAAAccessInfo();
621
622 if (InfoA.isMayAlias() || InfoB.isMayAlias())
624
625 // TODO: Implement the rest of the logic here. For example, two accesses
626 // with same final access types result in an access to an object of that final
627 // access type regardless of their base types.
629}
630
633 TBAAAccessInfo SrcInfo) {
634 if (DestInfo == SrcInfo)
635 return DestInfo;
636
637 if (!DestInfo || !SrcInfo)
638 return TBAAAccessInfo();
639
640 if (DestInfo.isMayAlias() || SrcInfo.isMayAlias())
642
643 // TODO: Implement the rest of the logic here. For example, two accesses
644 // with same final access types result in an access to an object of that final
645 // access type regardless of their base types.
647}
Defines the clang::ASTContext interface.
unsigned IsFirst
Indicates that this is the first token of the file.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
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.
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
llvm::MDNode * getBaseTypeInfo(QualType QTy)
getBaseTypeInfo - Get metadata that describes the given base access type.
llvm::MDNode * getTypeInfo(QualType QTy)
getTypeInfo - Get metadata used to describe accesses to objects of the given type.
TBAAAccessInfo getVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table pointer...
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purpose of memory transfer calls...
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purpose of type casts.
llvm::MDNode * getChar()
getChar - This is the mdnode for "char", which is special, and any types considered to be equivalent ...
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purpose of conditional oper...
llvm::MDNode * getAccessTagInfo(TBAAAccessInfo Info)
getAccessTagInfo - Get TBAA tag for a given memory access.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
getTBAAStructInfo - Get the TBAAStruct MDNode to be used for a memcpy of the given type.
CodeGenTBAA(ASTContext &Ctx, CodeGenTypes &CGTypes, llvm::Module &M, const CodeGenOptions &CGO, const LangOptions &Features)
TBAAAccessInfo getAccessInfo(QualType AccessType)
getAccessInfo - Get TBAA information that describes an access to an object of the given type.
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4371
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Describes a module or submodule.
Definition Module.h:340
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
bool isExternallyVisible() const
Definition Decl.h:435
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
Represents a struct/union/class.
Definition Decl.h:4512
bool hasFlexibleArrayMember() const
Definition Decl.h:4545
field_iterator field_end() const
Definition Decl.h:4718
field_range fields() const
Definition Decl.h:4715
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4696
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4712
field_iterator field_begin() const
Definition Decl.cpp:5397
Exposes information about the current target.
Definition TargetInfo.h:228
bool isVoidType() const
Definition TypeBase.h:9306
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:9016
bool isPointerType() const
Definition TypeBase.h:8917
bool isReferenceType() const
Definition TypeBase.h:8941
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9490
bool isStdByteType() const
Definition Type.cpp:3472
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2678
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
Defines the clang::TargetInfo interface.
bool typeHasMayAlias(QualType QTy)
Returns true if accesses to objects of type QTy are in the general char alias class because of a may_...
Definition TBAAUtils.cpp:16
QualType getTBAASignedCounterpart(const ASTContext &Ctx, const BuiltinType *BTy)
Returns the signed type whose TBAA type node an access to the unsigned builtin type BTy uses,...
Definition TBAAUtils.cpp:55
bool isValidTBAABaseType(QualType QTy)
Returns true if QTy is a valid base type to be used in TBAA access tags.
Definition TBAAUtils.cpp:40
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Structure with information about how a bitfield should be accessed.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits, not including padding.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
uint64_t Size
Size - The size of access, in bytes.
static TBAAAccessInfo getIncompleteInfo()
Definition CodeGenTBAA.h:71
llvm::MDNode * BaseType
BaseType - The base/leading access type.