Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp
Line
Count
Source (jump to first uncovered line)
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
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
3.33k
{}
39
40
3.33k
CodeGenTBAA::~CodeGenTBAA() {
41
3.33k
}
42
43
3.63k
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
3.63k
  if (!Root) {
49
3.01k
    if (Features.CPlusPlus)
50
1.21k
      Root = MDHelper.createTBAARoot("Simple C++ TBAA");
51
1.80k
    else
52
1.80k
      Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
53
3.01k
  }
54
55
3.63k
  return Root;
56
3.63k
}
57
58
llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name,
59
                                                llvm::MDNode *Parent,
60
22.4k
                                                uint64_t Size) {
61
22.4k
  if (CodeGenOpts.NewStructPathTBAA) {
62
117
    llvm::Metadata *Id = MDHelper.createString(Name);
63
117
    return MDHelper.createTBAATypeNode(Parent, Size, Id);
64
117
  }
65
22.3k
  return MDHelper.createTBAAScalarTypeNode(Name, Parent);
66
22.4k
}
67
68
21.0k
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
21.0k
  if (!Char)
74
3.01k
    Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1);
75
76
21.0k
  return Char;
77
21.0k
}
78
79
483k
static bool TypeHasMayAlias(QualType QTy) {
80
  // Tagged types have declarations, and therefore may have attributes.
81
483k
  if (auto *TD = QTy->getAsTagDecl())
82
19.0k
    if (TD->hasAttr<MayAliasAttr>())
83
27
      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
1.06M
  
while (auto *483k
TT = QTy->getAs<TypedefType>()) {
89
577k
    if (TT->getDecl()->hasAttr<MayAliasAttr>())
90
11
      return true;
91
577k
    QTy = TT->desugar();
92
577k
  }
93
483k
  return false;
94
483k
}
95
96
/// Check if the given type is a valid base type to be used in access tags.
97
257k
static bool isValidBaseType(QualType QTy) {
98
257k
  if (QTy->isReferenceType())
99
1.83k
    return false;
100
256k
  if (const RecordType *TTy = QTy->getAs<RecordType>()) {
101
21.4k
    const RecordDecl *RD = TTy->getDecl()->getDefinition();
102
    // Incomplete types are not valid base access types.
103
21.4k
    if (!RD)
104
0
      return false;
105
21.4k
    if (RD->hasFlexibleArrayMember())
106
39
      return false;
107
    // RD can be struct, union, class, interface or enum.
108
    // For now, we only handle struct and class.
109
21.3k
    if (RD->isStruct() || 
RD->isClass()5.62k
)
110
21.1k
      return true;
111
21.3k
  }
112
234k
  return false;
113
256k
}
114
115
22.4k
llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type *Ty) {
116
22.4k
  uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
117
118
  // Handle builtin types.
119
22.4k
  if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
120
16.3k
    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
17
    case BuiltinType::Char_U:
127
107
    case BuiltinType::Char_S:
128
468
    case BuiltinType::UChar:
129
856
    case BuiltinType::SChar:
130
856
      return getChar();
131
132
    // Unsigned types can alias their corresponding signed types.
133
390
    case BuiltinType::UShort:
134
390
      return getTypeInfo(Context.ShortTy);
135
586
    case BuiltinType::UInt:
136
586
      return getTypeInfo(Context.IntTy);
137
448
    case BuiltinType::ULong:
138
448
      return getTypeInfo(Context.LongTy);
139
49
    case BuiltinType::ULongLong:
140
49
      return getTypeInfo(Context.LongLongTy);
141
4
    case BuiltinType::UInt128:
142
4
      return getTypeInfo(Context.Int128Ty);
143
144
1
    case BuiltinType::UShortFract:
145
1
      return getTypeInfo(Context.ShortFractTy);
146
1
    case BuiltinType::UFract:
147
1
      return getTypeInfo(Context.FractTy);
148
1
    case BuiltinType::ULongFract:
149
1
      return getTypeInfo(Context.LongFractTy);
150
151
1
    case BuiltinType::SatUShortFract:
152
1
      return getTypeInfo(Context.SatShortFractTy);
153
1
    case BuiltinType::SatUFract:
154
1
      return getTypeInfo(Context.SatFractTy);
155
1
    case BuiltinType::SatULongFract:
156
1
      return getTypeInfo(Context.SatLongFractTy);
157
158
1
    case BuiltinType::UShortAccum:
159
1
      return getTypeInfo(Context.ShortAccumTy);
160
1
    case BuiltinType::UAccum:
161
1
      return getTypeInfo(Context.AccumTy);
162
1
    case BuiltinType::ULongAccum:
163
1
      return getTypeInfo(Context.LongAccumTy);
164
165
1
    case BuiltinType::SatUShortAccum:
166
1
      return getTypeInfo(Context.SatShortAccumTy);
167
1
    case BuiltinType::SatUAccum:
168
1
      return getTypeInfo(Context.SatAccumTy);
169
1
    case BuiltinType::SatULongAccum:
170
1
      return getTypeInfo(Context.SatLongAccumTy);
171
172
    // Treat all other builtin types as distinct types. This includes
173
    // treating wchar_t, char16_t, and char32_t as distinct from their
174
    // "underlying types".
175
13.9k
    default:
176
13.9k
      return createScalarTypeNode(BTy->getName(Features), getChar(), Size);
177
16.3k
    }
