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(0), Char(0) { 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 Root = MDHelper.createTBAARoot("Simple C/C++ TBAA"); 49 50 return Root; 51 } 52 53 // For struct-path aware TBAA, the scalar type has the same format as 54 // the struct type: name, offset, pointer to another node in the type DAG. 55 // For scalar TBAA, the scalar type is the same as the scalar tag: 56 // name and a parent pointer. 57 llvm::MDNode *CodeGenTBAA::createTBAAScalarType(StringRef Name, 58 llvm::MDNode *Parent) { 59 if (CodeGenOpts.StructPathTBAA) 60 return MDHelper.createTBAAScalarTypeNode(Name, Parent); 61 else 62 return MDHelper.createTBAANode(Name, Parent); 63 } 64 65 llvm::MDNode *CodeGenTBAA::getChar() { 66 // Define the root of the tree for user-accessible memory. C and C++ 67 // give special powers to char and certain similar types. However, 68 // these special powers only cover user-accessible memory, and doesn't 69 // include things like vtables. 70 if (!Char) 71 Char = createTBAAScalarType("omnipotent char", getRoot()); 72 73 return Char; 74 } 75 76 static bool TypeHasMayAlias(QualType QTy) { 77 // Tagged types have declarations, and therefore may have attributes. 78 if (const TagType *TTy = dyn_cast<TagType>(QTy)) 79 return TTy->getDecl()->hasAttr<MayAliasAttr>(); 80 81 // Typedef types have declarations, and therefore may have attributes. 82 if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) { 83 if (TTy->getDecl()->hasAttr<MayAliasAttr>()) 84 return true; 85 // Also, their underlying types may have relevant attributes. 86 return TypeHasMayAlias(TTy->desugar()); 87 } 88 89 return false; 90 } 91 92 llvm::MDNode * 93 CodeGenTBAA::getTBAAInfo(QualType QTy) { 94 // At -O0 TBAA is not emitted for regular types. 95 if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing) 96 return NULL; 97 98 // If the type has the may_alias attribute (even on a typedef), it is 99 // effectively in the general char alias class. 100 if (TypeHasMayAlias(QTy)) 101 return getChar(); 102 103 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 104 105 if (llvm::MDNode *N = MetadataCache[Ty]) 106 return N; 107 108 // Handle builtin types. 109 if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) { 110 switch (BTy->getKind()) { 111 // Character types are special and can alias anything. 112 // In C++, this technically only includes "char" and "unsigned char", 113 // and not "signed char". In C, it includes all three. For now, 114 // the risk of exploiting this detail in C++ seems likely to outweigh 115 // the benefit. 116 case BuiltinType::Char_U: 117 case BuiltinType::Char_S: 118 case BuiltinType::UChar: 119 case BuiltinType::SChar: 120 return getChar(); 121 122 // Unsigned types can alias their corresponding signed types. 123 case BuiltinType::UShort: 124 return getTBAAInfo(Context.ShortTy); 125 case BuiltinType::UInt: 126 return getTBAAInfo(Context.IntTy); 127 case BuiltinType::ULong: 128 return getTBAAInfo(Context.LongTy); 129 case BuiltinType::ULongLong: 130 return getTBAAInfo(Context.LongLongTy); 131 case BuiltinType::UInt128: 132 return getTBAAInfo(Context.Int128Ty); 133 134 // Treat all other builtin types as distinct types. This includes 135 // treating wchar_t, char16_t, and char32_t as distinct from their 136 // "underlying types". 137 default: 138 return MetadataCache[Ty] = 139 createTBAAScalarType(BTy->getName(Features), getChar()); 140 } 141 } 142 143 // Handle pointers. 144 // TODO: Implement C++'s type "similarity" and consider dis-"similar" 145 // pointers distinct. 146 if (Ty->isPointerType()) 147 return MetadataCache[Ty] = createTBAAScalarType("any pointer", 148 getChar()); 149 150 // Enum types are distinct types. In C++ they have "underlying types", 151 // however they aren't related for TBAA. 152 if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) { 153 // In C mode, two anonymous enums are compatible iff their members 154 // are the same -- see C99 6.2.7p1. For now, be conservative. We could 155 // theoretically implement this by combining information about all the 156 // members into a single identifying MDNode. 157 if (!Features.CPlusPlus && 158 ETy->getDecl()->getTypedefNameForAnonDecl()) 159 return MetadataCache[Ty] = getChar(); 160 161 // In C++ mode, types have linkage, so we can rely on the ODR and 162 // on their mangled names, if they're external. 163 // TODO: Is there a way to get a program-wide unique name for a 164 // decl with local linkage or no linkage? 165 if (Features.CPlusPlus && !ETy->getDecl()->isExternallyVisible()) 166 return MetadataCache[Ty] = getChar(); 167 168 // TODO: This is using the RTTI name. Is there a better way to get 169 // a unique string for a type? 170 SmallString<256> OutName; 171 llvm::raw_svector_ostream Out(OutName); 172 MContext.mangleCXXRTTIName(QualType(ETy, 0), Out); 173 Out.flush(); 174 return MetadataCache[Ty] = createTBAAScalarType(OutName, getChar()); 175 } 176 177 // For now, handle any other kind of type conservatively. 178 return MetadataCache[Ty] = getChar(); 179 } 180 181 llvm::MDNode *CodeGenTBAA::getTBAAInfoForVTablePtr() { 182 return createTBAAScalarType("vtable pointer", getRoot()); 183 } 184 185 bool 186 CodeGenTBAA::CollectFields(uint64_t BaseOffset, 187 QualType QTy, 188 SmallVectorImpl<llvm::MDBuilder::TBAAStructField> & 189 Fields, 190 bool MayAlias) { 191 /* Things not handled yet include: C++ base classes, bitfields, */ 192 193 if (const RecordType *TTy = QTy->getAs<RecordType>()) { 194 const RecordDecl *RD = TTy->getDecl()->getDefinition(); 195 if (RD->hasFlexibleArrayMember()) 196 return false; 197 198 // TODO: Handle C++ base classes. 199 if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD)) 200 if (Decl->bases_begin() != Decl->bases_end()) 201 return false; 202 203 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 204 205 unsigned idx = 0; 206 const FieldDecl *LastFD = 0; 207 bool IsMsStruct = RD->isMsStruct(Context); 208 for (RecordDecl::field_iterator i = RD->field_begin(), 209 e = RD->field_end(); i != e; ++i, ++idx) { 210 if (IsMsStruct) { 211 // Zero-length bitfields following non-bitfield members are ignored. 212 if (Context.ZeroBitfieldFollowsNonBitfield(*i, LastFD)) { 213 --idx; 214 continue; 215 } 216 LastFD = *i; 217 } 218 uint64_t Offset = BaseOffset + 219 Layout.getFieldOffset(idx) / Context.getCharWidth(); 220 QualType FieldQTy = i->getType(); 221 if (!CollectFields(Offset, FieldQTy, Fields, 222 MayAlias || TypeHasMayAlias(FieldQTy))) 223 return false; 224 } 225 return true; 226 } 227 228 /* Otherwise, treat whatever it is as a field. */ 229 uint64_t Offset = BaseOffset; 230 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity(); 231 llvm::MDNode *TBAAInfo = MayAlias ? getChar() : getTBAAInfo(QTy); 232 llvm::MDNode *TBAATag = CodeGenOpts.StructPathTBAA ? 233 getTBAAScalarTagInfo(TBAAInfo) : TBAAInfo; 234 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag)); 235 return true; 236 } 237 238 llvm::MDNode * 239 CodeGenTBAA::getTBAAStructInfo(QualType QTy) { 240 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 241 242 if (llvm::MDNode *N = StructMetadataCache[Ty]) 243 return N; 244 245 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields; 246 if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy))) 247 return MDHelper.createTBAAStructNode(Fields); 248 249 // For now, handle any other kind of type conservatively. 250 return StructMetadataCache[Ty] = NULL; 251 } 252 253 /// Check if the given type can be handled by path-aware TBAA. 254 static bool isTBAAPathStruct(QualType QTy) { 255 if (const RecordType *TTy = QTy->getAs<RecordType>()) { 256 const RecordDecl *RD = TTy->getDecl()->getDefinition(); 257 if (RD->hasFlexibleArrayMember()) 258 return false; 259 // RD can be struct, union, class, interface or enum. 260 // For now, we only handle struct and class. 261 if (RD->isStruct() || RD->isClass()) 262 return true; 263 } 264 return false; 265 } 266 267 llvm::MDNode * 268 CodeGenTBAA::getTBAAStructTypeInfo(QualType QTy) { 269 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); 270 assert(isTBAAPathStruct(QTy)); 271 272 if (llvm::MDNode *N = StructTypeMetadataCache[Ty]) 273 return N; 274 275 if (const RecordType *TTy = QTy->getAs<RecordType>()) { 276 const RecordDecl *RD = TTy->getDecl()->getDefinition(); 277 278 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 279 SmallVector <std::pair<llvm::MDNode*, uint64_t>, 4> Fields; 280 unsigned idx = 0; 281 const FieldDecl *LastFD = 0; 282 bool IsMsStruct = RD->isMsStruct(Context); 283 for (RecordDecl::field_iterator i = RD->field_begin(), 284 e = RD->field_end(); i != e; ++i, ++idx) { 285 if (IsMsStruct) { 286 // Zero-length bitfields following non-bitfield members are ignored. 287 if (Context.ZeroBitfieldFollowsNonBitfield(*i, LastFD)) { 288 --idx; 289 continue; 290 } 291 LastFD = *i; 292 } 293 294 QualType FieldQTy = i->getType(); 295 llvm::MDNode *FieldNode; 296 if (isTBAAPathStruct(FieldQTy)) 297 FieldNode = getTBAAStructTypeInfo(FieldQTy); 298 else 299 FieldNode = getTBAAInfo(FieldQTy); 300 if (!FieldNode) 301 return StructTypeMetadataCache[Ty] = NULL; 302 Fields.push_back(std::make_pair( 303 FieldNode, Layout.getFieldOffset(idx) / Context.getCharWidth())); 304 } 305 306 // TODO: This is using the RTTI name. Is there a better way to get 307 // a unique string for a type? 308 SmallString<256> OutName; 309 llvm::raw_svector_ostream Out(OutName); 310 MContext.mangleCXXRTTIName(QualType(Ty, 0), Out); 311 Out.flush(); 312 // Create the struct type node with a vector of pairs (offset, type). 313 return StructTypeMetadataCache[Ty] = 314 MDHelper.createTBAAStructTypeNode(OutName, Fields); 315 } 316 317 return StructMetadataCache[Ty] = NULL; 318 } 319 320 llvm::MDNode * 321 CodeGenTBAA::getTBAAStructTagInfo(QualType BaseQTy, llvm::MDNode *AccessNode, 322 uint64_t Offset) { 323 if (!CodeGenOpts.StructPathTBAA) 324 return AccessNode; 325 326 const Type *BTy = Context.getCanonicalType(BaseQTy).getTypePtr(); 327 TBAAPathTag PathTag = TBAAPathTag(BTy, AccessNode, Offset); 328 if (llvm::MDNode *N = StructTagMetadataCache[PathTag]) 329 return N; 330 331 llvm::MDNode *BNode = 0; 332 if (isTBAAPathStruct(BaseQTy)) 333 BNode = getTBAAStructTypeInfo(BaseQTy); 334 if (!BNode) 335 return StructTagMetadataCache[PathTag] = 336 MDHelper.createTBAAStructTagNode(AccessNode, AccessNode, 0); 337 338 return StructTagMetadataCache[PathTag] = 339 MDHelper.createTBAAStructTagNode(BNode, AccessNode, Offset); 340 } 341 342 llvm::MDNode * 343 CodeGenTBAA::getTBAAScalarTagInfo(llvm::MDNode *AccessNode) { 344 if (llvm::MDNode *N = ScalarTagMetadataCache[AccessNode]) 345 return N; 346 347 return ScalarTagMetadataCache[AccessNode] = 348 MDHelper.createTBAAStructTagNode(AccessNode, AccessNode, 0); 349 } 350