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