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