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