178
16.3k
  }
179
180
  // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
181
  // an object through a glvalue of other than one of the following types the
182
  // behavior is undefined: [...] a char, unsigned char, or std::byte type."
183
6.12k
  if (Ty->isStdByteType())
184
1
    return getChar();
185
186
  // Handle pointers and references.
187
  // TODO: Implement C++'s type "similarity" and consider dis-"similar"
188
  // pointers distinct.
189
6.12k
  if (Ty->isPointerType() || 
Ty->isReferenceType()2.15k
)
190
4.45k
    return createScalarTypeNode("any pointer", getChar(), Size);
191
192
  // Accesses to arrays are accesses to objects of their element types.
193
1.66k
  if (CodeGenOpts.NewStructPathTBAA && 
Ty->isArrayType()42
)
194
4
    return getTypeInfo(cast<ArrayType>(Ty)->getElementType());
195
196
  // Enum types are distinct types. In C++ they have "underlying types",
197
  // however they aren't related for TBAA.
198
1.66k
  if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
199
    // In C++ mode, types have linkage, so we can rely on the ODR and
200
    // on their mangled names, if they're external.
201
    // TODO: Is there a way to get a program-wide unique name for a
202
    // decl with local linkage or no linkage?
203
25
    if (!Features.CPlusPlus || 
!ETy->getDecl()->isExternallyVisible()24
)
204
6
      return getChar();
205
206
19
    SmallString<256> OutName;
207
19
    llvm::raw_svector_ostream Out(OutName);
208
19
    MContext.mangleTypeName(QualType(ETy, 0), Out);
209
19
    return createScalarTypeNode(OutName, getChar(), Size);
210
25
  }
211
212
1.64k
  if (const auto *EIT = dyn_cast<ExtIntType>(Ty)) {
213
352
    SmallString<256> OutName;
214
352
    llvm::raw_svector_ostream Out(OutName);
215
    // Don't specify signed/unsigned since integer types can alias despite sign
216
    // differences.
217
352
    Out << "_ExtInt(" << EIT->getNumBits() << ')';
218
352
    return createScalarTypeNode(OutName, getChar(), Size);
219
352
  }
220
221
  // For now, handle any other kind of type conservatively.
222
1.28k
  return getChar();
223
1.64k
}
224
225
244k
llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) {
226
  // At -O0 or relaxed aliasing, TBAA is not emitted for regular types.
227
244k
  if (CodeGenOpts.OptimizationLevel == 0 || 
CodeGenOpts.RelaxedAliasing244k
)
228
181
    return nullptr;
229
230
  // If the type has the may_alias attribute (even on a typedef), it is
231
  // effectively in the general char alias class.
232
244k
  if (TypeHasMayAlias(QTy))
233
0
    return getChar();
234
235
  // We need this function to not fall back to returning the "omnipotent char"
236
  // type node for aggregate and union types. Otherwise, any dereference of an
237
  // aggregate will result into the may-alias access descriptor, meaning all
238
  // subsequent accesses to direct and indirect members of that aggregate will
239
  // be considered may-alias too.
240
  // TODO: Combine getTypeInfo() and getBaseTypeInfo() into a single function.
241
244k
  if (isValidBaseType(QTy))
242
9.24k
    return getBaseTypeInfo(QTy);
243
244
235k
  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
245
235k
  if (llvm::MDNode *N = MetadataCache[Ty])
246
212k
    return N;
247
248
  // Note that the following helper call is allowed to add new nodes to the
249
  // cache, which invalidates all its previously obtained iterators. So we
250
  // first generate the node for the type and then add that node to the cache.
251
22.4k
  llvm::MDNode *TypeNode = getTypeInfoHelper(Ty);
252
22.4k
  return MetadataCache[Ty] = TypeNode;
253
235k
}
254
255
238k
TBAAAccessInfo CodeGenTBAA::getAccessInfo(QualType AccessType) {
256
  // Pointee values may have incomplete types, but they shall never be
257
  // dereferenced.
258
238k
  if (AccessType->isIncompleteType())
259
18
    return TBAAAccessInfo::getIncompleteInfo();
260
261
238k
  if (TypeHasMayAlias(AccessType))
262
38
    return TBAAAccessInfo::getMayAliasInfo();
263
264
238k
  uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
265
238k
  return TBAAAccessInfo(getTypeInfo(AccessType), Size);
266
238k
}
267
268
623
TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
269
623
  llvm::DataLayout DL(&Module);
