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