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