270
623
  unsigned Size = DL.getPointerTypeSize(VTablePtrType);
271
623
  return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size),
272
623
                        Size);
273
623
}
274
275
bool
276
CodeGenTBAA::CollectFields(uint64_t BaseOffset,
277
                           QualType QTy,
278
                           SmallVectorImpl<llvm::MDBuilder::TBAAStructField> &
279
                             Fields,
280
1.20k
                           bool MayAlias) {
281
  /* Things not handled yet include: C++ base classes, bitfields, */
282
283
1.20k
  if (const RecordType *TTy = QTy->getAs<RecordType>()) {
284
469
    const RecordDecl *RD = TTy->getDecl()->getDefinition();
285
469
    if (RD->hasFlexibleArrayMember())
286
2
      return false;
287
288
    // TODO: Handle C++ base classes.
289
467
    if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
290
244
      if (Decl->bases_begin() != Decl->bases_end())
291
17
        return false;
292
293
450
    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
294
295
450
    unsigned idx = 0;
296
450
    for (RecordDecl::field_iterator i = RD->field_begin(),
297
1.26k
         e = RD->field_end(); i != e; 
++i, ++idx813
) {
298
813
      if ((*i)->isZeroSize(Context) || 
(*i)->isUnnamedBitfield()804
)
299
37
        continue;
300
776
      uint64_t Offset = BaseOffset +
301
776
                        Layout.getFieldOffset(idx) / Context.getCharWidth();
302
776
      QualType FieldQTy = i->getType();
303
776
      if (!CollectFields(Offset, FieldQTy, Fields,
304
776
                         MayAlias || TypeHasMayAlias(FieldQTy)))
305
0
        return false;
306
776
    }
307
450
    return true;
308
450
  }
309
310
  /* Otherwise, treat whatever it is as a field. */
311
733
  uint64_t Offset = BaseOffset;
312
733
  uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
313
733
  llvm::MDNode *TBAAType = MayAlias ? 
getChar()0
: getTypeInfo(QTy);
314
733
  llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
315
733
  Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
316
733
  return true;
317
1.20k
}
318
319
llvm::MDNode *
320
426
CodeGenTBAA::getTBAAStructInfo(QualType QTy) {
321
426
  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
322
323
426
  if (llvm::MDNode *N = StructMetadataCache[Ty])
324
0
    return N;
325
326
426
  SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
327
426
  if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy)))
328
407
    return MDHelper.createTBAAStructNode(Fields);
329
330
  // For now, handle any other kind of type conservatively.
331
19
  return StructMetadataCache[Ty] = nullptr;
332
426
}
333
334
1.55k
llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) {
335
1.55k
  if (auto *TTy = dyn_cast<RecordType>(Ty)) {
336
1.55k
    const RecordDecl *RD = TTy->getDecl()->getDefinition();
337
1.55k
    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
338
1.55k
    SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
339
1.99k
    for (FieldDecl *Field : RD->fields()) {
340
1.99k
      if (Field->isZeroSize(Context) || 
Field->isUnnamedBitfield()1.94k
)
341
94
        continue;
342
1.90k
      QualType FieldQTy = Field->getType();
343
1.90k
      llvm::MDNode *TypeNode = isValidBaseType(FieldQTy) ?
344
1.69k
          
getBaseTypeInfo(FieldQTy)211
: getTypeInfo(FieldQTy);
345
1.90k
      if (!TypeNode)
346
2
        return BaseTypeMetadataCache[Ty] = nullptr;
347
348
1.89k
      uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex());
349
1.89k
      uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity();
350
1.89k
      uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity();
351
1.89k
      Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size,
352
1.89k
                                                        TypeNode));
353
1.89k
    }
