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 "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Mangle.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/CodeGenOptions.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Metadata.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Type.h"
29 using namespace clang;
30 using namespace CodeGen;
31
CodeGenTBAA(ASTContext & Ctx,llvm::Module & M,const CodeGenOptions & CGO,const LangOptions & Features,MangleContext & MContext)32 CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::Module &M,
33 const CodeGenOptions &CGO,
34 const LangOptions &Features, MangleContext &MContext)
35 : Context(Ctx), Module(M), CodeGenOpts(CGO),
36 Features(Features), MContext(MContext), MDHelper(M.getContext()),
37 Root(nullptr), Char(nullptr)
38 {}
39
~CodeGenTBAA()40 CodeGenTBAA::~CodeGenTBAA() {
41 }
42
getRoot()43 llvm::MDNode *CodeGenTBAA::getRoot() {
44 // Define the root of the tree. This identifies the tree, so that
45 // if our LLVM IR is linked with LLVM IR from a different front-end
46 // (or a different version of this front-end), their TBAA trees will
47 // remain distinct, and the optimizer will treat them conservatively.
48 if (!Root) {
49 if (Features.CPlusPlus)
50 Root = MDHelper.createTBAARoot("Simple C++ TBAA");
51 else
52 Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
53 }
54
55 return Root;
56 }
57
createScalarTypeNode(StringRef Name,llvm::MDNode * Parent,uint64_t Size)58 llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name,
59 llvm::MDNode *Parent,
60 uint64_t Size) {
61 if (CodeGenOpts.NewStructPathTBAA) {
62 llvm::Metadata *Id = MDHelper.createString(Name);
63 return MDHelper.createTBAATypeNode(Parent, Size, Id);
64 }
65 return MDHelper.createTBAAScalarTypeNode(Name, Parent);
66 }
67
getChar()68 llvm::MDNode *CodeGenTBAA::getChar() {
69 // Define the root of the tree for user-accessible memory. C and C++
70 // give special powers to char and certain similar types. However,
71 // these special powers only cover user-accessible memory, and doesn't
72 // include things like vtables.
73 if (!Char)
74 Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1);
75
76 return Char;
77 }
78
TypeHasMayAlias(QualType QTy)79 static bool TypeHasMayAlias(QualType QTy) {
80 // Tagged types have declarations, and therefore may have attributes.
81 if (auto *TD = QTy->getAsTagDecl())
82 if (TD->hasAttr<MayAliasAttr>())
83 return true;
84
85 // Also look for may_alias as a declaration attribute on a typedef.
86 // FIXME: We should follow GCC and model may_alias as a type attribute
87 // rather than as a declaration attribute.
88 while (auto *TT = QTy->getAs<TypedefType>()) {
89 if (TT->getDecl()->hasAttr<MayAliasAttr>())
90 return true;
91 QTy = TT->desugar();
92 }
93 return false;
94 }
95
96 /// Check if the given type is a valid base type to be used in access tags.
isValidBaseType(QualType QTy)97 static bool isValidBaseType(QualType QTy) {
98 if (QTy->isReferenceType())
99 return false;
100 if (const RecordType *TTy = QTy->getAs<RecordType>()) {
101 const RecordDecl *RD = TTy->getDecl()->getDefinition();
102 // Incomplete types are not valid base access types.
103 if (!RD)
104 return false;
105 if (RD->hasFlexibleArrayMember())
106 return false;
107 // RD can be struct, union, class, interface or enum.
108 // For now, we only handle struct and class.
109 if (RD->isStruct() || RD->isClass())
110 return true;
111 }
112 return false;
113 }
114
getTypeInfoHelper(const Type * Ty)115 llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type *Ty) {
116 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
117
118 // Handle builtin types.
119 if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
120 switch (BTy->getKind()) {
121 // Character types are special and can alias anything.
122 // In C++, this technically only includes "char" and "unsigned char",
123 // and not "signed char". In C, it includes all three. For now,
124 // the risk of exploiting this detail in C++ seems likely to outweigh
125 // the benefit.
126 case BuiltinType::Char_U:
127 case BuiltinType::Char_S:
128 case BuiltinType::UChar:
129 case BuiltinType::SChar:
130 return getChar();
131
132 // Unsigned types can alias their corresponding signed types.
133 case BuiltinType::UShort:
134 return getTypeInfo(Context.ShortTy);
135 case BuiltinType::UInt:
136 return getTypeInfo(Context.IntTy);
137 case BuiltinType::ULong:
138 return getTypeInfo(Context.LongTy);
139 case BuiltinType::ULongLong:
140 return getTypeInfo(Context.LongLongTy);
141 case BuiltinType::UInt128:
142 return getTypeInfo(Context.Int128Ty);
143
144 // Treat all other builtin types as distinct types. This includes
145 // treating wchar_t, char16_t, and char32_t as distinct from their
146 // "underlying types".
147 default:
148 return createScalarTypeNode(BTy->getName(Features), getChar(), Size);
149 }
150 }
151
152 // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
153 // an object through a glvalue of other than one of the following types the
154 // behavior is undefined: [...] a char, unsigned char, or std::byte type."
155 if (Ty->isStdByteType())
156 return getChar();
157
158 // Handle pointers and references.
159 // TODO: Implement C++'s type "similarity" and consider dis-"similar"
160 // pointers distinct.
161 if (Ty->isPointerType() || Ty->isReferenceType())
162 return createScalarTypeNode("any pointer", getChar(), Size);
163
164 // Accesses to arrays are accesses to objects of their element types.
165 if (CodeGenOpts.NewStructPathTBAA && Ty->isArrayType())
166 return getTypeInfo(cast<ArrayType>(Ty)->getElementType());
167
168 // Enum types are distinct types. In C++ they have "underlying types",
169 // however they aren't related for TBAA.
170 if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
171 // In C++ mode, types have linkage, so we can rely on the ODR and
172 // on their mangled names, if they're external.
173 // TODO: Is there a way to get a program-wide unique name for a
174 // decl with local linkage or no linkage?
175 if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
176 return getChar();
177
178 SmallString<256> OutName;
179 llvm::raw_svector_ostream Out(OutName);
180 MContext.mangleTypeName(QualType(ETy, 0), Out);
181 return createScalarTypeNode(OutName, getChar(), Size);
182 }
183
184 // For now, handle any other kind of type conservatively.
185 return getChar();
186 }
187
getTypeInfo(QualType QTy)188 llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) {
189 // At -O0 or relaxed aliasing, TBAA is not emitted for regular types.
190 if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
191 return nullptr;
192
193 // If the type has the may_alias attribute (even on a typedef), it is
194 // effectively in the general char alias class.
195 if (TypeHasMayAlias(QTy))
196 return getChar();
197
198 // We need this function to not fall back to returning the "omnipotent char"
199 // type node for aggregate and union types. Otherwise, any dereference of an
200 // aggregate will result into the may-alias access descriptor, meaning all
201 // subsequent accesses to direct and indirect members of that aggregate will
202 // be considered may-alias too.
203 // TODO: Combine getTypeInfo() and getBaseTypeInfo() into a single function.
204 if (isValidBaseType(QTy))
205 return getBaseTypeInfo(QTy);
206
207 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
208 if (llvm::MDNode *N = MetadataCache[Ty])
209 return N;
210
211 // Note that the following helper call is allowed to add new nodes to the
212 // cache, which invalidates all its previously obtained iterators. So we
213 // first generate the node for the type and then add that node to the cache.
214 llvm::MDNode *TypeNode = getTypeInfoHelper(Ty);
215 return MetadataCache[Ty] = TypeNode;
216 }
217
getAccessInfo(QualType AccessType)218 TBAAAccessInfo CodeGenTBAA::getAccessInfo(QualType AccessType) {
219 // Pointee values may have incomplete types, but they shall never be
220 // dereferenced.
221 if (AccessType->isIncompleteType())
222 return TBAAAccessInfo::getIncompleteInfo();
223
224 if (TypeHasMayAlias(AccessType))
225 return TBAAAccessInfo::getMayAliasInfo();
226
227 uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
228 return TBAAAccessInfo(getTypeInfo(AccessType), Size);
229 }
230
getVTablePtrAccessInfo(llvm::Type * VTablePtrType)231 TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
232 llvm::DataLayout DL(&Module);
233 unsigned Size = DL.getPointerTypeSize(VTablePtrType);
234 return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size),
235 Size);
236 }
237
238 bool
CollectFields(uint64_t BaseOffset,QualType QTy,SmallVectorImpl<llvm::MDBuilder::TBAAStructField> & Fields,bool MayAlias)239 CodeGenTBAA::CollectFields(uint64_t BaseOffset,
240 QualType QTy,
241 SmallVectorImpl<llvm::MDBuilder::TBAAStructField> &
242 Fields,
243 bool MayAlias) {
244 /* Things not handled yet include: C++ base classes, bitfields, */
245
246 if (const RecordType *TTy = QTy->getAs<RecordType>()) {
247 const RecordDecl *RD = TTy->getDecl()->getDefinition();
248 if (RD->hasFlexibleArrayMember())
249 return false;
250
251 // TODO: Handle C++ base classes.
252 if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
253 if (Decl->bases_begin() != Decl->bases_end())
254 return false;
255
256 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
257
258 unsigned idx = 0;
259 for (RecordDecl::field_iterator i = RD->field_begin(),
260 e = RD->field_end(); i != e; ++i, ++idx) {
261 if ((*i)->isZeroSize(Context) || (*i)->isUnnamedBitfield())
262 continue;
263 uint64_t Offset = BaseOffset +
264 Layout.getFieldOffset(idx) / Context.getCharWidth();
265 QualType FieldQTy = i->getType();
266 if (!CollectFields(Offset, FieldQTy, Fields,
267 MayAlias || TypeHasMayAlias(FieldQTy)))
268 return false;
269 }
270 return true;
271 }
272
273 /* Otherwise, treat whatever it is as a field. */
274 uint64_t Offset = BaseOffset;
275 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
276 llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy);
277 llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
278 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
279 return true;
280 }
281
282 llvm::MDNode *
getTBAAStructInfo(QualType QTy)283 CodeGenTBAA::getTBAAStructInfo(QualType QTy) {
284 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
285
286 if (llvm::MDNode *N = StructMetadataCache[Ty])
287 return N;
288
289 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
290 if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy)))
291 return MDHelper.createTBAAStructNode(Fields);
292
293 // For now, handle any other kind of type conservatively.
294 return StructMetadataCache[Ty] = nullptr;
295 }
296
getBaseTypeInfoHelper(const Type * Ty)297 llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) {
298 if (auto *TTy = dyn_cast<RecordType>(Ty)) {
299 const RecordDecl *RD = TTy->getDecl()->getDefinition();
300 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
301 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
302 for (FieldDecl *Field : RD->fields()) {
303 if (Field->isZeroSize(Context) || Field->isUnnamedBitfield())
304 continue;
305 QualType FieldQTy = Field->getType();
306 llvm::MDNode *TypeNode = isValidBaseType(FieldQTy) ?
307 getBaseTypeInfo(FieldQTy) : getTypeInfo(FieldQTy);
308 if (!TypeNode)
309 return BaseTypeMetadataCache[Ty] = nullptr;
310
311 uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex());
312 uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity();
313 uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity();
314 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size,
315 TypeNode));
316 }
317
318 SmallString<256> OutName;
319 if (Features.CPlusPlus) {
320 // Don't use the mangler for C code.
321 llvm::raw_svector_ostream Out(OutName);
322 MContext.mangleTypeName(QualType(Ty, 0), Out);
323 } else {
324 OutName = RD->getName();
325 }
326
327 if (CodeGenOpts.NewStructPathTBAA) {
328 llvm::MDNode *Parent = getChar();
329 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
330 llvm::Metadata *Id = MDHelper.createString(OutName);
331 return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields);
332 }
333
334 // Create the struct type node with a vector of pairs (offset, type).
335 SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes;
336 for (const auto &Field : Fields)
337 OffsetsAndTypes.push_back(std::make_pair(Field.Type, Field.Offset));
338 return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes);
339 }
340
341 return nullptr;
342 }
343
getBaseTypeInfo(QualType QTy)344 llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) {
345 if (!isValidBaseType(QTy))
346 return nullptr;
347
348 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
349 if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
350 return N;
351
352 // Note that the following helper call is allowed to add new nodes to the
353 // cache, which invalidates all its previously obtained iterators. So we
354 // first generate the node for the type and then add that node to the cache.
355 llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
356 return BaseTypeMetadataCache[Ty] = TypeNode;
357 }
358
getAccessTagInfo(TBAAAccessInfo Info)359 llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) {
360 assert(!Info.isIncomplete() && "Access to an object of an incomplete type!");
361
362 if (Info.isMayAlias())
363 Info = TBAAAccessInfo(getChar(), Info.Size);
364
365 if (!Info.AccessType)
366 return nullptr;
367
368 if (!CodeGenOpts.StructPathTBAA)
369 Info = TBAAAccessInfo(Info.AccessType, Info.Size);
370
371 llvm::MDNode *&N = AccessTagMetadataCache[Info];
372 if (N)
373 return N;
374
375 if (!Info.BaseType) {
376 Info.BaseType = Info.AccessType;
377 assert(!Info.Offset && "Nonzero offset for an access with no base type!");
378 }
379 if (CodeGenOpts.NewStructPathTBAA) {
380 return N = MDHelper.createTBAAAccessTag(Info.BaseType, Info.AccessType,
381 Info.Offset, Info.Size);
382 }
383 return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
384 Info.Offset);
385 }
386
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,TBAAAccessInfo TargetInfo)387 TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
388 TBAAAccessInfo TargetInfo) {
389 if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias())
390 return TBAAAccessInfo::getMayAliasInfo();
391 return TargetInfo;
392 }
393
394 TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,TBAAAccessInfo InfoB)395 CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
396 TBAAAccessInfo InfoB) {
397 if (InfoA == InfoB)
398 return InfoA;
399
400 if (!InfoA || !InfoB)
401 return TBAAAccessInfo();
402
403 if (InfoA.isMayAlias() || InfoB.isMayAlias())
404 return TBAAAccessInfo::getMayAliasInfo();
405
406 // TODO: Implement the rest of the logic here. For example, two accesses
407 // with same final access types result in an access to an object of that final
408 // access type regardless of their base types.
409 return TBAAAccessInfo::getMayAliasInfo();
410 }
411
412 TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,TBAAAccessInfo SrcInfo)413 CodeGenTBAA::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
414 TBAAAccessInfo SrcInfo) {
415 if (DestInfo == SrcInfo)
416 return DestInfo;
417
418 if (!DestInfo || !SrcInfo)
419 return TBAAAccessInfo();
420
421 if (DestInfo.isMayAlias() || SrcInfo.isMayAlias())
422 return TBAAAccessInfo::getMayAliasInfo();
423
424 // TODO: Implement the rest of the logic here. For example, two accesses
425 // with same final access types result in an access to an object of that final
426 // access type regardless of their base types.
427 return TBAAAccessInfo::getMayAliasInfo();
428 }
429