1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides Objective-C code generation targeting the GNU runtime. The 11 // class in this file generates structures used by the GNU Objective-C runtime 12 // library. These structures are defined in objc/objc.h and objc/objc-api.h in 13 // the GNU runtime distribution. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "CGObjCRuntime.h" 18 #include "CGCleanup.h" 19 #include "CodeGenFunction.h" 20 #include "CodeGenModule.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Basic/FileManager.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/StringMap.h" 30 #include "llvm/IR/CallSite.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/LLVMContext.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/Support/Compiler.h" 36 #include <cstdarg> 37 38 using namespace clang; 39 using namespace CodeGen; 40 41 namespace { 42 /// Class that lazily initialises the runtime function. Avoids inserting the 43 /// types and the function declaration into a module if they're not used, and 44 /// avoids constructing the type more than once if it's used more than once. 45 class LazyRuntimeFunction { 46 CodeGenModule *CGM; 47 llvm::FunctionType *FTy; 48 const char *FunctionName; 49 llvm::Constant *Function; 50 51 public: 52 /// Constructor leaves this class uninitialized, because it is intended to 53 /// be used as a field in another class and not all of the types that are 54 /// used as arguments will necessarily be available at construction time. 55 LazyRuntimeFunction() 56 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {} 57 58 /// Initialises the lazy function with the name, return type, and the types 59 /// of the arguments. 60 LLVM_END_WITH_NULL 61 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) { 62 CGM = Mod; 63 FunctionName = name; 64 Function = nullptr; 65 std::vector<llvm::Type *> ArgTys; 66 va_list Args; 67 va_start(Args, RetTy); 68 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *)) 69 ArgTys.push_back(ArgTy); 70 va_end(Args); 71 FTy = llvm::FunctionType::get(RetTy, ArgTys, false); 72 } 73 74 llvm::FunctionType *getType() { return FTy; } 75 76 /// Overloaded cast operator, allows the class to be implicitly cast to an 77 /// LLVM constant. 78 operator llvm::Constant *() { 79 if (!Function) { 80 if (!FunctionName) 81 return nullptr; 82 Function = 83 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName)); 84 } 85 return Function; 86 } 87 operator llvm::Function *() { 88 return cast<llvm::Function>((llvm::Constant *)*this); 89 } 90 }; 91 92 93 /// GNU Objective-C runtime code generation. This class implements the parts of 94 /// Objective-C support that are specific to the GNU family of runtimes (GCC, 95 /// GNUstep and ObjFW). 96 class CGObjCGNU : public CGObjCRuntime { 97 protected: 98 /// The LLVM module into which output is inserted 99 llvm::Module &TheModule; 100 /// strut objc_super. Used for sending messages to super. This structure 101 /// contains the receiver (object) and the expected class. 102 llvm::StructType *ObjCSuperTy; 103 /// struct objc_super*. The type of the argument to the superclass message 104 /// lookup functions. 105 llvm::PointerType *PtrToObjCSuperTy; 106 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring 107 /// SEL is included in a header somewhere, in which case it will be whatever 108 /// type is declared in that header, most likely {i8*, i8*}. 109 llvm::PointerType *SelectorTy; 110 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the 111 /// places where it's used 112 llvm::IntegerType *Int8Ty; 113 /// Pointer to i8 - LLVM type of char*, for all of the places where the 114 /// runtime needs to deal with C strings. 115 llvm::PointerType *PtrToInt8Ty; 116 /// Instance Method Pointer type. This is a pointer to a function that takes, 117 /// at a minimum, an object and a selector, and is the generic type for 118 /// Objective-C methods. Due to differences between variadic / non-variadic 119 /// calling conventions, it must always be cast to the correct type before 120 /// actually being used. 121 llvm::PointerType *IMPTy; 122 /// Type of an untyped Objective-C object. Clang treats id as a built-in type 123 /// when compiling Objective-C code, so this may be an opaque pointer (i8*), 124 /// but if the runtime header declaring it is included then it may be a 125 /// pointer to a structure. 126 llvm::PointerType *IdTy; 127 /// Pointer to a pointer to an Objective-C object. Used in the new ABI 128 /// message lookup function and some GC-related functions. 129 llvm::PointerType *PtrToIdTy; 130 /// The clang type of id. Used when using the clang CGCall infrastructure to 131 /// call Objective-C methods. 132 CanQualType ASTIdTy; 133 /// LLVM type for C int type. 134 llvm::IntegerType *IntTy; 135 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is 136 /// used in the code to document the difference between i8* meaning a pointer 137 /// to a C string and i8* meaning a pointer to some opaque type. 138 llvm::PointerType *PtrTy; 139 /// LLVM type for C long type. The runtime uses this in a lot of places where 140 /// it should be using intptr_t, but we can't fix this without breaking 141 /// compatibility with GCC... 142 llvm::IntegerType *LongTy; 143 /// LLVM type for C size_t. Used in various runtime data structures. 144 llvm::IntegerType *SizeTy; 145 /// LLVM type for C intptr_t. 146 llvm::IntegerType *IntPtrTy; 147 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions. 148 llvm::IntegerType *PtrDiffTy; 149 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance 150 /// variables. 151 llvm::PointerType *PtrToIntTy; 152 /// LLVM type for Objective-C BOOL type. 153 llvm::Type *BoolTy; 154 /// 32-bit integer type, to save us needing to look it up every time it's used. 155 llvm::IntegerType *Int32Ty; 156 /// 64-bit integer type, to save us needing to look it up every time it's used. 157 llvm::IntegerType *Int64Ty; 158 /// Metadata kind used to tie method lookups to message sends. The GNUstep 159 /// runtime provides some LLVM passes that can use this to do things like 160 /// automatic IMP caching and speculative inlining. 161 unsigned msgSendMDKind; 162 163 /// Helper function that generates a constant string and returns a pointer to 164 /// the start of the string. The result of this function can be used anywhere 165 /// where the C code specifies const char*. 166 llvm::Constant *MakeConstantString(const std::string &Str, 167 const std::string &Name="") { 168 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name.c_str()); 169 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(), 170 Array.getPointer(), Zeros); 171 } 172 173 /// Emits a linkonce_odr string, whose name is the prefix followed by the 174 /// string value. This allows the linker to combine the strings between 175 /// different modules. Used for EH typeinfo names, selector strings, and a 176 /// few other things. 177 llvm::Constant *ExportUniqueString(const std::string &Str, 178 const std::string prefix) { 179 std::string name = prefix + Str; 180 auto *ConstStr = TheModule.getGlobalVariable(name); 181 if (!ConstStr) { 182 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str); 183 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true, 184 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str); 185 } 186 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(), 187 ConstStr, Zeros); 188 } 189 190 /// Generates a global structure, initialized by the elements in the vector. 191 /// The element types must match the types of the structure elements in the 192 /// first argument. 193 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty, 194 ArrayRef<llvm::Constant *> V, 195 CharUnits Align, 196 StringRef Name="", 197 llvm::GlobalValue::LinkageTypes linkage 198 =llvm::GlobalValue::InternalLinkage) { 199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V); 200 auto GV = new llvm::GlobalVariable(TheModule, Ty, false, 201 linkage, C, Name); 202 GV->setAlignment(Align.getQuantity()); 203 return GV; 204 } 205 206 /// Generates a global array. The vector must contain the same number of 207 /// elements that the array type declares, of the type specified as the array 208 /// element type. 209 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty, 210 ArrayRef<llvm::Constant *> V, 211 CharUnits Align, 212 StringRef Name="", 213 llvm::GlobalValue::LinkageTypes linkage 214 =llvm::GlobalValue::InternalLinkage) { 215 llvm::Constant *C = llvm::ConstantArray::get(Ty, V); 216 auto GV = new llvm::GlobalVariable(TheModule, Ty, false, 217 linkage, C, Name); 218 GV->setAlignment(Align.getQuantity()); 219 return GV; 220 } 221 222 /// Generates a global array, inferring the array type from the specified 223 /// element type and the size of the initialiser. 224 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty, 225 ArrayRef<llvm::Constant *> V, 226 CharUnits Align, 227 StringRef Name="", 228 llvm::GlobalValue::LinkageTypes linkage 229 =llvm::GlobalValue::InternalLinkage) { 230 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size()); 231 return MakeGlobal(ArrayTy, V, Align, Name, linkage); 232 } 233 234 /// Returns a property name and encoding string. 235 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD, 236 const Decl *Container) { 237 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; 238 if ((R.getKind() == ObjCRuntime::GNUstep) && 239 (R.getVersion() >= VersionTuple(1, 6))) { 240 std::string NameAndAttributes; 241 std::string TypeStr; 242 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 243 NameAndAttributes += '\0'; 244 NameAndAttributes += TypeStr.length() + 3; 245 NameAndAttributes += TypeStr; 246 NameAndAttributes += '\0'; 247 NameAndAttributes += PD->getNameAsString(); 248 return MakeConstantString(NameAndAttributes); 249 } 250 return MakeConstantString(PD->getNameAsString()); 251 } 252 253 /// Push the property attributes into two structure fields. 254 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields, 255 ObjCPropertyDecl *property, bool isSynthesized=true, bool 256 isDynamic=true) { 257 int attrs = property->getPropertyAttributes(); 258 // For read-only properties, clear the copy and retain flags 259 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) { 260 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy; 261 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain; 262 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak; 263 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong; 264 } 265 // The first flags field has the same attribute values as clang uses internally 266 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff)); 267 attrs >>= 8; 268 attrs <<= 2; 269 // For protocol properties, synthesized and dynamic have no meaning, so we 270 // reuse these flags to indicate that this is a protocol property (both set 271 // has no meaning, as a property can't be both synthesized and dynamic) 272 attrs |= isSynthesized ? (1<<0) : 0; 273 attrs |= isDynamic ? (1<<1) : 0; 274 // The second field is the next four fields left shifted by two, with the 275 // low bit set to indicate whether the field is synthesized or dynamic. 276 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff)); 277 // Two padding fields 278 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0)); 279 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0)); 280 } 281 282 /// Ensures that the value has the required type, by inserting a bitcast if 283 /// required. This function lets us avoid inserting bitcasts that are 284 /// redundant. 285 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) { 286 if (V->getType() == Ty) return V; 287 return B.CreateBitCast(V, Ty); 288 } 289 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) { 290 if (V.getType() == Ty) return V; 291 return B.CreateBitCast(V, Ty); 292 } 293 294 // Some zeros used for GEPs in lots of places. 295 llvm::Constant *Zeros[2]; 296 /// Null pointer value. Mainly used as a terminator in various arrays. 297 llvm::Constant *NULLPtr; 298 /// LLVM context. 299 llvm::LLVMContext &VMContext; 300 301 private: 302 /// Placeholder for the class. Lots of things refer to the class before we've 303 /// actually emitted it. We use this alias as a placeholder, and then replace 304 /// it with a pointer to the class structure before finally emitting the 305 /// module. 306 llvm::GlobalAlias *ClassPtrAlias; 307 /// Placeholder for the metaclass. Lots of things refer to the class before 308 /// we've / actually emitted it. We use this alias as a placeholder, and then 309 /// replace / it with a pointer to the metaclass structure before finally 310 /// emitting the / module. 311 llvm::GlobalAlias *MetaClassPtrAlias; 312 /// All of the classes that have been generated for this compilation units. 313 std::vector<llvm::Constant*> Classes; 314 /// All of the categories that have been generated for this compilation units. 315 std::vector<llvm::Constant*> Categories; 316 /// All of the Objective-C constant strings that have been generated for this 317 /// compilation units. 318 std::vector<llvm::Constant*> ConstantStrings; 319 /// Map from string values to Objective-C constant strings in the output. 320 /// Used to prevent emitting Objective-C strings more than once. This should 321 /// not be required at all - CodeGenModule should manage this list. 322 llvm::StringMap<llvm::Constant*> ObjCStrings; 323 /// All of the protocols that have been declared. 324 llvm::StringMap<llvm::Constant*> ExistingProtocols; 325 /// For each variant of a selector, we store the type encoding and a 326 /// placeholder value. For an untyped selector, the type will be the empty 327 /// string. Selector references are all done via the module's selector table, 328 /// so we create an alias as a placeholder and then replace it with the real 329 /// value later. 330 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector; 331 /// Type of the selector map. This is roughly equivalent to the structure 332 /// used in the GNUstep runtime, which maintains a list of all of the valid 333 /// types for a selector in a table. 334 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> > 335 SelectorMap; 336 /// A map from selectors to selector types. This allows us to emit all 337 /// selectors of the same name and type together. 338 SelectorMap SelectorTable; 339 340 /// Selectors related to memory management. When compiling in GC mode, we 341 /// omit these. 342 Selector RetainSel, ReleaseSel, AutoreleaseSel; 343 /// Runtime functions used for memory management in GC mode. Note that clang 344 /// supports code generation for calling these functions, but neither GNU 345 /// runtime actually supports this API properly yet. 346 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, 347 WeakAssignFn, GlobalAssignFn; 348 349 typedef std::pair<std::string, std::string> ClassAliasPair; 350 /// All classes that have aliases set for them. 351 std::vector<ClassAliasPair> ClassAliases; 352 353 protected: 354 /// Function used for throwing Objective-C exceptions. 355 LazyRuntimeFunction ExceptionThrowFn; 356 /// Function used for rethrowing exceptions, used at the end of \@finally or 357 /// \@synchronize blocks. 358 LazyRuntimeFunction ExceptionReThrowFn; 359 /// Function called when entering a catch function. This is required for 360 /// differentiating Objective-C exceptions and foreign exceptions. 361 LazyRuntimeFunction EnterCatchFn; 362 /// Function called when exiting from a catch block. Used to do exception 363 /// cleanup. 364 LazyRuntimeFunction ExitCatchFn; 365 /// Function called when entering an \@synchronize block. Acquires the lock. 366 LazyRuntimeFunction SyncEnterFn; 367 /// Function called when exiting an \@synchronize block. Releases the lock. 368 LazyRuntimeFunction SyncExitFn; 369 370 private: 371 /// Function called if fast enumeration detects that the collection is 372 /// modified during the update. 373 LazyRuntimeFunction EnumerationMutationFn; 374 /// Function for implementing synthesized property getters that return an 375 /// object. 376 LazyRuntimeFunction GetPropertyFn; 377 /// Function for implementing synthesized property setters that return an 378 /// object. 379 LazyRuntimeFunction SetPropertyFn; 380 /// Function used for non-object declared property getters. 381 LazyRuntimeFunction GetStructPropertyFn; 382 /// Function used for non-object declared property setters. 383 LazyRuntimeFunction SetStructPropertyFn; 384 385 /// The version of the runtime that this class targets. Must match the 386 /// version in the runtime. 387 int RuntimeVersion; 388 /// The version of the protocol class. Used to differentiate between ObjC1 389 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional 390 /// components and can not contain declared properties. We always emit 391 /// Objective-C 2 property structures, but we have to pretend that they're 392 /// Objective-C 1 property structures when targeting the GCC runtime or it 393 /// will abort. 394 const int ProtocolVersion; 395 396 /// Generates an instance variable list structure. This is a structure 397 /// containing a size and an array of structures containing instance variable 398 /// metadata. This is used purely for introspection in the fragile ABI. In 399 /// the non-fragile ABI, it's used for instance variable fixup. 400 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 401 ArrayRef<llvm::Constant *> IvarTypes, 402 ArrayRef<llvm::Constant *> IvarOffsets); 403 404 /// Generates a method list structure. This is a structure containing a size 405 /// and an array of structures containing method metadata. 406 /// 407 /// This structure is used by both classes and categories, and contains a next 408 /// pointer allowing them to be chained together in a linked list. 409 llvm::Constant *GenerateMethodList(StringRef ClassName, 410 StringRef CategoryName, 411 ArrayRef<Selector> MethodSels, 412 ArrayRef<llvm::Constant *> MethodTypes, 413 bool isClassMethodList); 414 415 /// Emits an empty protocol. This is used for \@protocol() where no protocol 416 /// is found. The runtime will (hopefully) fix up the pointer to refer to the 417 /// real protocol. 418 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName); 419 420 /// Generates a list of property metadata structures. This follows the same 421 /// pattern as method and instance variable metadata lists. 422 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID, 423 SmallVectorImpl<Selector> &InstanceMethodSels, 424 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes); 425 426 /// Generates a list of referenced protocols. Classes, categories, and 427 /// protocols all use this structure. 428 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols); 429 430 /// To ensure that all protocols are seen by the runtime, we add a category on 431 /// a class defined in the runtime, declaring no methods, but adopting the 432 /// protocols. This is a horribly ugly hack, but it allows us to collect all 433 /// of the protocols without changing the ABI. 434 void GenerateProtocolHolderCategory(); 435 436 /// Generates a class structure. 437 llvm::Constant *GenerateClassStructure( 438 llvm::Constant *MetaClass, 439 llvm::Constant *SuperClass, 440 unsigned info, 441 const char *Name, 442 llvm::Constant *Version, 443 llvm::Constant *InstanceSize, 444 llvm::Constant *IVars, 445 llvm::Constant *Methods, 446 llvm::Constant *Protocols, 447 llvm::Constant *IvarOffsets, 448 llvm::Constant *Properties, 449 llvm::Constant *StrongIvarBitmap, 450 llvm::Constant *WeakIvarBitmap, 451 bool isMeta=false); 452 453 /// Generates a method list. This is used by protocols to define the required 454 /// and optional methods. 455 llvm::Constant *GenerateProtocolMethodList( 456 ArrayRef<llvm::Constant *> MethodNames, 457 ArrayRef<llvm::Constant *> MethodTypes); 458 459 /// Returns a selector with the specified type encoding. An empty string is 460 /// used to return an untyped selector (with the types field set to NULL). 461 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel, 462 const std::string &TypeEncoding); 463 464 /// Returns the variable used to store the offset of an instance variable. 465 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 466 const ObjCIvarDecl *Ivar); 467 /// Emits a reference to a class. This allows the linker to object if there 468 /// is no class of the matching name. 469 470 protected: 471 void EmitClassRef(const std::string &className); 472 473 /// Emits a pointer to the named class 474 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF, 475 const std::string &Name, bool isWeak); 476 477 /// Looks up the method for sending a message to the specified object. This 478 /// mechanism differs between the GCC and GNU runtimes, so this method must be 479 /// overridden in subclasses. 480 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF, 481 llvm::Value *&Receiver, 482 llvm::Value *cmd, 483 llvm::MDNode *node, 484 MessageSendInfo &MSI) = 0; 485 486 /// Looks up the method for sending a message to a superclass. This 487 /// mechanism differs between the GCC and GNU runtimes, so this method must 488 /// be overridden in subclasses. 489 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, 490 Address ObjCSuper, 491 llvm::Value *cmd, 492 MessageSendInfo &MSI) = 0; 493 494 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are 495 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 496 /// bits set to their values, LSB first, while larger ones are stored in a 497 /// structure of this / form: 498 /// 499 /// struct { int32_t length; int32_t values[length]; }; 500 /// 501 /// The values in the array are stored in host-endian format, with the least 502 /// significant bit being assumed to come first in the bitfield. Therefore, 503 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, 504 /// while a bitfield / with the 63rd bit set will be 1<<64. 505 llvm::Constant *MakeBitField(ArrayRef<bool> bits); 506 507 public: 508 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, 509 unsigned protocolClassVersion); 510 511 ConstantAddress GenerateConstantString(const StringLiteral *) override; 512 513 RValue 514 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return, 515 QualType ResultType, Selector Sel, 516 llvm::Value *Receiver, const CallArgList &CallArgs, 517 const ObjCInterfaceDecl *Class, 518 const ObjCMethodDecl *Method) override; 519 RValue 520 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return, 521 QualType ResultType, Selector Sel, 522 const ObjCInterfaceDecl *Class, 523 bool isCategoryImpl, llvm::Value *Receiver, 524 bool IsClassMessage, const CallArgList &CallArgs, 525 const ObjCMethodDecl *Method) override; 526 llvm::Value *GetClass(CodeGenFunction &CGF, 527 const ObjCInterfaceDecl *OID) override; 528 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override; 529 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override; 530 llvm::Value *GetSelector(CodeGenFunction &CGF, 531 const ObjCMethodDecl *Method) override; 532 llvm::Constant *GetEHType(QualType T) override; 533 534 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 535 const ObjCContainerDecl *CD) override; 536 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; 537 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; 538 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override; 539 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 540 const ObjCProtocolDecl *PD) override; 541 void GenerateProtocol(const ObjCProtocolDecl *PD) override; 542 llvm::Function *ModuleInitFunction() override; 543 llvm::Constant *GetPropertyGetFunction() override; 544 llvm::Constant *GetPropertySetFunction() override; 545 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, 546 bool copy) override; 547 llvm::Constant *GetSetStructFunction() override; 548 llvm::Constant *GetGetStructFunction() override; 549 llvm::Constant *GetCppAtomicObjectGetFunction() override; 550 llvm::Constant *GetCppAtomicObjectSetFunction() override; 551 llvm::Constant *EnumerationMutationFunction() override; 552 553 void EmitTryStmt(CodeGenFunction &CGF, 554 const ObjCAtTryStmt &S) override; 555 void EmitSynchronizedStmt(CodeGenFunction &CGF, 556 const ObjCAtSynchronizedStmt &S) override; 557 void EmitThrowStmt(CodeGenFunction &CGF, 558 const ObjCAtThrowStmt &S, 559 bool ClearInsertionPoint=true) override; 560 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF, 561 Address AddrWeakObj) override; 562 void EmitObjCWeakAssign(CodeGenFunction &CGF, 563 llvm::Value *src, Address dst) override; 564 void EmitObjCGlobalAssign(CodeGenFunction &CGF, 565 llvm::Value *src, Address dest, 566 bool threadlocal=false) override; 567 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src, 568 Address dest, llvm::Value *ivarOffset) override; 569 void EmitObjCStrongCastAssign(CodeGenFunction &CGF, 570 llvm::Value *src, Address dest) override; 571 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr, 572 Address SrcPtr, 573 llvm::Value *Size) override; 574 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy, 575 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, 576 unsigned CVRQualifiers) override; 577 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF, 578 const ObjCInterfaceDecl *Interface, 579 const ObjCIvarDecl *Ivar) override; 580 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; 581 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM, 582 const CGBlockInfo &blockInfo) override { 583 return NULLPtr; 584 } 585 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM, 586 const CGBlockInfo &blockInfo) override { 587 return NULLPtr; 588 } 589 590 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override { 591 return NULLPtr; 592 } 593 594 llvm::GlobalVariable *GetClassGlobal(StringRef Name, 595 bool Weak = false) override { 596 return nullptr; 597 } 598 }; 599 600 /// Class representing the legacy GCC Objective-C ABI. This is the default when 601 /// -fobjc-nonfragile-abi is not specified. 602 /// 603 /// The GCC ABI target actually generates code that is approximately compatible 604 /// with the new GNUstep runtime ABI, but refrains from using any features that 605 /// would not work with the GCC runtime. For example, clang always generates 606 /// the extended form of the class structure, and the extra fields are simply 607 /// ignored by GCC libobjc. 608 class CGObjCGCC : public CGObjCGNU { 609 /// The GCC ABI message lookup function. Returns an IMP pointing to the 610 /// method implementation for this message. 611 LazyRuntimeFunction MsgLookupFn; 612 /// The GCC ABI superclass message lookup function. Takes a pointer to a 613 /// structure describing the receiver and the class, and a selector as 614 /// arguments. Returns the IMP for the corresponding method. 615 LazyRuntimeFunction MsgLookupSuperFn; 616 617 protected: 618 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 619 llvm::Value *cmd, llvm::MDNode *node, 620 MessageSendInfo &MSI) override { 621 CGBuilderTy &Builder = CGF.Builder; 622 llvm::Value *args[] = { 623 EnforceType(Builder, Receiver, IdTy), 624 EnforceType(Builder, cmd, SelectorTy) }; 625 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args); 626 imp->setMetadata(msgSendMDKind, node); 627 return imp.getInstruction(); 628 } 629 630 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 631 llvm::Value *cmd, MessageSendInfo &MSI) override { 632 CGBuilderTy &Builder = CGF.Builder; 633 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper, 634 PtrToObjCSuperTy).getPointer(), cmd}; 635 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 636 } 637 638 public: 639 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) { 640 // IMP objc_msg_lookup(id, SEL); 641 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, 642 nullptr); 643 // IMP objc_msg_lookup_super(struct objc_super*, SEL); 644 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 645 PtrToObjCSuperTy, SelectorTy, nullptr); 646 } 647 }; 648 649 /// Class used when targeting the new GNUstep runtime ABI. 650 class CGObjCGNUstep : public CGObjCGNU { 651 /// The slot lookup function. Returns a pointer to a cacheable structure 652 /// that contains (among other things) the IMP. 653 LazyRuntimeFunction SlotLookupFn; 654 /// The GNUstep ABI superclass message lookup function. Takes a pointer to 655 /// a structure describing the receiver and the class, and a selector as 656 /// arguments. Returns the slot for the corresponding method. Superclass 657 /// message lookup rarely changes, so this is a good caching opportunity. 658 LazyRuntimeFunction SlotLookupSuperFn; 659 /// Specialised function for setting atomic retain properties 660 LazyRuntimeFunction SetPropertyAtomic; 661 /// Specialised function for setting atomic copy properties 662 LazyRuntimeFunction SetPropertyAtomicCopy; 663 /// Specialised function for setting nonatomic retain properties 664 LazyRuntimeFunction SetPropertyNonAtomic; 665 /// Specialised function for setting nonatomic copy properties 666 LazyRuntimeFunction SetPropertyNonAtomicCopy; 667 /// Function to perform atomic copies of C++ objects with nontrivial copy 668 /// constructors from Objective-C ivars. 669 LazyRuntimeFunction CxxAtomicObjectGetFn; 670 /// Function to perform atomic copies of C++ objects with nontrivial copy 671 /// constructors to Objective-C ivars. 672 LazyRuntimeFunction CxxAtomicObjectSetFn; 673 /// Type of an slot structure pointer. This is returned by the various 674 /// lookup functions. 675 llvm::Type *SlotTy; 676 677 public: 678 llvm::Constant *GetEHType(QualType T) override; 679 680 protected: 681 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 682 llvm::Value *cmd, llvm::MDNode *node, 683 MessageSendInfo &MSI) override { 684 CGBuilderTy &Builder = CGF.Builder; 685 llvm::Function *LookupFn = SlotLookupFn; 686 687 // Store the receiver on the stack so that we can reload it later 688 Address ReceiverPtr = 689 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign()); 690 Builder.CreateStore(Receiver, ReceiverPtr); 691 692 llvm::Value *self; 693 694 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) { 695 self = CGF.LoadObjCSelf(); 696 } else { 697 self = llvm::ConstantPointerNull::get(IdTy); 698 } 699 700 // The lookup function is guaranteed not to capture the receiver pointer. 701 LookupFn->setDoesNotCapture(1); 702 703 llvm::Value *args[] = { 704 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy), 705 EnforceType(Builder, cmd, SelectorTy), 706 EnforceType(Builder, self, IdTy) }; 707 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args); 708 slot.setOnlyReadsMemory(); 709 slot->setMetadata(msgSendMDKind, node); 710 711 // Load the imp from the slot 712 llvm::Value *imp = Builder.CreateAlignedLoad( 713 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4), 714 CGF.getPointerAlign()); 715 716 // The lookup function may have changed the receiver, so make sure we use 717 // the new one. 718 Receiver = Builder.CreateLoad(ReceiverPtr, true); 719 return imp; 720 } 721 722 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 723 llvm::Value *cmd, 724 MessageSendInfo &MSI) override { 725 CGBuilderTy &Builder = CGF.Builder; 726 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd}; 727 728 llvm::CallInst *slot = 729 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs); 730 slot->setOnlyReadsMemory(); 731 732 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4), 733 CGF.getPointerAlign()); 734 } 735 736 public: 737 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) { 738 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; 739 740 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy, 741 PtrTy, PtrTy, IntTy, IMPTy, nullptr); 742 SlotTy = llvm::PointerType::getUnqual(SlotStructTy); 743 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender); 744 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy, 745 SelectorTy, IdTy, nullptr); 746 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL); 747 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy, 748 PtrToObjCSuperTy, SelectorTy, nullptr); 749 // If we're in ObjC++ mode, then we want to make 750 if (CGM.getLangOpts().CPlusPlus) { 751 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 752 // void *__cxa_begin_catch(void *e) 753 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr); 754 // void __cxa_end_catch(void) 755 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr); 756 // void _Unwind_Resume_or_Rethrow(void*) 757 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, 758 PtrTy, nullptr); 759 } else if (R.getVersion() >= VersionTuple(1, 7)) { 760 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 761 // id objc_begin_catch(void *e) 762 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr); 763 // void objc_end_catch(void) 764 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr); 765 // void _Unwind_Resume_or_Rethrow(void*) 766 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, 767 PtrTy, nullptr); 768 } 769 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 770 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy, 771 SelectorTy, IdTy, PtrDiffTy, nullptr); 772 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy, 773 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr); 774 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy, 775 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr); 776 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy", 777 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr); 778 // void objc_setCppObjectAtomic(void *dest, const void *src, void 779 // *helper); 780 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy, 781 PtrTy, PtrTy, nullptr); 782 // void objc_getCppObjectAtomic(void *dest, const void *src, void 783 // *helper); 784 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy, 785 PtrTy, PtrTy, nullptr); 786 } 787 788 llvm::Constant *GetCppAtomicObjectGetFunction() override { 789 // The optimised functions were added in version 1.7 of the GNUstep 790 // runtime. 791 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 792 VersionTuple(1, 7)); 793 return CxxAtomicObjectGetFn; 794 } 795 796 llvm::Constant *GetCppAtomicObjectSetFunction() override { 797 // The optimised functions were added in version 1.7 of the GNUstep 798 // runtime. 799 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 800 VersionTuple(1, 7)); 801 return CxxAtomicObjectSetFn; 802 } 803 804 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, 805 bool copy) override { 806 // The optimised property functions omit the GC check, and so are not 807 // safe to use in GC mode. The standard functions are fast in GC mode, 808 // so there is less advantage in using them. 809 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC)); 810 // The optimised functions were added in version 1.7 of the GNUstep 811 // runtime. 812 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 813 VersionTuple(1, 7)); 814 815 if (atomic) { 816 if (copy) return SetPropertyAtomicCopy; 817 return SetPropertyAtomic; 818 } 819 820 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic; 821 } 822 }; 823 824 /// Support for the ObjFW runtime. 825 class CGObjCObjFW: public CGObjCGNU { 826 protected: 827 /// The GCC ABI message lookup function. Returns an IMP pointing to the 828 /// method implementation for this message. 829 LazyRuntimeFunction MsgLookupFn; 830 /// stret lookup function. While this does not seem to make sense at the 831 /// first look, this is required to call the correct forwarding function. 832 LazyRuntimeFunction MsgLookupFnSRet; 833 /// The GCC ABI superclass message lookup function. Takes a pointer to a 834 /// structure describing the receiver and the class, and a selector as 835 /// arguments. Returns the IMP for the corresponding method. 836 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet; 837 838 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 839 llvm::Value *cmd, llvm::MDNode *node, 840 MessageSendInfo &MSI) override { 841 CGBuilderTy &Builder = CGF.Builder; 842 llvm::Value *args[] = { 843 EnforceType(Builder, Receiver, IdTy), 844 EnforceType(Builder, cmd, SelectorTy) }; 845 846 llvm::CallSite imp; 847 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 848 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args); 849 else 850 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args); 851 852 imp->setMetadata(msgSendMDKind, node); 853 return imp.getInstruction(); 854 } 855 856 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 857 llvm::Value *cmd, MessageSendInfo &MSI) override { 858 CGBuilderTy &Builder = CGF.Builder; 859 llvm::Value *lookupArgs[] = { 860 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd, 861 }; 862 863 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 864 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs); 865 else 866 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 867 } 868 869 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name, 870 bool isWeak) override { 871 if (isWeak) 872 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak); 873 874 EmitClassRef(Name); 875 std::string SymbolName = "_OBJC_CLASS_" + Name; 876 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName); 877 if (!ClassSymbol) 878 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 879 llvm::GlobalValue::ExternalLinkage, 880 nullptr, SymbolName); 881 return ClassSymbol; 882 } 883 884 public: 885 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) { 886 // IMP objc_msg_lookup(id, SEL); 887 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr); 888 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy, 889 SelectorTy, nullptr); 890 // IMP objc_msg_lookup_super(struct objc_super*, SEL); 891 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 892 PtrToObjCSuperTy, SelectorTy, nullptr); 893 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy, 894 PtrToObjCSuperTy, SelectorTy, nullptr); 895 } 896 }; 897 } // end anonymous namespace 898 899 /// Emits a reference to a dummy variable which is emitted with each class. 900 /// This ensures that a linker error will be generated when trying to link 901 /// together modules where a referenced class is not defined. 902 void CGObjCGNU::EmitClassRef(const std::string &className) { 903 std::string symbolRef = "__objc_class_ref_" + className; 904 // Don't emit two copies of the same symbol 905 if (TheModule.getGlobalVariable(symbolRef)) 906 return; 907 std::string symbolName = "__objc_class_name_" + className; 908 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName); 909 if (!ClassSymbol) { 910 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 911 llvm::GlobalValue::ExternalLinkage, 912 nullptr, symbolName); 913 } 914 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true, 915 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef); 916 } 917 918 static std::string SymbolNameForMethod( StringRef ClassName, 919 StringRef CategoryName, const Selector MethodName, 920 bool isClassMethod) { 921 std::string MethodNameColonStripped = MethodName.getAsString(); 922 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(), 923 ':', '_'); 924 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" + 925 CategoryName + "_" + MethodNameColonStripped).str(); 926 } 927 928 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, 929 unsigned protocolClassVersion) 930 : CGObjCRuntime(cgm), TheModule(CGM.getModule()), 931 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr), 932 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion), 933 ProtocolVersion(protocolClassVersion) { 934 935 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend"); 936 937 CodeGenTypes &Types = CGM.getTypes(); 938 IntTy = cast<llvm::IntegerType>( 939 Types.ConvertType(CGM.getContext().IntTy)); 940 LongTy = cast<llvm::IntegerType>( 941 Types.ConvertType(CGM.getContext().LongTy)); 942 SizeTy = cast<llvm::IntegerType>( 943 Types.ConvertType(CGM.getContext().getSizeType())); 944 PtrDiffTy = cast<llvm::IntegerType>( 945 Types.ConvertType(CGM.getContext().getPointerDiffType())); 946 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 947 948 Int8Ty = llvm::Type::getInt8Ty(VMContext); 949 // C string type. Used in lots of places. 950 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty); 951 952 Zeros[0] = llvm::ConstantInt::get(LongTy, 0); 953 Zeros[1] = Zeros[0]; 954 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty); 955 // Get the selector Type. 956 QualType selTy = CGM.getContext().getObjCSelType(); 957 if (QualType() == selTy) { 958 SelectorTy = PtrToInt8Ty; 959 } else { 960 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy)); 961 } 962 963 PtrToIntTy = llvm::PointerType::getUnqual(IntTy); 964 PtrTy = PtrToInt8Ty; 965 966 Int32Ty = llvm::Type::getInt32Ty(VMContext); 967 Int64Ty = llvm::Type::getInt64Ty(VMContext); 968 969 IntPtrTy = 970 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty; 971 972 // Object type 973 QualType UnqualIdTy = CGM.getContext().getObjCIdType(); 974 ASTIdTy = CanQualType(); 975 if (UnqualIdTy != QualType()) { 976 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy); 977 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 978 } else { 979 IdTy = PtrToInt8Ty; 980 } 981 PtrToIdTy = llvm::PointerType::getUnqual(IdTy); 982 983 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr); 984 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy); 985 986 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 987 988 // void objc_exception_throw(id); 989 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr); 990 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr); 991 // int objc_sync_enter(id); 992 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr); 993 // int objc_sync_exit(id); 994 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr); 995 996 // void objc_enumerationMutation (id) 997 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, 998 IdTy, nullptr); 999 1000 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL) 1001 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy, 1002 PtrDiffTy, BoolTy, nullptr); 1003 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL) 1004 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy, 1005 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr); 1006 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) 1007 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy, 1008 PtrDiffTy, BoolTy, BoolTy, nullptr); 1009 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) 1010 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy, 1011 PtrDiffTy, BoolTy, BoolTy, nullptr); 1012 1013 // IMP type 1014 llvm::Type *IMPArgs[] = { IdTy, SelectorTy }; 1015 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs, 1016 true)); 1017 1018 const LangOptions &Opts = CGM.getLangOpts(); 1019 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount) 1020 RuntimeVersion = 10; 1021 1022 // Don't bother initialising the GC stuff unless we're compiling in GC mode 1023 if (Opts.getGC() != LangOptions::NonGC) { 1024 // This is a bit of an hack. We should sort this out by having a proper 1025 // CGObjCGNUstep subclass for GC, but we may want to really support the old 1026 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now 1027 // Get selectors needed in GC mode 1028 RetainSel = GetNullarySelector("retain", CGM.getContext()); 1029 ReleaseSel = GetNullarySelector("release", CGM.getContext()); 1030 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext()); 1031 1032 // Get functions needed in GC mode 1033 1034 // id objc_assign_ivar(id, id, ptrdiff_t); 1035 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy, 1036 nullptr); 1037 // id objc_assign_strongCast (id, id*) 1038 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy, 1039 PtrToIdTy, nullptr); 1040 // id objc_assign_global(id, id*); 1041 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy, 1042 nullptr); 1043 // id objc_assign_weak(id, id*); 1044 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr); 1045 // id objc_read_weak(id*); 1046 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr); 1047 // void *objc_memmove_collectable(void*, void *, size_t); 1048 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy, 1049 SizeTy, nullptr); 1050 } 1051 } 1052 1053 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF, 1054 const std::string &Name, bool isWeak) { 1055 llvm::Constant *ClassName = MakeConstantString(Name); 1056 // With the incompatible ABI, this will need to be replaced with a direct 1057 // reference to the class symbol. For the compatible nonfragile ABI we are 1058 // still performing this lookup at run time but emitting the symbol for the 1059 // class externally so that we can make the switch later. 1060 // 1061 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class 1062 // with memoized versions or with static references if it's safe to do so. 1063 if (!isWeak) 1064 EmitClassRef(Name); 1065 1066 llvm::Constant *ClassLookupFn = 1067 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), 1068 "objc_lookup_class"); 1069 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName); 1070 } 1071 1072 // This has to perform the lookup every time, since posing and related 1073 // techniques can modify the name -> class mapping. 1074 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF, 1075 const ObjCInterfaceDecl *OID) { 1076 auto *Value = 1077 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported()); 1078 if (CGM.getTriple().isOSBinFormatCOFF()) { 1079 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) { 1080 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass; 1081 if (OID->hasAttr<DLLExportAttr>()) 1082 DLLStorage = llvm::GlobalValue::DLLExportStorageClass; 1083 else if (OID->hasAttr<DLLImportAttr>()) 1084 DLLStorage = llvm::GlobalValue::DLLImportStorageClass; 1085 ClassSymbol->setDLLStorageClass(DLLStorage); 1086 } 1087 } 1088 return Value; 1089 } 1090 1091 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { 1092 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false); 1093 if (CGM.getTriple().isOSBinFormatCOFF()) { 1094 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) { 1095 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool"); 1096 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); 1097 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 1098 1099 const VarDecl *VD = nullptr; 1100 for (const auto &Result : DC->lookup(&II)) 1101 if ((VD = dyn_cast<VarDecl>(Result))) 1102 break; 1103 1104 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass; 1105 if (!VD || VD->hasAttr<DLLImportAttr>()) 1106 DLLStorage = llvm::GlobalValue::DLLImportStorageClass; 1107 else if (VD->hasAttr<DLLExportAttr>()) 1108 DLLStorage = llvm::GlobalValue::DLLExportStorageClass; 1109 1110 ClassSymbol->setDLLStorageClass(DLLStorage); 1111 } 1112 } 1113 return Value; 1114 } 1115 1116 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel, 1117 const std::string &TypeEncoding) { 1118 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel]; 1119 llvm::GlobalAlias *SelValue = nullptr; 1120 1121 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(), 1122 e = Types.end() ; i!=e ; i++) { 1123 if (i->first == TypeEncoding) { 1124 SelValue = i->second; 1125 break; 1126 } 1127 } 1128 if (!SelValue) { 1129 SelValue = llvm::GlobalAlias::create( 1130 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage, 1131 ".objc_selector_" + Sel.getAsString(), &TheModule); 1132 Types.emplace_back(TypeEncoding, SelValue); 1133 } 1134 1135 return SelValue; 1136 } 1137 1138 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) { 1139 llvm::Value *SelValue = GetSelector(CGF, Sel); 1140 1141 // Store it to a temporary. Does this satisfy the semantics of 1142 // GetAddrOfSelector? Hopefully. 1143 Address tmp = CGF.CreateTempAlloca(SelValue->getType(), 1144 CGF.getPointerAlign()); 1145 CGF.Builder.CreateStore(SelValue, tmp); 1146 return tmp; 1147 } 1148 1149 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) { 1150 return GetSelector(CGF, Sel, std::string()); 1151 } 1152 1153 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, 1154 const ObjCMethodDecl *Method) { 1155 std::string SelTypes; 1156 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes); 1157 return GetSelector(CGF, Method->getSelector(), SelTypes); 1158 } 1159 1160 llvm::Constant *CGObjCGNU::GetEHType(QualType T) { 1161 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) { 1162 // With the old ABI, there was only one kind of catchall, which broke 1163 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as 1164 // a pointer indicating object catchalls, and NULL to indicate real 1165 // catchalls 1166 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 1167 return MakeConstantString("@id"); 1168 } else { 1169 return nullptr; 1170 } 1171 } 1172 1173 // All other types should be Objective-C interface pointer types. 1174 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>(); 1175 assert(OPT && "Invalid @catch type."); 1176 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface(); 1177 assert(IDecl && "Invalid @catch type."); 1178 return MakeConstantString(IDecl->getIdentifier()->getName()); 1179 } 1180 1181 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) { 1182 if (!CGM.getLangOpts().CPlusPlus) 1183 return CGObjCGNU::GetEHType(T); 1184 1185 // For Objective-C++, we want to provide the ability to catch both C++ and 1186 // Objective-C objects in the same function. 1187 1188 // There's a particular fixed type info for 'id'. 1189 if (T->isObjCIdType() || 1190 T->isObjCQualifiedIdType()) { 1191 llvm::Constant *IDEHType = 1192 CGM.getModule().getGlobalVariable("__objc_id_type_info"); 1193 if (!IDEHType) 1194 IDEHType = 1195 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty, 1196 false, 1197 llvm::GlobalValue::ExternalLinkage, 1198 nullptr, "__objc_id_type_info"); 1199 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty); 1200 } 1201 1202 const ObjCObjectPointerType *PT = 1203 T->getAs<ObjCObjectPointerType>(); 1204 assert(PT && "Invalid @catch type."); 1205 const ObjCInterfaceType *IT = PT->getInterfaceType(); 1206 assert(IT && "Invalid @catch type."); 1207 std::string className = IT->getDecl()->getIdentifier()->getName(); 1208 1209 std::string typeinfoName = "__objc_eh_typeinfo_" + className; 1210 1211 // Return the existing typeinfo if it exists 1212 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName); 1213 if (typeinfo) 1214 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty); 1215 1216 // Otherwise create it. 1217 1218 // vtable for gnustep::libobjc::__objc_class_type_info 1219 // It's quite ugly hard-coding this. Ideally we'd generate it using the host 1220 // platform's name mangling. 1221 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE"; 1222 auto *Vtable = TheModule.getGlobalVariable(vtableName); 1223 if (!Vtable) { 1224 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true, 1225 llvm::GlobalValue::ExternalLinkage, 1226 nullptr, vtableName); 1227 } 1228 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2); 1229 auto *BVtable = llvm::ConstantExpr::getBitCast( 1230 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two), 1231 PtrToInt8Ty); 1232 1233 llvm::Constant *typeName = 1234 ExportUniqueString(className, "__objc_eh_typename_"); 1235 1236 std::vector<llvm::Constant*> fields; 1237 fields.push_back(BVtable); 1238 fields.push_back(typeName); 1239 llvm::Constant *TI = 1240 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr), 1241 fields, CGM.getPointerAlign(), 1242 "__objc_eh_typeinfo_" + className, 1243 llvm::GlobalValue::LinkOnceODRLinkage); 1244 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty); 1245 } 1246 1247 /// Generate an NSConstantString object. 1248 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) { 1249 1250 std::string Str = SL->getString().str(); 1251 CharUnits Align = CGM.getPointerAlign(); 1252 1253 // Look for an existing one 1254 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str); 1255 if (old != ObjCStrings.end()) 1256 return ConstantAddress(old->getValue(), Align); 1257 1258 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass; 1259 1260 if (StringClass.empty()) StringClass = "NXConstantString"; 1261 1262 std::string Sym = "_OBJC_CLASS_"; 1263 Sym += StringClass; 1264 1265 llvm::Constant *isa = TheModule.getNamedGlobal(Sym); 1266 1267 if (!isa) 1268 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false, 1269 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym); 1270 else if (isa->getType() != PtrToIdTy) 1271 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy); 1272 1273 std::vector<llvm::Constant*> Ivars; 1274 Ivars.push_back(isa); 1275 Ivars.push_back(MakeConstantString(Str)); 1276 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size())); 1277 llvm::Constant *ObjCStr = MakeGlobal( 1278 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr), 1279 Ivars, Align, ".objc_str"); 1280 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty); 1281 ObjCStrings[Str] = ObjCStr; 1282 ConstantStrings.push_back(ObjCStr); 1283 return ConstantAddress(ObjCStr, Align); 1284 } 1285 1286 ///Generates a message send where the super is the receiver. This is a message 1287 ///send to self with special delivery semantics indicating which class's method 1288 ///should be called. 1289 RValue 1290 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF, 1291 ReturnValueSlot Return, 1292 QualType ResultType, 1293 Selector Sel, 1294 const ObjCInterfaceDecl *Class, 1295 bool isCategoryImpl, 1296 llvm::Value *Receiver, 1297 bool IsClassMessage, 1298 const CallArgList &CallArgs, 1299 const ObjCMethodDecl *Method) { 1300 CGBuilderTy &Builder = CGF.Builder; 1301 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 1302 if (Sel == RetainSel || Sel == AutoreleaseSel) { 1303 return RValue::get(EnforceType(Builder, Receiver, 1304 CGM.getTypes().ConvertType(ResultType))); 1305 } 1306 if (Sel == ReleaseSel) { 1307 return RValue::get(nullptr); 1308 } 1309 } 1310 1311 llvm::Value *cmd = GetSelector(CGF, Sel); 1312 CallArgList ActualArgs; 1313 1314 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy); 1315 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType()); 1316 ActualArgs.addFrom(CallArgs); 1317 1318 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 1319 1320 llvm::Value *ReceiverClass = nullptr; 1321 if (isCategoryImpl) { 1322 llvm::Constant *classLookupFunction = nullptr; 1323 if (IsClassMessage) { 1324 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 1325 IdTy, PtrTy, true), "objc_get_meta_class"); 1326 } else { 1327 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 1328 IdTy, PtrTy, true), "objc_get_class"); 1329 } 1330 ReceiverClass = Builder.CreateCall(classLookupFunction, 1331 MakeConstantString(Class->getNameAsString())); 1332 } else { 1333 // Set up global aliases for the metaclass or class pointer if they do not 1334 // already exist. These will are forward-references which will be set to 1335 // pointers to the class and metaclass structure created for the runtime 1336 // load function. To send a message to super, we look up the value of the 1337 // super_class pointer from either the class or metaclass structure. 1338 if (IsClassMessage) { 1339 if (!MetaClassPtrAlias) { 1340 MetaClassPtrAlias = llvm::GlobalAlias::create( 1341 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage, 1342 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule); 1343 } 1344 ReceiverClass = MetaClassPtrAlias; 1345 } else { 1346 if (!ClassPtrAlias) { 1347 ClassPtrAlias = llvm::GlobalAlias::create( 1348 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage, 1349 ".objc_class_ref" + Class->getNameAsString(), &TheModule); 1350 } 1351 ReceiverClass = ClassPtrAlias; 1352 } 1353 } 1354 // Cast the pointer to a simplified version of the class structure 1355 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr); 1356 ReceiverClass = Builder.CreateBitCast(ReceiverClass, 1357 llvm::PointerType::getUnqual(CastTy)); 1358 // Get the superclass pointer 1359 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1); 1360 // Load the superclass pointer 1361 ReceiverClass = 1362 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign()); 1363 // Construct the structure used to look up the IMP 1364 llvm::StructType *ObjCSuperTy = llvm::StructType::get( 1365 Receiver->getType(), IdTy, nullptr); 1366 1367 // FIXME: Is this really supposed to be a dynamic alloca? 1368 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy), 1369 CGF.getPointerAlign()); 1370 1371 Builder.CreateStore(Receiver, 1372 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero())); 1373 Builder.CreateStore(ReceiverClass, 1374 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize())); 1375 1376 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy); 1377 1378 // Get the IMP 1379 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI); 1380 imp = EnforceType(Builder, imp, MSI.MessengerType); 1381 1382 llvm::Metadata *impMD[] = { 1383 llvm::MDString::get(VMContext, Sel.getAsString()), 1384 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()), 1385 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1386 llvm::Type::getInt1Ty(VMContext), IsClassMessage))}; 1387 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD); 1388 1389 CGCallee callee(CGCalleeInfo(), imp); 1390 1391 llvm::Instruction *call; 1392 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call); 1393 call->setMetadata(msgSendMDKind, node); 1394 return msgRet; 1395 } 1396 1397 /// Generate code for a message send expression. 1398 RValue 1399 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, 1400 ReturnValueSlot Return, 1401 QualType ResultType, 1402 Selector Sel, 1403 llvm::Value *Receiver, 1404 const CallArgList &CallArgs, 1405 const ObjCInterfaceDecl *Class, 1406 const ObjCMethodDecl *Method) { 1407 CGBuilderTy &Builder = CGF.Builder; 1408 1409 // Strip out message sends to retain / release in GC mode 1410 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 1411 if (Sel == RetainSel || Sel == AutoreleaseSel) { 1412 return RValue::get(EnforceType(Builder, Receiver, 1413 CGM.getTypes().ConvertType(ResultType))); 1414 } 1415 if (Sel == ReleaseSel) { 1416 return RValue::get(nullptr); 1417 } 1418 } 1419 1420 // If the return type is something that goes in an integer register, the 1421 // runtime will handle 0 returns. For other cases, we fill in the 0 value 1422 // ourselves. 1423 // 1424 // The language spec says the result of this kind of message send is 1425 // undefined, but lots of people seem to have forgotten to read that 1426 // paragraph and insist on sending messages to nil that have structure 1427 // returns. With GCC, this generates a random return value (whatever happens 1428 // to be on the stack / in those registers at the time) on most platforms, 1429 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts 1430 // the stack. 1431 bool isPointerSizedReturn = (ResultType->isAnyPointerType() || 1432 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType()); 1433 1434 llvm::BasicBlock *startBB = nullptr; 1435 llvm::BasicBlock *messageBB = nullptr; 1436 llvm::BasicBlock *continueBB = nullptr; 1437 1438 if (!isPointerSizedReturn) { 1439 startBB = Builder.GetInsertBlock(); 1440 messageBB = CGF.createBasicBlock("msgSend"); 1441 continueBB = CGF.createBasicBlock("continue"); 1442 1443 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 1444 llvm::Constant::getNullValue(Receiver->getType())); 1445 Builder.CreateCondBr(isNil, continueBB, messageBB); 1446 CGF.EmitBlock(messageBB); 1447 } 1448 1449 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 1450 llvm::Value *cmd; 1451 if (Method) 1452 cmd = GetSelector(CGF, Method); 1453 else 1454 cmd = GetSelector(CGF, Sel); 1455 cmd = EnforceType(Builder, cmd, SelectorTy); 1456 Receiver = EnforceType(Builder, Receiver, IdTy); 1457 1458 llvm::Metadata *impMD[] = { 1459 llvm::MDString::get(VMContext, Sel.getAsString()), 1460 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""), 1461 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1462 llvm::Type::getInt1Ty(VMContext), Class != nullptr))}; 1463 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD); 1464 1465 CallArgList ActualArgs; 1466 ActualArgs.add(RValue::get(Receiver), ASTIdTy); 1467 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType()); 1468 ActualArgs.addFrom(CallArgs); 1469 1470 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 1471 1472 // Get the IMP to call 1473 llvm::Value *imp; 1474 1475 // If we have non-legacy dispatch specified, we try using the objc_msgSend() 1476 // functions. These are not supported on all platforms (or all runtimes on a 1477 // given platform), so we 1478 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { 1479 case CodeGenOptions::Legacy: 1480 imp = LookupIMP(CGF, Receiver, cmd, node, MSI); 1481 break; 1482 case CodeGenOptions::Mixed: 1483 case CodeGenOptions::NonLegacy: 1484 if (CGM.ReturnTypeUsesFPRet(ResultType)) { 1485 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 1486 "objc_msgSend_fpret"); 1487 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) { 1488 // The actual types here don't matter - we're going to bitcast the 1489 // function anyway 1490 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 1491 "objc_msgSend_stret"); 1492 } else { 1493 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 1494 "objc_msgSend"); 1495 } 1496 } 1497 1498 // Reset the receiver in case the lookup modified it 1499 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false); 1500 1501 imp = EnforceType(Builder, imp, MSI.MessengerType); 1502 1503 llvm::Instruction *call; 1504 CGCallee callee(CGCalleeInfo(), imp); 1505 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call); 1506 call->setMetadata(msgSendMDKind, node); 1507 1508 1509 if (!isPointerSizedReturn) { 1510 messageBB = CGF.Builder.GetInsertBlock(); 1511 CGF.Builder.CreateBr(continueBB); 1512 CGF.EmitBlock(continueBB); 1513 if (msgRet.isScalar()) { 1514 llvm::Value *v = msgRet.getScalarVal(); 1515 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2); 1516 phi->addIncoming(v, messageBB); 1517 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB); 1518 msgRet = RValue::get(phi); 1519 } else if (msgRet.isAggregate()) { 1520 Address v = msgRet.getAggregateAddress(); 1521 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2); 1522 llvm::Type *RetTy = v.getElementType(); 1523 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null"); 1524 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy)); 1525 phi->addIncoming(v.getPointer(), messageBB); 1526 phi->addIncoming(NullVal.getPointer(), startBB); 1527 msgRet = RValue::getAggregate(Address(phi, v.getAlignment())); 1528 } else /* isComplex() */ { 1529 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal(); 1530 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2); 1531 phi->addIncoming(v.first, messageBB); 1532 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()), 1533 startBB); 1534 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2); 1535 phi2->addIncoming(v.second, messageBB); 1536 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()), 1537 startBB); 1538 msgRet = RValue::getComplex(phi, phi2); 1539 } 1540 } 1541 return msgRet; 1542 } 1543 1544 /// Generates a MethodList. Used in construction of a objc_class and 1545 /// objc_category structures. 1546 llvm::Constant *CGObjCGNU:: 1547 GenerateMethodList(StringRef ClassName, 1548 StringRef CategoryName, 1549 ArrayRef<Selector> MethodSels, 1550 ArrayRef<llvm::Constant *> MethodTypes, 1551 bool isClassMethodList) { 1552 if (MethodSels.empty()) 1553 return NULLPtr; 1554 // Get the method structure type. 1555 llvm::StructType *ObjCMethodTy = llvm::StructType::get( 1556 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 1557 PtrToInt8Ty, // Method types 1558 IMPTy, //Method pointer 1559 nullptr); 1560 std::vector<llvm::Constant*> Methods; 1561 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) { 1562 llvm::Constant *Method = 1563 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName, 1564 MethodSels[i], 1565 isClassMethodList)); 1566 assert(Method && "Can't generate metadata for method that doesn't exist"); 1567 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString()); 1568 Method = llvm::ConstantExpr::getBitCast(Method, 1569 IMPTy); 1570 Methods.push_back( 1571 llvm::ConstantStruct::get(ObjCMethodTy, {C, MethodTypes[i], Method})); 1572 } 1573 1574 // Array of method structures 1575 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy, 1576 Methods.size()); 1577 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy, 1578 Methods); 1579 1580 // Structure containing list pointer, array and array count 1581 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext); 1582 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy); 1583 ObjCMethodListTy->setBody( 1584 NextPtrTy, 1585 IntTy, 1586 ObjCMethodArrayTy, 1587 nullptr); 1588 1589 Methods.clear(); 1590 Methods.push_back(llvm::ConstantPointerNull::get( 1591 llvm::PointerType::getUnqual(ObjCMethodListTy))); 1592 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size())); 1593 Methods.push_back(MethodArray); 1594 1595 // Create an instance of the structure 1596 return MakeGlobal(ObjCMethodListTy, Methods, CGM.getPointerAlign(), 1597 ".objc_method_list"); 1598 } 1599 1600 /// Generates an IvarList. Used in construction of a objc_class. 1601 llvm::Constant *CGObjCGNU:: 1602 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 1603 ArrayRef<llvm::Constant *> IvarTypes, 1604 ArrayRef<llvm::Constant *> IvarOffsets) { 1605 if (IvarNames.size() == 0) 1606 return NULLPtr; 1607 // Get the method structure type. 1608 llvm::StructType *ObjCIvarTy = llvm::StructType::get( 1609 PtrToInt8Ty, 1610 PtrToInt8Ty, 1611 IntTy, 1612 nullptr); 1613 std::vector<llvm::Constant*> Ivars; 1614 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) { 1615 Ivars.push_back(llvm::ConstantStruct::get( 1616 ObjCIvarTy, {IvarNames[i], IvarTypes[i], IvarOffsets[i]})); 1617 } 1618 1619 // Array of method structures 1620 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy, 1621 IvarNames.size()); 1622 1623 llvm::Constant *Elements[] = { 1624 llvm::ConstantInt::get(IntTy, (int)IvarNames.size()), 1625 llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)}; 1626 // Structure containing array and array count 1627 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy, 1628 ObjCIvarArrayTy, 1629 nullptr); 1630 1631 // Create an instance of the structure 1632 return MakeGlobal(ObjCIvarListTy, Elements, CGM.getPointerAlign(), 1633 ".objc_ivar_list"); 1634 } 1635 1636 /// Generate a class structure 1637 llvm::Constant *CGObjCGNU::GenerateClassStructure( 1638 llvm::Constant *MetaClass, 1639 llvm::Constant *SuperClass, 1640 unsigned info, 1641 const char *Name, 1642 llvm::Constant *Version, 1643 llvm::Constant *InstanceSize, 1644 llvm::Constant *IVars, 1645 llvm::Constant *Methods, 1646 llvm::Constant *Protocols, 1647 llvm::Constant *IvarOffsets, 1648 llvm::Constant *Properties, 1649 llvm::Constant *StrongIvarBitmap, 1650 llvm::Constant *WeakIvarBitmap, 1651 bool isMeta) { 1652 // Set up the class structure 1653 // Note: Several of these are char*s when they should be ids. This is 1654 // because the runtime performs this translation on load. 1655 // 1656 // Fields marked New ABI are part of the GNUstep runtime. We emit them 1657 // anyway; the classes will still work with the GNU runtime, they will just 1658 // be ignored. 1659 llvm::StructType *ClassTy = llvm::StructType::get( 1660 PtrToInt8Ty, // isa 1661 PtrToInt8Ty, // super_class 1662 PtrToInt8Ty, // name 1663 LongTy, // version 1664 LongTy, // info 1665 LongTy, // instance_size 1666 IVars->getType(), // ivars 1667 Methods->getType(), // methods 1668 // These are all filled in by the runtime, so we pretend 1669 PtrTy, // dtable 1670 PtrTy, // subclass_list 1671 PtrTy, // sibling_class 1672 PtrTy, // protocols 1673 PtrTy, // gc_object_type 1674 // New ABI: 1675 LongTy, // abi_version 1676 IvarOffsets->getType(), // ivar_offsets 1677 Properties->getType(), // properties 1678 IntPtrTy, // strong_pointers 1679 IntPtrTy, // weak_pointers 1680 nullptr); 1681 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0); 1682 // Fill in the structure 1683 std::vector<llvm::Constant*> Elements; 1684 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty)); 1685 Elements.push_back(SuperClass); 1686 Elements.push_back(MakeConstantString(Name, ".class_name")); 1687 Elements.push_back(Zero); 1688 Elements.push_back(llvm::ConstantInt::get(LongTy, info)); 1689 if (isMeta) { 1690 llvm::DataLayout td(&TheModule); 1691 Elements.push_back( 1692 llvm::ConstantInt::get(LongTy, 1693 td.getTypeSizeInBits(ClassTy) / 1694 CGM.getContext().getCharWidth())); 1695 } else 1696 Elements.push_back(InstanceSize); 1697 Elements.push_back(IVars); 1698 Elements.push_back(Methods); 1699 Elements.push_back(NULLPtr); 1700 Elements.push_back(NULLPtr); 1701 Elements.push_back(NULLPtr); 1702 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy)); 1703 Elements.push_back(NULLPtr); 1704 Elements.push_back(llvm::ConstantInt::get(LongTy, 1)); 1705 Elements.push_back(IvarOffsets); 1706 Elements.push_back(Properties); 1707 Elements.push_back(StrongIvarBitmap); 1708 Elements.push_back(WeakIvarBitmap); 1709 // Create an instance of the structure 1710 // This is now an externally visible symbol, so that we can speed up class 1711 // messages in the next ABI. We may already have some weak references to 1712 // this, so check and fix them properly. 1713 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") + 1714 std::string(Name)); 1715 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym); 1716 llvm::Constant *Class = 1717 MakeGlobal(ClassTy, Elements, CGM.getPointerAlign(), ClassSym, 1718 llvm::GlobalValue::ExternalLinkage); 1719 if (ClassRef) { 1720 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class, 1721 ClassRef->getType())); 1722 ClassRef->removeFromParent(); 1723 Class->setName(ClassSym); 1724 } 1725 return Class; 1726 } 1727 1728 llvm::Constant *CGObjCGNU:: 1729 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames, 1730 ArrayRef<llvm::Constant *> MethodTypes) { 1731 // Get the method structure type. 1732 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get( 1733 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us. 1734 PtrToInt8Ty, 1735 nullptr); 1736 std::vector<llvm::Constant*> Methods; 1737 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) { 1738 Methods.push_back(llvm::ConstantStruct::get( 1739 ObjCMethodDescTy, {MethodNames[i], MethodTypes[i]})); 1740 } 1741 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy, 1742 MethodNames.size()); 1743 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, 1744 Methods); 1745 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get( 1746 IntTy, ObjCMethodArrayTy, nullptr); 1747 Methods.clear(); 1748 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size())); 1749 Methods.push_back(Array); 1750 return MakeGlobal(ObjCMethodDescListTy, Methods, CGM.getPointerAlign(), 1751 ".objc_method_list"); 1752 } 1753 1754 // Create the protocol list structure used in classes, categories and so on 1755 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){ 1756 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 1757 Protocols.size()); 1758 llvm::StructType *ProtocolListTy = llvm::StructType::get( 1759 PtrTy, //Should be a recurisve pointer, but it's always NULL here. 1760 SizeTy, 1761 ProtocolArrayTy, 1762 nullptr); 1763 std::vector<llvm::Constant*> Elements; 1764 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); 1765 iter != endIter ; iter++) { 1766 llvm::Constant *protocol = nullptr; 1767 llvm::StringMap<llvm::Constant*>::iterator value = 1768 ExistingProtocols.find(*iter); 1769 if (value == ExistingProtocols.end()) { 1770 protocol = GenerateEmptyProtocol(*iter); 1771 } else { 1772 protocol = value->getValue(); 1773 } 1774 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol, 1775 PtrToInt8Ty); 1776 Elements.push_back(Ptr); 1777 } 1778 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 1779 Elements); 1780 Elements.clear(); 1781 Elements.push_back(NULLPtr); 1782 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size())); 1783 Elements.push_back(ProtocolArray); 1784 return MakeGlobal(ProtocolListTy, Elements, CGM.getPointerAlign(), 1785 ".objc_protocol_list"); 1786 } 1787 1788 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF, 1789 const ObjCProtocolDecl *PD) { 1790 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()]; 1791 llvm::Type *T = 1792 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); 1793 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); 1794 } 1795 1796 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol( 1797 const std::string &ProtocolName) { 1798 SmallVector<std::string, 0> EmptyStringVector; 1799 SmallVector<llvm::Constant*, 0> EmptyConstantVector; 1800 1801 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector); 1802 llvm::Constant *MethodList = 1803 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector); 1804 // Protocols are objects containing lists of the methods implemented and 1805 // protocols adopted. 1806 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy, 1807 PtrToInt8Ty, 1808 ProtocolList->getType(), 1809 MethodList->getType(), 1810 MethodList->getType(), 1811 MethodList->getType(), 1812 MethodList->getType(), 1813 nullptr); 1814 // The isa pointer must be set to a magic number so the runtime knows it's 1815 // the correct layout. 1816 llvm::Constant *Elements[] = { 1817 llvm::ConstantExpr::getIntToPtr( 1818 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy), 1819 MakeConstantString(ProtocolName, ".objc_protocol_name"), ProtocolList, 1820 MethodList, MethodList, MethodList, MethodList}; 1821 return MakeGlobal(ProtocolTy, Elements, CGM.getPointerAlign(), 1822 ".objc_protocol"); 1823 } 1824 1825 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { 1826 ASTContext &Context = CGM.getContext(); 1827 std::string ProtocolName = PD->getNameAsString(); 1828 1829 // Use the protocol definition, if there is one. 1830 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 1831 PD = Def; 1832 1833 SmallVector<std::string, 16> Protocols; 1834 for (const auto *PI : PD->protocols()) 1835 Protocols.push_back(PI->getNameAsString()); 1836 SmallVector<llvm::Constant*, 16> InstanceMethodNames; 1837 SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 1838 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames; 1839 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes; 1840 for (const auto *I : PD->instance_methods()) { 1841 std::string TypeStr; 1842 Context.getObjCEncodingForMethodDecl(I, TypeStr); 1843 if (I->getImplementationControl() == ObjCMethodDecl::Optional) { 1844 OptionalInstanceMethodNames.push_back( 1845 MakeConstantString(I->getSelector().getAsString())); 1846 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 1847 } else { 1848 InstanceMethodNames.push_back( 1849 MakeConstantString(I->getSelector().getAsString())); 1850 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 1851 } 1852 } 1853 // Collect information about class methods: 1854 SmallVector<llvm::Constant*, 16> ClassMethodNames; 1855 SmallVector<llvm::Constant*, 16> ClassMethodTypes; 1856 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames; 1857 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes; 1858 for (const auto *I : PD->class_methods()) { 1859 std::string TypeStr; 1860 Context.getObjCEncodingForMethodDecl(I,TypeStr); 1861 if (I->getImplementationControl() == ObjCMethodDecl::Optional) { 1862 OptionalClassMethodNames.push_back( 1863 MakeConstantString(I->getSelector().getAsString())); 1864 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr)); 1865 } else { 1866 ClassMethodNames.push_back( 1867 MakeConstantString(I->getSelector().getAsString())); 1868 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 1869 } 1870 } 1871 1872 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 1873 llvm::Constant *InstanceMethodList = 1874 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes); 1875 llvm::Constant *ClassMethodList = 1876 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes); 1877 llvm::Constant *OptionalInstanceMethodList = 1878 GenerateProtocolMethodList(OptionalInstanceMethodNames, 1879 OptionalInstanceMethodTypes); 1880 llvm::Constant *OptionalClassMethodList = 1881 GenerateProtocolMethodList(OptionalClassMethodNames, 1882 OptionalClassMethodTypes); 1883 1884 // Property metadata: name, attributes, isSynthesized, setter name, setter 1885 // types, getter name, getter types. 1886 // The isSynthesized value is always set to 0 in a protocol. It exists to 1887 // simplify the runtime library by allowing it to use the same data 1888 // structures for protocol metadata everywhere. 1889 llvm::StructType *PropertyMetadataTy = llvm::StructType::get( 1890 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, 1891 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr); 1892 std::vector<llvm::Constant*> Properties; 1893 std::vector<llvm::Constant*> OptionalProperties; 1894 1895 // Add all of the property methods need adding to the method list and to the 1896 // property metadata list. 1897 for (auto *property : PD->instance_properties()) { 1898 std::vector<llvm::Constant*> Fields; 1899 1900 Fields.push_back(MakePropertyEncodingString(property, nullptr)); 1901 PushPropertyAttributes(Fields, property); 1902 1903 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) { 1904 std::string TypeStr; 1905 Context.getObjCEncodingForMethodDecl(getter,TypeStr); 1906 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 1907 InstanceMethodTypes.push_back(TypeEncoding); 1908 Fields.push_back(MakeConstantString(getter->getSelector().getAsString())); 1909 Fields.push_back(TypeEncoding); 1910 } else { 1911 Fields.push_back(NULLPtr); 1912 Fields.push_back(NULLPtr); 1913 } 1914 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) { 1915 std::string TypeStr; 1916 Context.getObjCEncodingForMethodDecl(setter,TypeStr); 1917 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 1918 InstanceMethodTypes.push_back(TypeEncoding); 1919 Fields.push_back(MakeConstantString(setter->getSelector().getAsString())); 1920 Fields.push_back(TypeEncoding); 1921 } else { 1922 Fields.push_back(NULLPtr); 1923 Fields.push_back(NULLPtr); 1924 } 1925 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) { 1926 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields)); 1927 } else { 1928 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields)); 1929 } 1930 } 1931 llvm::Constant *PropertyArray = llvm::ConstantArray::get( 1932 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties); 1933 llvm::Constant* PropertyListInitFields[] = 1934 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray}; 1935 1936 llvm::Constant *PropertyListInit = 1937 llvm::ConstantStruct::getAnon(PropertyListInitFields); 1938 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule, 1939 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage, 1940 PropertyListInit, ".objc_property_list"); 1941 1942 llvm::Constant *OptionalPropertyArray = 1943 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy, 1944 OptionalProperties.size()) , OptionalProperties); 1945 llvm::Constant* OptionalPropertyListInitFields[] = { 1946 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr, 1947 OptionalPropertyArray }; 1948 1949 llvm::Constant *OptionalPropertyListInit = 1950 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields); 1951 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule, 1952 OptionalPropertyListInit->getType(), false, 1953 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit, 1954 ".objc_property_list"); 1955 1956 // Protocols are objects containing lists of the methods implemented and 1957 // protocols adopted. 1958 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy, 1959 PtrToInt8Ty, 1960 ProtocolList->getType(), 1961 InstanceMethodList->getType(), 1962 ClassMethodList->getType(), 1963 OptionalInstanceMethodList->getType(), 1964 OptionalClassMethodList->getType(), 1965 PropertyList->getType(), 1966 OptionalPropertyList->getType(), 1967 nullptr); 1968 // The isa pointer must be set to a magic number so the runtime knows it's 1969 // the correct layout. 1970 llvm::Constant *Elements[] = { 1971 llvm::ConstantExpr::getIntToPtr( 1972 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy), 1973 MakeConstantString(ProtocolName, ".objc_protocol_name"), ProtocolList, 1974 InstanceMethodList, ClassMethodList, OptionalInstanceMethodList, 1975 OptionalClassMethodList, PropertyList, OptionalPropertyList}; 1976 ExistingProtocols[ProtocolName] = 1977 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements, 1978 CGM.getPointerAlign(), ".objc_protocol"), IdTy); 1979 } 1980 void CGObjCGNU::GenerateProtocolHolderCategory() { 1981 // Collect information about instance methods 1982 SmallVector<Selector, 1> MethodSels; 1983 SmallVector<llvm::Constant*, 1> MethodTypes; 1984 1985 std::vector<llvm::Constant*> Elements; 1986 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack"; 1987 const std::string CategoryName = "AnotherHack"; 1988 Elements.push_back(MakeConstantString(CategoryName)); 1989 Elements.push_back(MakeConstantString(ClassName)); 1990 // Instance method list 1991 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 1992 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy)); 1993 // Class method list 1994 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 1995 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy)); 1996 // Protocol list 1997 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy, 1998 ExistingProtocols.size()); 1999 llvm::StructType *ProtocolListTy = llvm::StructType::get( 2000 PtrTy, //Should be a recurisve pointer, but it's always NULL here. 2001 SizeTy, 2002 ProtocolArrayTy, 2003 nullptr); 2004 std::vector<llvm::Constant*> ProtocolElements; 2005 for (llvm::StringMapIterator<llvm::Constant*> iter = 2006 ExistingProtocols.begin(), endIter = ExistingProtocols.end(); 2007 iter != endIter ; iter++) { 2008 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(), 2009 PtrTy); 2010 ProtocolElements.push_back(Ptr); 2011 } 2012 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 2013 ProtocolElements); 2014 ProtocolElements.clear(); 2015 ProtocolElements.push_back(NULLPtr); 2016 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy, 2017 ExistingProtocols.size())); 2018 ProtocolElements.push_back(ProtocolArray); 2019 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy, 2020 ProtocolElements, CGM.getPointerAlign(), 2021 ".objc_protocol_list"), PtrTy)); 2022 Categories.push_back(llvm::ConstantExpr::getBitCast( 2023 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, 2024 PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()), 2025 PtrTy)); 2026 } 2027 2028 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are 2029 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 2030 /// bits set to their values, LSB first, while larger ones are stored in a 2031 /// structure of this / form: 2032 /// 2033 /// struct { int32_t length; int32_t values[length]; }; 2034 /// 2035 /// The values in the array are stored in host-endian format, with the least 2036 /// significant bit being assumed to come first in the bitfield. Therefore, a 2037 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a 2038 /// bitfield / with the 63rd bit set will be 1<<64. 2039 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) { 2040 int bitCount = bits.size(); 2041 int ptrBits = CGM.getDataLayout().getPointerSizeInBits(); 2042 if (bitCount < ptrBits) { 2043 uint64_t val = 1; 2044 for (int i=0 ; i<bitCount ; ++i) { 2045 if (bits[i]) val |= 1ULL<<(i+1); 2046 } 2047 return llvm::ConstantInt::get(IntPtrTy, val); 2048 } 2049 SmallVector<llvm::Constant *, 8> values; 2050 int v=0; 2051 while (v < bitCount) { 2052 int32_t word = 0; 2053 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) { 2054 if (bits[v]) word |= 1<<i; 2055 v++; 2056 } 2057 values.push_back(llvm::ConstantInt::get(Int32Ty, word)); 2058 } 2059 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size()); 2060 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values); 2061 llvm::Constant *fields[2] = { 2062 llvm::ConstantInt::get(Int32Ty, values.size()), 2063 array }; 2064 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy, 2065 nullptr), fields, CharUnits::fromQuantity(4)); 2066 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy); 2067 return ptr; 2068 } 2069 2070 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 2071 std::string ClassName = OCD->getClassInterface()->getNameAsString(); 2072 std::string CategoryName = OCD->getNameAsString(); 2073 // Collect information about instance methods 2074 SmallVector<Selector, 16> InstanceMethodSels; 2075 SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 2076 for (const auto *I : OCD->instance_methods()) { 2077 InstanceMethodSels.push_back(I->getSelector()); 2078 std::string TypeStr; 2079 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr); 2080 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 2081 } 2082 2083 // Collect information about class methods 2084 SmallVector<Selector, 16> ClassMethodSels; 2085 SmallVector<llvm::Constant*, 16> ClassMethodTypes; 2086 for (const auto *I : OCD->class_methods()) { 2087 ClassMethodSels.push_back(I->getSelector()); 2088 std::string TypeStr; 2089 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr); 2090 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 2091 } 2092 2093 // Collect the names of referenced protocols 2094 SmallVector<std::string, 16> Protocols; 2095 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl(); 2096 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols(); 2097 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 2098 E = Protos.end(); I != E; ++I) 2099 Protocols.push_back((*I)->getNameAsString()); 2100 2101 llvm::Constant *Elements[] = { 2102 MakeConstantString(CategoryName), MakeConstantString(ClassName), 2103 // Instance method list 2104 llvm::ConstantExpr::getBitCast( 2105 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels, 2106 InstanceMethodTypes, false), 2107 PtrTy), 2108 // Class method list 2109 llvm::ConstantExpr::getBitCast(GenerateMethodList(ClassName, CategoryName, 2110 ClassMethodSels, 2111 ClassMethodTypes, true), 2112 PtrTy), 2113 // Protocol list 2114 llvm::ConstantExpr::getBitCast(GenerateProtocolList(Protocols), PtrTy)}; 2115 Categories.push_back(llvm::ConstantExpr::getBitCast( 2116 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, 2117 PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()), 2118 PtrTy)); 2119 } 2120 2121 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID, 2122 SmallVectorImpl<Selector> &InstanceMethodSels, 2123 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) { 2124 ASTContext &Context = CGM.getContext(); 2125 // Property metadata: name, attributes, attributes2, padding1, padding2, 2126 // setter name, setter types, getter name, getter types. 2127 llvm::StructType *PropertyMetadataTy = llvm::StructType::get( 2128 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, 2129 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr); 2130 std::vector<llvm::Constant*> Properties; 2131 2132 // Add all of the property methods need adding to the method list and to the 2133 // property metadata list. 2134 for (auto *propertyImpl : OID->property_impls()) { 2135 std::vector<llvm::Constant*> Fields; 2136 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl(); 2137 bool isSynthesized = (propertyImpl->getPropertyImplementation() == 2138 ObjCPropertyImplDecl::Synthesize); 2139 bool isDynamic = (propertyImpl->getPropertyImplementation() == 2140 ObjCPropertyImplDecl::Dynamic); 2141 2142 Fields.push_back(MakePropertyEncodingString(property, OID)); 2143 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic); 2144 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) { 2145 std::string TypeStr; 2146 Context.getObjCEncodingForMethodDecl(getter,TypeStr); 2147 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 2148 if (isSynthesized) { 2149 InstanceMethodTypes.push_back(TypeEncoding); 2150 InstanceMethodSels.push_back(getter->getSelector()); 2151 } 2152 Fields.push_back(MakeConstantString(getter->getSelector().getAsString())); 2153 Fields.push_back(TypeEncoding); 2154 } else { 2155 Fields.push_back(NULLPtr); 2156 Fields.push_back(NULLPtr); 2157 } 2158 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) { 2159 std::string TypeStr; 2160 Context.getObjCEncodingForMethodDecl(setter,TypeStr); 2161 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 2162 if (isSynthesized) { 2163 InstanceMethodTypes.push_back(TypeEncoding); 2164 InstanceMethodSels.push_back(setter->getSelector()); 2165 } 2166 Fields.push_back(MakeConstantString(setter->getSelector().getAsString())); 2167 Fields.push_back(TypeEncoding); 2168 } else { 2169 Fields.push_back(NULLPtr); 2170 Fields.push_back(NULLPtr); 2171 } 2172 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields)); 2173 } 2174 llvm::ArrayType *PropertyArrayTy = 2175 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()); 2176 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy, 2177 Properties); 2178 llvm::Constant* PropertyListInitFields[] = 2179 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray}; 2180 2181 llvm::Constant *PropertyListInit = 2182 llvm::ConstantStruct::getAnon(PropertyListInitFields); 2183 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false, 2184 llvm::GlobalValue::InternalLinkage, PropertyListInit, 2185 ".objc_property_list"); 2186 } 2187 2188 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) { 2189 // Get the class declaration for which the alias is specified. 2190 ObjCInterfaceDecl *ClassDecl = 2191 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface()); 2192 ClassAliases.emplace_back(ClassDecl->getNameAsString(), 2193 OAD->getNameAsString()); 2194 } 2195 2196 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { 2197 ASTContext &Context = CGM.getContext(); 2198 2199 // Get the superclass name. 2200 const ObjCInterfaceDecl * SuperClassDecl = 2201 OID->getClassInterface()->getSuperClass(); 2202 std::string SuperClassName; 2203 if (SuperClassDecl) { 2204 SuperClassName = SuperClassDecl->getNameAsString(); 2205 EmitClassRef(SuperClassName); 2206 } 2207 2208 // Get the class name 2209 ObjCInterfaceDecl *ClassDecl = 2210 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 2211 std::string ClassName = ClassDecl->getNameAsString(); 2212 2213 // Emit the symbol that is used to generate linker errors if this class is 2214 // referenced in other modules but not declared. 2215 std::string classSymbolName = "__objc_class_name_" + ClassName; 2216 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) { 2217 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0)); 2218 } else { 2219 new llvm::GlobalVariable(TheModule, LongTy, false, 2220 llvm::GlobalValue::ExternalLinkage, 2221 llvm::ConstantInt::get(LongTy, 0), 2222 classSymbolName); 2223 } 2224 2225 // Get the size of instances. 2226 int instanceSize = 2227 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity(); 2228 2229 // Collect information about instance variables. 2230 SmallVector<llvm::Constant*, 16> IvarNames; 2231 SmallVector<llvm::Constant*, 16> IvarTypes; 2232 SmallVector<llvm::Constant*, 16> IvarOffsets; 2233 2234 std::vector<llvm::Constant*> IvarOffsetValues; 2235 SmallVector<bool, 16> WeakIvars; 2236 SmallVector<bool, 16> StrongIvars; 2237 2238 int superInstanceSize = !SuperClassDecl ? 0 : 2239 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity(); 2240 // For non-fragile ivars, set the instance size to 0 - {the size of just this 2241 // class}. The runtime will then set this to the correct value on load. 2242 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2243 instanceSize = 0 - (instanceSize - superInstanceSize); 2244 } 2245 2246 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD; 2247 IVD = IVD->getNextIvar()) { 2248 // Store the name 2249 IvarNames.push_back(MakeConstantString(IVD->getNameAsString())); 2250 // Get the type encoding for this ivar 2251 std::string TypeStr; 2252 Context.getObjCEncodingForType(IVD->getType(), TypeStr); 2253 IvarTypes.push_back(MakeConstantString(TypeStr)); 2254 // Get the offset 2255 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD); 2256 uint64_t Offset = BaseOffset; 2257 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2258 Offset = BaseOffset - superInstanceSize; 2259 } 2260 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset); 2261 // Create the direct offset value 2262 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." + 2263 IVD->getNameAsString(); 2264 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName); 2265 if (OffsetVar) { 2266 OffsetVar->setInitializer(OffsetValue); 2267 // If this is the real definition, change its linkage type so that 2268 // different modules will use this one, rather than their private 2269 // copy. 2270 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage); 2271 } else 2272 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy, 2273 false, llvm::GlobalValue::ExternalLinkage, 2274 OffsetValue, 2275 "__objc_ivar_offset_value_" + ClassName +"." + 2276 IVD->getNameAsString()); 2277 IvarOffsets.push_back(OffsetValue); 2278 IvarOffsetValues.push_back(OffsetVar); 2279 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime(); 2280 switch (lt) { 2281 case Qualifiers::OCL_Strong: 2282 StrongIvars.push_back(true); 2283 WeakIvars.push_back(false); 2284 break; 2285 case Qualifiers::OCL_Weak: 2286 StrongIvars.push_back(false); 2287 WeakIvars.push_back(true); 2288 break; 2289 default: 2290 StrongIvars.push_back(false); 2291 WeakIvars.push_back(false); 2292 } 2293 } 2294 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars); 2295 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars); 2296 llvm::GlobalVariable *IvarOffsetArray = 2297 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, CGM.getPointerAlign(), 2298 ".ivar.offsets"); 2299 2300 // Collect information about instance methods 2301 SmallVector<Selector, 16> InstanceMethodSels; 2302 SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 2303 for (const auto *I : OID->instance_methods()) { 2304 InstanceMethodSels.push_back(I->getSelector()); 2305 std::string TypeStr; 2306 Context.getObjCEncodingForMethodDecl(I,TypeStr); 2307 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 2308 } 2309 2310 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels, 2311 InstanceMethodTypes); 2312 2313 // Collect information about class methods 2314 SmallVector<Selector, 16> ClassMethodSels; 2315 SmallVector<llvm::Constant*, 16> ClassMethodTypes; 2316 for (const auto *I : OID->class_methods()) { 2317 ClassMethodSels.push_back(I->getSelector()); 2318 std::string TypeStr; 2319 Context.getObjCEncodingForMethodDecl(I,TypeStr); 2320 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 2321 } 2322 // Collect the names of referenced protocols 2323 SmallVector<std::string, 16> Protocols; 2324 for (const auto *I : ClassDecl->protocols()) 2325 Protocols.push_back(I->getNameAsString()); 2326 2327 // Get the superclass pointer. 2328 llvm::Constant *SuperClass; 2329 if (!SuperClassName.empty()) { 2330 SuperClass = MakeConstantString(SuperClassName, ".super_class_name"); 2331 } else { 2332 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty); 2333 } 2334 // Empty vector used to construct empty method lists 2335 SmallVector<llvm::Constant*, 1> empty; 2336 // Generate the method and instance variable lists 2337 llvm::Constant *MethodList = GenerateMethodList(ClassName, "", 2338 InstanceMethodSels, InstanceMethodTypes, false); 2339 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "", 2340 ClassMethodSels, ClassMethodTypes, true); 2341 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, 2342 IvarOffsets); 2343 // Irrespective of whether we are compiling for a fragile or non-fragile ABI, 2344 // we emit a symbol containing the offset for each ivar in the class. This 2345 // allows code compiled for the non-Fragile ABI to inherit from code compiled 2346 // for the legacy ABI, without causing problems. The converse is also 2347 // possible, but causes all ivar accesses to be fragile. 2348 2349 // Offset pointer for getting at the correct field in the ivar list when 2350 // setting up the alias. These are: The base address for the global, the 2351 // ivar array (second field), the ivar in this list (set for each ivar), and 2352 // the offset (third field in ivar structure) 2353 llvm::Type *IndexTy = Int32Ty; 2354 llvm::Constant *offsetPointerIndexes[] = {Zeros[0], 2355 llvm::ConstantInt::get(IndexTy, 1), nullptr, 2356 llvm::ConstantInt::get(IndexTy, 2) }; 2357 2358 unsigned ivarIndex = 0; 2359 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD; 2360 IVD = IVD->getNextIvar()) { 2361 const std::string Name = "__objc_ivar_offset_" + ClassName + '.' 2362 + IVD->getNameAsString(); 2363 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex); 2364 // Get the correct ivar field 2365 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr( 2366 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList, 2367 offsetPointerIndexes); 2368 // Get the existing variable, if one exists. 2369 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name); 2370 if (offset) { 2371 offset->setInitializer(offsetValue); 2372 // If this is the real definition, change its linkage type so that 2373 // different modules will use this one, rather than their private 2374 // copy. 2375 offset->setLinkage(llvm::GlobalValue::ExternalLinkage); 2376 } else { 2377 // Add a new alias if there isn't one already. 2378 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(), 2379 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name); 2380 (void) offset; // Silence dead store warning. 2381 } 2382 ++ivarIndex; 2383 } 2384 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0); 2385 2386 //Generate metaclass for class methods 2387 llvm::Constant *MetaClassStruct = GenerateClassStructure( 2388 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], 2389 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, 2390 NULLPtr, ZeroPtr, ZeroPtr, true); 2391 if (CGM.getTriple().isOSBinFormatCOFF()) { 2392 auto Storage = llvm::GlobalValue::DefaultStorageClass; 2393 if (OID->getClassInterface()->hasAttr<DLLImportAttr>()) 2394 Storage = llvm::GlobalValue::DLLImportStorageClass; 2395 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) 2396 Storage = llvm::GlobalValue::DLLExportStorageClass; 2397 cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage); 2398 } 2399 2400 // Generate the class structure 2401 llvm::Constant *ClassStruct = GenerateClassStructure( 2402 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr, 2403 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList, 2404 GenerateProtocolList(Protocols), IvarOffsetArray, Properties, 2405 StrongIvarBitmap, WeakIvarBitmap); 2406 if (CGM.getTriple().isOSBinFormatCOFF()) { 2407 auto Storage = llvm::GlobalValue::DefaultStorageClass; 2408 if (OID->getClassInterface()->hasAttr<DLLImportAttr>()) 2409 Storage = llvm::GlobalValue::DLLImportStorageClass; 2410 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) 2411 Storage = llvm::GlobalValue::DLLExportStorageClass; 2412 cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage); 2413 } 2414 2415 // Resolve the class aliases, if they exist. 2416 if (ClassPtrAlias) { 2417 ClassPtrAlias->replaceAllUsesWith( 2418 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy)); 2419 ClassPtrAlias->eraseFromParent(); 2420 ClassPtrAlias = nullptr; 2421 } 2422 if (MetaClassPtrAlias) { 2423 MetaClassPtrAlias->replaceAllUsesWith( 2424 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy)); 2425 MetaClassPtrAlias->eraseFromParent(); 2426 MetaClassPtrAlias = nullptr; 2427 } 2428 2429 // Add class structure to list to be added to the symtab later 2430 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty); 2431 Classes.push_back(ClassStruct); 2432 } 2433 2434 llvm::Function *CGObjCGNU::ModuleInitFunction() { 2435 // Only emit an ObjC load function if no Objective-C stuff has been called 2436 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && 2437 ExistingProtocols.empty() && SelectorTable.empty()) 2438 return nullptr; 2439 2440 // Add all referenced protocols to a category. 2441 GenerateProtocolHolderCategory(); 2442 2443 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>( 2444 SelectorTy->getElementType()); 2445 llvm::Type *SelStructPtrTy = SelectorTy; 2446 if (!SelStructTy) { 2447 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr); 2448 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy); 2449 } 2450 2451 std::vector<llvm::Constant*> Elements; 2452 llvm::Constant *Statics = NULLPtr; 2453 // Generate statics list: 2454 if (!ConstantStrings.empty()) { 2455 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 2456 ConstantStrings.size() + 1); 2457 ConstantStrings.push_back(NULLPtr); 2458 2459 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass; 2460 2461 if (StringClass.empty()) StringClass = "NXConstantString"; 2462 2463 Elements.push_back(MakeConstantString(StringClass, 2464 ".objc_static_class_name")); 2465 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, 2466 ConstantStrings)); 2467 llvm::StructType *StaticsListTy = 2468 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr); 2469 llvm::Type *StaticsListPtrTy = 2470 llvm::PointerType::getUnqual(StaticsListTy); 2471 Statics = MakeGlobal(StaticsListTy, Elements, CGM.getPointerAlign(), 2472 ".objc_statics"); 2473 llvm::ArrayType *StaticsListArrayTy = 2474 llvm::ArrayType::get(StaticsListPtrTy, 2); 2475 Elements.clear(); 2476 Elements.push_back(Statics); 2477 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy)); 2478 Statics = MakeGlobal(StaticsListArrayTy, Elements, 2479 CGM.getPointerAlign(), ".objc_statics_ptr"); 2480 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy); 2481 } 2482 // Array of classes, categories, and constant objects 2483 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty, 2484 Classes.size() + Categories.size() + 2); 2485 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy, 2486 llvm::Type::getInt16Ty(VMContext), 2487 llvm::Type::getInt16Ty(VMContext), 2488 ClassListTy, nullptr); 2489 2490 Elements.clear(); 2491 // Pointer to an array of selectors used in this module. 2492 std::vector<llvm::Constant*> Selectors; 2493 std::vector<llvm::GlobalAlias*> SelectorAliases; 2494 for (SelectorMap::iterator iter = SelectorTable.begin(), 2495 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) { 2496 2497 std::string SelNameStr = iter->first.getAsString(); 2498 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name"); 2499 2500 SmallVectorImpl<TypedSelector> &Types = iter->second; 2501 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(), 2502 e = Types.end() ; i!=e ; i++) { 2503 2504 llvm::Constant *SelectorTypeEncoding = NULLPtr; 2505 if (!i->first.empty()) 2506 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types"); 2507 2508 Elements.push_back(SelName); 2509 Elements.push_back(SelectorTypeEncoding); 2510 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 2511 Elements.clear(); 2512 2513 // Store the selector alias for later replacement 2514 SelectorAliases.push_back(i->second); 2515 } 2516 } 2517 unsigned SelectorCount = Selectors.size(); 2518 // NULL-terminate the selector list. This should not actually be required, 2519 // because the selector list has a length field. Unfortunately, the GCC 2520 // runtime decides to ignore the length field and expects a NULL terminator, 2521 // and GCC cooperates with this by always setting the length to 0. 2522 Elements.push_back(NULLPtr); 2523 Elements.push_back(NULLPtr); 2524 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 2525 Elements.clear(); 2526 2527 // Number of static selectors 2528 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount)); 2529 llvm::GlobalVariable *SelectorList = 2530 MakeGlobalArray(SelStructTy, Selectors, CGM.getPointerAlign(), 2531 ".objc_selector_list"); 2532 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, 2533 SelStructPtrTy)); 2534 2535 // Now that all of the static selectors exist, create pointers to them. 2536 for (unsigned int i=0 ; i<SelectorCount ; i++) { 2537 2538 llvm::Constant *Idxs[] = {Zeros[0], 2539 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]}; 2540 // FIXME: We're generating redundant loads and stores here! 2541 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr( 2542 SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2)); 2543 // If selectors are defined as an opaque type, cast the pointer to this 2544 // type. 2545 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy); 2546 SelectorAliases[i]->replaceAllUsesWith(SelPtr); 2547 SelectorAliases[i]->eraseFromParent(); 2548 } 2549 2550 // Number of classes defined. 2551 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), 2552 Classes.size())); 2553 // Number of categories defined 2554 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), 2555 Categories.size())); 2556 // Create an array of classes, then categories, then static object instances 2557 Classes.insert(Classes.end(), Categories.begin(), Categories.end()); 2558 // NULL-terminated list of static object instances (mainly constant strings) 2559 Classes.push_back(Statics); 2560 Classes.push_back(NULLPtr); 2561 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes); 2562 Elements.push_back(ClassList); 2563 // Construct the symbol table 2564 llvm::Constant *SymTab = 2565 MakeGlobal(SymTabTy, Elements, CGM.getPointerAlign()); 2566 2567 // The symbol table is contained in a module which has some version-checking 2568 // constants 2569 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy, 2570 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), 2571 (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr); 2572 Elements.clear(); 2573 // Runtime version, used for ABI compatibility checking. 2574 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion)); 2575 // sizeof(ModuleTy) 2576 llvm::DataLayout td(&TheModule); 2577 Elements.push_back( 2578 llvm::ConstantInt::get(LongTy, 2579 td.getTypeSizeInBits(ModuleTy) / 2580 CGM.getContext().getCharWidth())); 2581 2582 // The path to the source file where this module was declared 2583 SourceManager &SM = CGM.getContext().getSourceManager(); 2584 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID()); 2585 std::string path = 2586 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str(); 2587 Elements.push_back(MakeConstantString(path, ".objc_source_file_name")); 2588 Elements.push_back(SymTab); 2589 2590 if (RuntimeVersion >= 10) 2591 switch (CGM.getLangOpts().getGC()) { 2592 case LangOptions::GCOnly: 2593 Elements.push_back(llvm::ConstantInt::get(IntTy, 2)); 2594 break; 2595 case LangOptions::NonGC: 2596 if (CGM.getLangOpts().ObjCAutoRefCount) 2597 Elements.push_back(llvm::ConstantInt::get(IntTy, 1)); 2598 else 2599 Elements.push_back(llvm::ConstantInt::get(IntTy, 0)); 2600 break; 2601 case LangOptions::HybridGC: 2602 Elements.push_back(llvm::ConstantInt::get(IntTy, 1)); 2603 break; 2604 } 2605 2606 llvm::Value *Module = MakeGlobal(ModuleTy, Elements, CGM.getPointerAlign()); 2607 2608 // Create the load function calling the runtime entry point with the module 2609 // structure 2610 llvm::Function * LoadFunction = llvm::Function::Create( 2611 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 2612 llvm::GlobalValue::InternalLinkage, ".objc_load_function", 2613 &TheModule); 2614 llvm::BasicBlock *EntryBB = 2615 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 2616 CGBuilderTy Builder(CGM, VMContext); 2617 Builder.SetInsertPoint(EntryBB); 2618 2619 llvm::FunctionType *FT = 2620 llvm::FunctionType::get(Builder.getVoidTy(), 2621 llvm::PointerType::getUnqual(ModuleTy), true); 2622 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class"); 2623 Builder.CreateCall(Register, Module); 2624 2625 if (!ClassAliases.empty()) { 2626 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty}; 2627 llvm::FunctionType *RegisterAliasTy = 2628 llvm::FunctionType::get(Builder.getVoidTy(), 2629 ArgTypes, false); 2630 llvm::Function *RegisterAlias = llvm::Function::Create( 2631 RegisterAliasTy, 2632 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np", 2633 &TheModule); 2634 llvm::BasicBlock *AliasBB = 2635 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction); 2636 llvm::BasicBlock *NoAliasBB = 2637 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction); 2638 2639 // Branch based on whether the runtime provided class_registerAlias_np() 2640 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias, 2641 llvm::Constant::getNullValue(RegisterAlias->getType())); 2642 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB); 2643 2644 // The true branch (has alias registration function): 2645 Builder.SetInsertPoint(AliasBB); 2646 // Emit alias registration calls: 2647 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin(); 2648 iter != ClassAliases.end(); ++iter) { 2649 llvm::Constant *TheClass = 2650 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true); 2651 if (TheClass) { 2652 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy); 2653 Builder.CreateCall(RegisterAlias, 2654 {TheClass, MakeConstantString(iter->second)}); 2655 } 2656 } 2657 // Jump to end: 2658 Builder.CreateBr(NoAliasBB); 2659 2660 // Missing alias registration function, just return from the function: 2661 Builder.SetInsertPoint(NoAliasBB); 2662 } 2663 Builder.CreateRetVoid(); 2664 2665 return LoadFunction; 2666 } 2667 2668 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, 2669 const ObjCContainerDecl *CD) { 2670 const ObjCCategoryImplDecl *OCD = 2671 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext()); 2672 StringRef CategoryName = OCD ? OCD->getName() : ""; 2673 StringRef ClassName = CD->getName(); 2674 Selector MethodName = OMD->getSelector(); 2675 bool isClassMethod = !OMD->isInstanceMethod(); 2676 2677 CodeGenTypes &Types = CGM.getTypes(); 2678 llvm::FunctionType *MethodTy = 2679 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD)); 2680 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName, 2681 MethodName, isClassMethod); 2682 2683 llvm::Function *Method 2684 = llvm::Function::Create(MethodTy, 2685 llvm::GlobalValue::InternalLinkage, 2686 FunctionName, 2687 &TheModule); 2688 return Method; 2689 } 2690 2691 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() { 2692 return GetPropertyFn; 2693 } 2694 2695 llvm::Constant *CGObjCGNU::GetPropertySetFunction() { 2696 return SetPropertyFn; 2697 } 2698 2699 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic, 2700 bool copy) { 2701 return nullptr; 2702 } 2703 2704 llvm::Constant *CGObjCGNU::GetGetStructFunction() { 2705 return GetStructPropertyFn; 2706 } 2707 2708 llvm::Constant *CGObjCGNU::GetSetStructFunction() { 2709 return SetStructPropertyFn; 2710 } 2711 2712 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() { 2713 return nullptr; 2714 } 2715 2716 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() { 2717 return nullptr; 2718 } 2719 2720 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() { 2721 return EnumerationMutationFn; 2722 } 2723 2724 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF, 2725 const ObjCAtSynchronizedStmt &S) { 2726 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn); 2727 } 2728 2729 2730 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF, 2731 const ObjCAtTryStmt &S) { 2732 // Unlike the Apple non-fragile runtimes, which also uses 2733 // unwind-based zero cost exceptions, the GNU Objective C runtime's 2734 // EH support isn't a veneer over C++ EH. Instead, exception 2735 // objects are created by objc_exception_throw and destroyed by 2736 // the personality function; this avoids the need for bracketing 2737 // catch handlers with calls to __blah_begin_catch/__blah_end_catch 2738 // (or even _Unwind_DeleteException), but probably doesn't 2739 // interoperate very well with foreign exceptions. 2740 // 2741 // In Objective-C++ mode, we actually emit something equivalent to the C++ 2742 // exception handler. 2743 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn); 2744 } 2745 2746 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF, 2747 const ObjCAtThrowStmt &S, 2748 bool ClearInsertionPoint) { 2749 llvm::Value *ExceptionAsObject; 2750 2751 if (const Expr *ThrowExpr = S.getThrowExpr()) { 2752 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); 2753 ExceptionAsObject = Exception; 2754 } else { 2755 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 2756 "Unexpected rethrow outside @catch block."); 2757 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 2758 } 2759 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy); 2760 llvm::CallSite Throw = 2761 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject); 2762 Throw.setDoesNotReturn(); 2763 CGF.Builder.CreateUnreachable(); 2764 if (ClearInsertionPoint) 2765 CGF.Builder.ClearInsertionPoint(); 2766 } 2767 2768 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF, 2769 Address AddrWeakObj) { 2770 CGBuilderTy &B = CGF.Builder; 2771 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy); 2772 return B.CreateCall(WeakReadFn.getType(), WeakReadFn, 2773 AddrWeakObj.getPointer()); 2774 } 2775 2776 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF, 2777 llvm::Value *src, Address dst) { 2778 CGBuilderTy &B = CGF.Builder; 2779 src = EnforceType(B, src, IdTy); 2780 dst = EnforceType(B, dst, PtrToIdTy); 2781 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn, 2782 {src, dst.getPointer()}); 2783 } 2784 2785 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF, 2786 llvm::Value *src, Address dst, 2787 bool threadlocal) { 2788 CGBuilderTy &B = CGF.Builder; 2789 src = EnforceType(B, src, IdTy); 2790 dst = EnforceType(B, dst, PtrToIdTy); 2791 // FIXME. Add threadloca assign API 2792 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI"); 2793 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn, 2794 {src, dst.getPointer()}); 2795 } 2796 2797 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF, 2798 llvm::Value *src, Address dst, 2799 llvm::Value *ivarOffset) { 2800 CGBuilderTy &B = CGF.Builder; 2801 src = EnforceType(B, src, IdTy); 2802 dst = EnforceType(B, dst, IdTy); 2803 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn, 2804 {src, dst.getPointer(), ivarOffset}); 2805 } 2806 2807 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF, 2808 llvm::Value *src, Address dst) { 2809 CGBuilderTy &B = CGF.Builder; 2810 src = EnforceType(B, src, IdTy); 2811 dst = EnforceType(B, dst, PtrToIdTy); 2812 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn, 2813 {src, dst.getPointer()}); 2814 } 2815 2816 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF, 2817 Address DestPtr, 2818 Address SrcPtr, 2819 llvm::Value *Size) { 2820 CGBuilderTy &B = CGF.Builder; 2821 DestPtr = EnforceType(B, DestPtr, PtrTy); 2822 SrcPtr = EnforceType(B, SrcPtr, PtrTy); 2823 2824 B.CreateCall(MemMoveFn.getType(), MemMoveFn, 2825 {DestPtr.getPointer(), SrcPtr.getPointer(), Size}); 2826 } 2827 2828 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( 2829 const ObjCInterfaceDecl *ID, 2830 const ObjCIvarDecl *Ivar) { 2831 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 2832 + '.' + Ivar->getNameAsString(); 2833 // Emit the variable and initialize it with what we think the correct value 2834 // is. This allows code compiled with non-fragile ivars to work correctly 2835 // when linked against code which isn't (most of the time). 2836 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 2837 if (!IvarOffsetPointer) { 2838 // This will cause a run-time crash if we accidentally use it. A value of 2839 // 0 would seem more sensible, but will silently overwrite the isa pointer 2840 // causing a great deal of confusion. 2841 uint64_t Offset = -1; 2842 // We can't call ComputeIvarBaseOffset() here if we have the 2843 // implementation, because it will create an invalid ASTRecordLayout object 2844 // that we are then stuck with forever, so we only initialize the ivar 2845 // offset variable with a guess if we only have the interface. The 2846 // initializer will be reset later anyway, when we are generating the class 2847 // description. 2848 if (!CGM.getContext().getObjCImplementation( 2849 const_cast<ObjCInterfaceDecl *>(ID))) 2850 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar); 2851 2852 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset, 2853 /*isSigned*/true); 2854 // Don't emit the guess in non-PIC code because the linker will not be able 2855 // to replace it with the real version for a library. In non-PIC code you 2856 // must compile with the fragile ABI if you want to use ivars from a 2857 // GCC-compiled class. 2858 if (CGM.getLangOpts().PICLevel) { 2859 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule, 2860 Int32Ty, false, 2861 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess"); 2862 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 2863 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage, 2864 IvarOffsetGV, Name); 2865 } else { 2866 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 2867 llvm::Type::getInt32PtrTy(VMContext), false, 2868 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 2869 } 2870 } 2871 return IvarOffsetPointer; 2872 } 2873 2874 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF, 2875 QualType ObjectTy, 2876 llvm::Value *BaseValue, 2877 const ObjCIvarDecl *Ivar, 2878 unsigned CVRQualifiers) { 2879 const ObjCInterfaceDecl *ID = 2880 ObjectTy->getAs<ObjCObjectType>()->getInterface(); 2881 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 2882 EmitIvarOffset(CGF, ID, Ivar)); 2883 } 2884 2885 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, 2886 const ObjCInterfaceDecl *OID, 2887 const ObjCIvarDecl *OIVD) { 2888 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next; 2889 next = next->getNextIvar()) { 2890 if (OIVD == next) 2891 return OID; 2892 } 2893 2894 // Otherwise check in the super class. 2895 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 2896 return FindIvarInterface(Context, Super, OIVD); 2897 2898 return nullptr; 2899 } 2900 2901 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF, 2902 const ObjCInterfaceDecl *Interface, 2903 const ObjCIvarDecl *Ivar) { 2904 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2905 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar); 2906 2907 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage 2908 // and ExternalLinkage, so create a reference to the ivar global and rely on 2909 // the definition being created as part of GenerateClass. 2910 if (RuntimeVersion < 10 || 2911 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) 2912 return CGF.Builder.CreateZExtOrBitCast( 2913 CGF.Builder.CreateDefaultAlignedLoad(CGF.Builder.CreateAlignedLoad( 2914 ObjCIvarOffsetVariable(Interface, Ivar), 2915 CGF.getPointerAlign(), "ivar")), 2916 PtrDiffTy); 2917 std::string name = "__objc_ivar_offset_value_" + 2918 Interface->getNameAsString() +"." + Ivar->getNameAsString(); 2919 CharUnits Align = CGM.getIntAlign(); 2920 llvm::Value *Offset = TheModule.getGlobalVariable(name); 2921 if (!Offset) { 2922 auto GV = new llvm::GlobalVariable(TheModule, IntTy, 2923 false, llvm::GlobalValue::LinkOnceAnyLinkage, 2924 llvm::Constant::getNullValue(IntTy), name); 2925 GV->setAlignment(Align.getQuantity()); 2926 Offset = GV; 2927 } 2928 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align); 2929 if (Offset->getType() != PtrDiffTy) 2930 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy); 2931 return Offset; 2932 } 2933 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar); 2934 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true); 2935 } 2936 2937 CGObjCRuntime * 2938 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) { 2939 switch (CGM.getLangOpts().ObjCRuntime.getKind()) { 2940 case ObjCRuntime::GNUstep: 2941 return new CGObjCGNUstep(CGM); 2942 2943 case ObjCRuntime::GCC: 2944 return new CGObjCGCC(CGM); 2945 2946 case ObjCRuntime::ObjFW: 2947 return new CGObjCObjFW(CGM); 2948 2949 case ObjCRuntime::FragileMacOSX: 2950 case ObjCRuntime::MacOSX: 2951 case ObjCRuntime::iOS: 2952 case ObjCRuntime::WatchOS: 2953 llvm_unreachable("these runtimes are not GNU runtimes"); 2954 } 2955 llvm_unreachable("bad runtime"); 2956 } 2957