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