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" 23 #include "clang/Frontend/CodeGenOptions.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/Module.h" 29 #include "llvm/IR/Type.h" 30 using namespace clang; 31 using namespace CodeGen; 32 33 CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::Module &M, 34 const CodeGenOptions &CGO, 35 const LangOptions &Features, MangleContext &MContext) 36 : Context(Ctx), Module(M), CodeGenOpts(CGO), 37 Features(Features), MContext(MContext), MDHelper(M.getContext()), 38 Root(nullptr), Char(nullptr) 39 {} 40 41 CodeGenTBAA::~CodeGenTBAA() { 42 } 43 44 llvm::MDNode *CodeGenTBAA::getRoot() { 45 // Define the root of the tree. This identifies the tree, so that 46 // if our LLVM IR is linked with LLVM IR from a different front-end 47 // (or a different version of this front-end), their TBAA trees will 48 // remain distinct, and the optimizer will treat them conservatively. 49 if (!Root) { 50 if (Features.CPlusPlus) 51 Root = MDHelper.createTBAARoot("Simple C++ TBAA"); 52 else 53 Root = MDHelper.createTBAARoot("Simple C/C++ TBAA"); 54 } 55 56 return Root; 57 } 58 59 llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name, 60 llvm::MDNode *Parent, 61 uint64_t Size) { 62 (void)Size; // TODO: Support generation of size-aware type nodes. 63 return MDHelper.createTBAAScalarTypeNode(Name, Parent); 64 } 65 66 llvm::MDNode *CodeGenTBAA::getChar() { 67 // Define the root of the tree for user-accessible memory. C and C++ 68 // give special powers to char and certain similar types. However, 69 // these special powers only cover user-accessible memory, and doesn't 70 // include things like vtables. 71 if (!Char) 72 Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1); 73 74 return Char; 75 } 76 77 llvm::MDNode *CodeGenTBAA::getUnionMemberType(uint64_t Size) { 78 return createScalarTypeNode("union member", getChar(), Size); 79 } 80 81 static bool TypeHasMayAlias(QualType QTy) { 82 // Tagged types have declarations, and therefore may have attributes. 83 if (const TagType *TTy = dyn_cast<TagType>(QTy)) 84 return TTy->getDecl()->hasAttr<MayAliasAttr>(); 85 86 // Typedef types have declarations, and therefore may have attributes. 87 if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) { 88 if (TTy->getDecl()->hasAttr<MayAliasAttr>()) 89 return true; 90 // Also, their underlying types may have relevant attributes. 91 return TypeHasMayAlias(TTy->desugar()); 92 } 93 94 return false; 95 } 96 97 /// Check if the given type is a valid base type to be used in access tags. 98 static bool isValidBaseType(QualType QTy) { 99 if (QTy->isReferenceType()) 100 return false; 101 if (const RecordType *TTy = QTy->getAs<RecordType>()) { 102 const RecordDecl *RD = TTy->getDecl()->getDefinition(); 103 // Incomplete types are not valid base access types. 104 if (!RD) 105 return false; 106 if (RD->hasFlexibleArrayMember()) 107 return false; 108 // For now, we do not allow interface classes to be base access types. 109 if (RD->isStruct() || RD->isClass() || RD->isUnion()) 110 return true; 111 } 112 return false; 113 } 114 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 // Enum types are distinct types. In C++ they have "underlying types", 165 // however they aren't related for TBAA. 166 if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) { 167 // In C++ mode, types have linkage, so we can rely on the ODR and 168 // on their mangled names, if they're external. 169 // TODO: Is there a way to get a program-wide unique name for a 170 // decl with local linkage or no linkage? 171 if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible()) 172 return getChar(); 173 174 SmallString<256> OutName; 175 llvm::raw_svector_ostream Out(OutName); 176 MContext.mangleTypeName(QualType(ETy, 0), Out); 177 return createScalarTypeNode(OutName, getChar(), Size); 178 } 179 180 // For now, handle any other kind of type conservatively. 181 return getChar(); 182 } 183 184 llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) { 185 // At -O0 or relaxed aliasing, TBAA is not emitted for regular types. 186 if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing) 187 return nullptr; 188 189 // If the type has the may_alias attribute (even on a typedef), it is 190 // effectively in the general char alias class. 191 if (TypeHasMayAlias(QTy)) 192 return getChar(); 193 194 // We need this function to not fall back to returning the "omnipotent char" 195 // type node for aggregate and union types. Otherwise, any dereference of an 196 // aggregate will result into the may-alias access descriptor, meaning all 197 // subsequent accesses to direct and indirect members of that aggregate will 198 // be considered may-alias too. 199 // TODO: Combine getTypeInfo() and getBaseTypeInfo() into a single function. 200 if (isValidBaseType(QTy)) 201 return getBaseTypeInfo(QTy); 202 203 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 204 if (llvm::MDNode *N = MetadataCache[Ty]) 205 return N; 206 207 // Note that the following helper call is allowed to add new nodes to the 208 // cache, which invalidates all its previously obtained iterators. So we 209 // first generate the node for the type and then add that node to the cache. 210 llvm::MDNode *TypeNode = getTypeInfoHelper(Ty); 211 return MetadataCache[Ty] = TypeNode; 212 } 213 214 TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 215 llvm::DataLayout DL(&Module); 216 unsigned Size = DL.getPointerTypeSize(VTablePtrType); 217 return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size), 218 Size); 219 } 220 221 bool 222 CodeGenTBAA::CollectFields(uint64_t BaseOffset, 223 QualType QTy, 224 SmallVectorImpl<llvm::MDBuilder::TBAAStructField> & 225 Fields, 226 bool MayAlias) { 227 /* Things not handled yet include: C++ base classes, bitfields, */ 228 229 if (const RecordType *TTy = QTy->getAs<RecordType>()) { 230 const RecordDecl *RD = TTy->getDecl()->getDefinition(); 231 if (RD->hasFlexibleArrayMember()) 232 return false; 233 234 // TODO: Handle C++ base classes. 235 if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD)) 236 if (Decl->bases_begin() != Decl->bases_end()) 237 return false; 238 239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 240 241 unsigned idx = 0; 242 for (RecordDecl::field_iterator i = RD->field_begin(), 243 e = RD->field_end(); i != e; ++i, ++idx) { 244 uint64_t Offset = BaseOffset + 245 Layout.getFieldOffset(idx) / Context.getCharWidth(); 246 QualType FieldQTy = i->getType(); 247 if (!CollectFields(Offset, FieldQTy, Fields, 248 MayAlias || TypeHasMayAlias(FieldQTy))) 249 return false; 250 } 251 return true; 252 } 253 254 /* Otherwise, treat whatever it is as a field. */ 255 uint64_t Offset = BaseOffset; 256 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity(); 257 llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy); 258 llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size)); 259 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag)); 260 return true; 261 } 262 263 llvm::MDNode * 264 CodeGenTBAA::getTBAAStructInfo(QualType QTy) { 265 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 266 267 if (llvm::MDNode *N = StructMetadataCache[Ty]) 268 return N; 269 270 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields; 271 if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy))) 272 return MDHelper.createTBAAStructNode(Fields); 273 274 // For now, handle any other kind of type conservatively. 275 return StructMetadataCache[Ty] = nullptr; 276 } 277 278 llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) { 279 if (auto *TTy = dyn_cast<RecordType>(Ty)) { 280 const RecordDecl *RD = TTy->getDecl()->getDefinition(); 281 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 282 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields; 283 if (RD->isUnion()) { 284 // Unions are represented as structures with a single member that has a 285 // special type and occupies the whole object. 286 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity(); 287 llvm::MDNode *TypeNode = getUnionMemberType(Size); 288 Fields.push_back(llvm::MDBuilder::TBAAStructField(/* Offset= */ 0, Size, 289 TypeNode)); 290 } else { 291 for (FieldDecl *Field : RD->fields()) { 292 QualType FieldQTy = Field->getType(); 293 llvm::MDNode *TypeNode = isValidBaseType(FieldQTy) ? 294 getBaseTypeInfo(FieldQTy) : getTypeInfo(FieldQTy); 295 if (!TypeNode) 296 return nullptr; 297 298 uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex()); 299 uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity(); 300 uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity(); 301 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, 302 TypeNode)); 303 } 304 } 305 306 SmallString<256> OutName; 307 if (Features.CPlusPlus) { 308 // Don't use the mangler for C code. 309 llvm::raw_svector_ostream Out(OutName); 310 MContext.mangleTypeName(QualType(Ty, 0), Out); 311 } else { 312 OutName = RD->getName(); 313 } 314 315 // TODO: Support size-aware type nodes and create one here for the 316 // given aggregate type. 317 318 // Create the struct type node with a vector of pairs (offset, type). 319 SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes; 320 for (const auto &Field : Fields) 321 OffsetsAndTypes.push_back(std::make_pair(Field.TBAA, Field.Offset)); 322 return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes); 323 } 324 325 return nullptr; 326 } 327 328 llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) { 329 if (!isValidBaseType(QTy)) 330 return nullptr; 331 332 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 333 if (llvm::MDNode *N = BaseTypeMetadataCache[Ty]) 334 return N; 335 336 // Note that the following helper call is allowed to add new nodes to the 337 // cache, which invalidates all its previously obtained iterators. So we 338 // first generate the node for the type and then add that node to the cache. 339 llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty); 340 return BaseTypeMetadataCache[Ty] = TypeNode; 341 } 342 343 llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) { 344 assert(!Info.isIncomplete() && "Access to an object of an incomplete type!"); 345 346 if (Info.isMayAlias()) 347 Info = TBAAAccessInfo(getChar(), Info.Size); 348 else if (Info.isUnionMember()) 349 Info.AccessType = getUnionMemberType(Info.Size); 350 351 if (!Info.AccessType) 352 return nullptr; 353 354 if (!CodeGenOpts.StructPathTBAA) 355 Info = TBAAAccessInfo(Info.AccessType, Info.Size); 356 357 llvm::MDNode *&N = AccessTagMetadataCache[Info]; 358 if (N) 359 return N; 360 361 if (!Info.BaseType) { 362 Info.BaseType = Info.AccessType; 363 assert(!Info.Offset && "Nonzero offset for an access with no base type!"); 364 } 365 return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType, 366 Info.Offset); 367 } 368 369 TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 370 TBAAAccessInfo TargetInfo) { 371 if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias()) 372 return TBAAAccessInfo::getMayAliasInfo(); 373 return TargetInfo; 374 } 375 376 TBAAAccessInfo 377 CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 378 TBAAAccessInfo InfoB) { 379 if (InfoA == InfoB) 380 return InfoA; 381 382 if (!InfoA || !InfoB) 383 return TBAAAccessInfo(); 384 385 if (InfoA.isMayAlias() || InfoB.isMayAlias()) 386 return TBAAAccessInfo::getMayAliasInfo(); 387 388 // TODO: Implement the rest of the logic here. For example, two accesses 389 // with same final access types result in an access to an object of that final 390 // access type regardless of their base types. 391 return TBAAAccessInfo::getMayAliasInfo(); 392 } 393