354
355
1.55k
    SmallString<256> OutName;
356
1.55k
    if (Features.CPlusPlus) {
357
      // Don't use the mangler for C code.
358
1.13k
      llvm::raw_svector_ostream Out(OutName);
359
1.13k
      MContext.mangleTypeName(QualType(Ty, 0), Out);
360
1.13k
    } else {
361
418
      OutName = RD->getName();
362
418
    }
363
364
1.55k
    if (CodeGenOpts.NewStructPathTBAA) {
365
37
      llvm::MDNode *Parent = getChar();
366
37
      uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
367
37
      llvm::Metadata *Id = MDHelper.createString(OutName);
368
37
      return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields);
369
37
    }
370
371
    // Create the struct type node with a vector of pairs (offset, type).
372
1.51k
    SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes;
373
1.51k
    for (const auto &Field : Fields)
374
1.81k
        OffsetsAndTypes.push_back(std::make_pair(Field.Type, Field.Offset));
375
1.51k
    return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes);
376
1.55k
  }
377
378
0
  return nullptr;
379
1.55k
}
380
381
11.6k
llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) {
382
11.6k
  if (!isValidBaseType(QTy))
383
4
    return nullptr;
384
385
11.6k
  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
386
11.6k
  if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
387
10.1k
    return N;
388
389
  // Note that the following helper call is allowed to add new nodes to the
390
  // cache, which invalidates all its previously obtained iterators. So we
391
  // first generate the node for the type and then add that node to the cache.
392
1.55k
  llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
393
1.55k
  return BaseTypeMetadataCache[Ty] = TypeNode;
394
11.6k
}
395
396
228k
llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) {
397
228k
  assert(!Info.isIncomplete() && "Access to an object of an incomplete type!");
398
399
228k
  if (Info.isMayAlias())
400
72
    Info = TBAAAccessInfo(getChar(), Info.Size);
401
402
228k
  if (!Info.AccessType)
403
189
    return nullptr;
404
405
227k
  if (!CodeGenOpts.StructPathTBAA)
406
265
    Info = TBAAAccessInfo(Info.AccessType, Info.Size);
407
408
227k
  llvm::MDNode *&N = AccessTagMetadataCache[Info];
409
227k
  if (N)
410
211k
    return N;
411
412
16.6k
  if (!Info.BaseType) {
413
16.2k
    Info.BaseType = Info.AccessType;
414
16.2k
    assert(!Info.Offset && "Nonzero offset for an access with no base type!");
415
16.2k
  }
416
16.6k
  if (CodeGenOpts.NewStructPathTBAA) {
417
100
    return N = MDHelper.createTBAAAccessTag(Info.BaseType, Info.AccessType,
418
100
                                            Info.Offset, Info.Size);
419
100
  }
420
16.5k
  return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
421
16.5k
                                              Info.Offset);
422
16.6k
}
423
424
TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
425
308
                                                 TBAAAccessInfo TargetInfo) {
426
308
  if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias())
427
0
    return TBAAAccessInfo::getMayAliasInfo();
428
308
  return TargetInfo;
429
308
}
430
431
TBAAAccessInfo
432
CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
433
16
                                                 TBAAAccessInfo InfoB) {
434
16
  if (InfoA == InfoB)
435
14
    return InfoA;
436
437
2
  if (!InfoA || !InfoB)
438
0
    return TBAAAccessInfo();
439
440
2
  if (InfoA.isMayAlias() || 
InfoB.isMayAlias()1
)
441
2
    return TBAAAccessInfo::getMayAliasInfo();
442
443
  // TODO: Implement the rest of the logic here. For example, two accesses
444
  // with same final access types result in an access to an object of that final
445
  // access type regardless of their base types.
446
0
  return TBAAAccessInfo::getMayAliasInfo();
447
2
}
448
449
TBAAAccessInfo
450
CodeGenTBAA::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
451
0
                                            TBAAAccessInfo SrcInfo) {
452
0
  if (DestInfo == SrcInfo)
453
0
    return DestInfo;
454
455
0
  if (!DestInfo || !SrcInfo)
456
0
    return TBAAAccessInfo();
457
458
0
  if (DestInfo.isMayAlias() || SrcInfo.isMayAlias())
459
0
    return TBAAAccessInfo::getMayAliasInfo();
460
461
  // TODO: Implement the rest of the logic here. For example, two accesses
462
  // with same final access types result in an access to an object of that final
463
  // access type regardless of their base types.
464
0
  return TBAAAccessInfo::getMayAliasInfo();
465
0
}