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/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 39 CodeGenTBAA::~CodeGenTBAA() { 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 174 TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo() { 175 return TBAAAccessInfo(createTBAAScalarType("vtable pointer", getRoot())); 176 } 177 178 bool 179 CodeGenTBAA::CollectFields(uint64_t BaseOffset, 180 QualType QTy, 181 SmallVectorImpl<llvm::MDBuilder::TBAAStructField> & 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; 199 for (RecordDecl::field_iterator i = RD->field_begin(), 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 * 221 CodeGenTBAA::getTBAAStructInfo(QualType QTy) { 222 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 223 224 if (llvm::MDNode *N = StructMetadataCache[Ty]) 225 return N; 226 227 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields; 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 249 llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) { 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); 261 SmallVector <std::pair<llvm::MDNode*, uint64_t>, 4> Fields; 262 unsigned idx = 0; 263 for (RecordDecl::field_iterator i = RD->field_begin(), 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 290 llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) { 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 309 TBAAAccessInfo CodeGenTBAA::getMayAliasAccessInfo() { 310 return TBAAAccessInfo(getChar()); 311 } 312 313 TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 314 TBAAAccessInfo TargetInfo) { 315 TBAAAccessInfo MayAliasInfo = getMayAliasAccessInfo(); 316 if (SourceInfo == MayAliasInfo || TargetInfo == MayAliasInfo) 317 return MayAliasInfo; 318 return TargetInfo; 319 } 320