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