1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 provides Objective-C code generation targeting the GNU runtime. The 10 // class in this file generates structures used by the GNU Objective-C runtime 11 // library. These structures are defined in objc/objc.h and objc/objc-api.h in 12 // the GNU runtime distribution. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "CGCXXABI.h" 17 #include "CGCleanup.h" 18 #include "CGObjCRuntime.h" 19 #include "CodeGenFunction.h" 20 #include "CodeGenModule.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/Attr.h" 23 #include "clang/AST/Decl.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/RecordLayout.h" 26 #include "clang/AST/StmtObjC.h" 27 #include "clang/Basic/FileManager.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/CodeGen/ConstantInitBuilder.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/StringMap.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/Intrinsics.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/Support/Compiler.h" 37 #include "llvm/Support/ConvertUTF.h" 38 #include <cctype> 39 40 using namespace clang; 41 using namespace CodeGen; 42 43 namespace { 44 45 /// Class that lazily initialises the runtime function. Avoids inserting the 46 /// types and the function declaration into a module if they're not used, and 47 /// avoids constructing the type more than once if it's used more than once. 48 class LazyRuntimeFunction { 49 CodeGenModule *CGM; 50 llvm::FunctionType *FTy; 51 const char *FunctionName; 52 llvm::FunctionCallee Function; 53 54 public: 55 /// Constructor leaves this class uninitialized, because it is intended to 56 /// be used as a field in another class and not all of the types that are 57 /// used as arguments will necessarily be available at construction time. 58 LazyRuntimeFunction() 59 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {} 60 61 /// Initialises the lazy function with the name, return type, and the types 62 /// of the arguments. 63 template <typename... Tys> 64 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, 65 Tys *... Types) { 66 CGM = Mod; 67 FunctionName = name; 68 Function = nullptr; 69 if(sizeof...(Tys)) { 70 SmallVector<llvm::Type *, 8> ArgTys({Types...}); 71 FTy = llvm::FunctionType::get(RetTy, ArgTys, false); 72 } 73 else { 74 FTy = llvm::FunctionType::get(RetTy, None, false); 75 } 76 } 77 78 llvm::FunctionType *getType() { return FTy; } 79 80 /// Overloaded cast operator, allows the class to be implicitly cast to an 81 /// LLVM constant. 82 operator llvm::FunctionCallee() { 83 if (!Function) { 84 if (!FunctionName) 85 return nullptr; 86 Function = CGM->CreateRuntimeFunction(FTy, FunctionName); 87 } 88 return Function; 89 } 90 }; 91 92 93 /// GNU Objective-C runtime code generation. This class implements the parts of 94 /// Objective-C support that are specific to the GNU family of runtimes (GCC, 95 /// GNUstep and ObjFW). 96 class CGObjCGNU : public CGObjCRuntime { 97 protected: 98 /// The LLVM module into which output is inserted 99 llvm::Module &TheModule; 100 /// strut objc_super. Used for sending messages to super. This structure 101 /// contains the receiver (object) and the expected class. 102 llvm::StructType *ObjCSuperTy; 103 /// struct objc_super*. The type of the argument to the superclass message 104 /// lookup functions. 105 llvm::PointerType *PtrToObjCSuperTy; 106 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring 107 /// SEL is included in a header somewhere, in which case it will be whatever 108 /// type is declared in that header, most likely {i8*, i8*}. 109 llvm::PointerType *SelectorTy; 110 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the 111 /// places where it's used 112 llvm::IntegerType *Int8Ty; 113 /// Pointer to i8 - LLVM type of char*, for all of the places where the 114 /// runtime needs to deal with C strings. 115 llvm::PointerType *PtrToInt8Ty; 116 /// struct objc_protocol type 117 llvm::StructType *ProtocolTy; 118 /// Protocol * type. 119 llvm::PointerType *ProtocolPtrTy; 120 /// Instance Method Pointer type. This is a pointer to a function that takes, 121 /// at a minimum, an object and a selector, and is the generic type for 122 /// Objective-C methods. Due to differences between variadic / non-variadic 123 /// calling conventions, it must always be cast to the correct type before 124 /// actually being used. 125 llvm::PointerType *IMPTy; 126 /// Type of an untyped Objective-C object. Clang treats id as a built-in type 127 /// when compiling Objective-C code, so this may be an opaque pointer (i8*), 128 /// but if the runtime header declaring it is included then it may be a 129 /// pointer to a structure. 130 llvm::PointerType *IdTy; 131 /// Pointer to a pointer to an Objective-C object. Used in the new ABI 132 /// message lookup function and some GC-related functions. 133 llvm::PointerType *PtrToIdTy; 134 /// The clang type of id. Used when using the clang CGCall infrastructure to 135 /// call Objective-C methods. 136 CanQualType ASTIdTy; 137 /// LLVM type for C int type. 138 llvm::IntegerType *IntTy; 139 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is 140 /// used in the code to document the difference between i8* meaning a pointer 141 /// to a C string and i8* meaning a pointer to some opaque type. 142 llvm::PointerType *PtrTy; 143 /// LLVM type for C long type. The runtime uses this in a lot of places where 144 /// it should be using intptr_t, but we can't fix this without breaking 145 /// compatibility with GCC... 146 llvm::IntegerType *LongTy; 147 /// LLVM type for C size_t. Used in various runtime data structures. 148 llvm::IntegerType *SizeTy; 149 /// LLVM type for C intptr_t. 150 llvm::IntegerType *IntPtrTy; 151 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions. 152 llvm::IntegerType *PtrDiffTy; 153 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance 154 /// variables. 155 llvm::PointerType *PtrToIntTy; 156 /// LLVM type for Objective-C BOOL type. 157 llvm::Type *BoolTy; 158 /// 32-bit integer type, to save us needing to look it up every time it's used. 159 llvm::IntegerType *Int32Ty; 160 /// 64-bit integer type, to save us needing to look it up every time it's used. 161 llvm::IntegerType *Int64Ty; 162 /// The type of struct objc_property. 163 llvm::StructType *PropertyMetadataTy; 164 /// Metadata kind used to tie method lookups to message sends. The GNUstep 165 /// runtime provides some LLVM passes that can use this to do things like 166 /// automatic IMP caching and speculative inlining. 167 unsigned msgSendMDKind; 168 /// Does the current target use SEH-based exceptions? False implies 169 /// Itanium-style DWARF unwinding. 170 bool usesSEHExceptions; 171 172 /// Helper to check if we are targeting a specific runtime version or later. 173 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) { 174 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; 175 return (R.getKind() == kind) && 176 (R.getVersion() >= VersionTuple(major, minor)); 177 } 178 179 std::string ManglePublicSymbol(StringRef Name) { 180 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str(); 181 } 182 183 std::string SymbolForProtocol(Twine Name) { 184 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str(); 185 } 186 187 std::string SymbolForProtocolRef(StringRef Name) { 188 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str(); 189 } 190 191 192 /// Helper function that generates a constant string and returns a pointer to 193 /// the start of the string. The result of this function can be used anywhere 194 /// where the C code specifies const char*. 195 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") { 196 ConstantAddress Array = 197 CGM.GetAddrOfConstantCString(std::string(Str), Name); 198 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(), 199 Array.getPointer(), Zeros); 200 } 201 202 /// Emits a linkonce_odr string, whose name is the prefix followed by the 203 /// string value. This allows the linker to combine the strings between 204 /// different modules. Used for EH typeinfo names, selector strings, and a 205 /// few other things. 206 llvm::Constant *ExportUniqueString(const std::string &Str, 207 const std::string &prefix, 208 bool Private=false) { 209 std::string name = prefix + Str; 210 auto *ConstStr = TheModule.getGlobalVariable(name); 211 if (!ConstStr) { 212 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str); 213 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true, 214 llvm::GlobalValue::LinkOnceODRLinkage, value, name); 215 GV->setComdat(TheModule.getOrInsertComdat(name)); 216 if (Private) 217 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 218 ConstStr = GV; 219 } 220 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(), 221 ConstStr, Zeros); 222 } 223 224 /// Returns a property name and encoding string. 225 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD, 226 const Decl *Container) { 227 assert(!isRuntime(ObjCRuntime::GNUstep, 2)); 228 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) { 229 std::string NameAndAttributes; 230 std::string TypeStr = 231 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container); 232 NameAndAttributes += '\0'; 233 NameAndAttributes += TypeStr.length() + 3; 234 NameAndAttributes += TypeStr; 235 NameAndAttributes += '\0'; 236 NameAndAttributes += PD->getNameAsString(); 237 return MakeConstantString(NameAndAttributes); 238 } 239 return MakeConstantString(PD->getNameAsString()); 240 } 241 242 /// Push the property attributes into two structure fields. 243 void PushPropertyAttributes(ConstantStructBuilder &Fields, 244 const ObjCPropertyDecl *property, bool isSynthesized=true, bool 245 isDynamic=true) { 246 int attrs = property->getPropertyAttributes(); 247 // For read-only properties, clear the copy and retain flags 248 if (attrs & ObjCPropertyAttribute::kind_readonly) { 249 attrs &= ~ObjCPropertyAttribute::kind_copy; 250 attrs &= ~ObjCPropertyAttribute::kind_retain; 251 attrs &= ~ObjCPropertyAttribute::kind_weak; 252 attrs &= ~ObjCPropertyAttribute::kind_strong; 253 } 254 // The first flags field has the same attribute values as clang uses internally 255 Fields.addInt(Int8Ty, attrs & 0xff); 256 attrs >>= 8; 257 attrs <<= 2; 258 // For protocol properties, synthesized and dynamic have no meaning, so we 259 // reuse these flags to indicate that this is a protocol property (both set 260 // has no meaning, as a property can't be both synthesized and dynamic) 261 attrs |= isSynthesized ? (1<<0) : 0; 262 attrs |= isDynamic ? (1<<1) : 0; 263 // The second field is the next four fields left shifted by two, with the 264 // low bit set to indicate whether the field is synthesized or dynamic. 265 Fields.addInt(Int8Ty, attrs & 0xff); 266 // Two padding fields 267 Fields.addInt(Int8Ty, 0); 268 Fields.addInt(Int8Ty, 0); 269 } 270 271 virtual llvm::Constant *GenerateCategoryProtocolList(const 272 ObjCCategoryDecl *OCD); 273 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields, 274 int count) { 275 // int count; 276 Fields.addInt(IntTy, count); 277 // int size; (only in GNUstep v2 ABI. 278 if (isRuntime(ObjCRuntime::GNUstep, 2)) { 279 llvm::DataLayout td(&TheModule); 280 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) / 281 CGM.getContext().getCharWidth()); 282 } 283 // struct objc_property_list *next; 284 Fields.add(NULLPtr); 285 // struct objc_property properties[] 286 return Fields.beginArray(PropertyMetadataTy); 287 } 288 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray, 289 const ObjCPropertyDecl *property, 290 const Decl *OCD, 291 bool isSynthesized=true, bool 292 isDynamic=true) { 293 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy); 294 ASTContext &Context = CGM.getContext(); 295 Fields.add(MakePropertyEncodingString(property, OCD)); 296 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic); 297 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { 298 if (accessor) { 299 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor); 300 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 301 Fields.add(MakeConstantString(accessor->getSelector().getAsString())); 302 Fields.add(TypeEncoding); 303 } else { 304 Fields.add(NULLPtr); 305 Fields.add(NULLPtr); 306 } 307 }; 308 addPropertyMethod(property->getGetterMethodDecl()); 309 addPropertyMethod(property->getSetterMethodDecl()); 310 Fields.finishAndAddTo(PropertiesArray); 311 } 312 313 /// Ensures that the value has the required type, by inserting a bitcast if 314 /// required. This function lets us avoid inserting bitcasts that are 315 /// redundant. 316 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) { 317 if (V->getType() == Ty) return V; 318 return B.CreateBitCast(V, Ty); 319 } 320 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) { 321 if (V.getType() == Ty) 322 return V; 323 return B.CreateElementBitCast(V, Ty->getPointerElementType()); 324 } 325 326 // Some zeros used for GEPs in lots of places. 327 llvm::Constant *Zeros[2]; 328 /// Null pointer value. Mainly used as a terminator in various arrays. 329 llvm::Constant *NULLPtr; 330 /// LLVM context. 331 llvm::LLVMContext &VMContext; 332 333 protected: 334 335 /// Placeholder for the class. Lots of things refer to the class before we've 336 /// actually emitted it. We use this alias as a placeholder, and then replace 337 /// it with a pointer to the class structure before finally emitting the 338 /// module. 339 llvm::GlobalAlias *ClassPtrAlias; 340 /// Placeholder for the metaclass. Lots of things refer to the class before 341 /// we've / actually emitted it. We use this alias as a placeholder, and then 342 /// replace / it with a pointer to the metaclass structure before finally 343 /// emitting the / module. 344 llvm::GlobalAlias *MetaClassPtrAlias; 345 /// All of the classes that have been generated for this compilation units. 346 std::vector<llvm::Constant*> Classes; 347 /// All of the categories that have been generated for this compilation units. 348 std::vector<llvm::Constant*> Categories; 349 /// All of the Objective-C constant strings that have been generated for this 350 /// compilation units. 351 std::vector<llvm::Constant*> ConstantStrings; 352 /// Map from string values to Objective-C constant strings in the output. 353 /// Used to prevent emitting Objective-C strings more than once. This should 354 /// not be required at all - CodeGenModule should manage this list. 355 llvm::StringMap<llvm::Constant*> ObjCStrings; 356 /// All of the protocols that have been declared. 357 llvm::StringMap<llvm::Constant*> ExistingProtocols; 358 /// For each variant of a selector, we store the type encoding and a 359 /// placeholder value. For an untyped selector, the type will be the empty 360 /// string. Selector references are all done via the module's selector table, 361 /// so we create an alias as a placeholder and then replace it with the real 362 /// value later. 363 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector; 364 /// Type of the selector map. This is roughly equivalent to the structure 365 /// used in the GNUstep runtime, which maintains a list of all of the valid 366 /// types for a selector in a table. 367 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> > 368 SelectorMap; 369 /// A map from selectors to selector types. This allows us to emit all 370 /// selectors of the same name and type together. 371 SelectorMap SelectorTable; 372 373 /// Selectors related to memory management. When compiling in GC mode, we 374 /// omit these. 375 Selector RetainSel, ReleaseSel, AutoreleaseSel; 376 /// Runtime functions used for memory management in GC mode. Note that clang 377 /// supports code generation for calling these functions, but neither GNU 378 /// runtime actually supports this API properly yet. 379 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, 380 WeakAssignFn, GlobalAssignFn; 381 382 typedef std::pair<std::string, std::string> ClassAliasPair; 383 /// All classes that have aliases set for them. 384 std::vector<ClassAliasPair> ClassAliases; 385 386 protected: 387 /// Function used for throwing Objective-C exceptions. 388 LazyRuntimeFunction ExceptionThrowFn; 389 /// Function used for rethrowing exceptions, used at the end of \@finally or 390 /// \@synchronize blocks. 391 LazyRuntimeFunction ExceptionReThrowFn; 392 /// Function called when entering a catch function. This is required for 393 /// differentiating Objective-C exceptions and foreign exceptions. 394 LazyRuntimeFunction EnterCatchFn; 395 /// Function called when exiting from a catch block. Used to do exception 396 /// cleanup. 397 LazyRuntimeFunction ExitCatchFn; 398 /// Function called when entering an \@synchronize block. Acquires the lock. 399 LazyRuntimeFunction SyncEnterFn; 400 /// Function called when exiting an \@synchronize block. Releases the lock. 401 LazyRuntimeFunction SyncExitFn; 402 403 private: 404 /// Function called if fast enumeration detects that the collection is 405 /// modified during the update. 406 LazyRuntimeFunction EnumerationMutationFn; 407 /// Function for implementing synthesized property getters that return an 408 /// object. 409 LazyRuntimeFunction GetPropertyFn; 410 /// Function for implementing synthesized property setters that return an 411 /// object. 412 LazyRuntimeFunction SetPropertyFn; 413 /// Function used for non-object declared property getters. 414 LazyRuntimeFunction GetStructPropertyFn; 415 /// Function used for non-object declared property setters. 416 LazyRuntimeFunction SetStructPropertyFn; 417 418 protected: 419 /// The version of the runtime that this class targets. Must match the 420 /// version in the runtime. 421 int RuntimeVersion; 422 /// The version of the protocol class. Used to differentiate between ObjC1 423 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional 424 /// components and can not contain declared properties. We always emit 425 /// Objective-C 2 property structures, but we have to pretend that they're 426 /// Objective-C 1 property structures when targeting the GCC runtime or it 427 /// will abort. 428 const int ProtocolVersion; 429 /// The version of the class ABI. This value is used in the class structure 430 /// and indicates how various fields should be interpreted. 431 const int ClassABIVersion; 432 /// Generates an instance variable list structure. This is a structure 433 /// containing a size and an array of structures containing instance variable 434 /// metadata. This is used purely for introspection in the fragile ABI. In 435 /// the non-fragile ABI, it's used for instance variable fixup. 436 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 437 ArrayRef<llvm::Constant *> IvarTypes, 438 ArrayRef<llvm::Constant *> IvarOffsets, 439 ArrayRef<llvm::Constant *> IvarAlign, 440 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership); 441 442 /// Generates a method list structure. This is a structure containing a size 443 /// and an array of structures containing method metadata. 444 /// 445 /// This structure is used by both classes and categories, and contains a next 446 /// pointer allowing them to be chained together in a linked list. 447 llvm::Constant *GenerateMethodList(StringRef ClassName, 448 StringRef CategoryName, 449 ArrayRef<const ObjCMethodDecl*> Methods, 450 bool isClassMethodList); 451 452 /// Emits an empty protocol. This is used for \@protocol() where no protocol 453 /// is found. The runtime will (hopefully) fix up the pointer to refer to the 454 /// real protocol. 455 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName); 456 457 /// Generates a list of property metadata structures. This follows the same 458 /// pattern as method and instance variable metadata lists. 459 llvm::Constant *GeneratePropertyList(const Decl *Container, 460 const ObjCContainerDecl *OCD, 461 bool isClassProperty=false, 462 bool protocolOptionalProperties=false); 463 464 /// Generates a list of referenced protocols. Classes, categories, and 465 /// protocols all use this structure. 466 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols); 467 468 /// To ensure that all protocols are seen by the runtime, we add a category on 469 /// a class defined in the runtime, declaring no methods, but adopting the 470 /// protocols. This is a horribly ugly hack, but it allows us to collect all 471 /// of the protocols without changing the ABI. 472 void GenerateProtocolHolderCategory(); 473 474 /// Generates a class structure. 475 llvm::Constant *GenerateClassStructure( 476 llvm::Constant *MetaClass, 477 llvm::Constant *SuperClass, 478 unsigned info, 479 const char *Name, 480 llvm::Constant *Version, 481 llvm::Constant *InstanceSize, 482 llvm::Constant *IVars, 483 llvm::Constant *Methods, 484 llvm::Constant *Protocols, 485 llvm::Constant *IvarOffsets, 486 llvm::Constant *Properties, 487 llvm::Constant *StrongIvarBitmap, 488 llvm::Constant *WeakIvarBitmap, 489 bool isMeta=false); 490 491 /// Generates a method list. This is used by protocols to define the required 492 /// and optional methods. 493 virtual llvm::Constant *GenerateProtocolMethodList( 494 ArrayRef<const ObjCMethodDecl*> Methods); 495 /// Emits optional and required method lists. 496 template<class T> 497 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required, 498 llvm::Constant *&Optional) { 499 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods; 500 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods; 501 for (const auto *I : Methods) 502 if (I->isOptional()) 503 OptionalMethods.push_back(I); 504 else 505 RequiredMethods.push_back(I); 506 Required = GenerateProtocolMethodList(RequiredMethods); 507 Optional = GenerateProtocolMethodList(OptionalMethods); 508 } 509 510 /// Returns a selector with the specified type encoding. An empty string is 511 /// used to return an untyped selector (with the types field set to NULL). 512 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel, 513 const std::string &TypeEncoding); 514 515 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this 516 /// contains the class and ivar names, in the v2 ABI this contains the type 517 /// encoding as well. 518 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID, 519 const ObjCIvarDecl *Ivar) { 520 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 521 + '.' + Ivar->getNameAsString(); 522 return Name; 523 } 524 /// Returns the variable used to store the offset of an instance variable. 525 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 526 const ObjCIvarDecl *Ivar); 527 /// Emits a reference to a class. This allows the linker to object if there 528 /// is no class of the matching name. 529 void EmitClassRef(const std::string &className); 530 531 /// Emits a pointer to the named class 532 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF, 533 const std::string &Name, bool isWeak); 534 535 /// Looks up the method for sending a message to the specified object. This 536 /// mechanism differs between the GCC and GNU runtimes, so this method must be 537 /// overridden in subclasses. 538 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF, 539 llvm::Value *&Receiver, 540 llvm::Value *cmd, 541 llvm::MDNode *node, 542 MessageSendInfo &MSI) = 0; 543 544 /// Looks up the method for sending a message to a superclass. This 545 /// mechanism differs between the GCC and GNU runtimes, so this method must 546 /// be overridden in subclasses. 547 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, 548 Address ObjCSuper, 549 llvm::Value *cmd, 550 MessageSendInfo &MSI) = 0; 551 552 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are 553 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 554 /// bits set to their values, LSB first, while larger ones are stored in a 555 /// structure of this / form: 556 /// 557 /// struct { int32_t length; int32_t values[length]; }; 558 /// 559 /// The values in the array are stored in host-endian format, with the least 560 /// significant bit being assumed to come first in the bitfield. Therefore, 561 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, 562 /// while a bitfield / with the 63rd bit set will be 1<<64. 563 llvm::Constant *MakeBitField(ArrayRef<bool> bits); 564 565 public: 566 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, 567 unsigned protocolClassVersion, unsigned classABI=1); 568 569 ConstantAddress GenerateConstantString(const StringLiteral *) override; 570 571 RValue 572 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return, 573 QualType ResultType, Selector Sel, 574 llvm::Value *Receiver, const CallArgList &CallArgs, 575 const ObjCInterfaceDecl *Class, 576 const ObjCMethodDecl *Method) override; 577 RValue 578 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return, 579 QualType ResultType, Selector Sel, 580 const ObjCInterfaceDecl *Class, 581 bool isCategoryImpl, llvm::Value *Receiver, 582 bool IsClassMessage, const CallArgList &CallArgs, 583 const ObjCMethodDecl *Method) override; 584 llvm::Value *GetClass(CodeGenFunction &CGF, 585 const ObjCInterfaceDecl *OID) override; 586 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override; 587 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override; 588 llvm::Value *GetSelector(CodeGenFunction &CGF, 589 const ObjCMethodDecl *Method) override; 590 virtual llvm::Constant *GetConstantSelector(Selector Sel, 591 const std::string &TypeEncoding) { 592 llvm_unreachable("Runtime unable to generate constant selector"); 593 } 594 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) { 595 return GetConstantSelector(M->getSelector(), 596 CGM.getContext().getObjCEncodingForMethodDecl(M)); 597 } 598 llvm::Constant *GetEHType(QualType T) override; 599 600 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 601 const ObjCContainerDecl *CD) override; 602 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn, 603 const ObjCMethodDecl *OMD, 604 const ObjCContainerDecl *CD) override; 605 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; 606 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; 607 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override; 608 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 609 const ObjCProtocolDecl *PD) override; 610 void GenerateProtocol(const ObjCProtocolDecl *PD) override; 611 612 virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD); 613 614 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override { 615 return GenerateProtocolRef(PD); 616 } 617 618 llvm::Function *ModuleInitFunction() override; 619 llvm::FunctionCallee GetPropertyGetFunction() override; 620 llvm::FunctionCallee GetPropertySetFunction() override; 621 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic, 622 bool copy) override; 623 llvm::FunctionCallee GetSetStructFunction() override; 624 llvm::FunctionCallee GetGetStructFunction() override; 625 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override; 626 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override; 627 llvm::FunctionCallee EnumerationMutationFunction() override; 628 629 void EmitTryStmt(CodeGenFunction &CGF, 630 const ObjCAtTryStmt &S) override; 631 void EmitSynchronizedStmt(CodeGenFunction &CGF, 632 const ObjCAtSynchronizedStmt &S) override; 633 void EmitThrowStmt(CodeGenFunction &CGF, 634 const ObjCAtThrowStmt &S, 635 bool ClearInsertionPoint=true) override; 636 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF, 637 Address AddrWeakObj) override; 638 void EmitObjCWeakAssign(CodeGenFunction &CGF, 639 llvm::Value *src, Address dst) override; 640 void EmitObjCGlobalAssign(CodeGenFunction &CGF, 641 llvm::Value *src, Address dest, 642 bool threadlocal=false) override; 643 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src, 644 Address dest, llvm::Value *ivarOffset) override; 645 void EmitObjCStrongCastAssign(CodeGenFunction &CGF, 646 llvm::Value *src, Address dest) override; 647 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr, 648 Address SrcPtr, 649 llvm::Value *Size) override; 650 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy, 651 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, 652 unsigned CVRQualifiers) override; 653 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF, 654 const ObjCInterfaceDecl *Interface, 655 const ObjCIvarDecl *Ivar) override; 656 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; 657 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM, 658 const CGBlockInfo &blockInfo) override { 659 return NULLPtr; 660 } 661 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM, 662 const CGBlockInfo &blockInfo) override { 663 return NULLPtr; 664 } 665 666 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override { 667 return NULLPtr; 668 } 669 }; 670 671 /// Class representing the legacy GCC Objective-C ABI. This is the default when 672 /// -fobjc-nonfragile-abi is not specified. 673 /// 674 /// The GCC ABI target actually generates code that is approximately compatible 675 /// with the new GNUstep runtime ABI, but refrains from using any features that 676 /// would not work with the GCC runtime. For example, clang always generates 677 /// the extended form of the class structure, and the extra fields are simply 678 /// ignored by GCC libobjc. 679 class CGObjCGCC : public CGObjCGNU { 680 /// The GCC ABI message lookup function. Returns an IMP pointing to the 681 /// method implementation for this message. 682 LazyRuntimeFunction MsgLookupFn; 683 /// The GCC ABI superclass message lookup function. Takes a pointer to a 684 /// structure describing the receiver and the class, and a selector as 685 /// arguments. Returns the IMP for the corresponding method. 686 LazyRuntimeFunction MsgLookupSuperFn; 687 688 protected: 689 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 690 llvm::Value *cmd, llvm::MDNode *node, 691 MessageSendInfo &MSI) override { 692 CGBuilderTy &Builder = CGF.Builder; 693 llvm::Value *args[] = { 694 EnforceType(Builder, Receiver, IdTy), 695 EnforceType(Builder, cmd, SelectorTy) }; 696 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args); 697 imp->setMetadata(msgSendMDKind, node); 698 return imp; 699 } 700 701 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 702 llvm::Value *cmd, MessageSendInfo &MSI) override { 703 CGBuilderTy &Builder = CGF.Builder; 704 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper, 705 PtrToObjCSuperTy).getPointer(), cmd}; 706 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 707 } 708 709 public: 710 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) { 711 // IMP objc_msg_lookup(id, SEL); 712 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy); 713 // IMP objc_msg_lookup_super(struct objc_super*, SEL); 714 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 715 PtrToObjCSuperTy, SelectorTy); 716 } 717 }; 718 719 /// Class used when targeting the new GNUstep runtime ABI. 720 class CGObjCGNUstep : public CGObjCGNU { 721 /// The slot lookup function. Returns a pointer to a cacheable structure 722 /// that contains (among other things) the IMP. 723 LazyRuntimeFunction SlotLookupFn; 724 /// The GNUstep ABI superclass message lookup function. Takes a pointer to 725 /// a structure describing the receiver and the class, and a selector as 726 /// arguments. Returns the slot for the corresponding method. Superclass 727 /// message lookup rarely changes, so this is a good caching opportunity. 728 LazyRuntimeFunction SlotLookupSuperFn; 729 /// Specialised function for setting atomic retain properties 730 LazyRuntimeFunction SetPropertyAtomic; 731 /// Specialised function for setting atomic copy properties 732 LazyRuntimeFunction SetPropertyAtomicCopy; 733 /// Specialised function for setting nonatomic retain properties 734 LazyRuntimeFunction SetPropertyNonAtomic; 735 /// Specialised function for setting nonatomic copy properties 736 LazyRuntimeFunction SetPropertyNonAtomicCopy; 737 /// Function to perform atomic copies of C++ objects with nontrivial copy 738 /// constructors from Objective-C ivars. 739 LazyRuntimeFunction CxxAtomicObjectGetFn; 740 /// Function to perform atomic copies of C++ objects with nontrivial copy 741 /// constructors to Objective-C ivars. 742 LazyRuntimeFunction CxxAtomicObjectSetFn; 743 /// Type of a slot structure pointer. This is returned by the various 744 /// lookup functions. 745 llvm::Type *SlotTy; 746 /// Type of a slot structure. 747 llvm::Type *SlotStructTy; 748 749 public: 750 llvm::Constant *GetEHType(QualType T) override; 751 752 protected: 753 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 754 llvm::Value *cmd, llvm::MDNode *node, 755 MessageSendInfo &MSI) override { 756 CGBuilderTy &Builder = CGF.Builder; 757 llvm::FunctionCallee LookupFn = SlotLookupFn; 758 759 // Store the receiver on the stack so that we can reload it later 760 Address ReceiverPtr = 761 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign()); 762 Builder.CreateStore(Receiver, ReceiverPtr); 763 764 llvm::Value *self; 765 766 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) { 767 self = CGF.LoadObjCSelf(); 768 } else { 769 self = llvm::ConstantPointerNull::get(IdTy); 770 } 771 772 // The lookup function is guaranteed not to capture the receiver pointer. 773 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee())) 774 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture); 775 776 llvm::Value *args[] = { 777 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy), 778 EnforceType(Builder, cmd, SelectorTy), 779 EnforceType(Builder, self, IdTy) }; 780 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args); 781 slot->setOnlyReadsMemory(); 782 slot->setMetadata(msgSendMDKind, node); 783 784 // Load the imp from the slot 785 llvm::Value *imp = Builder.CreateAlignedLoad( 786 IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4), 787 CGF.getPointerAlign()); 788 789 // The lookup function may have changed the receiver, so make sure we use 790 // the new one. 791 Receiver = Builder.CreateLoad(ReceiverPtr, true); 792 return imp; 793 } 794 795 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 796 llvm::Value *cmd, 797 MessageSendInfo &MSI) override { 798 CGBuilderTy &Builder = CGF.Builder; 799 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd}; 800 801 llvm::CallInst *slot = 802 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs); 803 slot->setOnlyReadsMemory(); 804 805 return Builder.CreateAlignedLoad( 806 IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4), 807 CGF.getPointerAlign()); 808 } 809 810 public: 811 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {} 812 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI, 813 unsigned ClassABI) : 814 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) { 815 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; 816 817 SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy); 818 SlotTy = llvm::PointerType::getUnqual(SlotStructTy); 819 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender); 820 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy, 821 SelectorTy, IdTy); 822 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL); 823 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy, 824 PtrToObjCSuperTy, SelectorTy); 825 // If we're in ObjC++ mode, then we want to make 826 if (usesSEHExceptions) { 827 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 828 // void objc_exception_rethrow(void) 829 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy); 830 } else if (CGM.getLangOpts().CPlusPlus) { 831 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 832 // void *__cxa_begin_catch(void *e) 833 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy); 834 // void __cxa_end_catch(void) 835 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy); 836 // void _Unwind_Resume_or_Rethrow(void*) 837 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, 838 PtrTy); 839 } else if (R.getVersion() >= VersionTuple(1, 7)) { 840 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 841 // id objc_begin_catch(void *e) 842 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy); 843 // void objc_end_catch(void) 844 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy); 845 // void _Unwind_Resume_or_Rethrow(void*) 846 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy); 847 } 848 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 849 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy, 850 SelectorTy, IdTy, PtrDiffTy); 851 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy, 852 IdTy, SelectorTy, IdTy, PtrDiffTy); 853 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy, 854 IdTy, SelectorTy, IdTy, PtrDiffTy); 855 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy", 856 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy); 857 // void objc_setCppObjectAtomic(void *dest, const void *src, void 858 // *helper); 859 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy, 860 PtrTy, PtrTy); 861 // void objc_getCppObjectAtomic(void *dest, const void *src, void 862 // *helper); 863 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy, 864 PtrTy, PtrTy); 865 } 866 867 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override { 868 // The optimised functions were added in version 1.7 of the GNUstep 869 // runtime. 870 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 871 VersionTuple(1, 7)); 872 return CxxAtomicObjectGetFn; 873 } 874 875 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override { 876 // The optimised functions were added in version 1.7 of the GNUstep 877 // runtime. 878 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 879 VersionTuple(1, 7)); 880 return CxxAtomicObjectSetFn; 881 } 882 883 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic, 884 bool copy) override { 885 // The optimised property functions omit the GC check, and so are not 886 // safe to use in GC mode. The standard functions are fast in GC mode, 887 // so there is less advantage in using them. 888 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC)); 889 // The optimised functions were added in version 1.7 of the GNUstep 890 // runtime. 891 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 892 VersionTuple(1, 7)); 893 894 if (atomic) { 895 if (copy) return SetPropertyAtomicCopy; 896 return SetPropertyAtomic; 897 } 898 899 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic; 900 } 901 }; 902 903 /// GNUstep Objective-C ABI version 2 implementation. 904 /// This is the ABI that provides a clean break with the legacy GCC ABI and 905 /// cleans up a number of things that were added to work around 1980s linkers. 906 class CGObjCGNUstep2 : public CGObjCGNUstep { 907 enum SectionKind 908 { 909 SelectorSection = 0, 910 ClassSection, 911 ClassReferenceSection, 912 CategorySection, 913 ProtocolSection, 914 ProtocolReferenceSection, 915 ClassAliasSection, 916 ConstantStringSection 917 }; 918 static const char *const SectionsBaseNames[8]; 919 static const char *const PECOFFSectionsBaseNames[8]; 920 template<SectionKind K> 921 std::string sectionName() { 922 if (CGM.getTriple().isOSBinFormatCOFF()) { 923 std::string name(PECOFFSectionsBaseNames[K]); 924 name += "$m"; 925 return name; 926 } 927 return SectionsBaseNames[K]; 928 } 929 /// The GCC ABI superclass message lookup function. Takes a pointer to a 930 /// structure describing the receiver and the class, and a selector as 931 /// arguments. Returns the IMP for the corresponding method. 932 LazyRuntimeFunction MsgLookupSuperFn; 933 /// A flag indicating if we've emitted at least one protocol. 934 /// If we haven't, then we need to emit an empty protocol, to ensure that the 935 /// __start__objc_protocols and __stop__objc_protocols sections exist. 936 bool EmittedProtocol = false; 937 /// A flag indicating if we've emitted at least one protocol reference. 938 /// If we haven't, then we need to emit an empty protocol, to ensure that the 939 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections 940 /// exist. 941 bool EmittedProtocolRef = false; 942 /// A flag indicating if we've emitted at least one class. 943 /// If we haven't, then we need to emit an empty protocol, to ensure that the 944 /// __start__objc_classes and __stop__objc_classes sections / exist. 945 bool EmittedClass = false; 946 /// Generate the name of a symbol for a reference to a class. Accesses to 947 /// classes should be indirected via this. 948 949 typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>> 950 EarlyInitPair; 951 std::vector<EarlyInitPair> EarlyInitList; 952 953 std::string SymbolForClassRef(StringRef Name, bool isWeak) { 954 if (isWeak) 955 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str(); 956 else 957 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str(); 958 } 959 /// Generate the name of a class symbol. 960 std::string SymbolForClass(StringRef Name) { 961 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str(); 962 } 963 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName, 964 ArrayRef<llvm::Value*> Args) { 965 SmallVector<llvm::Type *,8> Types; 966 for (auto *Arg : Args) 967 Types.push_back(Arg->getType()); 968 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types, 969 false); 970 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName); 971 B.CreateCall(Fn, Args); 972 } 973 974 ConstantAddress GenerateConstantString(const StringLiteral *SL) override { 975 976 auto Str = SL->getString(); 977 CharUnits Align = CGM.getPointerAlign(); 978 979 // Look for an existing one 980 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str); 981 if (old != ObjCStrings.end()) 982 return ConstantAddress( 983 old->getValue(), old->getValue()->getType()->getPointerElementType(), 984 Align); 985 986 bool isNonASCII = SL->containsNonAscii(); 987 988 auto LiteralLength = SL->getLength(); 989 990 if ((CGM.getTarget().getPointerWidth(0) == 64) && 991 (LiteralLength < 9) && !isNonASCII) { 992 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit 993 // ASCII characters in the high 56 bits, followed by a 4-bit length and a 994 // 3-bit tag (which is always 4). 995 uint64_t str = 0; 996 // Fill in the characters 997 for (unsigned i=0 ; i<LiteralLength ; i++) 998 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7)); 999 // Fill in the length 1000 str |= LiteralLength << 3; 1001 // Set the tag 1002 str |= 4; 1003 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr( 1004 llvm::ConstantInt::get(Int64Ty, str), IdTy); 1005 ObjCStrings[Str] = ObjCStr; 1006 return ConstantAddress(ObjCStr, IdTy->getPointerElementType(), Align); 1007 } 1008 1009 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass; 1010 1011 if (StringClass.empty()) StringClass = "NSConstantString"; 1012 1013 std::string Sym = SymbolForClass(StringClass); 1014 1015 llvm::Constant *isa = TheModule.getNamedGlobal(Sym); 1016 1017 if (!isa) { 1018 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false, 1019 llvm::GlobalValue::ExternalLinkage, nullptr, Sym); 1020 if (CGM.getTriple().isOSBinFormatCOFF()) { 1021 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1022 } 1023 } else if (isa->getType() != PtrToIdTy) 1024 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy); 1025 1026 // struct 1027 // { 1028 // Class isa; 1029 // uint32_t flags; 1030 // uint32_t length; // Number of codepoints 1031 // uint32_t size; // Number of bytes 1032 // uint32_t hash; 1033 // const char *data; 1034 // }; 1035 1036 ConstantInitBuilder Builder(CGM); 1037 auto Fields = Builder.beginStruct(); 1038 if (!CGM.getTriple().isOSBinFormatCOFF()) { 1039 Fields.add(isa); 1040 } else { 1041 Fields.addNullPointer(PtrTy); 1042 } 1043 // For now, all non-ASCII strings are represented as UTF-16. As such, the 1044 // number of bytes is simply double the number of UTF-16 codepoints. In 1045 // ASCII strings, the number of bytes is equal to the number of non-ASCII 1046 // codepoints. 1047 if (isNonASCII) { 1048 unsigned NumU8CodeUnits = Str.size(); 1049 // A UTF-16 representation of a unicode string contains at most the same 1050 // number of code units as a UTF-8 representation. Allocate that much 1051 // space, plus one for the final null character. 1052 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1); 1053 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data(); 1054 llvm::UTF16 *ToPtr = &ToBuf[0]; 1055 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits, 1056 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion); 1057 uint32_t StringLength = ToPtr - &ToBuf[0]; 1058 // Add null terminator 1059 *ToPtr = 0; 1060 // Flags: 2 indicates UTF-16 encoding 1061 Fields.addInt(Int32Ty, 2); 1062 // Number of UTF-16 codepoints 1063 Fields.addInt(Int32Ty, StringLength); 1064 // Number of bytes 1065 Fields.addInt(Int32Ty, StringLength * 2); 1066 // Hash. Not currently initialised by the compiler. 1067 Fields.addInt(Int32Ty, 0); 1068 // pointer to the data string. 1069 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1); 1070 auto *C = llvm::ConstantDataArray::get(VMContext, Arr); 1071 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(), 1072 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str"); 1073 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1074 Fields.add(Buffer); 1075 } else { 1076 // Flags: 0 indicates ASCII encoding 1077 Fields.addInt(Int32Ty, 0); 1078 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint 1079 Fields.addInt(Int32Ty, Str.size()); 1080 // Number of bytes 1081 Fields.addInt(Int32Ty, Str.size()); 1082 // Hash. Not currently initialised by the compiler. 1083 Fields.addInt(Int32Ty, 0); 1084 // Data pointer 1085 Fields.add(MakeConstantString(Str)); 1086 } 1087 std::string StringName; 1088 bool isNamed = !isNonASCII; 1089 if (isNamed) { 1090 StringName = ".objc_str_"; 1091 for (int i=0,e=Str.size() ; i<e ; ++i) { 1092 unsigned char c = Str[i]; 1093 if (isalnum(c)) 1094 StringName += c; 1095 else if (c == ' ') 1096 StringName += '_'; 1097 else { 1098 isNamed = false; 1099 break; 1100 } 1101 } 1102 } 1103 llvm::GlobalVariable *ObjCStrGV = 1104 Fields.finishAndCreateGlobal( 1105 isNamed ? StringRef(StringName) : ".objc_string", 1106 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage 1107 : llvm::GlobalValue::PrivateLinkage); 1108 ObjCStrGV->setSection(sectionName<ConstantStringSection>()); 1109 if (isNamed) { 1110 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName)); 1111 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1112 } 1113 if (CGM.getTriple().isOSBinFormatCOFF()) { 1114 std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0}; 1115 EarlyInitList.emplace_back(Sym, v); 1116 } 1117 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy); 1118 ObjCStrings[Str] = ObjCStr; 1119 ConstantStrings.push_back(ObjCStr); 1120 return ConstantAddress(ObjCStr, IdTy->getPointerElementType(), Align); 1121 } 1122 1123 void PushProperty(ConstantArrayBuilder &PropertiesArray, 1124 const ObjCPropertyDecl *property, 1125 const Decl *OCD, 1126 bool isSynthesized=true, bool 1127 isDynamic=true) override { 1128 // struct objc_property 1129 // { 1130 // const char *name; 1131 // const char *attributes; 1132 // const char *type; 1133 // SEL getter; 1134 // SEL setter; 1135 // }; 1136 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy); 1137 ASTContext &Context = CGM.getContext(); 1138 Fields.add(MakeConstantString(property->getNameAsString())); 1139 std::string TypeStr = 1140 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD); 1141 Fields.add(MakeConstantString(TypeStr)); 1142 std::string typeStr; 1143 Context.getObjCEncodingForType(property->getType(), typeStr); 1144 Fields.add(MakeConstantString(typeStr)); 1145 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { 1146 if (accessor) { 1147 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor); 1148 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr)); 1149 } else { 1150 Fields.add(NULLPtr); 1151 } 1152 }; 1153 addPropertyMethod(property->getGetterMethodDecl()); 1154 addPropertyMethod(property->getSetterMethodDecl()); 1155 Fields.finishAndAddTo(PropertiesArray); 1156 } 1157 1158 llvm::Constant * 1159 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override { 1160 // struct objc_protocol_method_description 1161 // { 1162 // SEL selector; 1163 // const char *types; 1164 // }; 1165 llvm::StructType *ObjCMethodDescTy = 1166 llvm::StructType::get(CGM.getLLVMContext(), 1167 { PtrToInt8Ty, PtrToInt8Ty }); 1168 ASTContext &Context = CGM.getContext(); 1169 ConstantInitBuilder Builder(CGM); 1170 // struct objc_protocol_method_description_list 1171 // { 1172 // int count; 1173 // int size; 1174 // struct objc_protocol_method_description methods[]; 1175 // }; 1176 auto MethodList = Builder.beginStruct(); 1177 // int count; 1178 MethodList.addInt(IntTy, Methods.size()); 1179 // int size; // sizeof(struct objc_method_description) 1180 llvm::DataLayout td(&TheModule); 1181 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) / 1182 CGM.getContext().getCharWidth()); 1183 // struct objc_method_description[] 1184 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy); 1185 for (auto *M : Methods) { 1186 auto Method = MethodArray.beginStruct(ObjCMethodDescTy); 1187 Method.add(CGObjCGNU::GetConstantSelector(M)); 1188 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true))); 1189 Method.finishAndAddTo(MethodArray); 1190 } 1191 MethodArray.finishAndAddTo(MethodList); 1192 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list", 1193 CGM.getPointerAlign()); 1194 } 1195 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD) 1196 override { 1197 const auto &ReferencedProtocols = OCD->getReferencedProtocols(); 1198 auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(), 1199 ReferencedProtocols.end()); 1200 SmallVector<llvm::Constant *, 16> Protocols; 1201 for (const auto *PI : RuntimeProtocols) 1202 Protocols.push_back( 1203 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI), 1204 ProtocolPtrTy)); 1205 return GenerateProtocolList(Protocols); 1206 } 1207 1208 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 1209 llvm::Value *cmd, MessageSendInfo &MSI) override { 1210 // Don't access the slot unless we're trying to cache the result. 1211 CGBuilderTy &Builder = CGF.Builder; 1212 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper, 1213 PtrToObjCSuperTy).getPointer(), cmd}; 1214 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 1215 } 1216 1217 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) { 1218 std::string SymbolName = SymbolForClassRef(Name, isWeak); 1219 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName); 1220 if (ClassSymbol) 1221 return ClassSymbol; 1222 ClassSymbol = new llvm::GlobalVariable(TheModule, 1223 IdTy, false, llvm::GlobalValue::ExternalLinkage, 1224 nullptr, SymbolName); 1225 // If this is a weak symbol, then we are creating a valid definition for 1226 // the symbol, pointing to a weak definition of the real class pointer. If 1227 // this is not a weak reference, then we are expecting another compilation 1228 // unit to provide the real indirection symbol. 1229 if (isWeak) 1230 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule, 1231 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage, 1232 nullptr, SymbolForClass(Name))); 1233 else { 1234 if (CGM.getTriple().isOSBinFormatCOFF()) { 1235 IdentifierInfo &II = CGM.getContext().Idents.get(Name); 1236 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); 1237 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 1238 1239 const ObjCInterfaceDecl *OID = nullptr; 1240 for (const auto *Result : DC->lookup(&II)) 1241 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result))) 1242 break; 1243 1244 // The first Interface we find may be a @class, 1245 // which should only be treated as the source of 1246 // truth in the absence of a true declaration. 1247 assert(OID && "Failed to find ObjCInterfaceDecl"); 1248 const ObjCInterfaceDecl *OIDDef = OID->getDefinition(); 1249 if (OIDDef != nullptr) 1250 OID = OIDDef; 1251 1252 auto Storage = llvm::GlobalValue::DefaultStorageClass; 1253 if (OID->hasAttr<DLLImportAttr>()) 1254 Storage = llvm::GlobalValue::DLLImportStorageClass; 1255 else if (OID->hasAttr<DLLExportAttr>()) 1256 Storage = llvm::GlobalValue::DLLExportStorageClass; 1257 1258 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage); 1259 } 1260 } 1261 assert(ClassSymbol->getName() == SymbolName); 1262 return ClassSymbol; 1263 } 1264 llvm::Value *GetClassNamed(CodeGenFunction &CGF, 1265 const std::string &Name, 1266 bool isWeak) override { 1267 return CGF.Builder.CreateLoad( 1268 Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign())); 1269 } 1270 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) { 1271 // typedef enum { 1272 // ownership_invalid = 0, 1273 // ownership_strong = 1, 1274 // ownership_weak = 2, 1275 // ownership_unsafe = 3 1276 // } ivar_ownership; 1277 int Flag; 1278 switch (Ownership) { 1279 case Qualifiers::OCL_Strong: 1280 Flag = 1; 1281 break; 1282 case Qualifiers::OCL_Weak: 1283 Flag = 2; 1284 break; 1285 case Qualifiers::OCL_ExplicitNone: 1286 Flag = 3; 1287 break; 1288 case Qualifiers::OCL_None: 1289 case Qualifiers::OCL_Autoreleasing: 1290 assert(Ownership != Qualifiers::OCL_Autoreleasing); 1291 Flag = 0; 1292 } 1293 return Flag; 1294 } 1295 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 1296 ArrayRef<llvm::Constant *> IvarTypes, 1297 ArrayRef<llvm::Constant *> IvarOffsets, 1298 ArrayRef<llvm::Constant *> IvarAlign, 1299 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override { 1300 llvm_unreachable("Method should not be called!"); 1301 } 1302 1303 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override { 1304 std::string Name = SymbolForProtocol(ProtocolName); 1305 auto *GV = TheModule.getGlobalVariable(Name); 1306 if (!GV) { 1307 // Emit a placeholder symbol. 1308 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false, 1309 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 1310 GV->setAlignment(CGM.getPointerAlign().getAsAlign()); 1311 } 1312 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy); 1313 } 1314 1315 /// Existing protocol references. 1316 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs; 1317 1318 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 1319 const ObjCProtocolDecl *PD) override { 1320 auto Name = PD->getNameAsString(); 1321 auto *&Ref = ExistingProtocolRefs[Name]; 1322 if (!Ref) { 1323 auto *&Protocol = ExistingProtocols[Name]; 1324 if (!Protocol) 1325 Protocol = GenerateProtocolRef(PD); 1326 std::string RefName = SymbolForProtocolRef(Name); 1327 assert(!TheModule.getGlobalVariable(RefName)); 1328 // Emit a reference symbol. 1329 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, 1330 false, llvm::GlobalValue::LinkOnceODRLinkage, 1331 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName); 1332 GV->setComdat(TheModule.getOrInsertComdat(RefName)); 1333 GV->setSection(sectionName<ProtocolReferenceSection>()); 1334 GV->setAlignment(CGM.getPointerAlign().getAsAlign()); 1335 Ref = GV; 1336 } 1337 EmittedProtocolRef = true; 1338 return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref, 1339 CGM.getPointerAlign()); 1340 } 1341 1342 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) { 1343 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy, 1344 Protocols.size()); 1345 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 1346 Protocols); 1347 ConstantInitBuilder builder(CGM); 1348 auto ProtocolBuilder = builder.beginStruct(); 1349 ProtocolBuilder.addNullPointer(PtrTy); 1350 ProtocolBuilder.addInt(SizeTy, Protocols.size()); 1351 ProtocolBuilder.add(ProtocolArray); 1352 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list", 1353 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage); 1354 } 1355 1356 void GenerateProtocol(const ObjCProtocolDecl *PD) override { 1357 // Do nothing - we only emit referenced protocols. 1358 } 1359 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override { 1360 std::string ProtocolName = PD->getNameAsString(); 1361 auto *&Protocol = ExistingProtocols[ProtocolName]; 1362 if (Protocol) 1363 return Protocol; 1364 1365 EmittedProtocol = true; 1366 1367 auto SymName = SymbolForProtocol(ProtocolName); 1368 auto *OldGV = TheModule.getGlobalVariable(SymName); 1369 1370 // Use the protocol definition, if there is one. 1371 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 1372 PD = Def; 1373 else { 1374 // If there is no definition, then create an external linkage symbol and 1375 // hope that someone else fills it in for us (and fail to link if they 1376 // don't). 1377 assert(!OldGV); 1378 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy, 1379 /*isConstant*/false, 1380 llvm::GlobalValue::ExternalLinkage, nullptr, SymName); 1381 return Protocol; 1382 } 1383 1384 SmallVector<llvm::Constant*, 16> Protocols; 1385 auto RuntimeProtocols = 1386 GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end()); 1387 for (const auto *PI : RuntimeProtocols) 1388 Protocols.push_back( 1389 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI), 1390 ProtocolPtrTy)); 1391 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 1392 1393 // Collect information about methods 1394 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList; 1395 llvm::Constant *ClassMethodList, *OptionalClassMethodList; 1396 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList, 1397 OptionalInstanceMethodList); 1398 EmitProtocolMethodList(PD->class_methods(), ClassMethodList, 1399 OptionalClassMethodList); 1400 1401 // The isa pointer must be set to a magic number so the runtime knows it's 1402 // the correct layout. 1403 ConstantInitBuilder builder(CGM); 1404 auto ProtocolBuilder = builder.beginStruct(); 1405 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr( 1406 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy)); 1407 ProtocolBuilder.add(MakeConstantString(ProtocolName)); 1408 ProtocolBuilder.add(ProtocolList); 1409 ProtocolBuilder.add(InstanceMethodList); 1410 ProtocolBuilder.add(ClassMethodList); 1411 ProtocolBuilder.add(OptionalInstanceMethodList); 1412 ProtocolBuilder.add(OptionalClassMethodList); 1413 // Required instance properties 1414 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false)); 1415 // Optional instance properties 1416 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true)); 1417 // Required class properties 1418 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false)); 1419 // Optional class properties 1420 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true)); 1421 1422 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName, 1423 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage); 1424 GV->setSection(sectionName<ProtocolSection>()); 1425 GV->setComdat(TheModule.getOrInsertComdat(SymName)); 1426 if (OldGV) { 1427 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV, 1428 OldGV->getType())); 1429 OldGV->removeFromParent(); 1430 GV->setName(SymName); 1431 } 1432 Protocol = GV; 1433 return GV; 1434 } 1435 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) { 1436 if (Val->getType() == Ty) 1437 return Val; 1438 return llvm::ConstantExpr::getBitCast(Val, Ty); 1439 } 1440 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel, 1441 const std::string &TypeEncoding) override { 1442 return GetConstantSelector(Sel, TypeEncoding); 1443 } 1444 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) { 1445 if (TypeEncoding.empty()) 1446 return NULLPtr; 1447 std::string MangledTypes = std::string(TypeEncoding); 1448 std::replace(MangledTypes.begin(), MangledTypes.end(), 1449 '@', '\1'); 1450 std::string TypesVarName = ".objc_sel_types_" + MangledTypes; 1451 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName); 1452 if (!TypesGlobal) { 1453 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 1454 TypeEncoding); 1455 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(), 1456 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName); 1457 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName)); 1458 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1459 TypesGlobal = GV; 1460 } 1461 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(), 1462 TypesGlobal, Zeros); 1463 } 1464 llvm::Constant *GetConstantSelector(Selector Sel, 1465 const std::string &TypeEncoding) override { 1466 // @ is used as a special character in symbol names (used for symbol 1467 // versioning), so mangle the name to not include it. Replace it with a 1468 // character that is not a valid type encoding character (and, being 1469 // non-printable, never will be!) 1470 std::string MangledTypes = TypeEncoding; 1471 std::replace(MangledTypes.begin(), MangledTypes.end(), 1472 '@', '\1'); 1473 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" + 1474 MangledTypes).str(); 1475 if (auto *GV = TheModule.getNamedGlobal(SelVarName)) 1476 return EnforceType(GV, SelectorTy); 1477 ConstantInitBuilder builder(CGM); 1478 auto SelBuilder = builder.beginStruct(); 1479 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_", 1480 true)); 1481 SelBuilder.add(GetTypeString(TypeEncoding)); 1482 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName, 1483 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage); 1484 GV->setComdat(TheModule.getOrInsertComdat(SelVarName)); 1485 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1486 GV->setSection(sectionName<SelectorSection>()); 1487 auto *SelVal = EnforceType(GV, SelectorTy); 1488 return SelVal; 1489 } 1490 llvm::StructType *emptyStruct = nullptr; 1491 1492 /// Return pointers to the start and end of a section. On ELF platforms, we 1493 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set 1494 /// to the start and end of section names, as long as those section names are 1495 /// valid identifiers and the symbols are referenced but not defined. On 1496 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort 1497 /// by subsections and place everything that we want to reference in a middle 1498 /// subsection and then insert zero-sized symbols in subsections a and z. 1499 std::pair<llvm::Constant*,llvm::Constant*> 1500 GetSectionBounds(StringRef Section) { 1501 if (CGM.getTriple().isOSBinFormatCOFF()) { 1502 if (emptyStruct == nullptr) { 1503 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel"); 1504 emptyStruct->setBody({}, /*isPacked*/true); 1505 } 1506 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct); 1507 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) { 1508 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct, 1509 /*isConstant*/false, 1510 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix + 1511 Section); 1512 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility); 1513 Sym->setSection((Section + SecSuffix).str()); 1514 Sym->setComdat(TheModule.getOrInsertComdat((Prefix + 1515 Section).str())); 1516 Sym->setAlignment(CGM.getPointerAlign().getAsAlign()); 1517 return Sym; 1518 }; 1519 return { Sym("__start_", "$a"), Sym("__stop", "$z") }; 1520 } 1521 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy, 1522 /*isConstant*/false, 1523 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") + 1524 Section); 1525 Start->setVisibility(llvm::GlobalValue::HiddenVisibility); 1526 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy, 1527 /*isConstant*/false, 1528 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") + 1529 Section); 1530 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility); 1531 return { Start, Stop }; 1532 } 1533 CatchTypeInfo getCatchAllTypeInfo() override { 1534 return CGM.getCXXABI().getCatchAllTypeInfo(); 1535 } 1536 llvm::Function *ModuleInitFunction() override { 1537 llvm::Function *LoadFunction = llvm::Function::Create( 1538 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 1539 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function", 1540 &TheModule); 1541 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility); 1542 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function")); 1543 1544 llvm::BasicBlock *EntryBB = 1545 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 1546 CGBuilderTy B(CGM, VMContext); 1547 B.SetInsertPoint(EntryBB); 1548 ConstantInitBuilder builder(CGM); 1549 auto InitStructBuilder = builder.beginStruct(); 1550 InitStructBuilder.addInt(Int64Ty, 0); 1551 auto §ionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames; 1552 for (auto *s : sectionVec) { 1553 auto bounds = GetSectionBounds(s); 1554 InitStructBuilder.add(bounds.first); 1555 InitStructBuilder.add(bounds.second); 1556 } 1557 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init", 1558 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage); 1559 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility); 1560 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init")); 1561 1562 CallRuntimeFunction(B, "__objc_load", {InitStruct});; 1563 B.CreateRetVoid(); 1564 // Make sure that the optimisers don't delete this function. 1565 CGM.addCompilerUsedGlobal(LoadFunction); 1566 // FIXME: Currently ELF only! 1567 // We have to do this by hand, rather than with @llvm.ctors, so that the 1568 // linker can remove the duplicate invocations. 1569 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(), 1570 /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage, 1571 LoadFunction, ".objc_ctor"); 1572 // Check that this hasn't been renamed. This shouldn't happen, because 1573 // this function should be called precisely once. 1574 assert(InitVar->getName() == ".objc_ctor"); 1575 // In Windows, initialisers are sorted by the suffix. XCL is for library 1576 // initialisers, which run before user initialisers. We are running 1577 // Objective-C loads at the end of library load. This means +load methods 1578 // will run before any other static constructors, but that static 1579 // constructors can see a fully initialised Objective-C state. 1580 if (CGM.getTriple().isOSBinFormatCOFF()) 1581 InitVar->setSection(".CRT$XCLz"); 1582 else 1583 { 1584 if (CGM.getCodeGenOpts().UseInitArray) 1585 InitVar->setSection(".init_array"); 1586 else 1587 InitVar->setSection(".ctors"); 1588 } 1589 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility); 1590 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor")); 1591 CGM.addUsedGlobal(InitVar); 1592 for (auto *C : Categories) { 1593 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts()); 1594 Cat->setSection(sectionName<CategorySection>()); 1595 CGM.addUsedGlobal(Cat); 1596 } 1597 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init, 1598 StringRef Section) { 1599 auto nullBuilder = builder.beginStruct(); 1600 for (auto *F : Init) 1601 nullBuilder.add(F); 1602 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(), 1603 false, llvm::GlobalValue::LinkOnceODRLinkage); 1604 GV->setSection(Section); 1605 GV->setComdat(TheModule.getOrInsertComdat(Name)); 1606 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1607 CGM.addUsedGlobal(GV); 1608 return GV; 1609 }; 1610 for (auto clsAlias : ClassAliases) 1611 createNullGlobal(std::string(".objc_class_alias") + 1612 clsAlias.second, { MakeConstantString(clsAlias.second), 1613 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>()); 1614 // On ELF platforms, add a null value for each special section so that we 1615 // can always guarantee that the _start and _stop symbols will exist and be 1616 // meaningful. This is not required on COFF platforms, where our start and 1617 // stop symbols will create the section. 1618 if (!CGM.getTriple().isOSBinFormatCOFF()) { 1619 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr}, 1620 sectionName<SelectorSection>()); 1621 if (Categories.empty()) 1622 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr, 1623 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr}, 1624 sectionName<CategorySection>()); 1625 if (!EmittedClass) { 1626 createNullGlobal(".objc_null_cls_init_ref", NULLPtr, 1627 sectionName<ClassSection>()); 1628 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr }, 1629 sectionName<ClassReferenceSection>()); 1630 } 1631 if (!EmittedProtocol) 1632 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr, 1633 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, 1634 NULLPtr}, sectionName<ProtocolSection>()); 1635 if (!EmittedProtocolRef) 1636 createNullGlobal(".objc_null_protocol_ref", {NULLPtr}, 1637 sectionName<ProtocolReferenceSection>()); 1638 if (ClassAliases.empty()) 1639 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr }, 1640 sectionName<ClassAliasSection>()); 1641 if (ConstantStrings.empty()) { 1642 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0); 1643 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero, 1644 i32Zero, i32Zero, i32Zero, NULLPtr }, 1645 sectionName<ConstantStringSection>()); 1646 } 1647 } 1648 ConstantStrings.clear(); 1649 Categories.clear(); 1650 Classes.clear(); 1651 1652 if (EarlyInitList.size() > 0) { 1653 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy, 1654 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init", 1655 &CGM.getModule()); 1656 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry", 1657 Init)); 1658 for (const auto &lateInit : EarlyInitList) { 1659 auto *global = TheModule.getGlobalVariable(lateInit.first); 1660 if (global) { 1661 llvm::GlobalVariable *GV = lateInit.second.first; 1662 b.CreateAlignedStore( 1663 global, 1664 b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second), 1665 CGM.getPointerAlign().getAsAlign()); 1666 } 1667 } 1668 b.CreateRetVoid(); 1669 // We can't use the normal LLVM global initialisation array, because we 1670 // need to specify that this runs early in library initialisation. 1671 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 1672 /*isConstant*/true, llvm::GlobalValue::InternalLinkage, 1673 Init, ".objc_early_init_ptr"); 1674 InitVar->setSection(".CRT$XCLb"); 1675 CGM.addUsedGlobal(InitVar); 1676 } 1677 return nullptr; 1678 } 1679 /// In the v2 ABI, ivar offset variables use the type encoding in their name 1680 /// to trigger linker failures if the types don't match. 1681 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID, 1682 const ObjCIvarDecl *Ivar) override { 1683 std::string TypeEncoding; 1684 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding); 1685 // Prevent the @ from being interpreted as a symbol version. 1686 std::replace(TypeEncoding.begin(), TypeEncoding.end(), 1687 '@', '\1'); 1688 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 1689 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding; 1690 return Name; 1691 } 1692 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF, 1693 const ObjCInterfaceDecl *Interface, 1694 const ObjCIvarDecl *Ivar) override { 1695 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar); 1696 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 1697 if (!IvarOffsetPointer) 1698 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false, 1699 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 1700 CharUnits Align = CGM.getIntAlign(); 1701 llvm::Value *Offset = 1702 CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align); 1703 if (Offset->getType() != PtrDiffTy) 1704 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy); 1705 return Offset; 1706 } 1707 void GenerateClass(const ObjCImplementationDecl *OID) override { 1708 ASTContext &Context = CGM.getContext(); 1709 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF(); 1710 1711 // Get the class name 1712 ObjCInterfaceDecl *classDecl = 1713 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 1714 std::string className = classDecl->getNameAsString(); 1715 auto *classNameConstant = MakeConstantString(className); 1716 1717 ConstantInitBuilder builder(CGM); 1718 auto metaclassFields = builder.beginStruct(); 1719 // struct objc_class *isa; 1720 metaclassFields.addNullPointer(PtrTy); 1721 // struct objc_class *super_class; 1722 metaclassFields.addNullPointer(PtrTy); 1723 // const char *name; 1724 metaclassFields.add(classNameConstant); 1725 // long version; 1726 metaclassFields.addInt(LongTy, 0); 1727 // unsigned long info; 1728 // objc_class_flag_meta 1729 metaclassFields.addInt(LongTy, 1); 1730 // long instance_size; 1731 // Setting this to zero is consistent with the older ABI, but it might be 1732 // more sensible to set this to sizeof(struct objc_class) 1733 metaclassFields.addInt(LongTy, 0); 1734 // struct objc_ivar_list *ivars; 1735 metaclassFields.addNullPointer(PtrTy); 1736 // struct objc_method_list *methods 1737 // FIXME: Almost identical code is copied and pasted below for the 1738 // class, but refactoring it cleanly requires C++14 generic lambdas. 1739 if (OID->classmeth_begin() == OID->classmeth_end()) 1740 metaclassFields.addNullPointer(PtrTy); 1741 else { 1742 SmallVector<ObjCMethodDecl*, 16> ClassMethods; 1743 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(), 1744 OID->classmeth_end()); 1745 metaclassFields.addBitCast( 1746 GenerateMethodList(className, "", ClassMethods, true), 1747 PtrTy); 1748 } 1749 // void *dtable; 1750 metaclassFields.addNullPointer(PtrTy); 1751 // IMP cxx_construct; 1752 metaclassFields.addNullPointer(PtrTy); 1753 // IMP cxx_destruct; 1754 metaclassFields.addNullPointer(PtrTy); 1755 // struct objc_class *subclass_list 1756 metaclassFields.addNullPointer(PtrTy); 1757 // struct objc_class *sibling_class 1758 metaclassFields.addNullPointer(PtrTy); 1759 // struct objc_protocol_list *protocols; 1760 metaclassFields.addNullPointer(PtrTy); 1761 // struct reference_list *extra_data; 1762 metaclassFields.addNullPointer(PtrTy); 1763 // long abi_version; 1764 metaclassFields.addInt(LongTy, 0); 1765 // struct objc_property_list *properties 1766 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true)); 1767 1768 auto *metaclass = metaclassFields.finishAndCreateGlobal( 1769 ManglePublicSymbol("OBJC_METACLASS_") + className, 1770 CGM.getPointerAlign()); 1771 1772 auto classFields = builder.beginStruct(); 1773 // struct objc_class *isa; 1774 classFields.add(metaclass); 1775 // struct objc_class *super_class; 1776 // Get the superclass name. 1777 const ObjCInterfaceDecl * SuperClassDecl = 1778 OID->getClassInterface()->getSuperClass(); 1779 llvm::Constant *SuperClass = nullptr; 1780 if (SuperClassDecl) { 1781 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString()); 1782 SuperClass = TheModule.getNamedGlobal(SuperClassName); 1783 if (!SuperClass) 1784 { 1785 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false, 1786 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName); 1787 if (IsCOFF) { 1788 auto Storage = llvm::GlobalValue::DefaultStorageClass; 1789 if (SuperClassDecl->hasAttr<DLLImportAttr>()) 1790 Storage = llvm::GlobalValue::DLLImportStorageClass; 1791 else if (SuperClassDecl->hasAttr<DLLExportAttr>()) 1792 Storage = llvm::GlobalValue::DLLExportStorageClass; 1793 1794 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage); 1795 } 1796 } 1797 if (!IsCOFF) 1798 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy)); 1799 else 1800 classFields.addNullPointer(PtrTy); 1801 } else 1802 classFields.addNullPointer(PtrTy); 1803 // const char *name; 1804 classFields.add(classNameConstant); 1805 // long version; 1806 classFields.addInt(LongTy, 0); 1807 // unsigned long info; 1808 // !objc_class_flag_meta 1809 classFields.addInt(LongTy, 0); 1810 // long instance_size; 1811 int superInstanceSize = !SuperClassDecl ? 0 : 1812 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity(); 1813 // Instance size is negative for classes that have not yet had their ivar 1814 // layout calculated. 1815 classFields.addInt(LongTy, 1816 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() - 1817 superInstanceSize)); 1818 1819 if (classDecl->all_declared_ivar_begin() == nullptr) 1820 classFields.addNullPointer(PtrTy); 1821 else { 1822 int ivar_count = 0; 1823 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD; 1824 IVD = IVD->getNextIvar()) ivar_count++; 1825 llvm::DataLayout td(&TheModule); 1826 // struct objc_ivar_list *ivars; 1827 ConstantInitBuilder b(CGM); 1828 auto ivarListBuilder = b.beginStruct(); 1829 // int count; 1830 ivarListBuilder.addInt(IntTy, ivar_count); 1831 // size_t size; 1832 llvm::StructType *ObjCIvarTy = llvm::StructType::get( 1833 PtrToInt8Ty, 1834 PtrToInt8Ty, 1835 PtrToInt8Ty, 1836 Int32Ty, 1837 Int32Ty); 1838 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) / 1839 CGM.getContext().getCharWidth()); 1840 // struct objc_ivar ivars[] 1841 auto ivarArrayBuilder = ivarListBuilder.beginArray(); 1842 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD; 1843 IVD = IVD->getNextIvar()) { 1844 auto ivarTy = IVD->getType(); 1845 auto ivarBuilder = ivarArrayBuilder.beginStruct(); 1846 // const char *name; 1847 ivarBuilder.add(MakeConstantString(IVD->getNameAsString())); 1848 // const char *type; 1849 std::string TypeStr; 1850 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true); 1851 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true); 1852 ivarBuilder.add(MakeConstantString(TypeStr)); 1853 // int *offset; 1854 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD); 1855 uint64_t Offset = BaseOffset - superInstanceSize; 1856 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset); 1857 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD); 1858 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName); 1859 if (OffsetVar) 1860 OffsetVar->setInitializer(OffsetValue); 1861 else 1862 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy, 1863 false, llvm::GlobalValue::ExternalLinkage, 1864 OffsetValue, OffsetName); 1865 auto ivarVisibility = 1866 (IVD->getAccessControl() == ObjCIvarDecl::Private || 1867 IVD->getAccessControl() == ObjCIvarDecl::Package || 1868 classDecl->getVisibility() == HiddenVisibility) ? 1869 llvm::GlobalValue::HiddenVisibility : 1870 llvm::GlobalValue::DefaultVisibility; 1871 OffsetVar->setVisibility(ivarVisibility); 1872 ivarBuilder.add(OffsetVar); 1873 // Ivar size 1874 ivarBuilder.addInt(Int32Ty, 1875 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity()); 1876 // Alignment will be stored as a base-2 log of the alignment. 1877 unsigned align = 1878 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity()); 1879 // Objects that require more than 2^64-byte alignment should be impossible! 1880 assert(align < 64); 1881 // uint32_t flags; 1882 // Bits 0-1 are ownership. 1883 // Bit 2 indicates an extended type encoding 1884 // Bits 3-8 contain log2(aligment) 1885 ivarBuilder.addInt(Int32Ty, 1886 (align << 3) | (1<<2) | 1887 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime())); 1888 ivarBuilder.finishAndAddTo(ivarArrayBuilder); 1889 } 1890 ivarArrayBuilder.finishAndAddTo(ivarListBuilder); 1891 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list", 1892 CGM.getPointerAlign(), /*constant*/ false, 1893 llvm::GlobalValue::PrivateLinkage); 1894 classFields.add(ivarList); 1895 } 1896 // struct objc_method_list *methods 1897 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods; 1898 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(), 1899 OID->instmeth_end()); 1900 for (auto *propImpl : OID->property_impls()) 1901 if (propImpl->getPropertyImplementation() == 1902 ObjCPropertyImplDecl::Synthesize) { 1903 auto addIfExists = [&](const ObjCMethodDecl *OMD) { 1904 if (OMD && OMD->hasBody()) 1905 InstanceMethods.push_back(OMD); 1906 }; 1907 addIfExists(propImpl->getGetterMethodDecl()); 1908 addIfExists(propImpl->getSetterMethodDecl()); 1909 } 1910 1911 if (InstanceMethods.size() == 0) 1912 classFields.addNullPointer(PtrTy); 1913 else 1914 classFields.addBitCast( 1915 GenerateMethodList(className, "", InstanceMethods, false), 1916 PtrTy); 1917 // void *dtable; 1918 classFields.addNullPointer(PtrTy); 1919 // IMP cxx_construct; 1920 classFields.addNullPointer(PtrTy); 1921 // IMP cxx_destruct; 1922 classFields.addNullPointer(PtrTy); 1923 // struct objc_class *subclass_list 1924 classFields.addNullPointer(PtrTy); 1925 // struct objc_class *sibling_class 1926 classFields.addNullPointer(PtrTy); 1927 // struct objc_protocol_list *protocols; 1928 auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(), 1929 classDecl->protocol_end()); 1930 SmallVector<llvm::Constant *, 16> Protocols; 1931 for (const auto *I : RuntimeProtocols) 1932 Protocols.push_back( 1933 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I), 1934 ProtocolPtrTy)); 1935 if (Protocols.empty()) 1936 classFields.addNullPointer(PtrTy); 1937 else 1938 classFields.add(GenerateProtocolList(Protocols)); 1939 // struct reference_list *extra_data; 1940 classFields.addNullPointer(PtrTy); 1941 // long abi_version; 1942 classFields.addInt(LongTy, 0); 1943 // struct objc_property_list *properties 1944 classFields.add(GeneratePropertyList(OID, classDecl)); 1945 1946 llvm::GlobalVariable *classStruct = 1947 classFields.finishAndCreateGlobal(SymbolForClass(className), 1948 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage); 1949 1950 auto *classRefSymbol = GetClassVar(className); 1951 classRefSymbol->setSection(sectionName<ClassReferenceSection>()); 1952 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy)); 1953 1954 if (IsCOFF) { 1955 // we can't import a class struct. 1956 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) { 1957 classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1958 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1959 } 1960 1961 if (SuperClass) { 1962 std::pair<llvm::GlobalVariable*, int> v{classStruct, 1}; 1963 EarlyInitList.emplace_back(std::string(SuperClass->getName()), 1964 std::move(v)); 1965 } 1966 1967 } 1968 1969 1970 // Resolve the class aliases, if they exist. 1971 // FIXME: Class pointer aliases shouldn't exist! 1972 if (ClassPtrAlias) { 1973 ClassPtrAlias->replaceAllUsesWith( 1974 llvm::ConstantExpr::getBitCast(classStruct, IdTy)); 1975 ClassPtrAlias->eraseFromParent(); 1976 ClassPtrAlias = nullptr; 1977 } 1978 if (auto Placeholder = 1979 TheModule.getNamedGlobal(SymbolForClass(className))) 1980 if (Placeholder != classStruct) { 1981 Placeholder->replaceAllUsesWith( 1982 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType())); 1983 Placeholder->eraseFromParent(); 1984 classStruct->setName(SymbolForClass(className)); 1985 } 1986 if (MetaClassPtrAlias) { 1987 MetaClassPtrAlias->replaceAllUsesWith( 1988 llvm::ConstantExpr::getBitCast(metaclass, IdTy)); 1989 MetaClassPtrAlias->eraseFromParent(); 1990 MetaClassPtrAlias = nullptr; 1991 } 1992 assert(classStruct->getName() == SymbolForClass(className)); 1993 1994 auto classInitRef = new llvm::GlobalVariable(TheModule, 1995 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage, 1996 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className); 1997 classInitRef->setSection(sectionName<ClassSection>()); 1998 CGM.addUsedGlobal(classInitRef); 1999 2000 EmittedClass = true; 2001 } 2002 public: 2003 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) { 2004 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 2005 PtrToObjCSuperTy, SelectorTy); 2006 // struct objc_property 2007 // { 2008 // const char *name; 2009 // const char *attributes; 2010 // const char *type; 2011 // SEL getter; 2012 // SEL setter; 2013 // } 2014 PropertyMetadataTy = 2015 llvm::StructType::get(CGM.getLLVMContext(), 2016 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty }); 2017 } 2018 2019 }; 2020 2021 const char *const CGObjCGNUstep2::SectionsBaseNames[8] = 2022 { 2023 "__objc_selectors", 2024 "__objc_classes", 2025 "__objc_class_refs", 2026 "__objc_cats", 2027 "__objc_protocols", 2028 "__objc_protocol_refs", 2029 "__objc_class_aliases", 2030 "__objc_constant_string" 2031 }; 2032 2033 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] = 2034 { 2035 ".objcrt$SEL", 2036 ".objcrt$CLS", 2037 ".objcrt$CLR", 2038 ".objcrt$CAT", 2039 ".objcrt$PCL", 2040 ".objcrt$PCR", 2041 ".objcrt$CAL", 2042 ".objcrt$STR" 2043 }; 2044 2045 /// Support for the ObjFW runtime. 2046 class CGObjCObjFW: public CGObjCGNU { 2047 protected: 2048 /// The GCC ABI message lookup function. Returns an IMP pointing to the 2049 /// method implementation for this message. 2050 LazyRuntimeFunction MsgLookupFn; 2051 /// stret lookup function. While this does not seem to make sense at the 2052 /// first look, this is required to call the correct forwarding function. 2053 LazyRuntimeFunction MsgLookupFnSRet; 2054 /// The GCC ABI superclass message lookup function. Takes a pointer to a 2055 /// structure describing the receiver and the class, and a selector as 2056 /// arguments. Returns the IMP for the corresponding method. 2057 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet; 2058 2059 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 2060 llvm::Value *cmd, llvm::MDNode *node, 2061 MessageSendInfo &MSI) override { 2062 CGBuilderTy &Builder = CGF.Builder; 2063 llvm::Value *args[] = { 2064 EnforceType(Builder, Receiver, IdTy), 2065 EnforceType(Builder, cmd, SelectorTy) }; 2066 2067 llvm::CallBase *imp; 2068 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 2069 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args); 2070 else 2071 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args); 2072 2073 imp->setMetadata(msgSendMDKind, node); 2074 return imp; 2075 } 2076 2077 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 2078 llvm::Value *cmd, MessageSendInfo &MSI) override { 2079 CGBuilderTy &Builder = CGF.Builder; 2080 llvm::Value *lookupArgs[] = { 2081 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd, 2082 }; 2083 2084 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 2085 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs); 2086 else 2087 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 2088 } 2089 2090 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name, 2091 bool isWeak) override { 2092 if (isWeak) 2093 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak); 2094 2095 EmitClassRef(Name); 2096 std::string SymbolName = "_OBJC_CLASS_" + Name; 2097 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName); 2098 if (!ClassSymbol) 2099 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 2100 llvm::GlobalValue::ExternalLinkage, 2101 nullptr, SymbolName); 2102 return ClassSymbol; 2103 } 2104 2105 public: 2106 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) { 2107 // IMP objc_msg_lookup(id, SEL); 2108 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy); 2109 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy, 2110 SelectorTy); 2111 // IMP objc_msg_lookup_super(struct objc_super*, SEL); 2112 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 2113 PtrToObjCSuperTy, SelectorTy); 2114 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy, 2115 PtrToObjCSuperTy, SelectorTy); 2116 } 2117 }; 2118 } // end anonymous namespace 2119 2120 /// Emits a reference to a dummy variable which is emitted with each class. 2121 /// This ensures that a linker error will be generated when trying to link 2122 /// together modules where a referenced class is not defined. 2123 void CGObjCGNU::EmitClassRef(const std::string &className) { 2124 std::string symbolRef = "__objc_class_ref_" + className; 2125 // Don't emit two copies of the same symbol 2126 if (TheModule.getGlobalVariable(symbolRef)) 2127 return; 2128 std::string symbolName = "__objc_class_name_" + className; 2129 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName); 2130 if (!ClassSymbol) { 2131 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 2132 llvm::GlobalValue::ExternalLinkage, 2133 nullptr, symbolName); 2134 } 2135 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true, 2136 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef); 2137 } 2138 2139 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, 2140 unsigned protocolClassVersion, unsigned classABI) 2141 : CGObjCRuntime(cgm), TheModule(CGM.getModule()), 2142 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr), 2143 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion), 2144 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) { 2145 2146 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend"); 2147 usesSEHExceptions = 2148 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment(); 2149 2150 CodeGenTypes &Types = CGM.getTypes(); 2151 IntTy = cast<llvm::IntegerType>( 2152 Types.ConvertType(CGM.getContext().IntTy)); 2153 LongTy = cast<llvm::IntegerType>( 2154 Types.ConvertType(CGM.getContext().LongTy)); 2155 SizeTy = cast<llvm::IntegerType>( 2156 Types.ConvertType(CGM.getContext().getSizeType())); 2157 PtrDiffTy = cast<llvm::IntegerType>( 2158 Types.ConvertType(CGM.getContext().getPointerDiffType())); 2159 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 2160 2161 Int8Ty = llvm::Type::getInt8Ty(VMContext); 2162 // C string type. Used in lots of places. 2163 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty); 2164 ProtocolPtrTy = llvm::PointerType::getUnqual( 2165 Types.ConvertType(CGM.getContext().getObjCProtoType())); 2166 2167 Zeros[0] = llvm::ConstantInt::get(LongTy, 0); 2168 Zeros[1] = Zeros[0]; 2169 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty); 2170 // Get the selector Type. 2171 QualType selTy = CGM.getContext().getObjCSelType(); 2172 if (QualType() == selTy) { 2173 SelectorTy = PtrToInt8Ty; 2174 } else { 2175 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy)); 2176 } 2177 2178 PtrToIntTy = llvm::PointerType::getUnqual(IntTy); 2179 PtrTy = PtrToInt8Ty; 2180 2181 Int32Ty = llvm::Type::getInt32Ty(VMContext); 2182 Int64Ty = llvm::Type::getInt64Ty(VMContext); 2183 2184 IntPtrTy = 2185 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty; 2186 2187 // Object type 2188 QualType UnqualIdTy = CGM.getContext().getObjCIdType(); 2189 ASTIdTy = CanQualType(); 2190 if (UnqualIdTy != QualType()) { 2191 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy); 2192 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 2193 } else { 2194 IdTy = PtrToInt8Ty; 2195 } 2196 PtrToIdTy = llvm::PointerType::getUnqual(IdTy); 2197 ProtocolTy = llvm::StructType::get(IdTy, 2198 PtrToInt8Ty, // name 2199 PtrToInt8Ty, // protocols 2200 PtrToInt8Ty, // instance methods 2201 PtrToInt8Ty, // class methods 2202 PtrToInt8Ty, // optional instance methods 2203 PtrToInt8Ty, // optional class methods 2204 PtrToInt8Ty, // properties 2205 PtrToInt8Ty);// optional properties 2206 2207 // struct objc_property_gsv1 2208 // { 2209 // const char *name; 2210 // char attributes; 2211 // char attributes2; 2212 // char unused1; 2213 // char unused2; 2214 // const char *getter_name; 2215 // const char *getter_types; 2216 // const char *setter_name; 2217 // const char *setter_types; 2218 // } 2219 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), { 2220 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, 2221 PtrToInt8Ty, PtrToInt8Ty }); 2222 2223 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy); 2224 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy); 2225 2226 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 2227 2228 // void objc_exception_throw(id); 2229 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy); 2230 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy); 2231 // int objc_sync_enter(id); 2232 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy); 2233 // int objc_sync_exit(id); 2234 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy); 2235 2236 // void objc_enumerationMutation (id) 2237 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy); 2238 2239 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL) 2240 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy, 2241 PtrDiffTy, BoolTy); 2242 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL) 2243 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy, 2244 PtrDiffTy, IdTy, BoolTy, BoolTy); 2245 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) 2246 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy, 2247 PtrDiffTy, BoolTy, BoolTy); 2248 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) 2249 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy, 2250 PtrDiffTy, BoolTy, BoolTy); 2251 2252 // IMP type 2253 llvm::Type *IMPArgs[] = { IdTy, SelectorTy }; 2254 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs, 2255 true)); 2256 2257 const LangOptions &Opts = CGM.getLangOpts(); 2258 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount) 2259 RuntimeVersion = 10; 2260 2261 // Don't bother initialising the GC stuff unless we're compiling in GC mode 2262 if (Opts.getGC() != LangOptions::NonGC) { 2263 // This is a bit of an hack. We should sort this out by having a proper 2264 // CGObjCGNUstep subclass for GC, but we may want to really support the old 2265 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now 2266 // Get selectors needed in GC mode 2267 RetainSel = GetNullarySelector("retain", CGM.getContext()); 2268 ReleaseSel = GetNullarySelector("release", CGM.getContext()); 2269 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext()); 2270 2271 // Get functions needed in GC mode 2272 2273 // id objc_assign_ivar(id, id, ptrdiff_t); 2274 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy); 2275 // id objc_assign_strongCast (id, id*) 2276 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy, 2277 PtrToIdTy); 2278 // id objc_assign_global(id, id*); 2279 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy); 2280 // id objc_assign_weak(id, id*); 2281 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy); 2282 // id objc_read_weak(id*); 2283 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy); 2284 // void *objc_memmove_collectable(void*, void *, size_t); 2285 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy, 2286 SizeTy); 2287 } 2288 } 2289 2290 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF, 2291 const std::string &Name, bool isWeak) { 2292 llvm::Constant *ClassName = MakeConstantString(Name); 2293 // With the incompatible ABI, this will need to be replaced with a direct 2294 // reference to the class symbol. For the compatible nonfragile ABI we are 2295 // still performing this lookup at run time but emitting the symbol for the 2296 // class externally so that we can make the switch later. 2297 // 2298 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class 2299 // with memoized versions or with static references if it's safe to do so. 2300 if (!isWeak) 2301 EmitClassRef(Name); 2302 2303 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction( 2304 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class"); 2305 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName); 2306 } 2307 2308 // This has to perform the lookup every time, since posing and related 2309 // techniques can modify the name -> class mapping. 2310 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF, 2311 const ObjCInterfaceDecl *OID) { 2312 auto *Value = 2313 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported()); 2314 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) 2315 CGM.setGVProperties(ClassSymbol, OID); 2316 return Value; 2317 } 2318 2319 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { 2320 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false); 2321 if (CGM.getTriple().isOSBinFormatCOFF()) { 2322 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) { 2323 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool"); 2324 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); 2325 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 2326 2327 const VarDecl *VD = nullptr; 2328 for (const auto *Result : DC->lookup(&II)) 2329 if ((VD = dyn_cast<VarDecl>(Result))) 2330 break; 2331 2332 CGM.setGVProperties(ClassSymbol, VD); 2333 } 2334 } 2335 return Value; 2336 } 2337 2338 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel, 2339 const std::string &TypeEncoding) { 2340 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel]; 2341 llvm::GlobalAlias *SelValue = nullptr; 2342 2343 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(), 2344 e = Types.end() ; i!=e ; i++) { 2345 if (i->first == TypeEncoding) { 2346 SelValue = i->second; 2347 break; 2348 } 2349 } 2350 if (!SelValue) { 2351 SelValue = llvm::GlobalAlias::create(SelectorTy->getPointerElementType(), 0, 2352 llvm::GlobalValue::PrivateLinkage, 2353 ".objc_selector_" + Sel.getAsString(), 2354 &TheModule); 2355 Types.emplace_back(TypeEncoding, SelValue); 2356 } 2357 2358 return SelValue; 2359 } 2360 2361 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) { 2362 llvm::Value *SelValue = GetSelector(CGF, Sel); 2363 2364 // Store it to a temporary. Does this satisfy the semantics of 2365 // GetAddrOfSelector? Hopefully. 2366 Address tmp = CGF.CreateTempAlloca(SelValue->getType(), 2367 CGF.getPointerAlign()); 2368 CGF.Builder.CreateStore(SelValue, tmp); 2369 return tmp; 2370 } 2371 2372 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) { 2373 return GetTypedSelector(CGF, Sel, std::string()); 2374 } 2375 2376 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, 2377 const ObjCMethodDecl *Method) { 2378 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method); 2379 return GetTypedSelector(CGF, Method->getSelector(), SelTypes); 2380 } 2381 2382 llvm::Constant *CGObjCGNU::GetEHType(QualType T) { 2383 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) { 2384 // With the old ABI, there was only one kind of catchall, which broke 2385 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as 2386 // a pointer indicating object catchalls, and NULL to indicate real 2387 // catchalls 2388 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2389 return MakeConstantString("@id"); 2390 } else { 2391 return nullptr; 2392 } 2393 } 2394 2395 // All other types should be Objective-C interface pointer types. 2396 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>(); 2397 assert(OPT && "Invalid @catch type."); 2398 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface(); 2399 assert(IDecl && "Invalid @catch type."); 2400 return MakeConstantString(IDecl->getIdentifier()->getName()); 2401 } 2402 2403 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) { 2404 if (usesSEHExceptions) 2405 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T); 2406 2407 if (!CGM.getLangOpts().CPlusPlus) 2408 return CGObjCGNU::GetEHType(T); 2409 2410 // For Objective-C++, we want to provide the ability to catch both C++ and 2411 // Objective-C objects in the same function. 2412 2413 // There's a particular fixed type info for 'id'. 2414 if (T->isObjCIdType() || 2415 T->isObjCQualifiedIdType()) { 2416 llvm::Constant *IDEHType = 2417 CGM.getModule().getGlobalVariable("__objc_id_type_info"); 2418 if (!IDEHType) 2419 IDEHType = 2420 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty, 2421 false, 2422 llvm::GlobalValue::ExternalLinkage, 2423 nullptr, "__objc_id_type_info"); 2424 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty); 2425 } 2426 2427 const ObjCObjectPointerType *PT = 2428 T->getAs<ObjCObjectPointerType>(); 2429 assert(PT && "Invalid @catch type."); 2430 const ObjCInterfaceType *IT = PT->getInterfaceType(); 2431 assert(IT && "Invalid @catch type."); 2432 std::string className = 2433 std::string(IT->getDecl()->getIdentifier()->getName()); 2434 2435 std::string typeinfoName = "__objc_eh_typeinfo_" + className; 2436 2437 // Return the existing typeinfo if it exists 2438 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName); 2439 if (typeinfo) 2440 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty); 2441 2442 // Otherwise create it. 2443 2444 // vtable for gnustep::libobjc::__objc_class_type_info 2445 // It's quite ugly hard-coding this. Ideally we'd generate it using the host 2446 // platform's name mangling. 2447 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE"; 2448 auto *Vtable = TheModule.getGlobalVariable(vtableName); 2449 if (!Vtable) { 2450 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true, 2451 llvm::GlobalValue::ExternalLinkage, 2452 nullptr, vtableName); 2453 } 2454 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2); 2455 auto *BVtable = llvm::ConstantExpr::getBitCast( 2456 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two), 2457 PtrToInt8Ty); 2458 2459 llvm::Constant *typeName = 2460 ExportUniqueString(className, "__objc_eh_typename_"); 2461 2462 ConstantInitBuilder builder(CGM); 2463 auto fields = builder.beginStruct(); 2464 fields.add(BVtable); 2465 fields.add(typeName); 2466 llvm::Constant *TI = 2467 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className, 2468 CGM.getPointerAlign(), 2469 /*constant*/ false, 2470 llvm::GlobalValue::LinkOnceODRLinkage); 2471 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty); 2472 } 2473 2474 /// Generate an NSConstantString object. 2475 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) { 2476 2477 std::string Str = SL->getString().str(); 2478 CharUnits Align = CGM.getPointerAlign(); 2479 2480 // Look for an existing one 2481 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str); 2482 if (old != ObjCStrings.end()) 2483 return ConstantAddress(old->getValue(), Int8Ty, Align); 2484 2485 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass; 2486 2487 if (StringClass.empty()) StringClass = "NSConstantString"; 2488 2489 std::string Sym = "_OBJC_CLASS_"; 2490 Sym += StringClass; 2491 2492 llvm::Constant *isa = TheModule.getNamedGlobal(Sym); 2493 2494 if (!isa) 2495 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false, 2496 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym); 2497 else if (isa->getType() != PtrToIdTy) 2498 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy); 2499 2500 ConstantInitBuilder Builder(CGM); 2501 auto Fields = Builder.beginStruct(); 2502 Fields.add(isa); 2503 Fields.add(MakeConstantString(Str)); 2504 Fields.addInt(IntTy, Str.size()); 2505 llvm::Constant *ObjCStr = 2506 Fields.finishAndCreateGlobal(".objc_str", Align); 2507 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty); 2508 ObjCStrings[Str] = ObjCStr; 2509 ConstantStrings.push_back(ObjCStr); 2510 return ConstantAddress(ObjCStr, Int8Ty, Align); 2511 } 2512 2513 ///Generates a message send where the super is the receiver. This is a message 2514 ///send to self with special delivery semantics indicating which class's method 2515 ///should be called. 2516 RValue 2517 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF, 2518 ReturnValueSlot Return, 2519 QualType ResultType, 2520 Selector Sel, 2521 const ObjCInterfaceDecl *Class, 2522 bool isCategoryImpl, 2523 llvm::Value *Receiver, 2524 bool IsClassMessage, 2525 const CallArgList &CallArgs, 2526 const ObjCMethodDecl *Method) { 2527 CGBuilderTy &Builder = CGF.Builder; 2528 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 2529 if (Sel == RetainSel || Sel == AutoreleaseSel) { 2530 return RValue::get(EnforceType(Builder, Receiver, 2531 CGM.getTypes().ConvertType(ResultType))); 2532 } 2533 if (Sel == ReleaseSel) { 2534 return RValue::get(nullptr); 2535 } 2536 } 2537 2538 llvm::Value *cmd = GetSelector(CGF, Sel); 2539 CallArgList ActualArgs; 2540 2541 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy); 2542 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType()); 2543 ActualArgs.addFrom(CallArgs); 2544 2545 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 2546 2547 llvm::Value *ReceiverClass = nullptr; 2548 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2); 2549 if (isV2ABI) { 2550 ReceiverClass = GetClassNamed(CGF, 2551 Class->getSuperClass()->getNameAsString(), /*isWeak*/false); 2552 if (IsClassMessage) { 2553 // Load the isa pointer of the superclass is this is a class method. 2554 ReceiverClass = Builder.CreateBitCast(ReceiverClass, 2555 llvm::PointerType::getUnqual(IdTy)); 2556 ReceiverClass = 2557 Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign()); 2558 } 2559 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy); 2560 } else { 2561 if (isCategoryImpl) { 2562 llvm::FunctionCallee classLookupFunction = nullptr; 2563 if (IsClassMessage) { 2564 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 2565 IdTy, PtrTy, true), "objc_get_meta_class"); 2566 } else { 2567 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 2568 IdTy, PtrTy, true), "objc_get_class"); 2569 } 2570 ReceiverClass = Builder.CreateCall(classLookupFunction, 2571 MakeConstantString(Class->getNameAsString())); 2572 } else { 2573 // Set up global aliases for the metaclass or class pointer if they do not 2574 // already exist. These will are forward-references which will be set to 2575 // pointers to the class and metaclass structure created for the runtime 2576 // load function. To send a message to super, we look up the value of the 2577 // super_class pointer from either the class or metaclass structure. 2578 if (IsClassMessage) { 2579 if (!MetaClassPtrAlias) { 2580 MetaClassPtrAlias = llvm::GlobalAlias::create( 2581 IdTy->getPointerElementType(), 0, 2582 llvm::GlobalValue::InternalLinkage, 2583 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule); 2584 } 2585 ReceiverClass = MetaClassPtrAlias; 2586 } else { 2587 if (!ClassPtrAlias) { 2588 ClassPtrAlias = llvm::GlobalAlias::create( 2589 IdTy->getPointerElementType(), 0, 2590 llvm::GlobalValue::InternalLinkage, 2591 ".objc_class_ref" + Class->getNameAsString(), &TheModule); 2592 } 2593 ReceiverClass = ClassPtrAlias; 2594 } 2595 } 2596 // Cast the pointer to a simplified version of the class structure 2597 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy); 2598 ReceiverClass = Builder.CreateBitCast(ReceiverClass, 2599 llvm::PointerType::getUnqual(CastTy)); 2600 // Get the superclass pointer 2601 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1); 2602 // Load the superclass pointer 2603 ReceiverClass = 2604 Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign()); 2605 } 2606 // Construct the structure used to look up the IMP 2607 llvm::StructType *ObjCSuperTy = 2608 llvm::StructType::get(Receiver->getType(), IdTy); 2609 2610 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy, 2611 CGF.getPointerAlign()); 2612 2613 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0)); 2614 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1)); 2615 2616 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy); 2617 2618 // Get the IMP 2619 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI); 2620 imp = EnforceType(Builder, imp, MSI.MessengerType); 2621 2622 llvm::Metadata *impMD[] = { 2623 llvm::MDString::get(VMContext, Sel.getAsString()), 2624 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()), 2625 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 2626 llvm::Type::getInt1Ty(VMContext), IsClassMessage))}; 2627 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD); 2628 2629 CGCallee callee(CGCalleeInfo(), imp); 2630 2631 llvm::CallBase *call; 2632 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call); 2633 call->setMetadata(msgSendMDKind, node); 2634 return msgRet; 2635 } 2636 2637 /// Generate code for a message send expression. 2638 RValue 2639 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, 2640 ReturnValueSlot Return, 2641 QualType ResultType, 2642 Selector Sel, 2643 llvm::Value *Receiver, 2644 const CallArgList &CallArgs, 2645 const ObjCInterfaceDecl *Class, 2646 const ObjCMethodDecl *Method) { 2647 CGBuilderTy &Builder = CGF.Builder; 2648 2649 // Strip out message sends to retain / release in GC mode 2650 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 2651 if (Sel == RetainSel || Sel == AutoreleaseSel) { 2652 return RValue::get(EnforceType(Builder, Receiver, 2653 CGM.getTypes().ConvertType(ResultType))); 2654 } 2655 if (Sel == ReleaseSel) { 2656 return RValue::get(nullptr); 2657 } 2658 } 2659 2660 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 2661 llvm::Value *cmd; 2662 if (Method) 2663 cmd = GetSelector(CGF, Method); 2664 else 2665 cmd = GetSelector(CGF, Sel); 2666 cmd = EnforceType(Builder, cmd, SelectorTy); 2667 Receiver = EnforceType(Builder, Receiver, IdTy); 2668 2669 llvm::Metadata *impMD[] = { 2670 llvm::MDString::get(VMContext, Sel.getAsString()), 2671 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""), 2672 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 2673 llvm::Type::getInt1Ty(VMContext), Class != nullptr))}; 2674 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD); 2675 2676 CallArgList ActualArgs; 2677 ActualArgs.add(RValue::get(Receiver), ASTIdTy); 2678 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType()); 2679 ActualArgs.addFrom(CallArgs); 2680 2681 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 2682 2683 // Message sends are expected to return a zero value when the 2684 // receiver is nil. At one point, this was only guaranteed for 2685 // simple integer and pointer types, but expectations have grown 2686 // over time. 2687 // 2688 // Given a nil receiver, the GNU runtime's message lookup will 2689 // return a stub function that simply sets various return-value 2690 // registers to zero and then returns. That's good enough for us 2691 // if and only if (1) the calling conventions of that stub are 2692 // compatible with the signature we're using and (2) the registers 2693 // it sets are sufficient to produce a zero value of the return type. 2694 // Rather than doing a whole target-specific analysis, we assume it 2695 // only works for void, integer, and pointer types, and in all 2696 // other cases we do an explicit nil check is emitted code. In 2697 // addition to ensuring we produe a zero value for other types, this 2698 // sidesteps the few outright CC incompatibilities we know about that 2699 // could otherwise lead to crashes, like when a method is expected to 2700 // return on the x87 floating point stack or adjust the stack pointer 2701 // because of an indirect return. 2702 bool hasParamDestroyedInCallee = false; 2703 bool requiresExplicitZeroResult = false; 2704 bool requiresNilReceiverCheck = [&] { 2705 // We never need a check if we statically know the receiver isn't nil. 2706 if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false, 2707 Class, Receiver)) 2708 return false; 2709 2710 // If there's a consumed argument, we need a nil check. 2711 if (Method && Method->hasParamDestroyedInCallee()) { 2712 hasParamDestroyedInCallee = true; 2713 } 2714 2715 // If the return value isn't flagged as unused, and the result 2716 // type isn't in our narrow set where we assume compatibility, 2717 // we need a nil check to ensure a nil value. 2718 if (!Return.isUnused()) { 2719 if (ResultType->isVoidType()) { 2720 // void results are definitely okay. 2721 } else if (ResultType->hasPointerRepresentation() && 2722 CGM.getTypes().isZeroInitializable(ResultType)) { 2723 // Pointer types should be fine as long as they have 2724 // bitwise-zero null pointers. But do we need to worry 2725 // about unusual address spaces? 2726 } else if (ResultType->isIntegralOrEnumerationType()) { 2727 // Bitwise zero should always be zero for integral types. 2728 // FIXME: we probably need a size limit here, but we've 2729 // never imposed one before 2730 } else { 2731 // Otherwise, use an explicit check just to be sure. 2732 requiresExplicitZeroResult = true; 2733 } 2734 } 2735 2736 return hasParamDestroyedInCallee || requiresExplicitZeroResult; 2737 }(); 2738 2739 // We will need to explicitly zero-initialize an aggregate result slot 2740 // if we generally require explicit zeroing and we have an aggregate 2741 // result. 2742 bool requiresExplicitAggZeroing = 2743 requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType); 2744 2745 // The block we're going to end up in after any message send or nil path. 2746 llvm::BasicBlock *continueBB = nullptr; 2747 // The block that eventually branched to continueBB along the nil path. 2748 llvm::BasicBlock *nilPathBB = nullptr; 2749 // The block to do explicit work in along the nil path, if necessary. 2750 llvm::BasicBlock *nilCleanupBB = nullptr; 2751 2752 // Emit the nil-receiver check. 2753 if (requiresNilReceiverCheck) { 2754 llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend"); 2755 continueBB = CGF.createBasicBlock("continue"); 2756 2757 // If we need to zero-initialize an aggregate result or destroy 2758 // consumed arguments, we'll need a separate cleanup block. 2759 // Otherwise we can just branch directly to the continuation block. 2760 if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) { 2761 nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup"); 2762 } else { 2763 nilPathBB = Builder.GetInsertBlock(); 2764 } 2765 2766 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 2767 llvm::Constant::getNullValue(Receiver->getType())); 2768 Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB, 2769 messageBB); 2770 CGF.EmitBlock(messageBB); 2771 } 2772 2773 // Get the IMP to call 2774 llvm::Value *imp; 2775 2776 // If we have non-legacy dispatch specified, we try using the objc_msgSend() 2777 // functions. These are not supported on all platforms (or all runtimes on a 2778 // given platform), so we 2779 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { 2780 case CodeGenOptions::Legacy: 2781 imp = LookupIMP(CGF, Receiver, cmd, node, MSI); 2782 break; 2783 case CodeGenOptions::Mixed: 2784 case CodeGenOptions::NonLegacy: 2785 if (CGM.ReturnTypeUsesFPRet(ResultType)) { 2786 imp = 2787 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 2788 "objc_msgSend_fpret") 2789 .getCallee(); 2790 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) { 2791 // The actual types here don't matter - we're going to bitcast the 2792 // function anyway 2793 imp = 2794 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 2795 "objc_msgSend_stret") 2796 .getCallee(); 2797 } else { 2798 imp = CGM.CreateRuntimeFunction( 2799 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend") 2800 .getCallee(); 2801 } 2802 } 2803 2804 // Reset the receiver in case the lookup modified it 2805 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy); 2806 2807 imp = EnforceType(Builder, imp, MSI.MessengerType); 2808 2809 llvm::CallBase *call; 2810 CGCallee callee(CGCalleeInfo(), imp); 2811 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call); 2812 call->setMetadata(msgSendMDKind, node); 2813 2814 if (requiresNilReceiverCheck) { 2815 llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock(); 2816 CGF.Builder.CreateBr(continueBB); 2817 2818 // Emit the nil path if we decided it was necessary above. 2819 if (nilCleanupBB) { 2820 CGF.EmitBlock(nilCleanupBB); 2821 2822 if (hasParamDestroyedInCallee) { 2823 destroyCalleeDestroyedArguments(CGF, Method, CallArgs); 2824 } 2825 2826 if (requiresExplicitAggZeroing) { 2827 assert(msgRet.isAggregate()); 2828 Address addr = msgRet.getAggregateAddress(); 2829 CGF.EmitNullInitialization(addr, ResultType); 2830 } 2831 2832 nilPathBB = CGF.Builder.GetInsertBlock(); 2833 CGF.Builder.CreateBr(continueBB); 2834 } 2835 2836 // Enter the continuation block and emit a phi if required. 2837 CGF.EmitBlock(continueBB); 2838 if (msgRet.isScalar()) { 2839 llvm::Value *v = msgRet.getScalarVal(); 2840 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2); 2841 phi->addIncoming(v, nonNilPathBB); 2842 phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB); 2843 msgRet = RValue::get(phi); 2844 } else if (msgRet.isAggregate()) { 2845 // Aggregate zeroing is handled in nilCleanupBB when it's required. 2846 } else /* isComplex() */ { 2847 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal(); 2848 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2); 2849 phi->addIncoming(v.first, nonNilPathBB); 2850 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()), 2851 nilPathBB); 2852 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2); 2853 phi2->addIncoming(v.second, nonNilPathBB); 2854 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()), 2855 nilPathBB); 2856 msgRet = RValue::getComplex(phi, phi2); 2857 } 2858 } 2859 return msgRet; 2860 } 2861 2862 /// Generates a MethodList. Used in construction of a objc_class and 2863 /// objc_category structures. 2864 llvm::Constant *CGObjCGNU:: 2865 GenerateMethodList(StringRef ClassName, 2866 StringRef CategoryName, 2867 ArrayRef<const ObjCMethodDecl*> Methods, 2868 bool isClassMethodList) { 2869 if (Methods.empty()) 2870 return NULLPtr; 2871 2872 ConstantInitBuilder Builder(CGM); 2873 2874 auto MethodList = Builder.beginStruct(); 2875 MethodList.addNullPointer(CGM.Int8PtrTy); 2876 MethodList.addInt(Int32Ty, Methods.size()); 2877 2878 // Get the method structure type. 2879 llvm::StructType *ObjCMethodTy = 2880 llvm::StructType::get(CGM.getLLVMContext(), { 2881 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 2882 PtrToInt8Ty, // Method types 2883 IMPTy // Method pointer 2884 }); 2885 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2); 2886 if (isV2ABI) { 2887 // size_t size; 2888 llvm::DataLayout td(&TheModule); 2889 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) / 2890 CGM.getContext().getCharWidth()); 2891 ObjCMethodTy = 2892 llvm::StructType::get(CGM.getLLVMContext(), { 2893 IMPTy, // Method pointer 2894 PtrToInt8Ty, // Selector 2895 PtrToInt8Ty // Extended type encoding 2896 }); 2897 } else { 2898 ObjCMethodTy = 2899 llvm::StructType::get(CGM.getLLVMContext(), { 2900 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 2901 PtrToInt8Ty, // Method types 2902 IMPTy // Method pointer 2903 }); 2904 } 2905 auto MethodArray = MethodList.beginArray(); 2906 ASTContext &Context = CGM.getContext(); 2907 for (const auto *OMD : Methods) { 2908 llvm::Constant *FnPtr = 2909 TheModule.getFunction(getSymbolNameForMethod(OMD)); 2910 assert(FnPtr && "Can't generate metadata for method that doesn't exist"); 2911 auto Method = MethodArray.beginStruct(ObjCMethodTy); 2912 if (isV2ABI) { 2913 Method.addBitCast(FnPtr, IMPTy); 2914 Method.add(GetConstantSelector(OMD->getSelector(), 2915 Context.getObjCEncodingForMethodDecl(OMD))); 2916 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true))); 2917 } else { 2918 Method.add(MakeConstantString(OMD->getSelector().getAsString())); 2919 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD))); 2920 Method.addBitCast(FnPtr, IMPTy); 2921 } 2922 Method.finishAndAddTo(MethodArray); 2923 } 2924 MethodArray.finishAndAddTo(MethodList); 2925 2926 // Create an instance of the structure 2927 return MethodList.finishAndCreateGlobal(".objc_method_list", 2928 CGM.getPointerAlign()); 2929 } 2930 2931 /// Generates an IvarList. Used in construction of a objc_class. 2932 llvm::Constant *CGObjCGNU:: 2933 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 2934 ArrayRef<llvm::Constant *> IvarTypes, 2935 ArrayRef<llvm::Constant *> IvarOffsets, 2936 ArrayRef<llvm::Constant *> IvarAlign, 2937 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) { 2938 if (IvarNames.empty()) 2939 return NULLPtr; 2940 2941 ConstantInitBuilder Builder(CGM); 2942 2943 // Structure containing array count followed by array. 2944 auto IvarList = Builder.beginStruct(); 2945 IvarList.addInt(IntTy, (int)IvarNames.size()); 2946 2947 // Get the ivar structure type. 2948 llvm::StructType *ObjCIvarTy = 2949 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy); 2950 2951 // Array of ivar structures. 2952 auto Ivars = IvarList.beginArray(ObjCIvarTy); 2953 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) { 2954 auto Ivar = Ivars.beginStruct(ObjCIvarTy); 2955 Ivar.add(IvarNames[i]); 2956 Ivar.add(IvarTypes[i]); 2957 Ivar.add(IvarOffsets[i]); 2958 Ivar.finishAndAddTo(Ivars); 2959 } 2960 Ivars.finishAndAddTo(IvarList); 2961 2962 // Create an instance of the structure 2963 return IvarList.finishAndCreateGlobal(".objc_ivar_list", 2964 CGM.getPointerAlign()); 2965 } 2966 2967 /// Generate a class structure 2968 llvm::Constant *CGObjCGNU::GenerateClassStructure( 2969 llvm::Constant *MetaClass, 2970 llvm::Constant *SuperClass, 2971 unsigned info, 2972 const char *Name, 2973 llvm::Constant *Version, 2974 llvm::Constant *InstanceSize, 2975 llvm::Constant *IVars, 2976 llvm::Constant *Methods, 2977 llvm::Constant *Protocols, 2978 llvm::Constant *IvarOffsets, 2979 llvm::Constant *Properties, 2980 llvm::Constant *StrongIvarBitmap, 2981 llvm::Constant *WeakIvarBitmap, 2982 bool isMeta) { 2983 // Set up the class structure 2984 // Note: Several of these are char*s when they should be ids. This is 2985 // because the runtime performs this translation on load. 2986 // 2987 // Fields marked New ABI are part of the GNUstep runtime. We emit them 2988 // anyway; the classes will still work with the GNU runtime, they will just 2989 // be ignored. 2990 llvm::StructType *ClassTy = llvm::StructType::get( 2991 PtrToInt8Ty, // isa 2992 PtrToInt8Ty, // super_class 2993 PtrToInt8Ty, // name 2994 LongTy, // version 2995 LongTy, // info 2996 LongTy, // instance_size 2997 IVars->getType(), // ivars 2998 Methods->getType(), // methods 2999 // These are all filled in by the runtime, so we pretend 3000 PtrTy, // dtable 3001 PtrTy, // subclass_list 3002 PtrTy, // sibling_class 3003 PtrTy, // protocols 3004 PtrTy, // gc_object_type 3005 // New ABI: 3006 LongTy, // abi_version 3007 IvarOffsets->getType(), // ivar_offsets 3008 Properties->getType(), // properties 3009 IntPtrTy, // strong_pointers 3010 IntPtrTy // weak_pointers 3011 ); 3012 3013 ConstantInitBuilder Builder(CGM); 3014 auto Elements = Builder.beginStruct(ClassTy); 3015 3016 // Fill in the structure 3017 3018 // isa 3019 Elements.addBitCast(MetaClass, PtrToInt8Ty); 3020 // super_class 3021 Elements.add(SuperClass); 3022 // name 3023 Elements.add(MakeConstantString(Name, ".class_name")); 3024 // version 3025 Elements.addInt(LongTy, 0); 3026 // info 3027 Elements.addInt(LongTy, info); 3028 // instance_size 3029 if (isMeta) { 3030 llvm::DataLayout td(&TheModule); 3031 Elements.addInt(LongTy, 3032 td.getTypeSizeInBits(ClassTy) / 3033 CGM.getContext().getCharWidth()); 3034 } else 3035 Elements.add(InstanceSize); 3036 // ivars 3037 Elements.add(IVars); 3038 // methods 3039 Elements.add(Methods); 3040 // These are all filled in by the runtime, so we pretend 3041 // dtable 3042 Elements.add(NULLPtr); 3043 // subclass_list 3044 Elements.add(NULLPtr); 3045 // sibling_class 3046 Elements.add(NULLPtr); 3047 // protocols 3048 Elements.addBitCast(Protocols, PtrTy); 3049 // gc_object_type 3050 Elements.add(NULLPtr); 3051 // abi_version 3052 Elements.addInt(LongTy, ClassABIVersion); 3053 // ivar_offsets 3054 Elements.add(IvarOffsets); 3055 // properties 3056 Elements.add(Properties); 3057 // strong_pointers 3058 Elements.add(StrongIvarBitmap); 3059 // weak_pointers 3060 Elements.add(WeakIvarBitmap); 3061 // Create an instance of the structure 3062 // This is now an externally visible symbol, so that we can speed up class 3063 // messages in the next ABI. We may already have some weak references to 3064 // this, so check and fix them properly. 3065 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") + 3066 std::string(Name)); 3067 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym); 3068 llvm::Constant *Class = 3069 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false, 3070 llvm::GlobalValue::ExternalLinkage); 3071 if (ClassRef) { 3072 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class, 3073 ClassRef->getType())); 3074 ClassRef->removeFromParent(); 3075 Class->setName(ClassSym); 3076 } 3077 return Class; 3078 } 3079 3080 llvm::Constant *CGObjCGNU:: 3081 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) { 3082 // Get the method structure type. 3083 llvm::StructType *ObjCMethodDescTy = 3084 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty }); 3085 ASTContext &Context = CGM.getContext(); 3086 ConstantInitBuilder Builder(CGM); 3087 auto MethodList = Builder.beginStruct(); 3088 MethodList.addInt(IntTy, Methods.size()); 3089 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy); 3090 for (auto *M : Methods) { 3091 auto Method = MethodArray.beginStruct(ObjCMethodDescTy); 3092 Method.add(MakeConstantString(M->getSelector().getAsString())); 3093 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M))); 3094 Method.finishAndAddTo(MethodArray); 3095 } 3096 MethodArray.finishAndAddTo(MethodList); 3097 return MethodList.finishAndCreateGlobal(".objc_method_list", 3098 CGM.getPointerAlign()); 3099 } 3100 3101 // Create the protocol list structure used in classes, categories and so on 3102 llvm::Constant * 3103 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) { 3104 3105 ConstantInitBuilder Builder(CGM); 3106 auto ProtocolList = Builder.beginStruct(); 3107 ProtocolList.add(NULLPtr); 3108 ProtocolList.addInt(LongTy, Protocols.size()); 3109 3110 auto Elements = ProtocolList.beginArray(PtrToInt8Ty); 3111 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); 3112 iter != endIter ; iter++) { 3113 llvm::Constant *protocol = nullptr; 3114 llvm::StringMap<llvm::Constant*>::iterator value = 3115 ExistingProtocols.find(*iter); 3116 if (value == ExistingProtocols.end()) { 3117 protocol = GenerateEmptyProtocol(*iter); 3118 } else { 3119 protocol = value->getValue(); 3120 } 3121 Elements.addBitCast(protocol, PtrToInt8Ty); 3122 } 3123 Elements.finishAndAddTo(ProtocolList); 3124 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list", 3125 CGM.getPointerAlign()); 3126 } 3127 3128 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF, 3129 const ObjCProtocolDecl *PD) { 3130 auto protocol = GenerateProtocolRef(PD); 3131 llvm::Type *T = 3132 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); 3133 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); 3134 } 3135 3136 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) { 3137 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()]; 3138 if (!protocol) 3139 GenerateProtocol(PD); 3140 assert(protocol && "Unknown protocol"); 3141 return protocol; 3142 } 3143 3144 llvm::Constant * 3145 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) { 3146 llvm::Constant *ProtocolList = GenerateProtocolList({}); 3147 llvm::Constant *MethodList = GenerateProtocolMethodList({}); 3148 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty); 3149 // Protocols are objects containing lists of the methods implemented and 3150 // protocols adopted. 3151 ConstantInitBuilder Builder(CGM); 3152 auto Elements = Builder.beginStruct(); 3153 3154 // The isa pointer must be set to a magic number so the runtime knows it's 3155 // the correct layout. 3156 Elements.add(llvm::ConstantExpr::getIntToPtr( 3157 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy)); 3158 3159 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name")); 3160 Elements.add(ProtocolList); /* .protocol_list */ 3161 Elements.add(MethodList); /* .instance_methods */ 3162 Elements.add(MethodList); /* .class_methods */ 3163 Elements.add(MethodList); /* .optional_instance_methods */ 3164 Elements.add(MethodList); /* .optional_class_methods */ 3165 Elements.add(NULLPtr); /* .properties */ 3166 Elements.add(NULLPtr); /* .optional_properties */ 3167 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName), 3168 CGM.getPointerAlign()); 3169 } 3170 3171 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { 3172 if (PD->isNonRuntimeProtocol()) 3173 return; 3174 3175 std::string ProtocolName = PD->getNameAsString(); 3176 3177 // Use the protocol definition, if there is one. 3178 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 3179 PD = Def; 3180 3181 SmallVector<std::string, 16> Protocols; 3182 for (const auto *PI : PD->protocols()) 3183 Protocols.push_back(PI->getNameAsString()); 3184 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods; 3185 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods; 3186 for (const auto *I : PD->instance_methods()) 3187 if (I->isOptional()) 3188 OptionalInstanceMethods.push_back(I); 3189 else 3190 InstanceMethods.push_back(I); 3191 // Collect information about class methods: 3192 SmallVector<const ObjCMethodDecl*, 16> ClassMethods; 3193 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods; 3194 for (const auto *I : PD->class_methods()) 3195 if (I->isOptional()) 3196 OptionalClassMethods.push_back(I); 3197 else 3198 ClassMethods.push_back(I); 3199 3200 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 3201 llvm::Constant *InstanceMethodList = 3202 GenerateProtocolMethodList(InstanceMethods); 3203 llvm::Constant *ClassMethodList = 3204 GenerateProtocolMethodList(ClassMethods); 3205 llvm::Constant *OptionalInstanceMethodList = 3206 GenerateProtocolMethodList(OptionalInstanceMethods); 3207 llvm::Constant *OptionalClassMethodList = 3208 GenerateProtocolMethodList(OptionalClassMethods); 3209 3210 // Property metadata: name, attributes, isSynthesized, setter name, setter 3211 // types, getter name, getter types. 3212 // The isSynthesized value is always set to 0 in a protocol. It exists to 3213 // simplify the runtime library by allowing it to use the same data 3214 // structures for protocol metadata everywhere. 3215 3216 llvm::Constant *PropertyList = 3217 GeneratePropertyList(nullptr, PD, false, false); 3218 llvm::Constant *OptionalPropertyList = 3219 GeneratePropertyList(nullptr, PD, false, true); 3220 3221 // Protocols are objects containing lists of the methods implemented and 3222 // protocols adopted. 3223 // The isa pointer must be set to a magic number so the runtime knows it's 3224 // the correct layout. 3225 ConstantInitBuilder Builder(CGM); 3226 auto Elements = Builder.beginStruct(); 3227 Elements.add( 3228 llvm::ConstantExpr::getIntToPtr( 3229 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy)); 3230 Elements.add(MakeConstantString(ProtocolName)); 3231 Elements.add(ProtocolList); 3232 Elements.add(InstanceMethodList); 3233 Elements.add(ClassMethodList); 3234 Elements.add(OptionalInstanceMethodList); 3235 Elements.add(OptionalClassMethodList); 3236 Elements.add(PropertyList); 3237 Elements.add(OptionalPropertyList); 3238 ExistingProtocols[ProtocolName] = 3239 llvm::ConstantExpr::getBitCast( 3240 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()), 3241 IdTy); 3242 } 3243 void CGObjCGNU::GenerateProtocolHolderCategory() { 3244 // Collect information about instance methods 3245 3246 ConstantInitBuilder Builder(CGM); 3247 auto Elements = Builder.beginStruct(); 3248 3249 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack"; 3250 const std::string CategoryName = "AnotherHack"; 3251 Elements.add(MakeConstantString(CategoryName)); 3252 Elements.add(MakeConstantString(ClassName)); 3253 // Instance method list 3254 Elements.addBitCast(GenerateMethodList( 3255 ClassName, CategoryName, {}, false), PtrTy); 3256 // Class method list 3257 Elements.addBitCast(GenerateMethodList( 3258 ClassName, CategoryName, {}, true), PtrTy); 3259 3260 // Protocol list 3261 ConstantInitBuilder ProtocolListBuilder(CGM); 3262 auto ProtocolList = ProtocolListBuilder.beginStruct(); 3263 ProtocolList.add(NULLPtr); 3264 ProtocolList.addInt(LongTy, ExistingProtocols.size()); 3265 auto ProtocolElements = ProtocolList.beginArray(PtrTy); 3266 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end(); 3267 iter != endIter ; iter++) { 3268 ProtocolElements.addBitCast(iter->getValue(), PtrTy); 3269 } 3270 ProtocolElements.finishAndAddTo(ProtocolList); 3271 Elements.addBitCast( 3272 ProtocolList.finishAndCreateGlobal(".objc_protocol_list", 3273 CGM.getPointerAlign()), 3274 PtrTy); 3275 Categories.push_back(llvm::ConstantExpr::getBitCast( 3276 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()), 3277 PtrTy)); 3278 } 3279 3280 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are 3281 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 3282 /// bits set to their values, LSB first, while larger ones are stored in a 3283 /// structure of this / form: 3284 /// 3285 /// struct { int32_t length; int32_t values[length]; }; 3286 /// 3287 /// The values in the array are stored in host-endian format, with the least 3288 /// significant bit being assumed to come first in the bitfield. Therefore, a 3289 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a 3290 /// bitfield / with the 63rd bit set will be 1<<64. 3291 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) { 3292 int bitCount = bits.size(); 3293 int ptrBits = CGM.getDataLayout().getPointerSizeInBits(); 3294 if (bitCount < ptrBits) { 3295 uint64_t val = 1; 3296 for (int i=0 ; i<bitCount ; ++i) { 3297 if (bits[i]) val |= 1ULL<<(i+1); 3298 } 3299 return llvm::ConstantInt::get(IntPtrTy, val); 3300 } 3301 SmallVector<llvm::Constant *, 8> values; 3302 int v=0; 3303 while (v < bitCount) { 3304 int32_t word = 0; 3305 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) { 3306 if (bits[v]) word |= 1<<i; 3307 v++; 3308 } 3309 values.push_back(llvm::ConstantInt::get(Int32Ty, word)); 3310 } 3311 3312 ConstantInitBuilder builder(CGM); 3313 auto fields = builder.beginStruct(); 3314 fields.addInt(Int32Ty, values.size()); 3315 auto array = fields.beginArray(); 3316 for (auto v : values) array.add(v); 3317 array.finishAndAddTo(fields); 3318 3319 llvm::Constant *GS = 3320 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4)); 3321 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy); 3322 return ptr; 3323 } 3324 3325 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const 3326 ObjCCategoryDecl *OCD) { 3327 const auto &RefPro = OCD->getReferencedProtocols(); 3328 const auto RuntimeProtos = 3329 GetRuntimeProtocolList(RefPro.begin(), RefPro.end()); 3330 SmallVector<std::string, 16> Protocols; 3331 for (const auto *PD : RuntimeProtos) 3332 Protocols.push_back(PD->getNameAsString()); 3333 return GenerateProtocolList(Protocols); 3334 } 3335 3336 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 3337 const ObjCInterfaceDecl *Class = OCD->getClassInterface(); 3338 std::string ClassName = Class->getNameAsString(); 3339 std::string CategoryName = OCD->getNameAsString(); 3340 3341 // Collect the names of referenced protocols 3342 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl(); 3343 3344 ConstantInitBuilder Builder(CGM); 3345 auto Elements = Builder.beginStruct(); 3346 Elements.add(MakeConstantString(CategoryName)); 3347 Elements.add(MakeConstantString(ClassName)); 3348 // Instance method list 3349 SmallVector<ObjCMethodDecl*, 16> InstanceMethods; 3350 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(), 3351 OCD->instmeth_end()); 3352 Elements.addBitCast( 3353 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false), 3354 PtrTy); 3355 // Class method list 3356 3357 SmallVector<ObjCMethodDecl*, 16> ClassMethods; 3358 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(), 3359 OCD->classmeth_end()); 3360 Elements.addBitCast( 3361 GenerateMethodList(ClassName, CategoryName, ClassMethods, true), 3362 PtrTy); 3363 // Protocol list 3364 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy); 3365 if (isRuntime(ObjCRuntime::GNUstep, 2)) { 3366 const ObjCCategoryDecl *Category = 3367 Class->FindCategoryDeclaration(OCD->getIdentifier()); 3368 if (Category) { 3369 // Instance properties 3370 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy); 3371 // Class properties 3372 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy); 3373 } else { 3374 Elements.addNullPointer(PtrTy); 3375 Elements.addNullPointer(PtrTy); 3376 } 3377 } 3378 3379 Categories.push_back(llvm::ConstantExpr::getBitCast( 3380 Elements.finishAndCreateGlobal( 3381 std::string(".objc_category_")+ClassName+CategoryName, 3382 CGM.getPointerAlign()), 3383 PtrTy)); 3384 } 3385 3386 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container, 3387 const ObjCContainerDecl *OCD, 3388 bool isClassProperty, 3389 bool protocolOptionalProperties) { 3390 3391 SmallVector<const ObjCPropertyDecl *, 16> Properties; 3392 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet; 3393 bool isProtocol = isa<ObjCProtocolDecl>(OCD); 3394 ASTContext &Context = CGM.getContext(); 3395 3396 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties 3397 = [&](const ObjCProtocolDecl *Proto) { 3398 for (const auto *P : Proto->protocols()) 3399 collectProtocolProperties(P); 3400 for (const auto *PD : Proto->properties()) { 3401 if (isClassProperty != PD->isClassProperty()) 3402 continue; 3403 // Skip any properties that are declared in protocols that this class 3404 // conforms to but are not actually implemented by this class. 3405 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container)) 3406 continue; 3407 if (!PropertySet.insert(PD->getIdentifier()).second) 3408 continue; 3409 Properties.push_back(PD); 3410 } 3411 }; 3412 3413 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) 3414 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions()) 3415 for (auto *PD : ClassExt->properties()) { 3416 if (isClassProperty != PD->isClassProperty()) 3417 continue; 3418 PropertySet.insert(PD->getIdentifier()); 3419 Properties.push_back(PD); 3420 } 3421 3422 for (const auto *PD : OCD->properties()) { 3423 if (isClassProperty != PD->isClassProperty()) 3424 continue; 3425 // If we're generating a list for a protocol, skip optional / required ones 3426 // when generating the other list. 3427 if (isProtocol && (protocolOptionalProperties != PD->isOptional())) 3428 continue; 3429 // Don't emit duplicate metadata for properties that were already in a 3430 // class extension. 3431 if (!PropertySet.insert(PD->getIdentifier()).second) 3432 continue; 3433 3434 Properties.push_back(PD); 3435 } 3436 3437 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) 3438 for (const auto *P : OID->all_referenced_protocols()) 3439 collectProtocolProperties(P); 3440 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) 3441 for (const auto *P : CD->protocols()) 3442 collectProtocolProperties(P); 3443 3444 auto numProperties = Properties.size(); 3445 3446 if (numProperties == 0) 3447 return NULLPtr; 3448 3449 ConstantInitBuilder builder(CGM); 3450 auto propertyList = builder.beginStruct(); 3451 auto properties = PushPropertyListHeader(propertyList, numProperties); 3452 3453 // Add all of the property methods need adding to the method list and to the 3454 // property metadata list. 3455 for (auto *property : Properties) { 3456 bool isSynthesized = false; 3457 bool isDynamic = false; 3458 if (!isProtocol) { 3459 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container); 3460 if (propertyImpl) { 3461 isSynthesized = (propertyImpl->getPropertyImplementation() == 3462 ObjCPropertyImplDecl::Synthesize); 3463 isDynamic = (propertyImpl->getPropertyImplementation() == 3464 ObjCPropertyImplDecl::Dynamic); 3465 } 3466 } 3467 PushProperty(properties, property, Container, isSynthesized, isDynamic); 3468 } 3469 properties.finishAndAddTo(propertyList); 3470 3471 return propertyList.finishAndCreateGlobal(".objc_property_list", 3472 CGM.getPointerAlign()); 3473 } 3474 3475 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) { 3476 // Get the class declaration for which the alias is specified. 3477 ObjCInterfaceDecl *ClassDecl = 3478 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface()); 3479 ClassAliases.emplace_back(ClassDecl->getNameAsString(), 3480 OAD->getNameAsString()); 3481 } 3482 3483 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { 3484 ASTContext &Context = CGM.getContext(); 3485 3486 // Get the superclass name. 3487 const ObjCInterfaceDecl * SuperClassDecl = 3488 OID->getClassInterface()->getSuperClass(); 3489 std::string SuperClassName; 3490 if (SuperClassDecl) { 3491 SuperClassName = SuperClassDecl->getNameAsString(); 3492 EmitClassRef(SuperClassName); 3493 } 3494 3495 // Get the class name 3496 ObjCInterfaceDecl *ClassDecl = 3497 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 3498 std::string ClassName = ClassDecl->getNameAsString(); 3499 3500 // Emit the symbol that is used to generate linker errors if this class is 3501 // referenced in other modules but not declared. 3502 std::string classSymbolName = "__objc_class_name_" + ClassName; 3503 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) { 3504 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0)); 3505 } else { 3506 new llvm::GlobalVariable(TheModule, LongTy, false, 3507 llvm::GlobalValue::ExternalLinkage, 3508 llvm::ConstantInt::get(LongTy, 0), 3509 classSymbolName); 3510 } 3511 3512 // Get the size of instances. 3513 int instanceSize = 3514 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity(); 3515 3516 // Collect information about instance variables. 3517 SmallVector<llvm::Constant*, 16> IvarNames; 3518 SmallVector<llvm::Constant*, 16> IvarTypes; 3519 SmallVector<llvm::Constant*, 16> IvarOffsets; 3520 SmallVector<llvm::Constant*, 16> IvarAligns; 3521 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership; 3522 3523 ConstantInitBuilder IvarOffsetBuilder(CGM); 3524 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy); 3525 SmallVector<bool, 16> WeakIvars; 3526 SmallVector<bool, 16> StrongIvars; 3527 3528 int superInstanceSize = !SuperClassDecl ? 0 : 3529 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity(); 3530 // For non-fragile ivars, set the instance size to 0 - {the size of just this 3531 // class}. The runtime will then set this to the correct value on load. 3532 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 3533 instanceSize = 0 - (instanceSize - superInstanceSize); 3534 } 3535 3536 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD; 3537 IVD = IVD->getNextIvar()) { 3538 // Store the name 3539 IvarNames.push_back(MakeConstantString(IVD->getNameAsString())); 3540 // Get the type encoding for this ivar 3541 std::string TypeStr; 3542 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD); 3543 IvarTypes.push_back(MakeConstantString(TypeStr)); 3544 IvarAligns.push_back(llvm::ConstantInt::get(IntTy, 3545 Context.getTypeSize(IVD->getType()))); 3546 // Get the offset 3547 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD); 3548 uint64_t Offset = BaseOffset; 3549 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 3550 Offset = BaseOffset - superInstanceSize; 3551 } 3552 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset); 3553 // Create the direct offset value 3554 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." + 3555 IVD->getNameAsString(); 3556 3557 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName); 3558 if (OffsetVar) { 3559 OffsetVar->setInitializer(OffsetValue); 3560 // If this is the real definition, change its linkage type so that 3561 // different modules will use this one, rather than their private 3562 // copy. 3563 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage); 3564 } else 3565 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty, 3566 false, llvm::GlobalValue::ExternalLinkage, 3567 OffsetValue, OffsetName); 3568 IvarOffsets.push_back(OffsetValue); 3569 IvarOffsetValues.add(OffsetVar); 3570 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime(); 3571 IvarOwnership.push_back(lt); 3572 switch (lt) { 3573 case Qualifiers::OCL_Strong: 3574 StrongIvars.push_back(true); 3575 WeakIvars.push_back(false); 3576 break; 3577 case Qualifiers::OCL_Weak: 3578 StrongIvars.push_back(false); 3579 WeakIvars.push_back(true); 3580 break; 3581 default: 3582 StrongIvars.push_back(false); 3583 WeakIvars.push_back(false); 3584 } 3585 } 3586 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars); 3587 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars); 3588 llvm::GlobalVariable *IvarOffsetArray = 3589 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets", 3590 CGM.getPointerAlign()); 3591 3592 // Collect information about instance methods 3593 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods; 3594 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(), 3595 OID->instmeth_end()); 3596 3597 SmallVector<const ObjCMethodDecl*, 16> ClassMethods; 3598 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(), 3599 OID->classmeth_end()); 3600 3601 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl); 3602 3603 // Collect the names of referenced protocols 3604 auto RefProtocols = ClassDecl->protocols(); 3605 auto RuntimeProtocols = 3606 GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end()); 3607 SmallVector<std::string, 16> Protocols; 3608 for (const auto *I : RuntimeProtocols) 3609 Protocols.push_back(I->getNameAsString()); 3610 3611 // Get the superclass pointer. 3612 llvm::Constant *SuperClass; 3613 if (!SuperClassName.empty()) { 3614 SuperClass = MakeConstantString(SuperClassName, ".super_class_name"); 3615 } else { 3616 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty); 3617 } 3618 // Empty vector used to construct empty method lists 3619 SmallVector<llvm::Constant*, 1> empty; 3620 // Generate the method and instance variable lists 3621 llvm::Constant *MethodList = GenerateMethodList(ClassName, "", 3622 InstanceMethods, false); 3623 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "", 3624 ClassMethods, true); 3625 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, 3626 IvarOffsets, IvarAligns, IvarOwnership); 3627 // Irrespective of whether we are compiling for a fragile or non-fragile ABI, 3628 // we emit a symbol containing the offset for each ivar in the class. This 3629 // allows code compiled for the non-Fragile ABI to inherit from code compiled 3630 // for the legacy ABI, without causing problems. The converse is also 3631 // possible, but causes all ivar accesses to be fragile. 3632 3633 // Offset pointer for getting at the correct field in the ivar list when 3634 // setting up the alias. These are: The base address for the global, the 3635 // ivar array (second field), the ivar in this list (set for each ivar), and 3636 // the offset (third field in ivar structure) 3637 llvm::Type *IndexTy = Int32Ty; 3638 llvm::Constant *offsetPointerIndexes[] = {Zeros[0], 3639 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr, 3640 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) }; 3641 3642 unsigned ivarIndex = 0; 3643 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD; 3644 IVD = IVD->getNextIvar()) { 3645 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD); 3646 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex); 3647 // Get the correct ivar field 3648 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr( 3649 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList, 3650 offsetPointerIndexes); 3651 // Get the existing variable, if one exists. 3652 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name); 3653 if (offset) { 3654 offset->setInitializer(offsetValue); 3655 // If this is the real definition, change its linkage type so that 3656 // different modules will use this one, rather than their private 3657 // copy. 3658 offset->setLinkage(llvm::GlobalValue::ExternalLinkage); 3659 } else 3660 // Add a new alias if there isn't one already. 3661 new llvm::GlobalVariable(TheModule, offsetValue->getType(), 3662 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name); 3663 ++ivarIndex; 3664 } 3665 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0); 3666 3667 //Generate metaclass for class methods 3668 llvm::Constant *MetaClassStruct = GenerateClassStructure( 3669 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], 3670 NULLPtr, ClassMethodList, NULLPtr, NULLPtr, 3671 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true); 3672 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct), 3673 OID->getClassInterface()); 3674 3675 // Generate the class structure 3676 llvm::Constant *ClassStruct = GenerateClassStructure( 3677 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr, 3678 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList, 3679 GenerateProtocolList(Protocols), IvarOffsetArray, Properties, 3680 StrongIvarBitmap, WeakIvarBitmap); 3681 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct), 3682 OID->getClassInterface()); 3683 3684 // Resolve the class aliases, if they exist. 3685 if (ClassPtrAlias) { 3686 ClassPtrAlias->replaceAllUsesWith( 3687 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy)); 3688 ClassPtrAlias->eraseFromParent(); 3689 ClassPtrAlias = nullptr; 3690 } 3691 if (MetaClassPtrAlias) { 3692 MetaClassPtrAlias->replaceAllUsesWith( 3693 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy)); 3694 MetaClassPtrAlias->eraseFromParent(); 3695 MetaClassPtrAlias = nullptr; 3696 } 3697 3698 // Add class structure to list to be added to the symtab later 3699 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty); 3700 Classes.push_back(ClassStruct); 3701 } 3702 3703 llvm::Function *CGObjCGNU::ModuleInitFunction() { 3704 // Only emit an ObjC load function if no Objective-C stuff has been called 3705 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && 3706 ExistingProtocols.empty() && SelectorTable.empty()) 3707 return nullptr; 3708 3709 // Add all referenced protocols to a category. 3710 GenerateProtocolHolderCategory(); 3711 3712 llvm::StructType *selStructTy = 3713 dyn_cast<llvm::StructType>(SelectorTy->getPointerElementType()); 3714 llvm::Type *selStructPtrTy = SelectorTy; 3715 if (!selStructTy) { 3716 selStructTy = llvm::StructType::get(CGM.getLLVMContext(), 3717 { PtrToInt8Ty, PtrToInt8Ty }); 3718 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy); 3719 } 3720 3721 // Generate statics list: 3722 llvm::Constant *statics = NULLPtr; 3723 if (!ConstantStrings.empty()) { 3724 llvm::GlobalVariable *fileStatics = [&] { 3725 ConstantInitBuilder builder(CGM); 3726 auto staticsStruct = builder.beginStruct(); 3727 3728 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass; 3729 if (stringClass.empty()) stringClass = "NXConstantString"; 3730 staticsStruct.add(MakeConstantString(stringClass, 3731 ".objc_static_class_name")); 3732 3733 auto array = staticsStruct.beginArray(); 3734 array.addAll(ConstantStrings); 3735 array.add(NULLPtr); 3736 array.finishAndAddTo(staticsStruct); 3737 3738 return staticsStruct.finishAndCreateGlobal(".objc_statics", 3739 CGM.getPointerAlign()); 3740 }(); 3741 3742 ConstantInitBuilder builder(CGM); 3743 auto allStaticsArray = builder.beginArray(fileStatics->getType()); 3744 allStaticsArray.add(fileStatics); 3745 allStaticsArray.addNullPointer(fileStatics->getType()); 3746 3747 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr", 3748 CGM.getPointerAlign()); 3749 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy); 3750 } 3751 3752 // Array of classes, categories, and constant objects. 3753 3754 SmallVector<llvm::GlobalAlias*, 16> selectorAliases; 3755 unsigned selectorCount; 3756 3757 // Pointer to an array of selectors used in this module. 3758 llvm::GlobalVariable *selectorList = [&] { 3759 ConstantInitBuilder builder(CGM); 3760 auto selectors = builder.beginArray(selStructTy); 3761 auto &table = SelectorTable; // MSVC workaround 3762 std::vector<Selector> allSelectors; 3763 for (auto &entry : table) 3764 allSelectors.push_back(entry.first); 3765 llvm::sort(allSelectors); 3766 3767 for (auto &untypedSel : allSelectors) { 3768 std::string selNameStr = untypedSel.getAsString(); 3769 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name"); 3770 3771 for (TypedSelector &sel : table[untypedSel]) { 3772 llvm::Constant *selectorTypeEncoding = NULLPtr; 3773 if (!sel.first.empty()) 3774 selectorTypeEncoding = 3775 MakeConstantString(sel.first, ".objc_sel_types"); 3776 3777 auto selStruct = selectors.beginStruct(selStructTy); 3778 selStruct.add(selName); 3779 selStruct.add(selectorTypeEncoding); 3780 selStruct.finishAndAddTo(selectors); 3781 3782 // Store the selector alias for later replacement 3783 selectorAliases.push_back(sel.second); 3784 } 3785 } 3786 3787 // Remember the number of entries in the selector table. 3788 selectorCount = selectors.size(); 3789 3790 // NULL-terminate the selector list. This should not actually be required, 3791 // because the selector list has a length field. Unfortunately, the GCC 3792 // runtime decides to ignore the length field and expects a NULL terminator, 3793 // and GCC cooperates with this by always setting the length to 0. 3794 auto selStruct = selectors.beginStruct(selStructTy); 3795 selStruct.add(NULLPtr); 3796 selStruct.add(NULLPtr); 3797 selStruct.finishAndAddTo(selectors); 3798 3799 return selectors.finishAndCreateGlobal(".objc_selector_list", 3800 CGM.getPointerAlign()); 3801 }(); 3802 3803 // Now that all of the static selectors exist, create pointers to them. 3804 for (unsigned i = 0; i < selectorCount; ++i) { 3805 llvm::Constant *idxs[] = { 3806 Zeros[0], 3807 llvm::ConstantInt::get(Int32Ty, i) 3808 }; 3809 // FIXME: We're generating redundant loads and stores here! 3810 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr( 3811 selectorList->getValueType(), selectorList, idxs); 3812 // If selectors are defined as an opaque type, cast the pointer to this 3813 // type. 3814 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy); 3815 selectorAliases[i]->replaceAllUsesWith(selPtr); 3816 selectorAliases[i]->eraseFromParent(); 3817 } 3818 3819 llvm::GlobalVariable *symtab = [&] { 3820 ConstantInitBuilder builder(CGM); 3821 auto symtab = builder.beginStruct(); 3822 3823 // Number of static selectors 3824 symtab.addInt(LongTy, selectorCount); 3825 3826 symtab.addBitCast(selectorList, selStructPtrTy); 3827 3828 // Number of classes defined. 3829 symtab.addInt(CGM.Int16Ty, Classes.size()); 3830 // Number of categories defined 3831 symtab.addInt(CGM.Int16Ty, Categories.size()); 3832 3833 // Create an array of classes, then categories, then static object instances 3834 auto classList = symtab.beginArray(PtrToInt8Ty); 3835 classList.addAll(Classes); 3836 classList.addAll(Categories); 3837 // NULL-terminated list of static object instances (mainly constant strings) 3838 classList.add(statics); 3839 classList.add(NULLPtr); 3840 classList.finishAndAddTo(symtab); 3841 3842 // Construct the symbol table. 3843 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign()); 3844 }(); 3845 3846 // The symbol table is contained in a module which has some version-checking 3847 // constants 3848 llvm::Constant *module = [&] { 3849 llvm::Type *moduleEltTys[] = { 3850 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy 3851 }; 3852 llvm::StructType *moduleTy = 3853 llvm::StructType::get(CGM.getLLVMContext(), 3854 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10))); 3855 3856 ConstantInitBuilder builder(CGM); 3857 auto module = builder.beginStruct(moduleTy); 3858 // Runtime version, used for ABI compatibility checking. 3859 module.addInt(LongTy, RuntimeVersion); 3860 // sizeof(ModuleTy) 3861 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy)); 3862 3863 // The path to the source file where this module was declared 3864 SourceManager &SM = CGM.getContext().getSourceManager(); 3865 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID()); 3866 std::string path = 3867 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str(); 3868 module.add(MakeConstantString(path, ".objc_source_file_name")); 3869 module.add(symtab); 3870 3871 if (RuntimeVersion >= 10) { 3872 switch (CGM.getLangOpts().getGC()) { 3873 case LangOptions::GCOnly: 3874 module.addInt(IntTy, 2); 3875 break; 3876 case LangOptions::NonGC: 3877 if (CGM.getLangOpts().ObjCAutoRefCount) 3878 module.addInt(IntTy, 1); 3879 else 3880 module.addInt(IntTy, 0); 3881 break; 3882 case LangOptions::HybridGC: 3883 module.addInt(IntTy, 1); 3884 break; 3885 } 3886 } 3887 3888 return module.finishAndCreateGlobal("", CGM.getPointerAlign()); 3889 }(); 3890 3891 // Create the load function calling the runtime entry point with the module 3892 // structure 3893 llvm::Function * LoadFunction = llvm::Function::Create( 3894 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 3895 llvm::GlobalValue::InternalLinkage, ".objc_load_function", 3896 &TheModule); 3897 llvm::BasicBlock *EntryBB = 3898 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 3899 CGBuilderTy Builder(CGM, VMContext); 3900 Builder.SetInsertPoint(EntryBB); 3901 3902 llvm::FunctionType *FT = 3903 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true); 3904 llvm::FunctionCallee Register = 3905 CGM.CreateRuntimeFunction(FT, "__objc_exec_class"); 3906 Builder.CreateCall(Register, module); 3907 3908 if (!ClassAliases.empty()) { 3909 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty}; 3910 llvm::FunctionType *RegisterAliasTy = 3911 llvm::FunctionType::get(Builder.getVoidTy(), 3912 ArgTypes, false); 3913 llvm::Function *RegisterAlias = llvm::Function::Create( 3914 RegisterAliasTy, 3915 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np", 3916 &TheModule); 3917 llvm::BasicBlock *AliasBB = 3918 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction); 3919 llvm::BasicBlock *NoAliasBB = 3920 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction); 3921 3922 // Branch based on whether the runtime provided class_registerAlias_np() 3923 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias, 3924 llvm::Constant::getNullValue(RegisterAlias->getType())); 3925 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB); 3926 3927 // The true branch (has alias registration function): 3928 Builder.SetInsertPoint(AliasBB); 3929 // Emit alias registration calls: 3930 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin(); 3931 iter != ClassAliases.end(); ++iter) { 3932 llvm::Constant *TheClass = 3933 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true); 3934 if (TheClass) { 3935 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy); 3936 Builder.CreateCall(RegisterAlias, 3937 {TheClass, MakeConstantString(iter->second)}); 3938 } 3939 } 3940 // Jump to end: 3941 Builder.CreateBr(NoAliasBB); 3942 3943 // Missing alias registration function, just return from the function: 3944 Builder.SetInsertPoint(NoAliasBB); 3945 } 3946 Builder.CreateRetVoid(); 3947 3948 return LoadFunction; 3949 } 3950 3951 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, 3952 const ObjCContainerDecl *CD) { 3953 CodeGenTypes &Types = CGM.getTypes(); 3954 llvm::FunctionType *MethodTy = 3955 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD)); 3956 std::string FunctionName = getSymbolNameForMethod(OMD); 3957 3958 llvm::Function *Method 3959 = llvm::Function::Create(MethodTy, 3960 llvm::GlobalValue::InternalLinkage, 3961 FunctionName, 3962 &TheModule); 3963 return Method; 3964 } 3965 3966 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF, 3967 llvm::Function *Fn, 3968 const ObjCMethodDecl *OMD, 3969 const ObjCContainerDecl *CD) { 3970 // GNU runtime doesn't support direct calls at this time 3971 } 3972 3973 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() { 3974 return GetPropertyFn; 3975 } 3976 3977 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() { 3978 return SetPropertyFn; 3979 } 3980 3981 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic, 3982 bool copy) { 3983 return nullptr; 3984 } 3985 3986 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() { 3987 return GetStructPropertyFn; 3988 } 3989 3990 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() { 3991 return SetStructPropertyFn; 3992 } 3993 3994 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() { 3995 return nullptr; 3996 } 3997 3998 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() { 3999 return nullptr; 4000 } 4001 4002 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() { 4003 return EnumerationMutationFn; 4004 } 4005 4006 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF, 4007 const ObjCAtSynchronizedStmt &S) { 4008 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn); 4009 } 4010 4011 4012 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF, 4013 const ObjCAtTryStmt &S) { 4014 // Unlike the Apple non-fragile runtimes, which also uses 4015 // unwind-based zero cost exceptions, the GNU Objective C runtime's 4016 // EH support isn't a veneer over C++ EH. Instead, exception 4017 // objects are created by objc_exception_throw and destroyed by 4018 // the personality function; this avoids the need for bracketing 4019 // catch handlers with calls to __blah_begin_catch/__blah_end_catch 4020 // (or even _Unwind_DeleteException), but probably doesn't 4021 // interoperate very well with foreign exceptions. 4022 // 4023 // In Objective-C++ mode, we actually emit something equivalent to the C++ 4024 // exception handler. 4025 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn); 4026 } 4027 4028 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF, 4029 const ObjCAtThrowStmt &S, 4030 bool ClearInsertionPoint) { 4031 llvm::Value *ExceptionAsObject; 4032 bool isRethrow = false; 4033 4034 if (const Expr *ThrowExpr = S.getThrowExpr()) { 4035 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); 4036 ExceptionAsObject = Exception; 4037 } else { 4038 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 4039 "Unexpected rethrow outside @catch block."); 4040 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 4041 isRethrow = true; 4042 } 4043 if (isRethrow && usesSEHExceptions) { 4044 // For SEH, ExceptionAsObject may be undef, because the catch handler is 4045 // not passed it for catchalls and so it is not visible to the catch 4046 // funclet. The real thrown object will still be live on the stack at this 4047 // point and will be rethrown. If we are explicitly rethrowing the object 4048 // that was passed into the `@catch` block, then this code path is not 4049 // reached and we will instead call `objc_exception_throw` with an explicit 4050 // argument. 4051 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn); 4052 Throw->setDoesNotReturn(); 4053 } 4054 else { 4055 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy); 4056 llvm::CallBase *Throw = 4057 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject); 4058 Throw->setDoesNotReturn(); 4059 } 4060 CGF.Builder.CreateUnreachable(); 4061 if (ClearInsertionPoint) 4062 CGF.Builder.ClearInsertionPoint(); 4063 } 4064 4065 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF, 4066 Address AddrWeakObj) { 4067 CGBuilderTy &B = CGF.Builder; 4068 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy); 4069 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer()); 4070 } 4071 4072 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF, 4073 llvm::Value *src, Address dst) { 4074 CGBuilderTy &B = CGF.Builder; 4075 src = EnforceType(B, src, IdTy); 4076 dst = EnforceType(B, dst, PtrToIdTy); 4077 B.CreateCall(WeakAssignFn, {src, dst.getPointer()}); 4078 } 4079 4080 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF, 4081 llvm::Value *src, Address dst, 4082 bool threadlocal) { 4083 CGBuilderTy &B = CGF.Builder; 4084 src = EnforceType(B, src, IdTy); 4085 dst = EnforceType(B, dst, PtrToIdTy); 4086 // FIXME. Add threadloca assign API 4087 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI"); 4088 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()}); 4089 } 4090 4091 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF, 4092 llvm::Value *src, Address dst, 4093 llvm::Value *ivarOffset) { 4094 CGBuilderTy &B = CGF.Builder; 4095 src = EnforceType(B, src, IdTy); 4096 dst = EnforceType(B, dst, IdTy); 4097 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset}); 4098 } 4099 4100 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF, 4101 llvm::Value *src, Address dst) { 4102 CGBuilderTy &B = CGF.Builder; 4103 src = EnforceType(B, src, IdTy); 4104 dst = EnforceType(B, dst, PtrToIdTy); 4105 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()}); 4106 } 4107 4108 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF, 4109 Address DestPtr, 4110 Address SrcPtr, 4111 llvm::Value *Size) { 4112 CGBuilderTy &B = CGF.Builder; 4113 DestPtr = EnforceType(B, DestPtr, PtrTy); 4114 SrcPtr = EnforceType(B, SrcPtr, PtrTy); 4115 4116 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size}); 4117 } 4118 4119 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( 4120 const ObjCInterfaceDecl *ID, 4121 const ObjCIvarDecl *Ivar) { 4122 const std::string Name = GetIVarOffsetVariableName(ID, Ivar); 4123 // Emit the variable and initialize it with what we think the correct value 4124 // is. This allows code compiled with non-fragile ivars to work correctly 4125 // when linked against code which isn't (most of the time). 4126 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 4127 if (!IvarOffsetPointer) 4128 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 4129 llvm::Type::getInt32PtrTy(VMContext), false, 4130 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 4131 return IvarOffsetPointer; 4132 } 4133 4134 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF, 4135 QualType ObjectTy, 4136 llvm::Value *BaseValue, 4137 const ObjCIvarDecl *Ivar, 4138 unsigned CVRQualifiers) { 4139 const ObjCInterfaceDecl *ID = 4140 ObjectTy->castAs<ObjCObjectType>()->getInterface(); 4141 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 4142 EmitIvarOffset(CGF, ID, Ivar)); 4143 } 4144 4145 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, 4146 const ObjCInterfaceDecl *OID, 4147 const ObjCIvarDecl *OIVD) { 4148 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next; 4149 next = next->getNextIvar()) { 4150 if (OIVD == next) 4151 return OID; 4152 } 4153 4154 // Otherwise check in the super class. 4155 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 4156 return FindIvarInterface(Context, Super, OIVD); 4157 4158 return nullptr; 4159 } 4160 4161 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF, 4162 const ObjCInterfaceDecl *Interface, 4163 const ObjCIvarDecl *Ivar) { 4164 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 4165 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar); 4166 4167 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage 4168 // and ExternalLinkage, so create a reference to the ivar global and rely on 4169 // the definition being created as part of GenerateClass. 4170 if (RuntimeVersion < 10 || 4171 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) 4172 return CGF.Builder.CreateZExtOrBitCast( 4173 CGF.Builder.CreateAlignedLoad( 4174 Int32Ty, CGF.Builder.CreateAlignedLoad( 4175 llvm::Type::getInt32PtrTy(VMContext), 4176 ObjCIvarOffsetVariable(Interface, Ivar), 4177 CGF.getPointerAlign(), "ivar"), 4178 CharUnits::fromQuantity(4)), 4179 PtrDiffTy); 4180 std::string name = "__objc_ivar_offset_value_" + 4181 Interface->getNameAsString() +"." + Ivar->getNameAsString(); 4182 CharUnits Align = CGM.getIntAlign(); 4183 llvm::Value *Offset = TheModule.getGlobalVariable(name); 4184 if (!Offset) { 4185 auto GV = new llvm::GlobalVariable(TheModule, IntTy, 4186 false, llvm::GlobalValue::LinkOnceAnyLinkage, 4187 llvm::Constant::getNullValue(IntTy), name); 4188 GV->setAlignment(Align.getAsAlign()); 4189 Offset = GV; 4190 } 4191 Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align); 4192 if (Offset->getType() != PtrDiffTy) 4193 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy); 4194 return Offset; 4195 } 4196 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar); 4197 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true); 4198 } 4199 4200 CGObjCRuntime * 4201 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) { 4202 auto Runtime = CGM.getLangOpts().ObjCRuntime; 4203 switch (Runtime.getKind()) { 4204 case ObjCRuntime::GNUstep: 4205 if (Runtime.getVersion() >= VersionTuple(2, 0)) 4206 return new CGObjCGNUstep2(CGM); 4207 return new CGObjCGNUstep(CGM); 4208 4209 case ObjCRuntime::GCC: 4210 return new CGObjCGCC(CGM); 4211 4212 case ObjCRuntime::ObjFW: 4213 return new CGObjCObjFW(CGM); 4214 4215 case ObjCRuntime::FragileMacOSX: 4216 case ObjCRuntime::MacOSX: 4217 case ObjCRuntime::iOS: 4218 case ObjCRuntime::WatchOS: 4219 llvm_unreachable("these runtimes are not GNU runtimes"); 4220 } 4221 llvm_unreachable("bad runtime"); 4222 } 4223