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