clang  6.0.0svn
CodeGenTBAA.cpp
Go to the documentation of this file.
1 //===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the code that manages TBAA information and defines the TBAA policy
11 // for the optimizer to use. Relevant standards text includes:
12 //
13 // C99 6.5p7
14 // C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "CodeGenTBAA.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Mangle.h"
22 #include "clang/AST/RecordLayout.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/IR/Type.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
33  const CodeGenOptions &CGO,
34  const LangOptions &Features, MangleContext &MContext)
35  : Context(Ctx), CodeGenOpts(CGO), Features(Features), MContext(MContext),
36  MDHelper(VMContext), Root(nullptr), Char(nullptr) {
37 }
38 
40 }
41 
42 llvm::MDNode *CodeGenTBAA::getRoot() {
43  // Define the root of the tree. This identifies the tree, so that
44  // if our LLVM IR is linked with LLVM IR from a different front-end
45  // (or a different version of this front-end), their TBAA trees will
46  // remain distinct, and the optimizer will treat them conservatively.
47  if (!Root) {
48  if (Features.CPlusPlus)
49  Root = MDHelper.createTBAARoot("Simple C++ TBAA");
50  else
51  Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
52  }
53 
54  return Root;
55 }
56 
57 // For both scalar TBAA and struct-path aware TBAA, the scalar type has the
58 // same format: name, parent node, and offset.
59 llvm::MDNode *CodeGenTBAA::createTBAAScalarType(StringRef Name,
60  llvm::MDNode *Parent) {
61  return MDHelper.createTBAAScalarTypeNode(Name, Parent);
62 }
63 
64 llvm::MDNode *CodeGenTBAA::getChar() {
65  // Define the root of the tree for user-accessible memory. C and C++
66  // give special powers to char and certain similar types. However,
67  // these special powers only cover user-accessible memory, and doesn't
68  // include things like vtables.
69  if (!Char)
70  Char = createTBAAScalarType("omnipotent char", getRoot());
71 
72  return Char;
73 }
74 
75 static bool TypeHasMayAlias(QualType QTy) {
76  // Tagged types have declarations, and therefore may have attributes.
77  if (const TagType *TTy = dyn_cast<TagType>(QTy))
78  return TTy->getDecl()->hasAttr<MayAliasAttr>();
79 
80  // Typedef types have declarations, and therefore may have attributes.
81  if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) {
82  if (TTy->getDecl()->hasAttr<MayAliasAttr>())
83  return true;
84  // Also, their underlying types may have relevant attributes.
85  return TypeHasMayAlias(TTy->desugar());
86  }
87 
88  return false;
89 }
90 
91 llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) {
92  // At -O0 or relaxed aliasing, TBAA is not emitted for regular types.
93  if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
94  return nullptr;
95 
96  // If the type has the may_alias attribute (even on a typedef), it is
97  // effectively in the general char alias class.
98  if (TypeHasMayAlias(QTy))
99  return getChar();
100 
101  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
102 
103  if (llvm::MDNode *N = MetadataCache[Ty])
104  return N;
105 
106  // Handle builtin types.
107  if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
108  switch (BTy->getKind()) {
109  // Character types are special and can alias anything.
110  // In C++, this technically only includes "char" and "unsigned char",
111  // and not "signed char". In C, it includes all three. For now,
112  // the risk of exploiting this detail in C++ seems likely to outweigh
113  // the benefit.
114  case BuiltinType::Char_U:
115  case BuiltinType::Char_S:
116  case BuiltinType::UChar:
117  case BuiltinType::SChar:
118  return getChar();
119 
120  // Unsigned types can alias their corresponding signed types.
121  case BuiltinType::UShort:
122  return getTypeInfo(Context.ShortTy);
123  case BuiltinType::UInt:
124  return getTypeInfo(Context.IntTy);
125  case BuiltinType::ULong:
126  return getTypeInfo(Context.LongTy);
127  case BuiltinType::ULongLong:
128  return getTypeInfo(Context.LongLongTy);
129  case BuiltinType::UInt128:
130  return getTypeInfo(Context.Int128Ty);
131 
132  // Treat all other builtin types as distinct types. This includes
133  // treating wchar_t, char16_t, and char32_t as distinct from their
134  // "underlying types".
135  default:
136  return MetadataCache[Ty] =
137  createTBAAScalarType(BTy->getName(Features), getChar());
138  }
139  }
140 
141  // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
142  // an object through a glvalue of other than one of the following types the
143  // behavior is undefined: [...] a char, unsigned char, or std::byte type."
144  if (Ty->isStdByteType())
145  return MetadataCache[Ty] = getChar();
146 
147  // Handle pointers and references.
148  // TODO: Implement C++'s type "similarity" and consider dis-"similar"
149  // pointers distinct.
150  if (Ty->isPointerType() || Ty->isReferenceType())
151  return MetadataCache[Ty] = createTBAAScalarType("any pointer",
152  getChar());
153 
154  // Enum types are distinct types. In C++ they have "underlying types",
155  // however they aren't related for TBAA.
156  if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
157  // In C++ mode, types have linkage, so we can rely on the ODR and
158  // on their mangled names, if they're external.
159  // TODO: Is there a way to get a program-wide unique name for a
160  // decl with local linkage or no linkage?
161  if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
162  return MetadataCache[Ty] = getChar();
163 
164  SmallString<256> OutName;
165  llvm::raw_svector_ostream Out(OutName);
166  MContext.mangleTypeName(QualType(ETy, 0), Out);
167  return MetadataCache[Ty] = createTBAAScalarType(OutName, getChar());
168  }
169 
170  // For now, handle any other kind of type conservatively.
171  return MetadataCache[Ty] = getChar();
172 }
173 
175  return TBAAAccessInfo(createTBAAScalarType("vtable pointer", getRoot()));
176 }
177 
178 bool
179 CodeGenTBAA::CollectFields(uint64_t BaseOffset,
180  QualType QTy,
182  Fields,
183  bool MayAlias) {
184  /* Things not handled yet include: C++ base classes, bitfields, */
185 
186  if (const RecordType *TTy = QTy->getAs<RecordType>()) {
187  const RecordDecl *RD = TTy->getDecl()->getDefinition();
188  if (RD->hasFlexibleArrayMember())
189  return false;
190 
191  // TODO: Handle C++ base classes.
192  if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
193  if (Decl->bases_begin() != Decl->bases_end())
194  return false;
195 
196  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
197 
198  unsigned idx = 0;
200  e = RD->field_end(); i != e; ++i, ++idx) {
201  uint64_t Offset = BaseOffset +
202  Layout.getFieldOffset(idx) / Context.getCharWidth();
203  QualType FieldQTy = i->getType();
204  if (!CollectFields(Offset, FieldQTy, Fields,
205  MayAlias || TypeHasMayAlias(FieldQTy)))
206  return false;
207  }
208  return true;
209  }
210 
211  /* Otherwise, treat whatever it is as a field. */
212  uint64_t Offset = BaseOffset;
213  uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
214  llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy);
215  llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType));
216  Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
217  return true;
218 }
219 
220 llvm::MDNode *
222  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
223 
224  if (llvm::MDNode *N = StructMetadataCache[Ty])
225  return N;
226 
228  if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy)))
229  return MDHelper.createTBAAStructNode(Fields);
230 
231  // For now, handle any other kind of type conservatively.
232  return StructMetadataCache[Ty] = nullptr;
233 }
234 
235 /// Check if the given type is a valid base type to be used in access tags.
236 static bool isValidBaseType(QualType QTy) {
237  if (const RecordType *TTy = QTy->getAs<RecordType>()) {
238  const RecordDecl *RD = TTy->getDecl()->getDefinition();
239  if (RD->hasFlexibleArrayMember())
240  return false;
241  // RD can be struct, union, class, interface or enum.
242  // For now, we only handle struct and class.
243  if (RD->isStruct() || RD->isClass())
244  return true;
245  }
246  return false;
247 }
248 
250  if (!isValidBaseType(QTy))
251  return nullptr;
252 
253  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
254  if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
255  return N;
256 
257  if (const RecordType *TTy = QTy->getAs<RecordType>()) {
258  const RecordDecl *RD = TTy->getDecl()->getDefinition();
259 
260  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
262  unsigned idx = 0;
264  e = RD->field_end(); i != e; ++i, ++idx) {
265  QualType FieldQTy = i->getType();
266  llvm::MDNode *FieldNode = isValidBaseType(FieldQTy) ?
267  getBaseTypeInfo(FieldQTy) : getTypeInfo(FieldQTy);
268  if (!FieldNode)
269  return BaseTypeMetadataCache[Ty] = nullptr;
270  Fields.push_back(std::make_pair(
271  FieldNode, Layout.getFieldOffset(idx) / Context.getCharWidth()));
272  }
273 
274  SmallString<256> OutName;
275  if (Features.CPlusPlus) {
276  // Don't use the mangler for C code.
277  llvm::raw_svector_ostream Out(OutName);
278  MContext.mangleTypeName(QualType(Ty, 0), Out);
279  } else {
280  OutName = RD->getName();
281  }
282  // Create the struct type node with a vector of pairs (offset, type).
283  return BaseTypeMetadataCache[Ty] =
284  MDHelper.createTBAAStructTypeNode(OutName, Fields);
285  }
286 
287  return BaseTypeMetadataCache[Ty] = nullptr;
288 }
289 
291  if (!Info.AccessType)
292  return nullptr;
293 
294  if (!CodeGenOpts.StructPathTBAA)
295  Info = TBAAAccessInfo(Info.AccessType);
296 
297  llvm::MDNode *&N = AccessTagMetadataCache[Info];
298  if (N)
299  return N;
300 
301  if (!Info.BaseType) {
302  Info.BaseType = Info.AccessType;
303  assert(!Info.Offset && "Nonzero offset for an access with no base type!");
304  }
305  return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
306  Info.Offset);
307 }
308 
310  return TBAAAccessInfo(getChar());
311 }
312 
315  TBAAAccessInfo MayAliasInfo = getMayAliasAccessInfo();
316  if (SourceInfo == MayAliasInfo || TargetInfo == MayAliasInfo)
317  return MayAliasInfo;
318  return TargetInfo;
319 }
Defines the clang::ASTContext interface.
bool isStruct() const
Definition: Decl.h:3055
CanQualType LongLongTy
Definition: ASTContext.h:973
A (possibly-)qualified type.
Definition: Type.h:614
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
llvm::MDNode * AccessType
AccessType - The final access type.
Definition: CodeGenTBAA.h:63
The base class of the type hierarchy.
Definition: Type.h:1300
CanQualType LongTy
Definition: ASTContext.h:973
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6099
bool isClass() const
Definition: Decl.h:3057
TBAAAccessInfo getMayAliasAccessInfo()
getMayAliasAccessInfo - Get TBAA information that represents may-alias accesses.
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3384
CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext &VMContext, const CodeGenOptions &CGO, const LangOptions &Features, MangleContext &MContext)
Definition: CodeGenTBAA.cpp:32
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3503
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
static bool isValidBaseType(QualType QTy)
Check if the given type is a valid base type to be used in access tags.
uint32_t Offset
Definition: CacheTokens.cpp:43
TBAAAccessInfo getVTablePtrAccessInfo()
getVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table pointer...
field_iterator field_begin() const
Definition: Decl.cpp:3904
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:70
NodeId Parent
Definition: ASTDiff.cpp:192
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
Exposes information about the current target.
Definition: TargetInfo.h:55
static bool TypeHasMayAlias(QualType QTy)
Definition: CodeGenTBAA.cpp:75
field_iterator field_end() const
Definition: Decl.h:3516
CanQualType ShortTy
Definition: ASTContext.h:973
llvm::MDNode * getBaseTypeInfo(QualType QTy)
getBaseTypeInfo - Get metadata that describes the given base access type.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purpose of type casts. ...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:177
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3864
CanQualType Int128Ty
Definition: ASTContext.h:973
llvm::MDNode * BaseType
BaseType - The base/leading access type.
Definition: CodeGenTBAA.h:59
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:42
llvm::MDNode * getTBAAStructInfo(QualType QTy)
getTBAAStructInfo - Get the TBAAStruct MDNode to be used for a memcpy of the given type...
bool hasFlexibleArrayMember() const
Definition: Decl.h:3436
virtual void mangleTypeName(QualType T, raw_ostream &)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing...
llvm::MDNode * getTypeInfo(QualType QTy)
getTypeInfo - Get metadata used to describe accesses to objects of the given type.
Definition: CodeGenTBAA.cpp:91
Dataflow Directional Tag Classes.
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1566
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3839
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:1965
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2124
Represents a C++ struct/union/class.
Definition: DeclCXX.h:266
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2082
llvm::MDNode * getAccessTagInfo(TBAAAccessInfo Info)
getAccessTagInfo - Get TBAA tag for a given memory access.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
CanQualType IntTy
Definition: ASTContext.h:973
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
Definition: CodeGenTBAA.h:67