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