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