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