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