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