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