Coverage Report

Created: 2020-02-15 09:57

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