LLVM 24.0.0git
TypeBasedAliasAnalysis.cpp
Go to the documentation of this file.
1//===- TypeBasedAliasAnalysis.cpp - Type-Based Alias Analysis -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the TypeBasedAliasAnalysis pass, which implements
10// metadata-based TBAA.
11//
12// In LLVM IR, memory does not have types, so LLVM's own type system is not
13// suitable for doing TBAA. Instead, metadata is added to the IR to describe
14// a type system of a higher level language. This can be used to implement
15// typical C/C++ TBAA, but it can also be used to implement custom alias
16// analysis behavior for other languages.
17//
18// Scalar type nodes have up to three fields, e.g.:
19// !0 = !{ !"an example type tree" }
20// !1 = !{ !"int", !0 }
21// !2 = !{ !"float", !0 }
22// !3 = !{ !"const float", !2, i64 1 }
23//
24// The first field is an identity field. It can be any value, usually
25// an MDString, which uniquely identifies the type. The most important
26// name in the tree is the name of the root node. Two trees with
27// different root node names are entirely disjoint, even if they
28// have leaves with common names.
29//
30// The second field identifies the type's parent node in the tree, or
31// is null or omitted for a root node. A type is considered to alias
32// all of its descendants and all of its ancestors in the tree. Also,
33// a type is considered to alias all types in other trees, so that
34// bitcode produced from multiple front-ends is handled conservatively.
35//
36// If the third field is present, it's an integer which if equal to 1
37// indicates that the type is "constant" (meaning pointsToConstantMemory
38// should return true; see
39// http://llvm.org/docs/AliasAnalysis.html#OtherItfs).
40//
41// The MDNodes attached to an instruction using "!tbaa" are not plain type
42// nodes, but path tag nodes.
43//
44// The path tag node has 4 fields with the last field being optional.
45//
46// The first field is the base type node, it can be a struct type node
47// or a scalar type node. The second field is the access type node, it
48// must be a scalar type node. The third field is the offset into the base type.
49// The last field has the same meaning as the last field of our scalar TBAA:
50// it's an integer which if equal to 1 indicates that the access is "constant".
51//
52// The struct type node has a name and a list of pairs, one pair for each member
53// of the struct. The first element of each pair is a type node (a struct type
54// node or a scalar type node), specifying the type of the member, the second
55// element of each pair is the offset of the member.
56//
57// Given an example
58// typedef struct {
59// short s;
60// } A;
61// typedef struct {
62// uint16_t s;
63// A a;
64// } B;
65//
66// For an access to B.a.s, we attach !5 (a path tag node) to the load/store
67// instruction. The base type is !4 (struct B), the access type is !2 (scalar
68// type short) and the offset is 4.
69//
70// !0 = !{!"Simple C/C++ TBAA"}
71// !1 = !{!"omnipotent char", !0} // Scalar type node
72// !2 = !{!"short", !1} // Scalar type node
73// !3 = !{!"A", !2, i64 0} // Struct type node
74// !4 = !{!"B", !2, i64 0, !3, i64 4}
75// // Struct type node
76// !5 = !{!4, !2, i64 4} // Path tag node
77//
78// The struct type nodes and the scalar type nodes form a type DAG.
79// Root (!0)
80// char (!1) -- edge to Root
81// short (!2) -- edge to char
82// A (!3) -- edge with offset 0 to short
83// B (!4) -- edge with offset 0 to short and edge with offset 4 to A
84//
85// To check if two tags (tagX and tagY) can alias, we start from the base type
86// of tagX, follow the edge with the correct offset in the type DAG and adjust
87// the offset until we reach the base type of tagY or until we reach the Root
88// node.
89// If we reach the base type of tagY, compare the adjusted offset with
90// offset of tagY, return Alias if the offsets are the same, return NoAlias
91// otherwise.
92// If we reach the Root node, perform the above starting from base type of tagY
93// to see if we reach base type of tagX.
94//
95// If they have different roots, they're part of different potentially
96// unrelated type systems, so we return Alias to be conservative.
97// If neither node is an ancestor of the other and they have the same root,
98// then we say NoAlias.
99//
100//===----------------------------------------------------------------------===//
101
103#include "AnalysisOptions.h"
104#include "llvm/ADT/STLExtras.h"
105#include "llvm/ADT/SmallVector.h"
108#include "llvm/IR/Constants.h"
109#include "llvm/IR/DataLayout.h"
110#include "llvm/IR/DerivedTypes.h"
111#include "llvm/IR/InstrTypes.h"
112#include "llvm/IR/LLVMContext.h"
113#include "llvm/IR/Metadata.h"
114#include "llvm/IR/Module.h"
116#include "llvm/Pass.h"
117#include "llvm/Support/Casting.h"
118#include <cassert>
119#include <cstdint>
120
121using namespace llvm;
122
123namespace {
124
125/// isNewFormatTypeNode - Return true iff the given type node is in the new
126/// size-aware format.
127static bool isNewFormatTypeNode(const MDNode *N) {
128 if (N->getNumOperands() < 3)
129 return false;
130 // In the old format the first operand is a string.
131 if (!isa<MDNode>(N->getOperand(0)))
132 return false;
133 return true;
134}
135
136/// This is a simple wrapper around an MDNode which provides a higher-level
137/// interface by hiding the details of how alias analysis information is encoded
138/// in its operands.
139class TBAANode {
140 const MDNode *Node = nullptr;
141
142public:
143 TBAANode() = default;
144 explicit TBAANode(const MDNode *N) : Node(N) {}
145
146 /// getNode - Get the MDNode for this TBAANode.
147 const MDNode *getNode() const { return Node; }
148
149 /// isNewFormat - Return true iff the wrapped type node is in the new
150 /// size-aware format.
151 bool isNewFormat() const { return isNewFormatTypeNode(Node); }
152
153 /// getParent - Get this TBAANode's Alias tree parent.
154 TBAANode getParent() const {
155 if (isNewFormat())
156 return TBAANode(cast<MDNode>(Node->getOperand(0)));
157
158 if (Node->getNumOperands() < 2)
159 return TBAANode();
160 const MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
161 if (!P)
162 return TBAANode();
163 // Ok, this node has a valid parent. Return it.
164 return TBAANode(P);
165 }
166};
167
168/// This is a simple wrapper around an MDNode which provides a
169/// higher-level interface by hiding the details of how alias analysis
170/// information is encoded in its operands.
171class TBAAStructTagNode {
172 /// This node should be created with createTBAAAccessTag().
173 const MDNode *Node;
174
175public:
176 explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
177
178 /// Get the MDNode for this TBAAStructTagNode.
179 const MDNode *getNode() const { return Node; }
180
181 /// isNewFormat - Return true iff the wrapped access tag is in the new
182 /// size-aware format.
183 bool isNewFormat() const {
184 if (Node->getNumOperands() < 4)
185 return false;
186 if (const MDNode *AccessType = getAccessType())
187 if (!TBAANode(AccessType).isNewFormat())
188 return false;
189 return true;
190 }
191
192 const MDNode *getBaseType() const {
193 return dyn_cast_or_null<MDNode>(Node->getOperand(0));
194 }
195
196 const MDNode *getAccessType() const {
197 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
198 }
199
200 uint64_t getOffset() const {
201 return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue();
202 }
203
204 uint64_t getSize() const {
205 if (!isNewFormat())
206 return UINT64_MAX;
207 return mdconst::extract<ConstantInt>(Node->getOperand(3))->getZExtValue();
208 }
209
210 /// Test if this TBAAStructTagNode represents a type for objects
211 /// which are not modified (by any means) in the context where this
212 /// AliasAnalysis is relevant.
213 bool isTypeImmutable() const {
214 unsigned OpNo = isNewFormat() ? 4 : 3;
215 if (Node->getNumOperands() < OpNo + 1)
216 return false;
217 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(OpNo));
218 if (!CI)
219 return false;
220 return CI->getValue()[0];
221 }
222};
223
224/// This is a simple wrapper around an MDNode which provides a
225/// higher-level interface by hiding the details of how alias analysis
226/// information is encoded in its operands.
227class TBAAStructTypeNode {
228 /// This node should be created with createTBAATypeNode().
229 const MDNode *Node = nullptr;
230
231public:
232 TBAAStructTypeNode() = default;
233 explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
234
235 /// Get the MDNode for this TBAAStructTypeNode.
236 const MDNode *getNode() const { return Node; }
237
238 /// isNewFormat - Return true iff the wrapped type node is in the new
239 /// size-aware format.
240 bool isNewFormat() const { return isNewFormatTypeNode(Node); }
241
242 bool operator==(const TBAAStructTypeNode &Other) const {
243 return getNode() == Other.getNode();
244 }
245
246 /// getId - Return type identifier.
247 Metadata *getId() const {
248 return Node->getOperand(isNewFormat() ? 2 : 0);
249 }
250
251 unsigned getNumFields() const {
252 unsigned FirstFieldOpNo = isNewFormat() ? 3 : 1;
253 unsigned NumOpsPerField = isNewFormat() ? 3 : 2;
254 return (getNode()->getNumOperands() - FirstFieldOpNo) / NumOpsPerField;
255 }
256
257 TBAAStructTypeNode getFieldType(unsigned FieldIndex) const {
258 unsigned FirstFieldOpNo = isNewFormat() ? 3 : 1;
259 unsigned NumOpsPerField = isNewFormat() ? 3 : 2;
260 unsigned OpIndex = FirstFieldOpNo + FieldIndex * NumOpsPerField;
261 auto *TypeNode = cast<MDNode>(getNode()->getOperand(OpIndex));
262 return TBAAStructTypeNode(TypeNode);
263 }
264
265 /// Get this TBAAStructTypeNode's field in the type DAG with
266 /// given offset. Update the offset to be relative to the field type.
267 TBAAStructTypeNode getField(uint64_t &Offset) const {
268 bool NewFormat = isNewFormat();
269 const ArrayRef<MDOperand> Operands = Node->operands();
270 const unsigned NumOperands = Operands.size();
271
272 if (NewFormat) {
273 // New-format root and scalar type nodes have no fields.
274 if (NumOperands < 6)
275 return TBAAStructTypeNode();
276 } else {
277 // Parent can be omitted for the root node.
278 if (NumOperands < 2)
279 return TBAAStructTypeNode();
280
281 // Fast path for a scalar type node and a struct type node with a single
282 // field.
283 if (NumOperands <= 3) {
284 uint64_t Cur =
285 NumOperands == 2
286 ? 0
287 : mdconst::extract<ConstantInt>(Operands[2])->getZExtValue();
288 Offset -= Cur;
289 MDNode *P = dyn_cast_or_null<MDNode>(Operands[1]);
290 if (!P)
291 return TBAAStructTypeNode();
292 return TBAAStructTypeNode(P);
293 }
294 }
295
296 // Assume the offsets are in order. We return the previous field if
297 // the current offset is bigger than the given offset.
298 unsigned FirstFieldOpNo = NewFormat ? 3 : 1;
299 unsigned NumOpsPerField = NewFormat ? 3 : 2;
300 unsigned TheIdx = 0;
301
302 for (unsigned Idx = FirstFieldOpNo; Idx < NumOperands;
303 Idx += NumOpsPerField) {
304 uint64_t Cur =
305 mdconst::extract<ConstantInt>(Operands[Idx + 1])->getZExtValue();
306 if (Cur > Offset) {
307 assert(Idx >= FirstFieldOpNo + NumOpsPerField &&
308 "TBAAStructTypeNode::getField should have an offset match!");
309 TheIdx = Idx - NumOpsPerField;
310 break;
311 }
312 }
313 // Move along the last field.
314 if (TheIdx == 0)
315 TheIdx = NumOperands - NumOpsPerField;
316 uint64_t Cur =
317 mdconst::extract<ConstantInt>(Operands[TheIdx + 1])->getZExtValue();
318 Offset -= Cur;
319 MDNode *P = dyn_cast_or_null<MDNode>(Operands[TheIdx]);
320 if (!P)
321 return TBAAStructTypeNode();
322 return TBAAStructTypeNode(P);
323 }
324};
325
326} // end anonymous namespace
327
329 const MemoryLocation &LocB,
330 AAQueryInfo &AAQI, const Instruction *) {
331 if (!shouldUseTBAA())
333
334 if (Aliases(LocA.AATags.TBAA, LocB.AATags.TBAA))
336
337 // Otherwise return a definitive result.
339}
340
342 const Instruction *CtxI) {
343 if (!shouldUseTBAA())
345
346 const auto *N = Loc.AATags.TBAA;
347 if (!N)
349
350 // There cannot be any alias with errno if TBAA proves the given memory
351 // location does not alias errno.
352 const auto *ErrnoTBAAMD =
353 CtxI->getModule()->getNamedMetadata("llvm.errno.tbaa");
354 if (!ErrnoTBAAMD || any_of(ErrnoTBAAMD->operands(), [&](const auto *Node) {
355 return Aliases(N, Node);
356 }))
359}
360
362 AAQueryInfo &AAQI,
363 bool IgnoreLocals) {
364 if (!shouldUseTBAA())
365 return ModRefInfo::ModRef;
366
367 const MDNode *M = Loc.AATags.TBAA;
368 if (!M)
369 return ModRefInfo::ModRef;
370
371 // If this is an "immutable" type, we can assume the pointer is pointing
372 // to constant memory.
373 if (TBAAStructTagNode(M).isTypeImmutable())
375
376 return ModRefInfo::ModRef;
377}
378
380 AAQueryInfo &AAQI) {
381 if (!shouldUseTBAA())
382 return MemoryEffects::unknown();
383
384 // If this is an "immutable" type, the access is not observable.
385 if (const MDNode *M = Call->getMetadata(LLVMContext::MD_tbaa))
386 if (TBAAStructTagNode(M).isTypeImmutable())
387 return MemoryEffects::none();
388
389 return MemoryEffects::unknown();
390}
391
393 // Functions don't have metadata.
394 return MemoryEffects::unknown();
395}
396
398 const MemoryLocation &Loc,
399 AAQueryInfo &AAQI) {
400 if (!shouldUseTBAA())
401 return ModRefInfo::ModRef;
402
403 if (const MDNode *L = Loc.AATags.TBAA)
404 if (const MDNode *M = Call->getMetadata(LLVMContext::MD_tbaa))
405 if (!Aliases(L, M))
407
408 return ModRefInfo::ModRef;
409}
410
412 const CallBase *Call2,
413 AAQueryInfo &AAQI) {
414 if (!shouldUseTBAA())
415 return ModRefInfo::ModRef;
416
417 if (const MDNode *M1 = Call1->getMetadata(LLVMContext::MD_tbaa))
418 if (const MDNode *M2 = Call2->getMetadata(LLVMContext::MD_tbaa))
419 if (!Aliases(M1, M2))
421
422 return ModRefInfo::ModRef;
423}
424
426 // For struct-path aware TBAA, we use the access type of the tag.
427 TBAAStructTagNode Tag(this);
428 TBAAStructTypeNode AccessType(Tag.getAccessType());
429 if(auto *Id = dyn_cast<MDString>(AccessType.getId()))
430 if (Id->getString() == "vtable pointer")
431 return true;
432 return false;
433}
434
435static bool matchAccessTags(const MDNode *A, const MDNode *B,
436 const MDNode **GenericTag = nullptr);
437
439 const MDNode *GenericTag;
440 matchAccessTags(A, B, &GenericTag);
441 return const_cast<MDNode*>(GenericTag);
442}
443
444static const MDNode *getLeastCommonType(const MDNode *A, const MDNode *B) {
445 if (!A || !B)
446 return nullptr;
447
448 if (A == B)
449 return A;
450
452 TBAANode TA(A);
453 while (TA.getNode()) {
454 assert(!is_contained(PathA, TA.getNode()) &&
455 "Cycle found in TBAA metadata.");
456 PathA.push_back(TA.getNode());
457 TA = TA.getParent();
458 }
459
461 TBAANode TB(B);
462 while (TB.getNode()) {
463 assert(!is_contained(PathB, TB.getNode()) &&
464 "Cycle found in TBAA metadata.");
465 PathB.push_back(TB.getNode());
466 TB = TB.getParent();
467 }
468
469 int IA = PathA.size() - 1;
470 int IB = PathB.size() - 1;
471
472 const MDNode *Ret = nullptr;
473 while (IA >= 0 && IB >= 0) {
474 if (PathA[IA] == PathB[IB])
475 Ret = PathA[IA];
476 else
477 break;
478 --IA;
479 --IB;
480 }
481
482 return Ret;
483}
484
486 AAMDNodes Result;
487 Result.TBAA = MDNode::getMostGenericTBAA(TBAA, Other.TBAA);
488 Result.TBAAStruct = nullptr;
489 Result.Scope = MDNode::getMostGenericAliasScope(Scope, Other.Scope);
490 Result.NoAlias = MDNode::intersect(NoAlias, Other.NoAlias);
491 Result.NoAliasAddrSpace = MDNode::getMostGenericNoaliasAddrspace(
492 NoAliasAddrSpace, Other.NoAliasAddrSpace);
493 return Result;
494}
495
497 AAMDNodes Result;
498 Result.TBAA = Result.TBAAStruct = nullptr;
499 Result.Scope = MDNode::getMostGenericAliasScope(Scope, Other.Scope);
500 Result.NoAlias = MDNode::intersect(NoAlias, Other.NoAlias);
501 Result.NoAliasAddrSpace = MDNode::getMostGenericNoaliasAddrspace(
502 NoAliasAddrSpace, Other.NoAliasAddrSpace);
503 return Result;
504}
505
506static const MDNode *createAccessTag(const MDNode *AccessType) {
507 // If there is no access type or the access type is the root node, then
508 // we don't have any useful access tag to return.
509 if (!AccessType || AccessType->getNumOperands() < 2)
510 return nullptr;
511
512 Type *Int64 = IntegerType::get(AccessType->getContext(), 64);
513 auto *OffsetNode = ConstantAsMetadata::get(ConstantInt::get(Int64, 0));
514
515 if (TBAAStructTypeNode(AccessType).isNewFormat()) {
516 // TODO: Take access ranges into account when matching access tags and
517 // fix this code to generate actual access sizes for generic tags.
518 uint64_t AccessSize = UINT64_MAX;
519 auto *SizeNode =
520 ConstantAsMetadata::get(ConstantInt::get(Int64, AccessSize));
521 Metadata *Ops[] = {const_cast<MDNode*>(AccessType),
522 const_cast<MDNode*>(AccessType),
523 OffsetNode, SizeNode};
524 return MDNode::get(AccessType->getContext(), Ops);
525 }
526
527 Metadata *Ops[] = {const_cast<MDNode*>(AccessType),
528 const_cast<MDNode*>(AccessType),
529 OffsetNode};
530 return MDNode::get(AccessType->getContext(), Ops);
531}
532
533static bool hasField(TBAAStructTypeNode BaseType,
534 TBAAStructTypeNode FieldType) {
535 for (unsigned I = 0, E = BaseType.getNumFields(); I != E; ++I) {
536 TBAAStructTypeNode T = BaseType.getFieldType(I);
537 if (T == FieldType || hasField(T, FieldType))
538 return true;
539 }
540 return false;
541}
542
543/// Return true if for two given accesses, one of the accessed objects may be a
544/// subobject of the other. The \p BaseTag and \p SubobjectTag parameters
545/// describe the accesses to the base object and the subobject respectively.
546/// \p CommonType must be the metadata node describing the common type of the
547/// accessed objects. On return, \p MayAlias is set to true iff these accesses
548/// may alias and \p Generic, if not null, points to the most generic access
549/// tag for the given two.
550static bool mayBeAccessToSubobjectOf(TBAAStructTagNode BaseTag,
551 TBAAStructTagNode SubobjectTag,
552 const MDNode *CommonType,
553 const MDNode **GenericTag,
554 bool &MayAlias) {
555 // If the base object is of the least common type, then this may be an access
556 // to its subobject.
557 if (BaseTag.getAccessType() == BaseTag.getBaseType() &&
558 BaseTag.getAccessType() == CommonType) {
559 if (GenericTag)
560 *GenericTag = createAccessTag(CommonType);
561 MayAlias = true;
562 return true;
563 }
564
565 // If the access to the base object is through a field of the subobject's
566 // type, then this may be an access to that field. To check for that we start
567 // from the base type, follow the edge with the correct offset in the type DAG
568 // and adjust the offset until we reach the field type or until we reach the
569 // access type.
570 bool NewFormat = BaseTag.isNewFormat();
571 TBAAStructTypeNode BaseType(BaseTag.getBaseType());
572 uint64_t OffsetInBase = BaseTag.getOffset();
573
574 for (;;) {
575 // In the old format there is no distinction between fields and parent
576 // types, so in this case we consider all nodes up to the root.
577 if (!BaseType.getNode()) {
578 assert(!NewFormat && "Did not see access type in access path!");
579 break;
580 }
581
582 if (BaseType.getNode() == SubobjectTag.getBaseType()) {
583 MayAlias = OffsetInBase == SubobjectTag.getOffset() ||
584 BaseType.getNode() == BaseTag.getAccessType() ||
585 SubobjectTag.getBaseType() == SubobjectTag.getAccessType();
586 if (GenericTag) {
587 if (!MayAlias) {
588 *GenericTag = createAccessTag(CommonType);
589 } else if (SubobjectTag.isTypeImmutable() &&
590 !BaseTag.isTypeImmutable()) {
591 // The generic tag can only be immutable if both accesses are, so
592 // drop the flag and keep the rest of the tag.
593 const MDNode *Tag = SubobjectTag.getNode();
594 unsigned FlagOpNo = SubobjectTag.isNewFormat() ? 4 : 3;
595 SmallVector<Metadata *, 4> Ops(Tag->operands().take_front(FlagOpNo));
596 *GenericTag = MDNode::get(Tag->getContext(), Ops);
597 } else {
598 *GenericTag = SubobjectTag.getNode();
599 }
600 }
601 return true;
602 }
603
604 // With new-format nodes we stop at the access type.
605 if (NewFormat && BaseType.getNode() == BaseTag.getAccessType())
606 break;
607
608 // Follow the edge with the correct offset. Offset will be adjusted to
609 // be relative to the field type.
610 BaseType = BaseType.getField(OffsetInBase);
611 }
612
613 // If the base object has a direct or indirect field of the subobject's type,
614 // then this may be an access to that field. We need this to check now that
615 // we support aggregates as access types.
616 if (NewFormat) {
617 // TBAAStructTypeNode BaseAccessType(BaseTag.getAccessType());
618 TBAAStructTypeNode FieldType(SubobjectTag.getBaseType());
619 if (hasField(BaseType, FieldType)) {
620 if (GenericTag)
621 *GenericTag = createAccessTag(CommonType);
622 MayAlias = true;
623 return true;
624 }
625 }
626
627 return false;
628}
629
630/// matchTags - Return true if the given couple of accesses are allowed to
631/// overlap. If \arg GenericTag is not null, then on return it points to the
632/// most generic access descriptor for the given two.
633static bool matchAccessTags(const MDNode *A, const MDNode *B,
634 const MDNode **GenericTag) {
635 if (A == B) {
636 if (GenericTag)
637 *GenericTag = A;
638 return true;
639 }
640
641 // Accesses with no TBAA information may alias with any other accesses.
642 if (!A || !B) {
643 if (GenericTag)
644 *GenericTag = nullptr;
645 return true;
646 }
647
648 TBAAStructTagNode TagA(A), TagB(B);
649 const MDNode *CommonType = getLeastCommonType(TagA.getAccessType(),
650 TagB.getAccessType());
651
652 // If the final access types have different roots, they're part of different
653 // potentially unrelated type systems, so we must be conservative.
654 if (!CommonType) {
655 if (GenericTag)
656 *GenericTag = nullptr;
657 return true;
658 }
659
660 // If one of the accessed objects may be a subobject of the other, then such
661 // accesses may alias.
662 bool MayAlias;
663 if (mayBeAccessToSubobjectOf(/* BaseTag= */ TagA, /* SubobjectTag= */ TagB,
664 CommonType, GenericTag, MayAlias) ||
665 mayBeAccessToSubobjectOf(/* BaseTag= */ TagB, /* SubobjectTag= */ TagA,
666 CommonType, GenericTag, MayAlias))
667 return MayAlias;
668
669 // Otherwise, we've proved there's no alias.
670 if (GenericTag)
671 *GenericTag = createAccessTag(CommonType);
672 return false;
673}
674
675/// Aliases - Test whether the access represented by tag A may alias the
676/// access represented by tag B.
677bool TypeBasedAAResult::Aliases(const MDNode *A, const MDNode *B) const {
678 return matchAccessTags(A, B);
679}
680
682 bool UsingTypeSanitizer)
683 : Opts(getAnalysisOptions(C)), UsingTypeSanitizer(UsingTypeSanitizer) {}
684
685bool TypeBasedAAResult::shouldUseTBAA() const {
686 return Opts.enable_tbaa && !UsingTypeSanitizer;
687}
688
689AnalysisKey TypeBasedAA::Key;
690
692 return TypeBasedAAResult(F.getContext(),
693 F.hasFnAttribute(Attribute::SanitizeType));
694}
695
697INITIALIZE_PASS(TypeBasedAAWrapperPass, "tbaa", "Type-Based Alias Analysis",
698 false, true)
699
701 return new TypeBasedAAWrapperPass();
702}
703
705
707 Result.reset(
708 new TypeBasedAAResult(M.getContext(), /*UsingTypeSanitizer=*/false));
709 return false;
710}
711
713 Result.reset();
714 return false;
715}
716
720
722 // Fast path if there's no offset
723 if (Offset == 0)
724 return MD;
725
726 // The correct behavior here is to add the offset into the TBAA
727 // struct node offset. The base type, however may not have defined
728 // a type at this additional offset, resulting in errors. Since
729 // this method is only used within a given load/store access
730 // the offset provided is only used to subdivide the previous load
731 // maintaining the validity of the previous TBAA.
732 //
733 // This, however, should be revisited in the future.
734 return MD;
735}
736
737// Read a !tbaa.struct field entry (an offset or a size) as a 64-bit value.
738// Returns std::nullopt if it does not fit in 64 bits.
739static std::optional<uint64_t> getTBAAStructFieldAsInt64(const MDOperand &Op) {
740 return mdconst::extract<ConstantInt>(Op)->getValue().tryZExtValue();
741}
742
743static bool isScalarAccessTag(const MDNode *Tag) {
744 TBAAStructTagNode T(Tag);
745 return T.getAccessType() == T.getBaseType();
746}
747
749 // Fast path if there's no offset
750 if (Offset == 0)
751 return MD;
753 for (size_t i = 0, size = MD->getNumOperands(); i < size; i += 3) {
755 ConstantInt *InnerSize =
757 // Don't include any triples that aren't in bounds
758 if (InnerOffset->getZExtValue() + InnerSize->getZExtValue() <= Offset)
759 continue;
760
761 uint64_t NewSize = InnerSize->getZExtValue();
762 uint64_t NewOffset = InnerOffset->getZExtValue() - Offset;
763 if (InnerOffset->getZExtValue() < Offset) {
764 NewOffset = 0;
765 NewSize -= Offset - InnerOffset->getZExtValue();
766 }
767
768 // Shift the offset of the triple
770 ConstantInt::get(InnerOffset->getType(), NewOffset)));
772 ConstantInt::get(InnerSize->getType(), NewSize)));
773 Sub.push_back(MD->getOperand(i + 2));
774 }
775 return MDNode::get(MD->getContext(), Sub);
776}
777
778MDNode *AAMDNodes::extendToTBAA(MDNode *MD, std::optional<uint64_t> Len) {
779 // Fast path if 0-length
780 if (Len == 0)
781 return nullptr;
782
783 TBAAStructTagNode Tag(MD);
784
785 // Only new format TBAA has a size
786 if (!Tag.isNewFormat())
787 return MD;
788
789 // If unknown size, drop the TBAA.
790 if (!Len)
791 return nullptr;
792
793 // Otherwise, create TBAA with the new Len
794 ArrayRef<MDOperand> MDOperands = MD->operands();
795 SmallVector<Metadata *, 4> NextNodes(MDOperands);
796 ConstantInt *PreviousSize = mdconst::extract<ConstantInt>(NextNodes[3]);
797
798 // Don't create a new MDNode if it is the same length.
799 if (PreviousSize->equalsInt(*Len))
800 return MD;
801
802 NextNodes[3] =
803 ConstantAsMetadata::get(ConstantInt::get(PreviousSize->getType(), *Len));
804 return MDNode::get(MD->getContext(), NextNodes);
805}
806
808 if (auto *CI = dyn_cast<ConstantInt>(Size))
809 return extendTo(CI->getValue().tryZExtValue());
810 return extendTo(std::nullopt);
811}
812
814 AAMDNodes New = *this;
815 MDNode *M = New.TBAAStruct;
816
817 // The access may cover several !tbaa.struct fields (e.g. a {int, int} copy
818 // widened to an i64 load/store). If those fields share a single tag and cover
819 // [0, AccessSize) with no gaps, that tag still describes the whole access.
820 New.TBAAStruct = nullptr;
821 if (New.TBAA || !M)
822 return New;
823 MDNode *CommonTag = nullptr;
824 uint64_t Offset = 0;
825 for (size_t I = 0, E = M->getNumOperands(); I + 2 < E && Offset < AccessSize;
826 I += 3) {
827 std::optional<uint64_t> FieldOffset =
828 getTBAAStructFieldAsInt64(M->getOperand(I));
829 std::optional<uint64_t> FieldSize =
830 getTBAAStructFieldAsInt64(M->getOperand(I + 1));
831 MDNode *FieldTag = dyn_cast_or_null<MDNode>(M->getOperand(I + 2));
832 if (!FieldOffset || !FieldSize || !FieldTag ||
833 !isScalarAccessTag(FieldTag) || *FieldOffset != Offset ||
834 (CommonTag && FieldTag != CommonTag))
835 break;
836 CommonTag = FieldTag;
837 // The final field may extend beyond the access.
838 Offset += std::min(*FieldSize, uint64_t(AccessSize) - Offset);
839 }
840 if (Offset == AccessSize)
841 New.TBAA = CommonTag;
842 return New;
843}
844
846 const DataLayout &DL) {
847 AAMDNodes New = shift(Offset);
848 if (!DL.typeSizeEqualsStoreSize(AccessTy))
849 return New;
850 TypeSize Size = DL.getTypeStoreSize(AccessTy);
851 if (Size.isScalable())
852 return New;
853
854 return New.adjustForAccess(Size.getKnownMinValue());
855}
856
857AAMDNodes AAMDNodes::adjustForAccess(size_t Offset, unsigned AccessSize) {
858 AAMDNodes New = shift(Offset);
859 return New.adjustForAccess(AccessSize);
860}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static MemAccessTy getAccessType(const TargetTransformInfo &TTI, Instruction *Inst, Value *OperandVal)
Return the type of the memory being accessed.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallVector class.
static bool matchAccessTags(const MDNode *A, const MDNode *B, const MDNode **GenericTag=nullptr)
matchTags - Return true if the given couple of accesses are allowed to overlap.
static bool mayBeAccessToSubobjectOf(TBAAStructTagNode BaseTag, TBAAStructTagNode SubobjectTag, const MDNode *CommonType, const MDNode **GenericTag, bool &MayAlias)
Return true if for two given accesses, one of the accessed objects may be a subobject of the other.
static bool isScalarAccessTag(const MDNode *Tag)
static std::optional< uint64_t > getTBAAStructFieldAsInt64(const MDOperand &Op)
static bool hasField(TBAAStructTypeNode BaseType, TBAAStructTypeNode FieldType)
static const MDNode * createAccessTag(const MDNode *AccessType)
static const MDNode * getLeastCommonType(const MDNode *A, const MDNode *B)
This is the interface for a metadata-based TBAA.
static unsigned getSize(unsigned Kind)
This class stores info we want to provide to or retain within an alias query.
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition APInt.h:1572
The possible results of an alias query.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
bool equalsInt(uint64_t V) const
A helper method that can be used to determine if the constant contained within is equal to a constant...
Definition Constants.h:194
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:283
ImmutablePass(char &pid)
Definition Pass.h:285
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1087
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
LLVM_ABI bool isTBAAVtableAccess() const
Check whether MDNode is a vtable access.
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:649
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
LLVMContext & getContext() const
Definition Metadata.h:1251
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Representation for a specific memory location.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:320
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A simple AA result that uses TBAA metadata to answer queries.
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Instruction *CtxI)
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, AAQueryInfo &AAQI, const Instruction *CtxI)
LLVM_ABI TypeBasedAAResult(const LLVMContext &C, bool UsingTypeSanitizer)
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, bool IgnoreLocals)
LLVM_ABI ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, AAQueryInfo &AAQI)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI)
Legacy wrapper pass to provide the TypeBasedAAResult object.
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI TypeBasedAAResult run(Function &F, FunctionAnalysisManager &AM)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:708
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
unsigned M1(unsigned Val)
Definition VE.h:394
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
LLVM_ABI ImmutablePass * createTypeBasedAAWrapperPass()
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
#define N
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
static LLVM_ABI MDNode * shiftTBAAStruct(MDNode *M, size_t off)
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:804
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:798
AAMDNodes extendTo(std::optional< uint64_t > Len) const
Create a new AAMDNode that describes this AAMDNode after extending it to apply to a series of bytes o...
Definition Metadata.h:849
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:792
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
Definition Metadata.h:835
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:801
static LLVM_ABI MDNode * extendToTBAA(MDNode *TBAA, std::optional< uint64_t > Len)
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
AAMDNodes()=default
static LLVM_ABI MDNode * shiftTBAA(MDNode *M, size_t off)
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29