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