CGObjCMac.cpp revision 09796d6a23c683413470efd19dd5ad331d91af7d
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===// 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 targetting the Apple runtime. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CGObjCRuntime.h" 15 16#include "CodeGenModule.h" 17#include "CodeGenFunction.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/Basic/LangOptions.h" 22 23#include "llvm/Module.h" 24#include "llvm/ADT/DenseSet.h" 25#include "llvm/Target/TargetData.h" 26#include <sstream> 27 28using namespace clang; 29using namespace CodeGen; 30 31namespace { 32 33 typedef std::vector<llvm::Constant*> ConstantVector; 34 35 // FIXME: We should find a nicer way to make the labels for 36 // metadata, string concatenation is lame. 37 38class ObjCCommonTypesHelper { 39protected: 40 CodeGen::CodeGenModule &CGM; 41 42public: 43 const llvm::Type *ShortTy, *IntTy, *LongTy; 44 const llvm::Type *Int8PtrTy; 45 46 /// ObjectPtrTy - LLVM type for object handles (typeof(id)) 47 const llvm::Type *ObjectPtrTy; 48 49 /// PtrObjectPtrTy - LLVM type for id * 50 const llvm::Type *PtrObjectPtrTy; 51 52 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) 53 const llvm::Type *SelectorPtrTy; 54 /// ProtocolPtrTy - LLVM type for external protocol handles 55 /// (typeof(Protocol)) 56 const llvm::Type *ExternalProtocolPtrTy; 57 58 // SuperCTy - clang type for struct objc_super. 59 QualType SuperCTy; 60 // SuperPtrCTy - clang type for struct objc_super *. 61 QualType SuperPtrCTy; 62 63 /// SuperTy - LLVM type for struct objc_super. 64 const llvm::StructType *SuperTy; 65 /// SuperPtrTy - LLVM type for struct objc_super *. 66 const llvm::Type *SuperPtrTy; 67 68 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t 69 /// in GCC parlance). 70 const llvm::StructType *PropertyTy; 71 72 /// PropertyListTy - LLVM type for struct objc_property_list 73 /// (_prop_list_t in GCC parlance). 74 const llvm::StructType *PropertyListTy; 75 /// PropertyListPtrTy - LLVM type for struct objc_property_list*. 76 const llvm::Type *PropertyListPtrTy; 77 78 // MethodTy - LLVM type for struct objc_method. 79 const llvm::StructType *MethodTy; 80 81 /// CacheTy - LLVM type for struct objc_cache. 82 const llvm::Type *CacheTy; 83 /// CachePtrTy - LLVM type for struct objc_cache *. 84 const llvm::Type *CachePtrTy; 85 86 llvm::Function *GetPropertyFn, *SetPropertyFn; 87 88 llvm::Function *EnumerationMutationFn; 89 90 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. 91 llvm::Function *GcReadWeakFn; 92 93 /// GcAssignWeakFn -- LLVM objc_assign_weak function. 94 llvm::Function *GcAssignWeakFn; 95 96 /// GcAssignGlobalFn -- LLVM objc_assign_global function. 97 llvm::Function *GcAssignGlobalFn; 98 99 /// GcAssignIvarFn -- LLVM objc_assign_ivar function. 100 llvm::Function *GcAssignIvarFn; 101 102 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. 103 llvm::Function *GcAssignStrongCastFn; 104 105 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); 106 ~ObjCCommonTypesHelper(){} 107}; 108 109/// ObjCTypesHelper - Helper class that encapsulates lazy 110/// construction of varies types used during ObjC generation. 111class ObjCTypesHelper : public ObjCCommonTypesHelper { 112private: 113 114 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn; 115 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn, 116 *MessageSendSuperFpretFn; 117 118public: 119 /// SymtabTy - LLVM type for struct objc_symtab. 120 const llvm::StructType *SymtabTy; 121 /// SymtabPtrTy - LLVM type for struct objc_symtab *. 122 const llvm::Type *SymtabPtrTy; 123 /// ModuleTy - LLVM type for struct objc_module. 124 const llvm::StructType *ModuleTy; 125 126 /// ProtocolTy - LLVM type for struct objc_protocol. 127 const llvm::StructType *ProtocolTy; 128 /// ProtocolPtrTy - LLVM type for struct objc_protocol *. 129 const llvm::Type *ProtocolPtrTy; 130 /// ProtocolExtensionTy - LLVM type for struct 131 /// objc_protocol_extension. 132 const llvm::StructType *ProtocolExtensionTy; 133 /// ProtocolExtensionTy - LLVM type for struct 134 /// objc_protocol_extension *. 135 const llvm::Type *ProtocolExtensionPtrTy; 136 /// MethodDescriptionTy - LLVM type for struct 137 /// objc_method_description. 138 const llvm::StructType *MethodDescriptionTy; 139 /// MethodDescriptionListTy - LLVM type for struct 140 /// objc_method_description_list. 141 const llvm::StructType *MethodDescriptionListTy; 142 /// MethodDescriptionListPtrTy - LLVM type for struct 143 /// objc_method_description_list *. 144 const llvm::Type *MethodDescriptionListPtrTy; 145 /// ProtocolListTy - LLVM type for struct objc_property_list. 146 const llvm::Type *ProtocolListTy; 147 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. 148 const llvm::Type *ProtocolListPtrTy; 149 /// CategoryTy - LLVM type for struct objc_category. 150 const llvm::StructType *CategoryTy; 151 /// ClassTy - LLVM type for struct objc_class. 152 const llvm::StructType *ClassTy; 153 /// ClassPtrTy - LLVM type for struct objc_class *. 154 const llvm::Type *ClassPtrTy; 155 /// ClassExtensionTy - LLVM type for struct objc_class_ext. 156 const llvm::StructType *ClassExtensionTy; 157 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. 158 const llvm::Type *ClassExtensionPtrTy; 159 // IvarTy - LLVM type for struct objc_ivar. 160 const llvm::StructType *IvarTy; 161 /// IvarListTy - LLVM type for struct objc_ivar_list. 162 const llvm::Type *IvarListTy; 163 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. 164 const llvm::Type *IvarListPtrTy; 165 /// MethodListTy - LLVM type for struct objc_method_list. 166 const llvm::Type *MethodListTy; 167 /// MethodListPtrTy - LLVM type for struct objc_method_list *. 168 const llvm::Type *MethodListPtrTy; 169 170 /// ExceptionDataTy - LLVM type for struct _objc_exception_data. 171 const llvm::Type *ExceptionDataTy; 172 173 /// ExceptionThrowFn - LLVM objc_exception_throw function. 174 llvm::Function *ExceptionThrowFn; 175 176 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. 177 llvm::Function *ExceptionTryEnterFn; 178 179 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. 180 llvm::Function *ExceptionTryExitFn; 181 182 /// ExceptionExtractFn - LLVM objc_exception_extract function. 183 llvm::Function *ExceptionExtractFn; 184 185 /// ExceptionMatchFn - LLVM objc_exception_match function. 186 llvm::Function *ExceptionMatchFn; 187 188 /// SetJmpFn - LLVM _setjmp function. 189 llvm::Function *SetJmpFn; 190 191 /// SyncEnterFn - LLVM object_sync_enter function. 192 llvm::Function *SyncEnterFn; 193 194 /// SyncExitFn - LLVM object_sync_exit function. 195 llvm::Function *SyncExitFn; 196 197public: 198 ObjCTypesHelper(CodeGen::CodeGenModule &cgm); 199 ~ObjCTypesHelper() {} 200 201 202 llvm::Function *getSendFn(bool IsSuper) { 203 return IsSuper ? MessageSendSuperFn : MessageSendFn; 204 } 205 206 llvm::Function *getSendStretFn(bool IsSuper) { 207 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn; 208 } 209 210 llvm::Function *getSendFpretFn(bool IsSuper) { 211 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn; 212 } 213}; 214 215/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's 216/// modern abi 217class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { 218public: 219 // MethodListnfABITy - LLVM for struct _method_list_t 220 const llvm::StructType *MethodListnfABITy; 221 222 // MethodListnfABIPtrTy - LLVM for struct _method_list_t* 223 const llvm::Type *MethodListnfABIPtrTy; 224 225 // ProtocolnfABITy = LLVM for struct _protocol_t 226 const llvm::StructType *ProtocolnfABITy; 227 228 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list 229 const llvm::StructType *ProtocolListnfABITy; 230 231 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* 232 const llvm::Type *ProtocolListnfABIPtrTy; 233 234 // ClassnfABITy - LLVM for struct _class_t 235 const llvm::StructType *ClassnfABITy; 236 237 // ClassnfABIPtrTy - LLVM for struct _class_t* 238 const llvm::Type *ClassnfABIPtrTy; 239 240 // IvarnfABITy - LLVM for struct _ivar_t 241 const llvm::StructType *IvarnfABITy; 242 243 // IvarListnfABITy - LLVM for struct _ivar_list_t 244 const llvm::StructType *IvarListnfABITy; 245 246 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* 247 const llvm::Type *IvarListnfABIPtrTy; 248 249 // ClassRonfABITy - LLVM for struct _class_ro_t 250 const llvm::StructType *ClassRonfABITy; 251 252 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 253 const llvm::Type *ImpnfABITy; 254 255 // CategorynfABITy - LLVM for struct _category_t 256 const llvm::StructType *CategorynfABITy; 257 258 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); 259 ~ObjCNonFragileABITypesHelper(){} 260}; 261 262class CGObjCCommonMac : public CodeGen::CGObjCRuntime { 263protected: 264 CodeGen::CodeGenModule &CGM; 265 // FIXME! May not be needing this after all. 266 unsigned ObjCABI; 267 268 /// LazySymbols - Symbols to generate a lazy reference for. See 269 /// DefinedSymbols and FinishModule(). 270 std::set<IdentifierInfo*> LazySymbols; 271 272 /// DefinedSymbols - External symbols which are defined by this 273 /// module. The symbols in this list and LazySymbols are used to add 274 /// special linker symbols which ensure that Objective-C modules are 275 /// linked properly. 276 std::set<IdentifierInfo*> DefinedSymbols; 277 278 /// ClassNames - uniqued class names. 279 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames; 280 281 /// MethodVarNames - uniqued method variable names. 282 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; 283 284 /// MethodVarTypes - uniqued method type signatures. We have to use 285 /// a StringMap here because have no other unique reference. 286 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; 287 288 /// MethodDefinitions - map of methods which have been defined in 289 /// this translation unit. 290 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; 291 292 /// PropertyNames - uniqued method variable names. 293 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; 294 295 /// ClassReferences - uniqued class references. 296 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; 297 298 /// SelectorReferences - uniqued selector references. 299 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; 300 301 /// Protocols - Protocols for which an objc_protocol structure has 302 /// been emitted. Forward declarations are handled by creating an 303 /// empty structure whose initializer is filled in when/if defined. 304 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; 305 306 /// DefinedProtocols - Protocols which have actually been 307 /// defined. We should not need this, see FIXME in GenerateProtocol. 308 llvm::DenseSet<IdentifierInfo*> DefinedProtocols; 309 310 /// DefinedClasses - List of defined classes. 311 std::vector<llvm::GlobalValue*> DefinedClasses; 312 313 /// DefinedCategories - List of defined categories. 314 std::vector<llvm::GlobalValue*> DefinedCategories; 315 316 /// UsedGlobals - List of globals to pack into the llvm.used metadata 317 /// to prevent them from being clobbered. 318 std::vector<llvm::GlobalVariable*> UsedGlobals; 319 320 /// GetNameForMethod - Return a name for the given method. 321 /// \param[out] NameOut - The return value. 322 void GetNameForMethod(const ObjCMethodDecl *OMD, 323 const ObjCContainerDecl *CD, 324 std::string &NameOut); 325 326 /// GetMethodVarName - Return a unique constant for the given 327 /// selector's name. The return value has type char *. 328 llvm::Constant *GetMethodVarName(Selector Sel); 329 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); 330 llvm::Constant *GetMethodVarName(const std::string &Name); 331 332 /// GetMethodVarType - Return a unique constant for the given 333 /// selector's name. The return value has type char *. 334 335 // FIXME: This is a horrible name. 336 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D); 337 llvm::Constant *GetMethodVarType(const std::string &Name); 338 339 /// GetPropertyName - Return a unique constant for the given 340 /// name. The return value has type char *. 341 llvm::Constant *GetPropertyName(IdentifierInfo *Ident); 342 343 // FIXME: This can be dropped once string functions are unified. 344 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, 345 const Decl *Container); 346 347 /// GetClassName - Return a unique constant for the given selector's 348 /// name. The return value has type char *. 349 llvm::Constant *GetClassName(IdentifierInfo *Ident); 350 351 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID, 352 RecordDecl::field_iterator &FIV, 353 RecordDecl::field_iterator &PIV); 354 /// EmitPropertyList - Emit the given property list. The return 355 /// value has type PropertyListPtrTy. 356 llvm::Constant *EmitPropertyList(const std::string &Name, 357 const Decl *Container, 358 const ObjCContainerDecl *OCD, 359 const ObjCCommonTypesHelper &ObjCTypes); 360 361 /// GetProtocolRef - Return a reference to the internal protocol 362 /// description, creating an empty one if it has not been 363 /// defined. The return value has type ProtocolPtrTy. 364 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); 365 366public: 367 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm) 368 { } 369 370 virtual llvm::Constant *GenerateConstantString(const std::string &String); 371 372 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 373 const ObjCContainerDecl *CD=0); 374 375 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 376 377 /// GetOrEmitProtocol - Get the protocol object for the given 378 /// declaration, emitting it if necessary. The return value has type 379 /// ProtocolPtrTy. 380 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0; 381 382 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 383 /// object for the given declaration, emitting it if needed. These 384 /// forward references will be filled in with empty bodies if no 385 /// definition is seen. The return value has type ProtocolPtrTy. 386 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0; 387}; 388 389class CGObjCMac : public CGObjCCommonMac { 390private: 391 ObjCTypesHelper ObjCTypes; 392 /// EmitImageInfo - Emit the image info marker used to encode some module 393 /// level information. 394 void EmitImageInfo(); 395 396 /// EmitModuleInfo - Another marker encoding module level 397 /// information. 398 void EmitModuleInfo(); 399 400 /// EmitModuleSymols - Emit module symbols, the list of defined 401 /// classes and categories. The result has type SymtabPtrTy. 402 llvm::Constant *EmitModuleSymbols(); 403 404 /// FinishModule - Write out global data structures at the end of 405 /// processing a translation unit. 406 void FinishModule(); 407 408 /// EmitClassExtension - Generate the class extension structure used 409 /// to store the weak ivar layout and properties. The return value 410 /// has type ClassExtensionPtrTy. 411 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID); 412 413 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 414 /// for the given class. 415 llvm::Value *EmitClassRef(CGBuilderTy &Builder, 416 const ObjCInterfaceDecl *ID); 417 418 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 419 QualType ResultType, 420 Selector Sel, 421 llvm::Value *Arg0, 422 QualType Arg0Ty, 423 bool IsSuper, 424 const CallArgList &CallArgs); 425 426 /// EmitIvarList - Emit the ivar list for the given 427 /// implementation. If ForClass is true the list of class ivars 428 /// (i.e. metaclass ivars) is emitted, otherwise the list of 429 /// interface ivars will be emitted. The return value has type 430 /// IvarListPtrTy. 431 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, 432 bool ForClass); 433 434 /// EmitMetaClass - Emit a forward reference to the class structure 435 /// for the metaclass of the given interface. The return value has 436 /// type ClassPtrTy. 437 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); 438 439 /// EmitMetaClass - Emit a class structure for the metaclass of the 440 /// given implementation. The return value has type ClassPtrTy. 441 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, 442 llvm::Constant *Protocols, 443 const llvm::Type *InterfaceTy, 444 const ConstantVector &Methods); 445 446 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 447 448 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 449 450 /// EmitMethodList - Emit the method list for the given 451 /// implementation. The return value has type MethodListPtrTy. 452 llvm::Constant *EmitMethodList(const std::string &Name, 453 const char *Section, 454 const ConstantVector &Methods); 455 456 /// EmitMethodDescList - Emit a method description list for a list of 457 /// method declarations. 458 /// - TypeName: The name for the type containing the methods. 459 /// - IsProtocol: True iff these methods are for a protocol. 460 /// - ClassMethds: True iff these are class methods. 461 /// - Required: When true, only "required" methods are 462 /// listed. Similarly, when false only "optional" methods are 463 /// listed. For classes this should always be true. 464 /// - begin, end: The method list to output. 465 /// 466 /// The return value has type MethodDescriptionListPtrTy. 467 llvm::Constant *EmitMethodDescList(const std::string &Name, 468 const char *Section, 469 const ConstantVector &Methods); 470 471 /// GetOrEmitProtocol - Get the protocol object for the given 472 /// declaration, emitting it if necessary. The return value has type 473 /// ProtocolPtrTy. 474 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 475 476 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 477 /// object for the given declaration, emitting it if needed. These 478 /// forward references will be filled in with empty bodies if no 479 /// definition is seen. The return value has type ProtocolPtrTy. 480 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 481 482 /// EmitProtocolExtension - Generate the protocol extension 483 /// structure used to store optional instance and class methods, and 484 /// protocol properties. The return value has type 485 /// ProtocolExtensionPtrTy. 486 llvm::Constant * 487 EmitProtocolExtension(const ObjCProtocolDecl *PD, 488 const ConstantVector &OptInstanceMethods, 489 const ConstantVector &OptClassMethods); 490 491 /// EmitProtocolList - Generate the list of referenced 492 /// protocols. The return value has type ProtocolListPtrTy. 493 llvm::Constant *EmitProtocolList(const std::string &Name, 494 ObjCProtocolDecl::protocol_iterator begin, 495 ObjCProtocolDecl::protocol_iterator end); 496 497 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 498 /// for the given selector. 499 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); 500 501 public: 502 CGObjCMac(CodeGen::CodeGenModule &cgm); 503 504 virtual llvm::Function *ModuleInitFunction(); 505 506 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 507 QualType ResultType, 508 Selector Sel, 509 llvm::Value *Receiver, 510 bool IsClassMessage, 511 const CallArgList &CallArgs); 512 513 virtual CodeGen::RValue 514 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 515 QualType ResultType, 516 Selector Sel, 517 const ObjCInterfaceDecl *Class, 518 llvm::Value *Receiver, 519 bool IsClassMessage, 520 const CallArgList &CallArgs); 521 522 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 523 const ObjCInterfaceDecl *ID); 524 525 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); 526 527 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 528 529 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 530 531 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 532 const ObjCProtocolDecl *PD); 533 534 virtual llvm::Function *GetPropertyGetFunction(); 535 virtual llvm::Function *GetPropertySetFunction(); 536 virtual llvm::Function *EnumerationMutationFunction(); 537 538 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 539 const Stmt &S); 540 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 541 const ObjCAtThrowStmt &S); 542 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 543 llvm::Value *AddrWeakObj); 544 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 545 llvm::Value *src, llvm::Value *dst); 546 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 547 llvm::Value *src, llvm::Value *dest); 548 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 549 llvm::Value *src, llvm::Value *dest); 550 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 551 llvm::Value *src, llvm::Value *dest); 552}; 553 554class CGObjCNonFragileABIMac : public CGObjCCommonMac { 555private: 556 ObjCNonFragileABITypesHelper ObjCTypes; 557 llvm::GlobalVariable* ObjCEmptyCacheVar; 558 llvm::GlobalVariable* ObjCEmptyVtableVar; 559 560 /// FinishNonFragileABIModule - Write out global data structures at the end of 561 /// processing a translation unit. 562 void FinishNonFragileABIModule(); 563 564 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags, 565 unsigned InstanceStart, 566 unsigned InstanceSize, 567 const ObjCImplementationDecl *ID); 568 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName, 569 llvm::Constant *IsAGV, 570 llvm::Constant *SuperClassGV, 571 llvm::Constant *ClassRoGV, 572 bool HiddenVisibility); 573 574 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 575 576 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 577 578 /// EmitMethodList - Emit the method list for the given 579 /// implementation. The return value has type MethodListnfABITy. 580 llvm::Constant *EmitMethodList(const std::string &Name, 581 const char *Section, 582 const ConstantVector &Methods); 583 /// EmitIvarList - Emit the ivar list for the given 584 /// implementation. If ForClass is true the list of class ivars 585 /// (i.e. metaclass ivars) is emitted, otherwise the list of 586 /// interface ivars will be emitted. The return value has type 587 /// IvarListnfABIPtrTy. 588 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID); 589 590 llvm::Constant *EmitIvarOffsetVar(const ObjCImplementationDecl *ID, 591 const ObjCIvarDecl *Ivar, 592 unsigned long int offset); 593 594 /// GetOrEmitProtocol - Get the protocol object for the given 595 /// declaration, emitting it if necessary. The return value has type 596 /// ProtocolPtrTy. 597 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 598 599 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 600 /// object for the given declaration, emitting it if needed. These 601 /// forward references will be filled in with empty bodies if no 602 /// definition is seen. The return value has type ProtocolPtrTy. 603 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 604 605 /// EmitProtocolList - Generate the list of referenced 606 /// protocols. The return value has type ProtocolListPtrTy. 607 llvm::Constant *EmitProtocolList(const std::string &Name, 608 ObjCProtocolDecl::protocol_iterator begin, 609 ObjCProtocolDecl::protocol_iterator end); 610 611public: 612 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); 613 // FIXME. All stubs for now! 614 virtual llvm::Function *ModuleInitFunction(); 615 616 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 617 QualType ResultType, 618 Selector Sel, 619 llvm::Value *Receiver, 620 bool IsClassMessage, 621 const CallArgList &CallArgs) 622 {return RValue::get(0);} 623 624 virtual CodeGen::RValue 625 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 626 QualType ResultType, 627 Selector Sel, 628 const ObjCInterfaceDecl *Class, 629 llvm::Value *Receiver, 630 bool IsClassMessage, 631 const CallArgList &CallArgs){ return RValue::get(0);} 632 633 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 634 const ObjCInterfaceDecl *ID){ return 0; } 635 636 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel) 637 { return 0; } 638 639 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 640 641 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 642 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 643 const ObjCProtocolDecl *PD); 644 645 virtual llvm::Function *GetPropertyGetFunction(){ return 0; } 646 virtual llvm::Function *GetPropertySetFunction() 647 { return 0; } 648 virtual llvm::Function *EnumerationMutationFunction() 649 { return 0; } 650 651 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 652 const Stmt &S) 653 { return; } 654 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 655 const ObjCAtThrowStmt &S) 656 { return; } 657 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 658 llvm::Value *AddrWeakObj) 659 { return 0; } 660 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 661 llvm::Value *src, llvm::Value *dst) 662 { return; } 663 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 664 llvm::Value *src, llvm::Value *dest) 665 { return; } 666 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 667 llvm::Value *src, llvm::Value *dest) 668 { return; } 669 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 670 llvm::Value *src, llvm::Value *dest) 671 { return; } 672}; 673 674} // end anonymous namespace 675 676/* *** Helper Functions *** */ 677 678/// getConstantGEP() - Help routine to construct simple GEPs. 679static llvm::Constant *getConstantGEP(llvm::Constant *C, 680 unsigned idx0, 681 unsigned idx1) { 682 llvm::Value *Idxs[] = { 683 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0), 684 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1) 685 }; 686 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2); 687} 688 689/* *** CGObjCMac Public Interface *** */ 690 691CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), 692 ObjCTypes(cgm) 693{ 694 ObjCABI = 1; 695 EmitImageInfo(); 696} 697 698/// GetClass - Return a reference to the class for the given interface 699/// decl. 700llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder, 701 const ObjCInterfaceDecl *ID) { 702 return EmitClassRef(Builder, ID); 703} 704 705/// GetSelector - Return the pointer to the unique'd string for this selector. 706llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) { 707 return EmitSelector(Builder, Sel); 708} 709 710/// Generate a constant CFString object. 711/* 712 struct __builtin_CFString { 713 const int *isa; // point to __CFConstantStringClassReference 714 int flags; 715 const char *str; 716 long length; 717 }; 718*/ 719 720llvm::Constant *CGObjCCommonMac::GenerateConstantString( 721 const std::string &String) { 722 return CGM.GetAddrOfConstantCFString(String); 723} 724 725/// Generates a message send where the super is the receiver. This is 726/// a message send to self with special delivery semantics indicating 727/// which class's method should be called. 728CodeGen::RValue 729CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 730 QualType ResultType, 731 Selector Sel, 732 const ObjCInterfaceDecl *Class, 733 llvm::Value *Receiver, 734 bool IsClassMessage, 735 const CodeGen::CallArgList &CallArgs) { 736 // Create and init a super structure; this is a (receiver, class) 737 // pair we will pass to objc_msgSendSuper. 738 llvm::Value *ObjCSuper = 739 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 740 llvm::Value *ReceiverAsObject = 741 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 742 CGF.Builder.CreateStore(ReceiverAsObject, 743 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 744 745 // If this is a class message the metaclass is passed as the target. 746 llvm::Value *Target; 747 if (IsClassMessage) { 748 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class); 749 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1); 750 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr); 751 Target = Super; 752 } else { 753 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 754 } 755 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 756 // and ObjCTypes types. 757 const llvm::Type *ClassTy = 758 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 759 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 760 CGF.Builder.CreateStore(Target, 761 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 762 763 return EmitMessageSend(CGF, ResultType, Sel, 764 ObjCSuper, ObjCTypes.SuperPtrCTy, 765 true, CallArgs); 766} 767 768/// Generate code for a message send expression. 769CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 770 QualType ResultType, 771 Selector Sel, 772 llvm::Value *Receiver, 773 bool IsClassMessage, 774 const CallArgList &CallArgs) { 775 llvm::Value *Arg0 = 776 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp"); 777 return EmitMessageSend(CGF, ResultType, Sel, 778 Arg0, CGF.getContext().getObjCIdType(), 779 false, CallArgs); 780} 781 782CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, 783 QualType ResultType, 784 Selector Sel, 785 llvm::Value *Arg0, 786 QualType Arg0Ty, 787 bool IsSuper, 788 const CallArgList &CallArgs) { 789 CallArgList ActualArgs; 790 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 791 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder, 792 Sel)), 793 CGF.getContext().getObjCSelType())); 794 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 795 796 const llvm::FunctionType *FTy = 797 CGM.getTypes().GetFunctionType(CGFunctionInfo(ResultType, ActualArgs, 798 false)); 799 800 llvm::Constant *Fn; 801 if (CGM.ReturnTypeUsesSret(ResultType)) { 802 Fn = ObjCTypes.getSendStretFn(IsSuper); 803 } else if (ResultType->isFloatingType()) { 804 // FIXME: Sadly, this is wrong. This actually depends on the 805 // architecture. This happens to be right for x86-32 though. 806 Fn = ObjCTypes.getSendFpretFn(IsSuper); 807 } else { 808 Fn = ObjCTypes.getSendFn(IsSuper); 809 } 810 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy)); 811 return CGF.EmitCall(Fn, ResultType, ActualArgs); 812} 813 814llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder, 815 const ObjCProtocolDecl *PD) { 816 // FIXME: I don't understand why gcc generates this, or where it is 817 // resolved. Investigate. Its also wasteful to look this up over and 818 // over. 819 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 820 821 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 822 ObjCTypes.ExternalProtocolPtrTy); 823} 824 825void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { 826 // FIXME: We shouldn't need this, the protocol decl should contain 827 // enough information to tell us whether this was a declaration or a 828 // definition. 829 DefinedProtocols.insert(PD->getIdentifier()); 830 831 // If we have generated a forward reference to this protocol, emit 832 // it now. Otherwise do nothing, the protocol objects are lazily 833 // emitted. 834 if (Protocols.count(PD->getIdentifier())) 835 GetOrEmitProtocol(PD); 836} 837 838llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { 839 if (DefinedProtocols.count(PD->getIdentifier())) 840 return GetOrEmitProtocol(PD); 841 return GetOrEmitProtocolRef(PD); 842} 843 844/* 845 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions 846 struct _objc_protocol { 847 struct _objc_protocol_extension *isa; 848 char *protocol_name; 849 struct _objc_protocol_list *protocol_list; 850 struct _objc__method_prototype_list *instance_methods; 851 struct _objc__method_prototype_list *class_methods 852 }; 853 854 See EmitProtocolExtension(). 855*/ 856llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { 857 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 858 859 // Early exit if a defining object has already been generated. 860 if (Entry && Entry->hasInitializer()) 861 return Entry; 862 863 // FIXME: I don't understand why gcc generates this, or where it is 864 // resolved. Investigate. Its also wasteful to look this up over and 865 // over. 866 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 867 868 const char *ProtocolName = PD->getNameAsCString(); 869 870 // Construct method lists. 871 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 872 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 873 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(), 874 e = PD->instmeth_end(); i != e; ++i) { 875 ObjCMethodDecl *MD = *i; 876 llvm::Constant *C = GetMethodDescriptionConstant(MD); 877 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 878 OptInstanceMethods.push_back(C); 879 } else { 880 InstanceMethods.push_back(C); 881 } 882 } 883 884 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(), 885 e = PD->classmeth_end(); i != e; ++i) { 886 ObjCMethodDecl *MD = *i; 887 llvm::Constant *C = GetMethodDescriptionConstant(MD); 888 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 889 OptClassMethods.push_back(C); 890 } else { 891 ClassMethods.push_back(C); 892 } 893 } 894 895 std::vector<llvm::Constant*> Values(5); 896 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods); 897 Values[1] = GetClassName(PD->getIdentifier()); 898 Values[2] = 899 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(), 900 PD->protocol_begin(), 901 PD->protocol_end()); 902 Values[3] = 903 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" 904 + PD->getNameAsString(), 905 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 906 InstanceMethods); 907 Values[4] = 908 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" 909 + PD->getNameAsString(), 910 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 911 ClassMethods); 912 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 913 Values); 914 915 if (Entry) { 916 // Already created, fix the linkage and update the initializer. 917 Entry->setLinkage(llvm::GlobalValue::InternalLinkage); 918 Entry->setInitializer(Init); 919 } else { 920 Entry = 921 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 922 llvm::GlobalValue::InternalLinkage, 923 Init, 924 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName, 925 &CGM.getModule()); 926 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 927 UsedGlobals.push_back(Entry); 928 // FIXME: Is this necessary? Why only for protocol? 929 Entry->setAlignment(4); 930 } 931 932 return Entry; 933} 934 935llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { 936 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 937 938 if (!Entry) { 939 // We use the initializer as a marker of whether this is a forward 940 // reference or not. At module finalization we add the empty 941 // contents for protocols which were referenced but never defined. 942 Entry = 943 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 944 llvm::GlobalValue::ExternalLinkage, 945 0, 946 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(), 947 &CGM.getModule()); 948 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 949 UsedGlobals.push_back(Entry); 950 // FIXME: Is this necessary? Why only for protocol? 951 Entry->setAlignment(4); 952 } 953 954 return Entry; 955} 956 957/* 958 struct _objc_protocol_extension { 959 uint32_t size; 960 struct objc_method_description_list *optional_instance_methods; 961 struct objc_method_description_list *optional_class_methods; 962 struct objc_property_list *instance_properties; 963 }; 964*/ 965llvm::Constant * 966CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, 967 const ConstantVector &OptInstanceMethods, 968 const ConstantVector &OptClassMethods) { 969 uint64_t Size = 970 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy); 971 std::vector<llvm::Constant*> Values(4); 972 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 973 Values[1] = 974 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" 975 + PD->getNameAsString(), 976 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 977 OptInstanceMethods); 978 Values[2] = 979 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" 980 + PD->getNameAsString(), 981 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 982 OptClassMethods); 983 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + 984 PD->getNameAsString(), 985 0, PD, ObjCTypes); 986 987 // Return null if no extension bits are used. 988 if (Values[1]->isNullValue() && Values[2]->isNullValue() && 989 Values[3]->isNullValue()) 990 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 991 992 llvm::Constant *Init = 993 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); 994 llvm::GlobalVariable *GV = 995 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false, 996 llvm::GlobalValue::InternalLinkage, 997 Init, 998 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(), 999 &CGM.getModule()); 1000 // No special section, but goes in llvm.used 1001 UsedGlobals.push_back(GV); 1002 1003 return GV; 1004} 1005 1006/* 1007 struct objc_protocol_list { 1008 struct objc_protocol_list *next; 1009 long count; 1010 Protocol *list[]; 1011 }; 1012*/ 1013llvm::Constant * 1014CGObjCMac::EmitProtocolList(const std::string &Name, 1015 ObjCProtocolDecl::protocol_iterator begin, 1016 ObjCProtocolDecl::protocol_iterator end) { 1017 std::vector<llvm::Constant*> ProtocolRefs; 1018 1019 for (; begin != end; ++begin) 1020 ProtocolRefs.push_back(GetProtocolRef(*begin)); 1021 1022 // Just return null for empty protocol lists 1023 if (ProtocolRefs.empty()) 1024 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1025 1026 // This list is null terminated. 1027 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); 1028 1029 std::vector<llvm::Constant*> Values(3); 1030 // This field is only used by the runtime. 1031 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1032 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 1033 Values[2] = 1034 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, 1035 ProtocolRefs.size()), 1036 ProtocolRefs); 1037 1038 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1039 llvm::GlobalVariable *GV = 1040 new llvm::GlobalVariable(Init->getType(), false, 1041 llvm::GlobalValue::InternalLinkage, 1042 Init, 1043 Name, 1044 &CGM.getModule()); 1045 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip"); 1046 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); 1047} 1048 1049/* 1050 struct _objc_property { 1051 const char * const name; 1052 const char * const attributes; 1053 }; 1054 1055 struct _objc_property_list { 1056 uint32_t entsize; // sizeof (struct _objc_property) 1057 uint32_t prop_count; 1058 struct _objc_property[prop_count]; 1059 }; 1060*/ 1061llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name, 1062 const Decl *Container, 1063 const ObjCContainerDecl *OCD, 1064 const ObjCCommonTypesHelper &ObjCTypes) { 1065 std::vector<llvm::Constant*> Properties, Prop(2); 1066 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(), 1067 E = OCD->prop_end(); I != E; ++I) { 1068 const ObjCPropertyDecl *PD = *I; 1069 Prop[0] = GetPropertyName(PD->getIdentifier()); 1070 Prop[1] = GetPropertyTypeString(PD, Container); 1071 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, 1072 Prop)); 1073 } 1074 1075 // Return null for empty list. 1076 if (Properties.empty()) 1077 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1078 1079 unsigned PropertySize = 1080 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy); 1081 std::vector<llvm::Constant*> Values(3); 1082 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); 1083 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); 1084 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, 1085 Properties.size()); 1086 Values[2] = llvm::ConstantArray::get(AT, Properties); 1087 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1088 1089 llvm::GlobalVariable *GV = 1090 new llvm::GlobalVariable(Init->getType(), false, 1091 llvm::GlobalValue::InternalLinkage, 1092 Init, 1093 Name, 1094 &CGM.getModule()); 1095 if (ObjCABI == 2) 1096 GV->setSection("__DATA, __objc_const"); 1097 // No special section on property lists? 1098 UsedGlobals.push_back(GV); 1099 return llvm::ConstantExpr::getBitCast(GV, 1100 ObjCTypes.PropertyListPtrTy); 1101 1102} 1103 1104/* 1105 struct objc_method_description_list { 1106 int count; 1107 struct objc_method_description list[]; 1108 }; 1109*/ 1110llvm::Constant * 1111CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 1112 std::vector<llvm::Constant*> Desc(2); 1113 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1114 ObjCTypes.SelectorPtrTy); 1115 Desc[1] = GetMethodVarType(MD); 1116 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, 1117 Desc); 1118} 1119 1120llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name, 1121 const char *Section, 1122 const ConstantVector &Methods) { 1123 // Return null for empty list. 1124 if (Methods.empty()) 1125 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 1126 1127 std::vector<llvm::Constant*> Values(2); 1128 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1129 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, 1130 Methods.size()); 1131 Values[1] = llvm::ConstantArray::get(AT, Methods); 1132 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1133 1134 llvm::GlobalVariable *GV = 1135 new llvm::GlobalVariable(Init->getType(), false, 1136 llvm::GlobalValue::InternalLinkage, 1137 Init, Name, &CGM.getModule()); 1138 GV->setSection(Section); 1139 UsedGlobals.push_back(GV); 1140 return llvm::ConstantExpr::getBitCast(GV, 1141 ObjCTypes.MethodDescriptionListPtrTy); 1142} 1143 1144/* 1145 struct _objc_category { 1146 char *category_name; 1147 char *class_name; 1148 struct _objc_method_list *instance_methods; 1149 struct _objc_method_list *class_methods; 1150 struct _objc_protocol_list *protocols; 1151 uint32_t size; // <rdar://4585769> 1152 struct _objc_property_list *instance_properties; 1153 }; 1154 */ 1155void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 1156 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy); 1157 1158 // FIXME: This is poor design, the OCD should have a pointer to the 1159 // category decl. Additionally, note that Category can be null for 1160 // the @implementation w/o an @interface case. Sema should just 1161 // create one for us as it does for @implementation so everyone else 1162 // can live life under a clear blue sky. 1163 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 1164 const ObjCCategoryDecl *Category = 1165 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 1166 std::string ExtName(Interface->getNameAsString() + "_" + 1167 OCD->getNameAsString()); 1168 1169 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1170 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), 1171 e = OCD->instmeth_end(); i != e; ++i) { 1172 // Instance methods should always be defined. 1173 InstanceMethods.push_back(GetMethodConstant(*i)); 1174 } 1175 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), 1176 e = OCD->classmeth_end(); i != e; ++i) { 1177 // Class methods should always be defined. 1178 ClassMethods.push_back(GetMethodConstant(*i)); 1179 } 1180 1181 std::vector<llvm::Constant*> Values(7); 1182 Values[0] = GetClassName(OCD->getIdentifier()); 1183 Values[1] = GetClassName(Interface->getIdentifier()); 1184 Values[2] = 1185 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") + 1186 ExtName, 1187 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1188 InstanceMethods); 1189 Values[3] = 1190 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName, 1191 "__OBJC,__cat_class_meth,regular,no_dead_strip", 1192 ClassMethods); 1193 if (Category) { 1194 Values[4] = 1195 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName, 1196 Category->protocol_begin(), 1197 Category->protocol_end()); 1198 } else { 1199 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1200 } 1201 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1202 1203 // If there is no category @interface then there can be no properties. 1204 if (Category) { 1205 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName, 1206 OCD, Category, ObjCTypes); 1207 } else { 1208 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1209 } 1210 1211 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, 1212 Values); 1213 1214 llvm::GlobalVariable *GV = 1215 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false, 1216 llvm::GlobalValue::InternalLinkage, 1217 Init, 1218 std::string("\01L_OBJC_CATEGORY_")+ExtName, 1219 &CGM.getModule()); 1220 GV->setSection("__OBJC,__category,regular,no_dead_strip"); 1221 UsedGlobals.push_back(GV); 1222 DefinedCategories.push_back(GV); 1223} 1224 1225// FIXME: Get from somewhere? 1226enum ClassFlags { 1227 eClassFlags_Factory = 0x00001, 1228 eClassFlags_Meta = 0x00002, 1229 // <rdr://5142207> 1230 eClassFlags_HasCXXStructors = 0x02000, 1231 eClassFlags_Hidden = 0x20000, 1232 eClassFlags_ABI2_Hidden = 0x00010, 1233 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634> 1234}; 1235 1236// <rdr://5142207&4705298&4843145> 1237static bool IsClassHidden(const ObjCInterfaceDecl *ID) { 1238 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) { 1239 // FIXME: Support -fvisibility 1240 switch (attr->getVisibility()) { 1241 default: 1242 assert(0 && "Unknown visibility"); 1243 return false; 1244 case VisibilityAttr::DefaultVisibility: 1245 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here? 1246 return false; 1247 case VisibilityAttr::HiddenVisibility: 1248 return true; 1249 } 1250 } else { 1251 return false; // FIXME: Support -fvisibility 1252 } 1253} 1254 1255/* 1256 struct _objc_class { 1257 Class isa; 1258 Class super_class; 1259 const char *name; 1260 long version; 1261 long info; 1262 long instance_size; 1263 struct _objc_ivar_list *ivars; 1264 struct _objc_method_list *methods; 1265 struct _objc_cache *cache; 1266 struct _objc_protocol_list *protocols; 1267 // Objective-C 1.0 extensions (<rdr://4585769>) 1268 const char *ivar_layout; 1269 struct _objc_class_ext *ext; 1270 }; 1271 1272 See EmitClassExtension(); 1273 */ 1274void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { 1275 DefinedSymbols.insert(ID->getIdentifier()); 1276 1277 std::string ClassName = ID->getNameAsString(); 1278 // FIXME: Gross 1279 ObjCInterfaceDecl *Interface = 1280 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 1281 llvm::Constant *Protocols = 1282 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(), 1283 Interface->protocol_begin(), 1284 Interface->protocol_end()); 1285 const llvm::Type *InterfaceTy = 1286 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface)); 1287 unsigned Flags = eClassFlags_Factory; 1288 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy); 1289 1290 // FIXME: Set CXX-structors flag. 1291 if (IsClassHidden(ID->getClassInterface())) 1292 Flags |= eClassFlags_Hidden; 1293 1294 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1295 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), 1296 e = ID->instmeth_end(); i != e; ++i) { 1297 // Instance methods should always be defined. 1298 InstanceMethods.push_back(GetMethodConstant(*i)); 1299 } 1300 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), 1301 e = ID->classmeth_end(); i != e; ++i) { 1302 // Class methods should always be defined. 1303 ClassMethods.push_back(GetMethodConstant(*i)); 1304 } 1305 1306 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), 1307 e = ID->propimpl_end(); i != e; ++i) { 1308 ObjCPropertyImplDecl *PID = *i; 1309 1310 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1311 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1312 1313 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 1314 if (llvm::Constant *C = GetMethodConstant(MD)) 1315 InstanceMethods.push_back(C); 1316 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 1317 if (llvm::Constant *C = GetMethodConstant(MD)) 1318 InstanceMethods.push_back(C); 1319 } 1320 } 1321 1322 std::vector<llvm::Constant*> Values(12); 1323 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods); 1324 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { 1325 // Record a reference to the super class. 1326 LazySymbols.insert(Super->getIdentifier()); 1327 1328 Values[ 1] = 1329 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1330 ObjCTypes.ClassPtrTy); 1331 } else { 1332 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1333 } 1334 Values[ 2] = GetClassName(ID->getIdentifier()); 1335 // Version is always 0. 1336 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1337 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1338 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1339 Values[ 6] = EmitIvarList(ID, false); 1340 Values[ 7] = 1341 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(), 1342 "__OBJC,__inst_meth,regular,no_dead_strip", 1343 InstanceMethods); 1344 // cache is always NULL. 1345 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1346 Values[ 9] = Protocols; 1347 // FIXME: Set ivar_layout 1348 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1349 Values[11] = EmitClassExtension(ID); 1350 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1351 Values); 1352 1353 llvm::GlobalVariable *GV = 1354 new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1355 llvm::GlobalValue::InternalLinkage, 1356 Init, 1357 std::string("\01L_OBJC_CLASS_")+ClassName, 1358 &CGM.getModule()); 1359 GV->setSection("__OBJC,__class,regular,no_dead_strip"); 1360 UsedGlobals.push_back(GV); 1361 // FIXME: Why? 1362 GV->setAlignment(32); 1363 DefinedClasses.push_back(GV); 1364} 1365 1366llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, 1367 llvm::Constant *Protocols, 1368 const llvm::Type *InterfaceTy, 1369 const ConstantVector &Methods) { 1370 unsigned Flags = eClassFlags_Meta; 1371 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy); 1372 1373 if (IsClassHidden(ID->getClassInterface())) 1374 Flags |= eClassFlags_Hidden; 1375 1376 std::vector<llvm::Constant*> Values(12); 1377 // The isa for the metaclass is the root of the hierarchy. 1378 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 1379 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 1380 Root = Super; 1381 Values[ 0] = 1382 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()), 1383 ObjCTypes.ClassPtrTy); 1384 // The super class for the metaclass is emitted as the name of the 1385 // super class. The runtime fixes this up to point to the 1386 // *metaclass* for the super class. 1387 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { 1388 Values[ 1] = 1389 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1390 ObjCTypes.ClassPtrTy); 1391 } else { 1392 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1393 } 1394 Values[ 2] = GetClassName(ID->getIdentifier()); 1395 // Version is always 0. 1396 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1397 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1398 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1399 Values[ 6] = EmitIvarList(ID, true); 1400 Values[ 7] = 1401 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(), 1402 "__OBJC,__inst_meth,regular,no_dead_strip", 1403 Methods); 1404 // cache is always NULL. 1405 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1406 Values[ 9] = Protocols; 1407 // ivar_layout for metaclass is always NULL. 1408 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1409 // The class extension is always unused for metaclasses. 1410 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1411 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1412 Values); 1413 1414 std::string Name("\01L_OBJC_METACLASS_"); 1415 Name += ID->getNameAsCString(); 1416 1417 // Check for a forward reference. 1418 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 1419 if (GV) { 1420 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1421 "Forward metaclass reference has incorrect type."); 1422 GV->setLinkage(llvm::GlobalValue::InternalLinkage); 1423 GV->setInitializer(Init); 1424 } else { 1425 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1426 llvm::GlobalValue::InternalLinkage, 1427 Init, Name, 1428 &CGM.getModule()); 1429 } 1430 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); 1431 UsedGlobals.push_back(GV); 1432 // FIXME: Why? 1433 GV->setAlignment(32); 1434 1435 return GV; 1436} 1437 1438llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { 1439 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString(); 1440 1441 // FIXME: Should we look these up somewhere other than the 1442 // module. Its a bit silly since we only generate these while 1443 // processing an implementation, so exactly one pointer would work 1444 // if know when we entered/exitted an implementation block. 1445 1446 // Check for an existing forward reference. 1447 // Previously, metaclass with internal linkage may have been defined. 1448 // pass 'true' as 2nd argument so it is returned. 1449 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) { 1450 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1451 "Forward metaclass reference has incorrect type."); 1452 return GV; 1453 } else { 1454 // Generate as an external reference to keep a consistent 1455 // module. This will be patched up when we emit the metaclass. 1456 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1457 llvm::GlobalValue::ExternalLinkage, 1458 0, 1459 Name, 1460 &CGM.getModule()); 1461 } 1462} 1463 1464/* 1465 struct objc_class_ext { 1466 uint32_t size; 1467 const char *weak_ivar_layout; 1468 struct _objc_property_list *properties; 1469 }; 1470*/ 1471llvm::Constant * 1472CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) { 1473 uint64_t Size = 1474 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy); 1475 1476 std::vector<llvm::Constant*> Values(3); 1477 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1478 // FIXME: Output weak_ivar_layout string. 1479 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1480 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 1481 ID, ID->getClassInterface(), ObjCTypes); 1482 1483 // Return null if no extension bits are used. 1484 if (Values[1]->isNullValue() && Values[2]->isNullValue()) 1485 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1486 1487 llvm::Constant *Init = 1488 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); 1489 llvm::GlobalVariable *GV = 1490 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false, 1491 llvm::GlobalValue::InternalLinkage, 1492 Init, 1493 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(), 1494 &CGM.getModule()); 1495 // No special section, but goes in llvm.used 1496 UsedGlobals.push_back(GV); 1497 1498 return GV; 1499} 1500 1501/// countInheritedIvars - count number of ivars in class and its super class(s) 1502/// 1503static int countInheritedIvars(const ObjCInterfaceDecl *OI) { 1504 int count = 0; 1505 if (!OI) 1506 return 0; 1507 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass(); 1508 if (SuperClass) 1509 count += countInheritedIvars(SuperClass); 1510 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1511 E = OI->ivar_end(); I != E; ++I) 1512 ++count; 1513 return count; 1514} 1515 1516/* 1517 struct objc_ivar { 1518 char *ivar_name; 1519 char *ivar_type; 1520 int ivar_offset; 1521 }; 1522 1523 struct objc_ivar_list { 1524 int ivar_count; 1525 struct objc_ivar list[count]; 1526 }; 1527 */ 1528llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, 1529 bool ForClass) { 1530 std::vector<llvm::Constant*> Ivars, Ivar(3); 1531 1532 // When emitting the root class GCC emits ivar entries for the 1533 // actual class structure. It is not clear if we need to follow this 1534 // behavior; for now lets try and get away with not doing it. If so, 1535 // the cleanest solution would be to make up an ObjCInterfaceDecl 1536 // for the class. 1537 if (ForClass) 1538 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1539 1540 ObjCInterfaceDecl *OID = 1541 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 1542 const llvm::Type *InterfaceTy = 1543 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID)); 1544 const llvm::StructLayout *Layout = 1545 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); 1546 1547 RecordDecl::field_iterator ifield, pfield; 1548 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield); 1549 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) { 1550 FieldDecl *Field = *ifield; 1551 unsigned Offset = Layout->getElementOffset(CGM.getTypes(). 1552 getLLVMFieldNo(Field)); 1553 if (Field->getIdentifier()) 1554 Ivar[0] = GetMethodVarName(Field->getIdentifier()); 1555 else 1556 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1557 std::string TypeStr; 1558 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); 1559 Ivar[1] = GetMethodVarType(TypeStr); 1560 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset); 1561 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar)); 1562 } 1563 1564 // Return null for empty list. 1565 if (Ivars.empty()) 1566 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1567 1568 std::vector<llvm::Constant*> Values(2); 1569 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 1570 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, 1571 Ivars.size()); 1572 Values[1] = llvm::ConstantArray::get(AT, Ivars); 1573 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1574 1575 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" : 1576 "\01L_OBJC_INSTANCE_VARIABLES_"); 1577 llvm::GlobalVariable *GV = 1578 new llvm::GlobalVariable(Init->getType(), false, 1579 llvm::GlobalValue::InternalLinkage, 1580 Init, 1581 Prefix + ID->getNameAsString(), 1582 &CGM.getModule()); 1583 if (ForClass) { 1584 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip"); 1585 // FIXME: Why is this only here? 1586 GV->setAlignment(32); 1587 } else { 1588 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip"); 1589 } 1590 UsedGlobals.push_back(GV); 1591 return llvm::ConstantExpr::getBitCast(GV, 1592 ObjCTypes.IvarListPtrTy); 1593} 1594 1595/* 1596 struct objc_method { 1597 SEL method_name; 1598 char *method_types; 1599 void *method; 1600 }; 1601 1602 struct objc_method_list { 1603 struct objc_method_list *obsolete; 1604 int count; 1605 struct objc_method methods_list[count]; 1606 }; 1607*/ 1608 1609/// GetMethodConstant - Return a struct objc_method constant for the 1610/// given method if it has been defined. The result is null if the 1611/// method has not been defined. The return value has type MethodPtrTy. 1612llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { 1613 // FIXME: Use DenseMap::lookup 1614 llvm::Function *Fn = MethodDefinitions[MD]; 1615 if (!Fn) 1616 return 0; 1617 1618 std::vector<llvm::Constant*> Method(3); 1619 Method[0] = 1620 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1621 ObjCTypes.SelectorPtrTy); 1622 Method[1] = GetMethodVarType(MD); 1623 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 1624 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 1625} 1626 1627llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name, 1628 const char *Section, 1629 const ConstantVector &Methods) { 1630 // Return null for empty list. 1631 if (Methods.empty()) 1632 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); 1633 1634 std::vector<llvm::Constant*> Values(3); 1635 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1636 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1637 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 1638 Methods.size()); 1639 Values[2] = llvm::ConstantArray::get(AT, Methods); 1640 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1641 1642 llvm::GlobalVariable *GV = 1643 new llvm::GlobalVariable(Init->getType(), false, 1644 llvm::GlobalValue::InternalLinkage, 1645 Init, 1646 Name, 1647 &CGM.getModule()); 1648 GV->setSection(Section); 1649 UsedGlobals.push_back(GV); 1650 return llvm::ConstantExpr::getBitCast(GV, 1651 ObjCTypes.MethodListPtrTy); 1652} 1653 1654llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD, 1655 const ObjCContainerDecl *CD) { 1656 std::string Name; 1657 GetNameForMethod(OMD, CD, Name); 1658 1659 const llvm::FunctionType *MethodTy = 1660 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext())); 1661 llvm::Function *Method = 1662 llvm::Function::Create(MethodTy, 1663 llvm::GlobalValue::InternalLinkage, 1664 Name, 1665 &CGM.getModule()); 1666 MethodDefinitions.insert(std::make_pair(OMD, Method)); 1667 1668 return Method; 1669} 1670 1671llvm::Function *CGObjCMac::ModuleInitFunction() { 1672 // Abuse this interface function as a place to finalize. 1673 FinishModule(); 1674 1675 return NULL; 1676} 1677 1678llvm::Function *CGObjCMac::GetPropertyGetFunction() { 1679 return ObjCTypes.GetPropertyFn; 1680} 1681 1682llvm::Function *CGObjCMac::GetPropertySetFunction() { 1683 return ObjCTypes.SetPropertyFn; 1684} 1685 1686llvm::Function *CGObjCMac::EnumerationMutationFunction() 1687{ 1688 return ObjCTypes.EnumerationMutationFn; 1689} 1690 1691/* 1692 1693Objective-C setjmp-longjmp (sjlj) Exception Handling 1694-- 1695 1696The basic framework for a @try-catch-finally is as follows: 1697{ 1698 objc_exception_data d; 1699 id _rethrow = null; 1700 1701 objc_exception_try_enter(&d); 1702 if (!setjmp(d.jmp_buf)) { 1703 ... try body ... 1704 } else { 1705 // exception path 1706 id _caught = objc_exception_extract(&d); 1707 1708 // enter new try scope for handlers 1709 if (!setjmp(d.jmp_buf)) { 1710 ... match exception and execute catch blocks ... 1711 1712 // fell off end, rethrow. 1713 _rethrow = _caught; 1714 ... jump-through-finally to finally_rethrow ... 1715 } else { 1716 // exception in catch block 1717 _rethrow = objc_exception_extract(&d); 1718 ... jump-through-finally_no_exit to finally_rethrow ... 1719 } 1720 } 1721 ... jump-through-finally to finally_end ... 1722 1723finally: 1724 // match either the initial try_enter or the catch try_enter, 1725 // depending on the path followed. 1726 objc_exception_try_exit(&d); 1727finally_no_exit: 1728 ... finally block .... 1729 ... dispatch to finally destination ... 1730 1731finally_rethrow: 1732 objc_exception_throw(_rethrow); 1733 1734finally_end: 1735} 1736 1737This framework differs slightly from the one gcc uses, in that gcc 1738uses _rethrow to determine if objc_exception_try_exit should be called 1739and if the object should be rethrown. This breaks in the face of 1740throwing nil and introduces unnecessary branches. 1741 1742We specialize this framework for a few particular circumstances: 1743 1744 - If there are no catch blocks, then we avoid emitting the second 1745 exception handling context. 1746 1747 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id 1748 e)) we avoid emitting the code to rethrow an uncaught exception. 1749 1750 - FIXME: If there is no @finally block we can do a few more 1751 simplifications. 1752 1753Rethrows and Jumps-Through-Finally 1754-- 1755 1756Support for implicit rethrows and jumping through the finally block is 1757handled by storing the current exception-handling context in 1758ObjCEHStack. 1759 1760In order to implement proper @finally semantics, we support one basic 1761mechanism for jumping through the finally block to an arbitrary 1762destination. Constructs which generate exits from a @try or @catch 1763block use this mechanism to implement the proper semantics by chaining 1764jumps, as necessary. 1765 1766This mechanism works like the one used for indirect goto: we 1767arbitrarily assign an ID to each destination and store the ID for the 1768destination in a variable prior to entering the finally block. At the 1769end of the finally block we simply create a switch to the proper 1770destination. 1771 1772Code gen for @synchronized(expr) stmt; 1773Effectively generating code for: 1774objc_sync_enter(expr); 1775@try stmt @finally { objc_sync_exit(expr); } 1776*/ 1777 1778void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1779 const Stmt &S) { 1780 bool isTry = isa<ObjCAtTryStmt>(S); 1781 // Create various blocks we refer to for handling @finally. 1782 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 1783 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit"); 1784 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 1785 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 1786 llvm::Value *DestCode = 1787 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst"); 1788 1789 // Generate jump code. Done here so we can directly add things to 1790 // the switch instruction. 1791 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump"); 1792 llvm::SwitchInst *FinallySwitch = 1793 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump), 1794 FinallyEnd, 10, FinallyJump); 1795 1796 // Push an EH context entry, used for handling rethrows and jumps 1797 // through finally. 1798 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit, 1799 FinallySwitch, DestCode); 1800 CGF.ObjCEHStack.push_back(&EHEntry); 1801 1802 // Allocate memory for the exception data and rethrow pointer. 1803 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, 1804 "exceptiondata.ptr"); 1805 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, 1806 "_rethrow"); 1807 if (!isTry) { 1808 // For @synchronized, call objc_sync_enter(sync.expr) 1809 llvm::Value *Arg = CGF.EmitScalarExpr( 1810 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1811 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy); 1812 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg); 1813 } 1814 1815 // Enter a new try block and call setjmp. 1816 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); 1817 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0, 1818 "jmpbufarray"); 1819 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp"); 1820 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, 1821 JmpBufPtr, "result"); 1822 1823 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 1824 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 1825 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"), 1826 TryHandler, TryBlock); 1827 1828 // Emit the @try block. 1829 CGF.EmitBlock(TryBlock); 1830 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 1831 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 1832 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd); 1833 1834 // Emit the "exception in @try" block. 1835 CGF.EmitBlock(TryHandler); 1836 1837 // Retrieve the exception object. We may emit multiple blocks but 1838 // nothing can cross this so the value is already in SSA form. 1839 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, 1840 ExceptionData, 1841 "caught"); 1842 EHEntry.Exception = Caught; 1843 if (!isTry) 1844 { 1845 CGF.Builder.CreateStore(Caught, RethrowPtr); 1846 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false); 1847 } 1848 else if (const ObjCAtCatchStmt* CatchStmt = 1849 cast<ObjCAtTryStmt>(S).getCatchStmts()) 1850 { 1851 // Enter a new exception try block (in case a @catch block throws 1852 // an exception). 1853 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); 1854 1855 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, 1856 JmpBufPtr, "result"); 1857 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"); 1858 1859 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch"); 1860 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler"); 1861 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); 1862 1863 CGF.EmitBlock(CatchBlock); 1864 1865 // Handle catch list. As a special case we check if everything is 1866 // matched and avoid generating code for falling off the end if 1867 // so. 1868 bool AllMatched = false; 1869 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 1870 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch"); 1871 1872 const DeclStmt *CatchParam = 1873 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt()); 1874 const VarDecl *VD = 0; 1875 const PointerType *PT = 0; 1876 1877 // catch(...) always matches. 1878 if (!CatchParam) { 1879 AllMatched = true; 1880 } else { 1881 VD = cast<VarDecl>(CatchParam->getSolitaryDecl()); 1882 PT = VD->getType()->getAsPointerType(); 1883 1884 // catch(id e) always matches. 1885 // FIXME: For the time being we also match id<X>; this should 1886 // be rejected by Sema instead. 1887 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) || 1888 VD->getType()->isObjCQualifiedIdType()) 1889 AllMatched = true; 1890 } 1891 1892 if (AllMatched) { 1893 if (CatchParam) { 1894 CGF.EmitStmt(CatchParam); 1895 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 1896 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD)); 1897 } 1898 1899 CGF.EmitStmt(CatchStmt->getCatchBody()); 1900 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd); 1901 break; 1902 } 1903 1904 assert(PT && "Unexpected non-pointer type in @catch"); 1905 QualType T = PT->getPointeeType(); 1906 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType(); 1907 assert(ObjCType && "Catch parameter must have Objective-C type!"); 1908 1909 // Check if the @catch block matches the exception object. 1910 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl()); 1911 1912 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn, 1913 Class, Caught, "match"); 1914 1915 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched"); 1916 1917 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), 1918 MatchedBlock, NextCatchBlock); 1919 1920 // Emit the @catch block. 1921 CGF.EmitBlock(MatchedBlock); 1922 CGF.EmitStmt(CatchParam); 1923 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 1924 1925 llvm::Value *Tmp = 1926 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()), 1927 "tmp"); 1928 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD)); 1929 1930 CGF.EmitStmt(CatchStmt->getCatchBody()); 1931 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd); 1932 1933 CGF.EmitBlock(NextCatchBlock); 1934 } 1935 1936 if (!AllMatched) { 1937 // None of the handlers caught the exception, so store it to be 1938 // rethrown at the end of the @finally block. 1939 CGF.Builder.CreateStore(Caught, RethrowPtr); 1940 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow); 1941 } 1942 1943 // Emit the exception handler for the @catch blocks. 1944 CGF.EmitBlock(CatchHandler); 1945 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, 1946 ExceptionData), 1947 RethrowPtr); 1948 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false); 1949 } else { 1950 CGF.Builder.CreateStore(Caught, RethrowPtr); 1951 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false); 1952 } 1953 1954 // Pop the exception-handling stack entry. It is important to do 1955 // this now, because the code in the @finally block is not in this 1956 // context. 1957 CGF.ObjCEHStack.pop_back(); 1958 1959 // Emit the @finally block. 1960 CGF.EmitBlock(FinallyBlock); 1961 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData); 1962 1963 CGF.EmitBlock(FinallyNoExit); 1964 if (isTry) { 1965 if (const ObjCAtFinallyStmt* FinallyStmt = 1966 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 1967 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 1968 } 1969 else { 1970 // For @synchronized objc_sync_exit(expr); As finally's sole statement. 1971 // For @synchronized, call objc_sync_enter(sync.expr) 1972 llvm::Value *Arg = CGF.EmitScalarExpr( 1973 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1974 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy); 1975 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg); 1976 } 1977 1978 CGF.EmitBlock(FinallyJump); 1979 1980 CGF.EmitBlock(FinallyRethrow); 1981 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, 1982 CGF.Builder.CreateLoad(RethrowPtr)); 1983 CGF.Builder.CreateUnreachable(); 1984 1985 CGF.EmitBlock(FinallyEnd); 1986} 1987 1988void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 1989 const ObjCAtThrowStmt &S) { 1990 llvm::Value *ExceptionAsObject; 1991 1992 if (const Expr *ThrowExpr = S.getThrowExpr()) { 1993 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 1994 ExceptionAsObject = 1995 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); 1996 } else { 1997 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) && 1998 "Unexpected rethrow outside @catch block."); 1999 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception; 2000 } 2001 2002 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject); 2003 CGF.Builder.CreateUnreachable(); 2004 2005 // Clear the insertion point to indicate we are in unreachable code. 2006 CGF.Builder.ClearInsertionPoint(); 2007} 2008 2009void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E, 2010 llvm::BasicBlock *Dst, 2011 bool ExecuteTryExit) { 2012 if (!HaveInsertPoint()) 2013 return; 2014 2015 // Find the destination code for this block. We always use 0 for the 2016 // fallthrough block (default destination). 2017 llvm::SwitchInst *SI = E->FinallySwitch; 2018 llvm::ConstantInt *ID; 2019 if (Dst == SI->getDefaultDest()) { 2020 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0); 2021 } else { 2022 ID = SI->findCaseDest(Dst); 2023 if (!ID) { 2024 // No code found, get a new unique one by just using the number 2025 // of switch successors. 2026 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors()); 2027 SI->addCase(ID, Dst); 2028 } 2029 } 2030 2031 // Set the destination code and branch. 2032 Builder.CreateStore(ID, E->DestCode); 2033 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit); 2034} 2035 2036/// EmitObjCWeakRead - Code gen for loading value of a __weak 2037/// object: objc_read_weak (id *src) 2038/// 2039llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 2040 llvm::Value *AddrWeakObj) 2041{ 2042 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 2043 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn, 2044 AddrWeakObj, "weakread"); 2045 return read_weak; 2046} 2047 2048/// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 2049/// objc_assign_weak (id src, id *dst) 2050/// 2051void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 2052 llvm::Value *src, llvm::Value *dst) 2053{ 2054 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2055 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2056 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn, 2057 src, dst, "weakassign"); 2058 return; 2059} 2060 2061/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 2062/// objc_assign_global (id src, id *dst) 2063/// 2064void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 2065 llvm::Value *src, llvm::Value *dst) 2066{ 2067 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2068 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2069 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn, 2070 src, dst, "globalassign"); 2071 return; 2072} 2073 2074/// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 2075/// objc_assign_ivar (id src, id *dst) 2076/// 2077void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 2078 llvm::Value *src, llvm::Value *dst) 2079{ 2080 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2081 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2082 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn, 2083 src, dst, "assignivar"); 2084 return; 2085} 2086 2087/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 2088/// objc_assign_strongCast (id src, id *dst) 2089/// 2090void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 2091 llvm::Value *src, llvm::Value *dst) 2092{ 2093 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2094 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2095 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn, 2096 src, dst, "weakassign"); 2097 return; 2098} 2099 2100/* *** Private Interface *** */ 2101 2102/// EmitImageInfo - Emit the image info marker used to encode some module 2103/// level information. 2104/// 2105/// See: <rdr://4810609&4810587&4810587> 2106/// struct IMAGE_INFO { 2107/// unsigned version; 2108/// unsigned flags; 2109/// }; 2110enum ImageInfoFlags { 2111 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies 2112 eImageInfo_GarbageCollected = (1 << 1), 2113 eImageInfo_GCOnly = (1 << 2) 2114}; 2115 2116void CGObjCMac::EmitImageInfo() { 2117 unsigned version = 0; // Version is unused? 2118 unsigned flags = 0; 2119 2120 // FIXME: Fix and continue? 2121 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 2122 flags |= eImageInfo_GarbageCollected; 2123 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 2124 flags |= eImageInfo_GCOnly; 2125 2126 // Emitted as int[2]; 2127 llvm::Constant *values[2] = { 2128 llvm::ConstantInt::get(llvm::Type::Int32Ty, version), 2129 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags) 2130 }; 2131 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2); 2132 llvm::GlobalVariable *GV = 2133 new llvm::GlobalVariable(AT, true, 2134 llvm::GlobalValue::InternalLinkage, 2135 llvm::ConstantArray::get(AT, values, 2), 2136 "\01L_OBJC_IMAGE_INFO", 2137 &CGM.getModule()); 2138 2139 if (ObjCABI == 1) { 2140 GV->setSection("__OBJC, __image_info,regular"); 2141 } else { 2142 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); 2143 } 2144 2145 UsedGlobals.push_back(GV); 2146} 2147 2148 2149// struct objc_module { 2150// unsigned long version; 2151// unsigned long size; 2152// const char *name; 2153// Symtab symtab; 2154// }; 2155 2156// FIXME: Get from somewhere 2157static const int ModuleVersion = 7; 2158 2159void CGObjCMac::EmitModuleInfo() { 2160 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy); 2161 2162 std::vector<llvm::Constant*> Values(4); 2163 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion); 2164 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 2165 // This used to be the filename, now it is unused. <rdr://4327263> 2166 Values[2] = GetClassName(&CGM.getContext().Idents.get("")); 2167 Values[3] = EmitModuleSymbols(); 2168 2169 llvm::GlobalVariable *GV = 2170 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false, 2171 llvm::GlobalValue::InternalLinkage, 2172 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, 2173 Values), 2174 "\01L_OBJC_MODULES", 2175 &CGM.getModule()); 2176 GV->setSection("__OBJC,__module_info,regular,no_dead_strip"); 2177 UsedGlobals.push_back(GV); 2178} 2179 2180llvm::Constant *CGObjCMac::EmitModuleSymbols() { 2181 unsigned NumClasses = DefinedClasses.size(); 2182 unsigned NumCategories = DefinedCategories.size(); 2183 2184 // Return null if no symbols were defined. 2185 if (!NumClasses && !NumCategories) 2186 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); 2187 2188 std::vector<llvm::Constant*> Values(5); 2189 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 2190 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); 2191 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); 2192 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); 2193 2194 // The runtime expects exactly the list of defined classes followed 2195 // by the list of defined categories, in a single array. 2196 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories); 2197 for (unsigned i=0; i<NumClasses; i++) 2198 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 2199 ObjCTypes.Int8PtrTy); 2200 for (unsigned i=0; i<NumCategories; i++) 2201 Symbols[NumClasses + i] = 2202 llvm::ConstantExpr::getBitCast(DefinedCategories[i], 2203 ObjCTypes.Int8PtrTy); 2204 2205 Values[4] = 2206 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 2207 NumClasses + NumCategories), 2208 Symbols); 2209 2210 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 2211 2212 llvm::GlobalVariable *GV = 2213 new llvm::GlobalVariable(Init->getType(), false, 2214 llvm::GlobalValue::InternalLinkage, 2215 Init, 2216 "\01L_OBJC_SYMBOLS", 2217 &CGM.getModule()); 2218 GV->setSection("__OBJC,__symbols,regular,no_dead_strip"); 2219 UsedGlobals.push_back(GV); 2220 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); 2221} 2222 2223llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder, 2224 const ObjCInterfaceDecl *ID) { 2225 LazySymbols.insert(ID->getIdentifier()); 2226 2227 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 2228 2229 if (!Entry) { 2230 llvm::Constant *Casted = 2231 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()), 2232 ObjCTypes.ClassPtrTy); 2233 Entry = 2234 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false, 2235 llvm::GlobalValue::InternalLinkage, 2236 Casted, "\01L_OBJC_CLASS_REFERENCES_", 2237 &CGM.getModule()); 2238 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip"); 2239 UsedGlobals.push_back(Entry); 2240 } 2241 2242 return Builder.CreateLoad(Entry, false, "tmp"); 2243} 2244 2245llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) { 2246 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 2247 2248 if (!Entry) { 2249 llvm::Constant *Casted = 2250 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 2251 ObjCTypes.SelectorPtrTy); 2252 Entry = 2253 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false, 2254 llvm::GlobalValue::InternalLinkage, 2255 Casted, "\01L_OBJC_SELECTOR_REFERENCES_", 2256 &CGM.getModule()); 2257 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip"); 2258 UsedGlobals.push_back(Entry); 2259 } 2260 2261 return Builder.CreateLoad(Entry, false, "tmp"); 2262} 2263 2264llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) { 2265 llvm::GlobalVariable *&Entry = ClassNames[Ident]; 2266 2267 if (!Entry) { 2268 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName()); 2269 Entry = 2270 new llvm::GlobalVariable(C->getType(), false, 2271 llvm::GlobalValue::InternalLinkage, 2272 C, "\01L_OBJC_CLASS_NAME_", 2273 &CGM.getModule()); 2274 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2275 UsedGlobals.push_back(Entry); 2276 } 2277 2278 return getConstantGEP(Entry, 0, 0); 2279} 2280 2281llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { 2282 llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; 2283 2284 if (!Entry) { 2285 // FIXME: Avoid std::string copying. 2286 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString()); 2287 Entry = 2288 new llvm::GlobalVariable(C->getType(), false, 2289 llvm::GlobalValue::InternalLinkage, 2290 C, "\01L_OBJC_METH_VAR_NAME_", 2291 &CGM.getModule()); 2292 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2293 UsedGlobals.push_back(Entry); 2294 } 2295 2296 return getConstantGEP(Entry, 0, 0); 2297} 2298 2299// FIXME: Merge into a single cstring creation function. 2300llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { 2301 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); 2302} 2303 2304// FIXME: Merge into a single cstring creation function. 2305llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) { 2306 return GetMethodVarName(&CGM.getContext().Idents.get(Name)); 2307} 2308 2309llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) { 2310 llvm::GlobalVariable *&Entry = MethodVarTypes[Name]; 2311 2312 if (!Entry) { 2313 llvm::Constant *C = llvm::ConstantArray::get(Name); 2314 Entry = 2315 new llvm::GlobalVariable(C->getType(), false, 2316 llvm::GlobalValue::InternalLinkage, 2317 C, "\01L_OBJC_METH_VAR_TYPE_", 2318 &CGM.getModule()); 2319 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2320 UsedGlobals.push_back(Entry); 2321 } 2322 2323 return getConstantGEP(Entry, 0, 0); 2324} 2325 2326// FIXME: Merge into a single cstring creation function. 2327llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) { 2328 std::string TypeStr; 2329 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D), 2330 TypeStr); 2331 return GetMethodVarType(TypeStr); 2332} 2333 2334// FIXME: Merge into a single cstring creation function. 2335llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { 2336 llvm::GlobalVariable *&Entry = PropertyNames[Ident]; 2337 2338 if (!Entry) { 2339 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName()); 2340 Entry = 2341 new llvm::GlobalVariable(C->getType(), false, 2342 llvm::GlobalValue::InternalLinkage, 2343 C, "\01L_OBJC_PROP_NAME_ATTR_", 2344 &CGM.getModule()); 2345 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2346 UsedGlobals.push_back(Entry); 2347 } 2348 2349 return getConstantGEP(Entry, 0, 0); 2350} 2351 2352// FIXME: Merge into a single cstring creation function. 2353// FIXME: This Decl should be more precise. 2354llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, 2355 const Decl *Container) { 2356 std::string TypeStr; 2357 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 2358 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); 2359} 2360 2361void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, 2362 const ObjCContainerDecl *CD, 2363 std::string &NameOut) { 2364 // FIXME: Find the mangling GCC uses. 2365 NameOut = (D->isInstanceMethod() ? "-" : "+"); 2366 NameOut += '['; 2367 assert (CD && "Missing container decl in GetNameForMethod"); 2368 NameOut += CD->getNameAsString(); 2369 // FIXME. For a method in a category, (CAT_NAME) is inserted here. 2370 // Right now! there is not enough info. to do this. 2371 NameOut += ' '; 2372 NameOut += D->getSelector().getAsString(); 2373 NameOut += ']'; 2374} 2375 2376/// GetFirstIvarInRecord - This routine returns the record for the 2377/// implementation of the fiven class OID. It also returns field 2378/// corresponding to the first ivar in the class in FIV. It also 2379/// returns the one before the first ivar. 2380/// 2381const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord( 2382 const ObjCInterfaceDecl *OID, 2383 RecordDecl::field_iterator &FIV, 2384 RecordDecl::field_iterator &PIV) { 2385 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass()); 2386 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID); 2387 RecordDecl::field_iterator ifield = RD->field_begin(); 2388 RecordDecl::field_iterator pfield = RD->field_end(); 2389 while (countSuperClassIvars-- > 0) { 2390 pfield = ifield; 2391 ++ifield; 2392 } 2393 FIV = ifield; 2394 PIV = pfield; 2395 return RD; 2396} 2397 2398void CGObjCMac::FinishModule() { 2399 EmitModuleInfo(); 2400 2401 // Emit the dummy bodies for any protocols which were referenced but 2402 // never defined. 2403 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator 2404 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) { 2405 if (i->second->hasInitializer()) 2406 continue; 2407 2408 std::vector<llvm::Constant*> Values(5); 2409 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 2410 Values[1] = GetClassName(i->first); 2411 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 2412 Values[3] = Values[4] = 2413 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 2414 i->second->setLinkage(llvm::GlobalValue::InternalLinkage); 2415 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 2416 Values)); 2417 } 2418 2419 std::vector<llvm::Constant*> Used; 2420 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 2421 e = UsedGlobals.end(); i != e; ++i) { 2422 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 2423 } 2424 2425 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 2426 llvm::GlobalValue *GV = 2427 new llvm::GlobalVariable(AT, false, 2428 llvm::GlobalValue::AppendingLinkage, 2429 llvm::ConstantArray::get(AT, Used), 2430 "llvm.used", 2431 &CGM.getModule()); 2432 2433 GV->setSection("llvm.metadata"); 2434 2435 // Add assembler directives to add lazy undefined symbol references 2436 // for classes which are referenced but not defined. This is 2437 // important for correct linker interaction. 2438 2439 // FIXME: Uh, this isn't particularly portable. 2440 std::stringstream s; 2441 2442 if (!CGM.getModule().getModuleInlineAsm().empty()) 2443 s << "\n"; 2444 2445 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(), 2446 e = LazySymbols.end(); i != e; ++i) { 2447 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n"; 2448 } 2449 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(), 2450 e = DefinedSymbols.end(); i != e; ++i) { 2451 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n" 2452 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n"; 2453 } 2454 2455 CGM.getModule().appendModuleInlineAsm(s.str()); 2456} 2457 2458CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) 2459 : CGObjCCommonMac(cgm), 2460 ObjCTypes(cgm) 2461{ 2462 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL; 2463 ObjCABI = 2; 2464} 2465 2466/* *** */ 2467 2468ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) 2469: CGM(cgm) 2470{ 2471 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 2472 ASTContext &Ctx = CGM.getContext(); 2473 2474 ShortTy = Types.ConvertType(Ctx.ShortTy); 2475 IntTy = Types.ConvertType(Ctx.IntTy); 2476 LongTy = Types.ConvertType(Ctx.LongTy); 2477 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 2478 2479 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); 2480 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); 2481 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); 2482 2483 // FIXME: It would be nice to unify this with the opaque type, so 2484 // that the IR comes out a bit cleaner. 2485 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); 2486 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); 2487 2488 // I'm not sure I like this. The implicit coordination is a bit 2489 // gross. We should solve this in a reasonable fashion because this 2490 // is a pretty common task (match some runtime data structure with 2491 // an LLVM data structure). 2492 2493 // FIXME: This is leaked. 2494 // FIXME: Merge with rewriter code? 2495 2496 // struct _objc_super { 2497 // id self; 2498 // Class cls; 2499 // } 2500 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 2501 SourceLocation(), 2502 &Ctx.Idents.get("_objc_super")); 2503 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 2504 Ctx.getObjCIdType(), 0, false)); 2505 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 2506 Ctx.getObjCClassType(), 0, false)); 2507 RD->completeDefinition(Ctx); 2508 2509 SuperCTy = Ctx.getTagDeclType(RD); 2510 SuperPtrCTy = Ctx.getPointerType(SuperCTy); 2511 2512 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); 2513 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); 2514 2515 // struct _prop_t { 2516 // char *name; 2517 // char *attributes; 2518 // } 2519 PropertyTy = llvm::StructType::get(Int8PtrTy, 2520 Int8PtrTy, 2521 NULL); 2522 CGM.getModule().addTypeName("struct._prop_t", 2523 PropertyTy); 2524 2525 // struct _prop_list_t { 2526 // uint32_t entsize; // sizeof(struct _prop_t) 2527 // uint32_t count_of_properties; 2528 // struct _prop_t prop_list[count_of_properties]; 2529 // } 2530 PropertyListTy = llvm::StructType::get(IntTy, 2531 IntTy, 2532 llvm::ArrayType::get(PropertyTy, 0), 2533 NULL); 2534 CGM.getModule().addTypeName("struct._prop_list_t", 2535 PropertyListTy); 2536 // struct _prop_list_t * 2537 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); 2538 2539 // struct _objc_method { 2540 // SEL _cmd; 2541 // char *method_type; 2542 // char *_imp; 2543 // } 2544 MethodTy = llvm::StructType::get(SelectorPtrTy, 2545 Int8PtrTy, 2546 Int8PtrTy, 2547 NULL); 2548 CGM.getModule().addTypeName("struct._objc_method", MethodTy); 2549 2550 // struct _objc_cache * 2551 CacheTy = llvm::OpaqueType::get(); 2552 CGM.getModule().addTypeName("struct._objc_cache", CacheTy); 2553 CachePtrTy = llvm::PointerType::getUnqual(CacheTy); 2554 2555 // Property manipulation functions. 2556 2557 // id objc_getProperty (id, SEL, ptrdiff_t, bool) 2558 std::vector<const llvm::Type*> Params; 2559 Params.push_back(ObjectPtrTy); 2560 Params.push_back(SelectorPtrTy); 2561 Params.push_back(LongTy); 2562 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy)); 2563 GetPropertyFn = 2564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2565 Params, 2566 false), 2567 "objc_getProperty"); 2568 2569 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 2570 Params.clear(); 2571 Params.push_back(ObjectPtrTy); 2572 Params.push_back(SelectorPtrTy); 2573 Params.push_back(LongTy); 2574 Params.push_back(ObjectPtrTy); 2575 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy)); 2576 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy)); 2577 SetPropertyFn = 2578 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2579 Params, 2580 false), 2581 "objc_setProperty"); 2582 // Enumeration mutation. 2583 2584 Params.clear(); 2585 Params.push_back(ObjectPtrTy); 2586 EnumerationMutationFn = 2587 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2588 Params, 2589 false), 2590 "objc_enumerationMutation"); 2591 2592 // gc's API 2593 // id objc_read_weak (id *) 2594 Params.clear(); 2595 Params.push_back(PtrObjectPtrTy); 2596 GcReadWeakFn = 2597 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2598 Params, 2599 false), 2600 "objc_read_weak"); 2601 // id objc_assign_weak (id, id *) 2602 Params.clear(); 2603 Params.push_back(ObjectPtrTy); 2604 Params.push_back(PtrObjectPtrTy); 2605 GcAssignWeakFn = 2606 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2607 Params, 2608 false), 2609 "objc_assign_weak"); 2610 GcAssignGlobalFn = 2611 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2612 Params, 2613 false), 2614 "objc_assign_global"); 2615 GcAssignIvarFn = 2616 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2617 Params, 2618 false), 2619 "objc_assign_ivar"); 2620 GcAssignStrongCastFn = 2621 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2622 Params, 2623 false), 2624 "objc_assign_strongCast"); 2625} 2626 2627ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) 2628 : ObjCCommonTypesHelper(cgm) 2629{ 2630 // struct _objc_method_description { 2631 // SEL name; 2632 // char *types; 2633 // } 2634 MethodDescriptionTy = 2635 llvm::StructType::get(SelectorPtrTy, 2636 Int8PtrTy, 2637 NULL); 2638 CGM.getModule().addTypeName("struct._objc_method_description", 2639 MethodDescriptionTy); 2640 2641 // struct _objc_method_description_list { 2642 // int count; 2643 // struct _objc_method_description[1]; 2644 // } 2645 MethodDescriptionListTy = 2646 llvm::StructType::get(IntTy, 2647 llvm::ArrayType::get(MethodDescriptionTy, 0), 2648 NULL); 2649 CGM.getModule().addTypeName("struct._objc_method_description_list", 2650 MethodDescriptionListTy); 2651 2652 // struct _objc_method_description_list * 2653 MethodDescriptionListPtrTy = 2654 llvm::PointerType::getUnqual(MethodDescriptionListTy); 2655 2656 // Protocol description structures 2657 2658 // struct _objc_protocol_extension { 2659 // uint32_t size; // sizeof(struct _objc_protocol_extension) 2660 // struct _objc_method_description_list *optional_instance_methods; 2661 // struct _objc_method_description_list *optional_class_methods; 2662 // struct _objc_property_list *instance_properties; 2663 // } 2664 ProtocolExtensionTy = 2665 llvm::StructType::get(IntTy, 2666 MethodDescriptionListPtrTy, 2667 MethodDescriptionListPtrTy, 2668 PropertyListPtrTy, 2669 NULL); 2670 CGM.getModule().addTypeName("struct._objc_protocol_extension", 2671 ProtocolExtensionTy); 2672 2673 // struct _objc_protocol_extension * 2674 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); 2675 2676 // Handle recursive construction of Protocol and ProtocolList types 2677 2678 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get(); 2679 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 2680 2681 const llvm::Type *T = 2682 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder), 2683 LongTy, 2684 llvm::ArrayType::get(ProtocolTyHolder, 0), 2685 NULL); 2686 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T); 2687 2688 // struct _objc_protocol { 2689 // struct _objc_protocol_extension *isa; 2690 // char *protocol_name; 2691 // struct _objc_protocol **_objc_protocol_list; 2692 // struct _objc_method_description_list *instance_methods; 2693 // struct _objc_method_description_list *class_methods; 2694 // } 2695 T = llvm::StructType::get(ProtocolExtensionPtrTy, 2696 Int8PtrTy, 2697 llvm::PointerType::getUnqual(ProtocolListTyHolder), 2698 MethodDescriptionListPtrTy, 2699 MethodDescriptionListPtrTy, 2700 NULL); 2701 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T); 2702 2703 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get()); 2704 CGM.getModule().addTypeName("struct._objc_protocol_list", 2705 ProtocolListTy); 2706 // struct _objc_protocol_list * 2707 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); 2708 2709 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get()); 2710 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy); 2711 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); 2712 2713 // Class description structures 2714 2715 // struct _objc_ivar { 2716 // char *ivar_name; 2717 // char *ivar_type; 2718 // int ivar_offset; 2719 // } 2720 IvarTy = llvm::StructType::get(Int8PtrTy, 2721 Int8PtrTy, 2722 IntTy, 2723 NULL); 2724 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy); 2725 2726 // struct _objc_ivar_list * 2727 IvarListTy = llvm::OpaqueType::get(); 2728 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy); 2729 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); 2730 2731 // struct _objc_method_list * 2732 MethodListTy = llvm::OpaqueType::get(); 2733 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy); 2734 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); 2735 2736 // struct _objc_class_extension * 2737 ClassExtensionTy = 2738 llvm::StructType::get(IntTy, 2739 Int8PtrTy, 2740 PropertyListPtrTy, 2741 NULL); 2742 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy); 2743 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); 2744 2745 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 2746 2747 // struct _objc_class { 2748 // Class isa; 2749 // Class super_class; 2750 // char *name; 2751 // long version; 2752 // long info; 2753 // long instance_size; 2754 // struct _objc_ivar_list *ivars; 2755 // struct _objc_method_list *methods; 2756 // struct _objc_cache *cache; 2757 // struct _objc_protocol_list *protocols; 2758 // char *ivar_layout; 2759 // struct _objc_class_ext *ext; 2760 // }; 2761 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 2762 llvm::PointerType::getUnqual(ClassTyHolder), 2763 Int8PtrTy, 2764 LongTy, 2765 LongTy, 2766 LongTy, 2767 IvarListPtrTy, 2768 MethodListPtrTy, 2769 CachePtrTy, 2770 ProtocolListPtrTy, 2771 Int8PtrTy, 2772 ClassExtensionPtrTy, 2773 NULL); 2774 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T); 2775 2776 ClassTy = cast<llvm::StructType>(ClassTyHolder.get()); 2777 CGM.getModule().addTypeName("struct._objc_class", ClassTy); 2778 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); 2779 2780 // struct _objc_category { 2781 // char *category_name; 2782 // char *class_name; 2783 // struct _objc_method_list *instance_method; 2784 // struct _objc_method_list *class_method; 2785 // uint32_t size; // sizeof(struct _objc_category) 2786 // struct _objc_property_list *instance_properties;// category's @property 2787 // } 2788 CategoryTy = llvm::StructType::get(Int8PtrTy, 2789 Int8PtrTy, 2790 MethodListPtrTy, 2791 MethodListPtrTy, 2792 ProtocolListPtrTy, 2793 IntTy, 2794 PropertyListPtrTy, 2795 NULL); 2796 CGM.getModule().addTypeName("struct._objc_category", CategoryTy); 2797 2798 // Global metadata structures 2799 2800 // struct _objc_symtab { 2801 // long sel_ref_cnt; 2802 // SEL *refs; 2803 // short cls_def_cnt; 2804 // short cat_def_cnt; 2805 // char *defs[cls_def_cnt + cat_def_cnt]; 2806 // } 2807 SymtabTy = llvm::StructType::get(LongTy, 2808 SelectorPtrTy, 2809 ShortTy, 2810 ShortTy, 2811 llvm::ArrayType::get(Int8PtrTy, 0), 2812 NULL); 2813 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy); 2814 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); 2815 2816 // struct _objc_module { 2817 // long version; 2818 // long size; // sizeof(struct _objc_module) 2819 // char *name; 2820 // struct _objc_symtab* symtab; 2821 // } 2822 ModuleTy = 2823 llvm::StructType::get(LongTy, 2824 LongTy, 2825 Int8PtrTy, 2826 SymtabPtrTy, 2827 NULL); 2828 CGM.getModule().addTypeName("struct._objc_module", ModuleTy); 2829 2830 // Message send functions. 2831 2832 // id objc_msgSend (id, SEL, ...) 2833 std::vector<const llvm::Type*> Params; 2834 Params.push_back(ObjectPtrTy); 2835 Params.push_back(SelectorPtrTy); 2836 MessageSendFn = 2837 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2838 Params, 2839 true), 2840 "objc_msgSend"); 2841 2842 // id objc_msgSend_stret (id, SEL, ...) 2843 Params.clear(); 2844 Params.push_back(ObjectPtrTy); 2845 Params.push_back(SelectorPtrTy); 2846 MessageSendStretFn = 2847 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2848 Params, 2849 true), 2850 "objc_msgSend_stret"); 2851 2852 // 2853 Params.clear(); 2854 Params.push_back(ObjectPtrTy); 2855 Params.push_back(SelectorPtrTy); 2856 // FIXME: This should be long double on x86_64? 2857 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...) 2858 MessageSendFpretFn = 2859 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy, 2860 Params, 2861 true), 2862 "objc_msgSend_fpret"); 2863 2864 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...) 2865 Params.clear(); 2866 Params.push_back(SuperPtrTy); 2867 Params.push_back(SelectorPtrTy); 2868 MessageSendSuperFn = 2869 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2870 Params, 2871 true), 2872 "objc_msgSendSuper"); 2873 2874 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super, 2875 // SEL op, ...) 2876 Params.clear(); 2877 Params.push_back(Int8PtrTy); 2878 Params.push_back(SuperPtrTy); 2879 Params.push_back(SelectorPtrTy); 2880 MessageSendSuperStretFn = 2881 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2882 Params, 2883 true), 2884 "objc_msgSendSuper_stret"); 2885 2886 // There is no objc_msgSendSuper_fpret? How can that work? 2887 MessageSendSuperFpretFn = MessageSendSuperFn; 2888 2889 // FIXME: This is the size of the setjmp buffer and should be 2890 // target specific. 18 is what's used on 32-bit X86. 2891 uint64_t SetJmpBufferSize = 18; 2892 2893 // Exceptions 2894 const llvm::Type *StackPtrTy = 2895 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4); 2896 2897 ExceptionDataTy = 2898 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty, 2899 SetJmpBufferSize), 2900 StackPtrTy, NULL); 2901 CGM.getModule().addTypeName("struct._objc_exception_data", 2902 ExceptionDataTy); 2903 2904 Params.clear(); 2905 Params.push_back(ObjectPtrTy); 2906 ExceptionThrowFn = 2907 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2908 Params, 2909 false), 2910 "objc_exception_throw"); 2911 2912 Params.clear(); 2913 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); 2914 ExceptionTryEnterFn = 2915 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2916 Params, 2917 false), 2918 "objc_exception_try_enter"); 2919 ExceptionTryExitFn = 2920 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2921 Params, 2922 false), 2923 "objc_exception_try_exit"); 2924 ExceptionExtractFn = 2925 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2926 Params, 2927 false), 2928 "objc_exception_extract"); 2929 2930 Params.clear(); 2931 Params.push_back(ClassPtrTy); 2932 Params.push_back(ObjectPtrTy); 2933 ExceptionMatchFn = 2934 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 2935 Params, 2936 false), 2937 "objc_exception_match"); 2938 2939 // synchronized APIs 2940 // void objc_sync_enter (id) 2941 Params.clear(); 2942 Params.push_back(ObjectPtrTy); 2943 SyncEnterFn = 2944 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2945 Params, 2946 false), 2947 "objc_sync_enter"); 2948 // void objc_sync_exit (id) 2949 SyncExitFn = 2950 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2951 Params, 2952 false), 2953 "objc_sync_exit"); 2954 2955 2956 Params.clear(); 2957 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty)); 2958 SetJmpFn = 2959 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 2960 Params, 2961 false), 2962 "_setjmp"); 2963 2964} 2965 2966ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) 2967: ObjCCommonTypesHelper(cgm) 2968{ 2969 // struct _method_list_t { 2970 // uint32_t entsize; // sizeof(struct _objc_method) 2971 // uint32_t method_count; 2972 // struct _objc_method method_list[method_count]; 2973 // } 2974 MethodListnfABITy = llvm::StructType::get(IntTy, 2975 IntTy, 2976 llvm::ArrayType::get(MethodTy, 0), 2977 NULL); 2978 CGM.getModule().addTypeName("struct.__method_list_t", 2979 MethodListnfABITy); 2980 // struct method_list_t * 2981 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); 2982 2983 // struct _protocol_t { 2984 // id isa; // NULL 2985 // const char * const protocol_name; 2986 // const struct _protocol_list_t * protocol_list; // super protocols 2987 // const struct method_list_t * const instance_methods; 2988 // const struct method_list_t * const class_methods; 2989 // const struct method_list_t *optionalInstanceMethods; 2990 // const struct method_list_t *optionalClassMethods; 2991 // const struct _prop_list_t * properties; 2992 // const uint32_t size; // sizeof(struct _protocol_t) 2993 // const uint32_t flags; // = 0 2994 // } 2995 2996 // Holder for struct _protocol_list_t * 2997 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 2998 2999 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy, 3000 Int8PtrTy, 3001 llvm::PointerType::getUnqual( 3002 ProtocolListTyHolder), 3003 MethodListnfABIPtrTy, 3004 MethodListnfABIPtrTy, 3005 MethodListnfABIPtrTy, 3006 MethodListnfABIPtrTy, 3007 PropertyListPtrTy, 3008 IntTy, 3009 IntTy, 3010 NULL); 3011 CGM.getModule().addTypeName("struct._protocol_t", 3012 ProtocolnfABITy); 3013 3014 // struct _protocol_list_t { 3015 // long protocol_count; // Note, this is 32/64 bit 3016 // struct _protocol_t[protocol_count]; 3017 // } 3018 ProtocolListnfABITy = llvm::StructType::get(LongTy, 3019 llvm::ArrayType::get( 3020 ProtocolnfABITy, 0), 3021 NULL); 3022 CGM.getModule().addTypeName("struct._objc_protocol_list", 3023 ProtocolListnfABITy); 3024 3025 // struct _objc_protocol_list* 3026 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); 3027 3028 // FIXME! Is this doing the right thing? 3029 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo( 3030 ProtocolListnfABIPtrTy); 3031 3032 // struct _ivar_t { 3033 // unsigned long int *offset; // pointer to ivar offset location 3034 // char *name; 3035 // char *type; 3036 // uint32_t alignment; 3037 // uint32_t size; 3038 // } 3039 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy), 3040 Int8PtrTy, 3041 Int8PtrTy, 3042 IntTy, 3043 IntTy, 3044 NULL); 3045 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy); 3046 3047 // struct _ivar_list_t { 3048 // uint32 entsize; // sizeof(struct _ivar_t) 3049 // uint32 count; 3050 // struct _iver_t list[count]; 3051 // } 3052 IvarListnfABITy = llvm::StructType::get(IntTy, 3053 IntTy, 3054 llvm::ArrayType::get( 3055 IvarnfABITy, 0), 3056 NULL); 3057 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy); 3058 3059 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); 3060 3061 // struct _class_ro_t { 3062 // uint32_t const flags; 3063 // uint32_t const instanceStart; 3064 // uint32_t const instanceSize; 3065 // uint32_t const reserved; // only when building for 64bit targets 3066 // const uint8_t * const ivarLayout; 3067 // const char *const name; 3068 // const struct _method_list_t * const baseMethods; 3069 // const struct _objc_protocol_list *const baseProtocols; 3070 // const struct _ivar_list_t *const ivars; 3071 // const uint8_t * const weakIvarLayout; 3072 // const struct _prop_list_t * const properties; 3073 // } 3074 3075 // FIXME. Add 'reserved' field in 64bit abi mode! 3076 ClassRonfABITy = llvm::StructType::get(IntTy, 3077 IntTy, 3078 IntTy, 3079 Int8PtrTy, 3080 Int8PtrTy, 3081 MethodListnfABIPtrTy, 3082 ProtocolListnfABIPtrTy, 3083 IvarListnfABIPtrTy, 3084 Int8PtrTy, 3085 PropertyListPtrTy, 3086 NULL); 3087 CGM.getModule().addTypeName("struct._class_ro_t", 3088 ClassRonfABITy); 3089 3090 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 3091 std::vector<const llvm::Type*> Params; 3092 Params.push_back(ObjectPtrTy); 3093 Params.push_back(SelectorPtrTy); 3094 ImpnfABITy = llvm::PointerType::getUnqual( 3095 llvm::FunctionType::get(ObjectPtrTy, Params, false)); 3096 3097 // struct _class_t { 3098 // struct _class_t *isa; 3099 // struct _class_t * const superclass; 3100 // void *cache; 3101 // IMP *vtable; 3102 // struct class_ro_t *ro; 3103 // } 3104 3105 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 3106 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 3107 llvm::PointerType::getUnqual(ClassTyHolder), 3108 CachePtrTy, 3109 llvm::PointerType::getUnqual(ImpnfABITy), 3110 llvm::PointerType::getUnqual( 3111 ClassRonfABITy), 3112 NULL); 3113 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy); 3114 3115 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo( 3116 ClassnfABITy); 3117 3118 // LLVM for struct _class_t * 3119 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); 3120 3121 // struct _category_t { 3122 // const char * const name; 3123 // struct _class_t *const cls; 3124 // const struct _method_list_t * const instance_methods; 3125 // const struct _method_list_t * const class_methods; 3126 // const struct _protocol_list_t * const protocols; 3127 // const struct _prop_list_t * const properties; 3128 // } 3129 CategorynfABITy = llvm::StructType::get(Int8PtrTy, 3130 ClassnfABIPtrTy, 3131 MethodListnfABIPtrTy, 3132 MethodListnfABIPtrTy, 3133 ProtocolListnfABIPtrTy, 3134 PropertyListPtrTy, 3135 NULL); 3136 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy); 3137 3138} 3139 3140llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() { 3141 FinishNonFragileABIModule(); 3142 3143 return NULL; 3144} 3145 3146void CGObjCNonFragileABIMac::FinishNonFragileABIModule() { 3147 // nonfragile abi has no module definition. 3148 3149 // Build list of all implemented classe addresses in array 3150 // L_OBJC_LABEL_CLASS_$. 3151 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$ 3152 // list of 'nonlazy' implementations (defined as those with a +load{} 3153 // method!!). 3154 unsigned NumClasses = DefinedClasses.size(); 3155 if (NumClasses) { 3156 std::vector<llvm::Constant*> Symbols(NumClasses); 3157 for (unsigned i=0; i<NumClasses; i++) 3158 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 3159 ObjCTypes.Int8PtrTy); 3160 llvm::Constant* Init = 3161 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 3162 NumClasses), 3163 Symbols); 3164 3165 llvm::GlobalVariable *GV = 3166 new llvm::GlobalVariable(Init->getType(), false, 3167 llvm::GlobalValue::InternalLinkage, 3168 Init, 3169 "\01L_OBJC_LABEL_CLASS_$", 3170 &CGM.getModule()); 3171 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip"); 3172 UsedGlobals.push_back(GV); 3173 } 3174 3175 // Build list of all implemented category addresses in array 3176 // L_OBJC_LABEL_CATEGORY_$. 3177 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$ 3178 // list of 'nonlazy' category implementations (defined as those with a +load{} 3179 // method!!). 3180 unsigned NumCategory = DefinedCategories.size(); 3181 if (NumCategory) { 3182 std::vector<llvm::Constant*> Symbols(NumCategory); 3183 for (unsigned i=0; i<NumCategory; i++) 3184 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i], 3185 ObjCTypes.Int8PtrTy); 3186 llvm::Constant* Init = 3187 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 3188 NumCategory), 3189 Symbols); 3190 3191 llvm::GlobalVariable *GV = 3192 new llvm::GlobalVariable(Init->getType(), false, 3193 llvm::GlobalValue::InternalLinkage, 3194 Init, 3195 "\01L_OBJC_LABEL_CATEGORY_$", 3196 &CGM.getModule()); 3197 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip"); 3198 UsedGlobals.push_back(GV); 3199 } 3200 3201 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags }; 3202 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0 3203 std::vector<llvm::Constant*> Values(2); 3204 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0); 3205 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0); 3206 llvm::Constant* Init = llvm::ConstantArray::get( 3207 llvm::ArrayType::get(ObjCTypes.IntTy, 2), 3208 Values); 3209 llvm::GlobalVariable *IMGV = 3210 new llvm::GlobalVariable(Init->getType(), false, 3211 llvm::GlobalValue::InternalLinkage, 3212 Init, 3213 "\01L_OBJC_IMAGE_INFO", 3214 &CGM.getModule()); 3215 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); 3216 UsedGlobals.push_back(IMGV); 3217 3218 std::vector<llvm::Constant*> Used; 3219 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 3220 e = UsedGlobals.end(); i != e; ++i) { 3221 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 3222 } 3223 3224 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 3225 llvm::GlobalValue *GV = 3226 new llvm::GlobalVariable(AT, false, 3227 llvm::GlobalValue::AppendingLinkage, 3228 llvm::ConstantArray::get(AT, Used), 3229 "llvm.used", 3230 &CGM.getModule()); 3231 3232 GV->setSection("llvm.metadata"); 3233 3234} 3235 3236// Metadata flags 3237enum MetaDataDlags { 3238 CLS = 0x0, 3239 CLS_META = 0x1, 3240 CLS_ROOT = 0x2, 3241 OBJC2_CLS_HIDDEN = 0x10, 3242 CLS_EXCEPTION = 0x20 3243}; 3244/// BuildClassRoTInitializer - generate meta-data for: 3245/// struct _class_ro_t { 3246/// uint32_t const flags; 3247/// uint32_t const instanceStart; 3248/// uint32_t const instanceSize; 3249/// uint32_t const reserved; // only when building for 64bit targets 3250/// const uint8_t * const ivarLayout; 3251/// const char *const name; 3252/// const struct _method_list_t * const baseMethods; 3253/// const struct _protocol_list_t *const baseProtocols; 3254/// const struct _ivar_list_t *const ivars; 3255/// const uint8_t * const weakIvarLayout; 3256/// const struct _prop_list_t * const properties; 3257/// } 3258/// 3259llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer( 3260 unsigned flags, 3261 unsigned InstanceStart, 3262 unsigned InstanceSize, 3263 const ObjCImplementationDecl *ID) { 3264 std::string ClassName = ID->getNameAsString(); 3265 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets! 3266 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); 3267 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart); 3268 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize); 3269 // FIXME. For 64bit targets add 0 here. 3270 // FIXME. ivarLayout is currently null! 3271 Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 3272 Values[ 4] = GetClassName(ID->getIdentifier()); 3273 // const struct _method_list_t * const baseMethods; 3274 std::vector<llvm::Constant*> Methods; 3275 std::string MethodListName("\01l_OBJC_$_"); 3276 if (flags & CLS_META) { 3277 MethodListName += "CLASS_METHODS_" + ID->getNameAsString(); 3278 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), 3279 e = ID->classmeth_end(); i != e; ++i) { 3280 // Class methods should always be defined. 3281 Methods.push_back(GetMethodConstant(*i)); 3282 } 3283 } else { 3284 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString(); 3285 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), 3286 e = ID->instmeth_end(); i != e; ++i) { 3287 // Instance methods should always be defined. 3288 Methods.push_back(GetMethodConstant(*i)); 3289 } 3290 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), 3291 e = ID->propimpl_end(); i != e; ++i) { 3292 ObjCPropertyImplDecl *PID = *i; 3293 3294 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){ 3295 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3296 3297 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 3298 if (llvm::Constant *C = GetMethodConstant(MD)) 3299 Methods.push_back(C); 3300 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 3301 if (llvm::Constant *C = GetMethodConstant(MD)) 3302 Methods.push_back(C); 3303 } 3304 } 3305 } 3306 Values[ 5] = EmitMethodList(MethodListName, 3307 "__DATA, __objc_const", Methods); 3308 3309 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 3310 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer"); 3311 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_" 3312 + OID->getNameAsString(), 3313 OID->protocol_begin(), 3314 OID->protocol_end()); 3315 3316 if (flags & CLS_META) 3317 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 3318 else 3319 Values[ 7] = EmitIvarList(ID); 3320 // FIXME. weakIvarLayout is currently null. 3321 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 3322 if (flags & CLS_META) 3323 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 3324 else 3325 Values[ 9] = 3326 EmitPropertyList( 3327 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 3328 ID, ID->getClassInterface(), ObjCTypes); 3329 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy, 3330 Values); 3331 llvm::GlobalVariable *CLASS_RO_GV = 3332 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false, 3333 llvm::GlobalValue::InternalLinkage, 3334 Init, 3335 (flags & CLS_META) ? 3336 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName : 3337 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName, 3338 &CGM.getModule()); 3339 CLASS_RO_GV->setAlignment( 3340 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy)); 3341 CLASS_RO_GV->setSection("__DATA, __objc_const"); 3342 UsedGlobals.push_back(CLASS_RO_GV); 3343 return CLASS_RO_GV; 3344 3345} 3346 3347/// BuildClassMetaData - This routine defines that to-level meta-data 3348/// for the given ClassName for: 3349/// struct _class_t { 3350/// struct _class_t *isa; 3351/// struct _class_t * const superclass; 3352/// void *cache; 3353/// IMP *vtable; 3354/// struct class_ro_t *ro; 3355/// } 3356/// 3357llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData( 3358 std::string &ClassName, 3359 llvm::Constant *IsAGV, 3360 llvm::Constant *SuperClassGV, 3361 llvm::Constant *ClassRoGV, 3362 bool HiddenVisibility) { 3363 std::vector<llvm::Constant*> Values(5); 3364 Values[0] = IsAGV; 3365 Values[1] = SuperClassGV 3366 ? SuperClassGV 3367 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy); 3368 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar 3369 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar 3370 Values[4] = ClassRoGV; // &CLASS_RO_GV 3371 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy, 3372 Values); 3373 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(ClassName); 3374 if (GV) 3375 GV->setInitializer(Init); 3376 else 3377 GV = 3378 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 3379 llvm::GlobalValue::ExternalLinkage, 3380 Init, 3381 ClassName, 3382 &CGM.getModule()); 3383 GV->setSection("__DATA, __objc_data"); 3384 GV->setAlignment( 3385 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy)); 3386 if (HiddenVisibility) 3387 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 3388 UsedGlobals.push_back(GV); 3389 return GV; 3390} 3391 3392void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) { 3393 std::string ClassName = ID->getNameAsString(); 3394 if (!ObjCEmptyCacheVar) { 3395 ObjCEmptyCacheVar = new llvm::GlobalVariable( 3396 ObjCTypes.CachePtrTy, 3397 false, 3398 llvm::GlobalValue::ExternalLinkage, 3399 0, 3400 "\01_objc_empty_cache", 3401 &CGM.getModule()); 3402 UsedGlobals.push_back(ObjCEmptyCacheVar); 3403 3404 ObjCEmptyVtableVar = new llvm::GlobalVariable( 3405 llvm::PointerType::getUnqual( 3406 ObjCTypes.ImpnfABITy), 3407 false, 3408 llvm::GlobalValue::ExternalLinkage, 3409 0, 3410 "\01_objc_empty_vtable", 3411 &CGM.getModule()); 3412 UsedGlobals.push_back(ObjCEmptyVtableVar); 3413 } 3414 assert(ID->getClassInterface() && 3415 "CGObjCNonFragileABIMac::GenerateClass - class is 0"); 3416 uint32_t InstanceStart = 3417 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy); 3418 uint32_t InstanceSize = InstanceStart; 3419 uint32_t flags = CLS_META; 3420 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_"); 3421 std::string ObjCClassName("\01_OBJC_CLASS_$_"); 3422 3423 llvm::GlobalVariable *SuperClassGV, *IsAGV; 3424 3425 bool classIsHidden = IsClassHidden(ID->getClassInterface()); 3426 if (classIsHidden) 3427 flags |= OBJC2_CLS_HIDDEN; 3428 if (!ID->getClassInterface()->getSuperClass()) { 3429 // class is root 3430 flags |= CLS_ROOT; 3431 std::string SuperClassName = ObjCClassName + ClassName; 3432 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName); 3433 if (!SuperClassGV) 3434 SuperClassGV = 3435 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 3436 llvm::GlobalValue::ExternalLinkage, 3437 0, 3438 SuperClassName, 3439 &CGM.getModule()); 3440 UsedGlobals.push_back(SuperClassGV); 3441 std::string IsAClassName = ObjCMetaClassName + ClassName; 3442 IsAGV = CGM.getModule().getGlobalVariable(IsAClassName); 3443 if (!IsAGV) 3444 IsAGV = 3445 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 3446 llvm::GlobalValue::ExternalLinkage, 3447 0, 3448 IsAClassName, 3449 &CGM.getModule()); 3450 UsedGlobals.push_back(IsAGV); 3451 } else { 3452 // Has a root. Current class is not a root. 3453 std::string RootClassName = 3454 ID->getClassInterface()->getSuperClass()->getNameAsString(); 3455 std::string SuperClassName = ObjCMetaClassName + RootClassName; 3456 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName); 3457 if (!SuperClassGV) 3458 SuperClassGV = 3459 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 3460 llvm::GlobalValue::ExternalLinkage, 3461 0, 3462 SuperClassName, 3463 &CGM.getModule()); 3464 UsedGlobals.push_back(SuperClassGV); 3465 IsAGV = SuperClassGV; 3466 } 3467 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags, 3468 InstanceStart, 3469 InstanceSize,ID); 3470 std::string TClassName = ObjCMetaClassName + ClassName; 3471 llvm::GlobalVariable *MetaTClass = 3472 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV, 3473 classIsHidden); 3474 3475 // Metadata for the class 3476 flags = CLS; 3477 if (classIsHidden) 3478 flags |= OBJC2_CLS_HIDDEN; 3479 if (!ID->getClassInterface()->getSuperClass()) { 3480 flags |= CLS_ROOT; 3481 SuperClassGV = 0; 3482 } 3483 else { 3484 // Has a root. Current class is not a root. 3485 std::string RootClassName = 3486 ID->getClassInterface()->getSuperClass()->getNameAsString(); 3487 std::string SuperClassName = ObjCClassName + RootClassName; 3488 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName); 3489 if (!SuperClassGV) 3490 SuperClassGV = 3491 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 3492 llvm::GlobalValue::ExternalLinkage, 3493 0, 3494 SuperClassName, 3495 &CGM.getModule()); 3496 UsedGlobals.push_back(SuperClassGV); 3497 3498 } 3499 3500 InstanceStart = InstanceSize = 0; 3501 if (ObjCInterfaceDecl *OID = 3502 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) { 3503 // FIXME. Share this with the one in EmitIvarList. 3504 const llvm::Type *InterfaceTy = 3505 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID)); 3506 const llvm::StructLayout *Layout = 3507 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); 3508 3509 RecordDecl::field_iterator firstField, lastField; 3510 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField); 3511 3512 for (RecordDecl::field_iterator e = RD->field_end(), 3513 ifield = firstField; ifield != e; ++ifield) 3514 lastField = ifield; 3515 3516 if (lastField != RD->field_end()) { 3517 FieldDecl *Field = *lastField; 3518 const llvm::Type *FieldTy = 3519 CGM.getTypes().ConvertTypeForMem(Field->getType()); 3520 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); 3521 InstanceSize = Layout->getElementOffset( 3522 CGM.getTypes().getLLVMFieldNo(Field)) + 3523 Size; 3524 if (firstField == RD->field_end()) 3525 InstanceStart = InstanceSize; 3526 else 3527 InstanceStart = Layout->getElementOffset(CGM.getTypes(). 3528 getLLVMFieldNo(*firstField)); 3529 } 3530 } 3531 CLASS_RO_GV = BuildClassRoTInitializer(flags, 3532 InstanceStart, 3533 InstanceSize, 3534 ID); 3535 3536 TClassName = ObjCClassName + ClassName; 3537 llvm::GlobalVariable *ClassMD = 3538 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV, 3539 classIsHidden); 3540 DefinedClasses.push_back(ClassMD); 3541} 3542 3543/// GenerateProtocolRef - This routine is called to generate code for 3544/// a protocol reference expression; as in: 3545/// @code 3546/// @protocol(Proto1); 3547/// @endcode 3548/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1 3549/// which will hold address of the protocol meta-data. 3550/// 3551llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder, 3552 const ObjCProtocolDecl *PD) { 3553 3554 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 3555 ObjCTypes.ExternalProtocolPtrTy); 3556 3557 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_"); 3558 ProtocolName += PD->getNameAsCString(); 3559 3560 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); 3561 if (PTGV) 3562 return Builder.CreateLoad(PTGV, false, "tmp"); 3563 PTGV = new llvm::GlobalVariable( 3564 Init->getType(), false, 3565 llvm::GlobalValue::WeakLinkage, 3566 Init, 3567 ProtocolName, 3568 &CGM.getModule()); 3569 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip"); 3570 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 3571 UsedGlobals.push_back(PTGV); 3572 return Builder.CreateLoad(PTGV, false, "tmp"); 3573} 3574 3575/// GenerateCategory - Build metadata for a category implementation. 3576/// struct _category_t { 3577/// const char * const name; 3578/// struct _class_t *const cls; 3579/// const struct _method_list_t * const instance_methods; 3580/// const struct _method_list_t * const class_methods; 3581/// const struct _protocol_list_t * const protocols; 3582/// const struct _prop_list_t * const properties; 3583/// } 3584/// 3585void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) 3586{ 3587 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 3588 const char *Prefix = "\01l_OBJC_$_CATEGORY_"; 3589 std::string ExtCatName(Prefix + Interface->getNameAsString()+ 3590 "_$_" + OCD->getNameAsString()); 3591 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString()); 3592 3593 std::vector<llvm::Constant*> Values(6); 3594 Values[0] = GetClassName(OCD->getIdentifier()); 3595 // meta-class entry symbol 3596 llvm::GlobalVariable *ClassGV = 3597 CGM.getModule().getGlobalVariable(ExtClassName); 3598 if (!ClassGV) 3599 ClassGV = 3600 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 3601 llvm::GlobalValue::ExternalLinkage, 3602 0, 3603 ExtClassName, 3604 &CGM.getModule()); 3605 UsedGlobals.push_back(ClassGV); 3606 Values[1] = ClassGV; 3607 std::vector<llvm::Constant*> Methods; 3608 std::string MethodListName(Prefix); 3609 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() + 3610 "_$_" + OCD->getNameAsString(); 3611 3612 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), 3613 e = OCD->instmeth_end(); i != e; ++i) { 3614 // Instance methods should always be defined. 3615 Methods.push_back(GetMethodConstant(*i)); 3616 } 3617 3618 Values[2] = EmitMethodList(MethodListName, 3619 "__DATA, __objc_const", 3620 Methods); 3621 3622 MethodListName = Prefix; 3623 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" + 3624 OCD->getNameAsString(); 3625 Methods.clear(); 3626 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), 3627 e = OCD->classmeth_end(); i != e; ++i) { 3628 // Class methods should always be defined. 3629 Methods.push_back(GetMethodConstant(*i)); 3630 } 3631 3632 Values[3] = EmitMethodList(MethodListName, 3633 "__DATA, __objc_const", 3634 Methods); 3635 const ObjCCategoryDecl *Category = 3636 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 3637 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_" 3638 + Interface->getNameAsString() + "_$_" 3639 + Category->getNameAsString(), 3640 Category->protocol_begin(), 3641 Category->protocol_end()); 3642 3643 std::string ExtName(Interface->getNameAsString() + "_$_" + 3644 OCD->getNameAsString()); 3645 Values[5] = 3646 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, 3647 OCD, Category, ObjCTypes); 3648 llvm::Constant *Init = 3649 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy, 3650 Values); 3651 llvm::GlobalVariable *GCATV 3652 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy, 3653 false, 3654 llvm::GlobalValue::InternalLinkage, 3655 Init, 3656 ExtCatName, 3657 &CGM.getModule()); 3658 GCATV->setAlignment( 3659 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy)); 3660 GCATV->setSection("__DATA, __objc_const"); 3661 UsedGlobals.push_back(GCATV); 3662 DefinedCategories.push_back(GCATV); 3663} 3664 3665/// GetMethodConstant - Return a struct objc_method constant for the 3666/// given method if it has been defined. The result is null if the 3667/// method has not been defined. The return value has type MethodPtrTy. 3668llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant( 3669 const ObjCMethodDecl *MD) { 3670 // FIXME: Use DenseMap::lookup 3671 llvm::Function *Fn = MethodDefinitions[MD]; 3672 if (!Fn) 3673 return 0; 3674 3675 std::vector<llvm::Constant*> Method(3); 3676 Method[0] = 3677 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 3678 ObjCTypes.SelectorPtrTy); 3679 Method[1] = GetMethodVarType(MD); 3680 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 3681 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 3682} 3683 3684/// EmitMethodList - Build meta-data for method declarations 3685/// struct _method_list_t { 3686/// uint32_t entsize; // sizeof(struct _objc_method) 3687/// uint32_t method_count; 3688/// struct _objc_method method_list[method_count]; 3689/// } 3690/// 3691llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList( 3692 const std::string &Name, 3693 const char *Section, 3694 const ConstantVector &Methods) { 3695 // Return null for empty list. 3696 if (Methods.empty()) 3697 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy); 3698 3699 std::vector<llvm::Constant*> Values(3); 3700 // sizeof(struct _objc_method) 3701 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy); 3702 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 3703 // method_count 3704 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 3705 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 3706 Methods.size()); 3707 Values[2] = llvm::ConstantArray::get(AT, Methods); 3708 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 3709 3710 llvm::GlobalVariable *GV = 3711 new llvm::GlobalVariable(Init->getType(), false, 3712 llvm::GlobalValue::InternalLinkage, 3713 Init, 3714 Name, 3715 &CGM.getModule()); 3716 GV->setAlignment( 3717 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 3718 GV->setSection(Section); 3719 UsedGlobals.push_back(GV); 3720 return llvm::ConstantExpr::getBitCast(GV, 3721 ObjCTypes.MethodListnfABIPtrTy); 3722} 3723 3724llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar( 3725 const ObjCImplementationDecl *ID, 3726 const ObjCIvarDecl *Ivar, 3727 unsigned long int Offset) { 3728 3729 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.' 3730 + Ivar->getNameAsString()); 3731 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset); 3732 3733 llvm::GlobalVariable *IvarOffsetGV = 3734 CGM.getModule().getGlobalVariable(ExternalName); 3735 if (IvarOffsetGV) { 3736 // ivar offset symbol already built due to user code referencing it. 3737 IvarOffsetGV->setAlignment( 3738 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy)); 3739 IvarOffsetGV->setInitializer(Init); 3740 UsedGlobals.push_back(IvarOffsetGV); 3741 return IvarOffsetGV; 3742 } 3743 3744 IvarOffsetGV = 3745 new llvm::GlobalVariable(Init->getType(), 3746 false, 3747 llvm::GlobalValue::ExternalLinkage, 3748 Init, 3749 ExternalName, 3750 &CGM.getModule()); 3751 IvarOffsetGV->setAlignment( 3752 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy)); 3753 // @private and @package have hidden visibility. 3754 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public || 3755 Ivar->getAccessControl() == ObjCIvarDecl::Protected); 3756 if (!globalVisibility) 3757 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 3758 else 3759 if (const ObjCInterfaceDecl *OID = ID->getClassInterface()) 3760 if (IsClassHidden(OID)) 3761 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 3762 3763 IvarOffsetGV->setSection("__DATA, __objc_const"); 3764 UsedGlobals.push_back(IvarOffsetGV); 3765 3766 return llvm::ConstantExpr::getBitCast( 3767 IvarOffsetGV, 3768 llvm::PointerType::getUnqual(ObjCTypes.LongTy)); 3769} 3770 3771/// EmitIvarList - Emit the ivar list for the given 3772/// implementation. If ForClass is true the list of class ivars 3773/// (i.e. metaclass ivars) is emitted, otherwise the list of 3774/// interface ivars will be emitted. The return value has type 3775/// IvarListnfABIPtrTy. 3776/// struct _ivar_t { 3777/// unsigned long int *offset; // pointer to ivar offset location 3778/// char *name; 3779/// char *type; 3780/// uint32_t alignment; 3781/// uint32_t size; 3782/// } 3783/// struct _ivar_list_t { 3784/// uint32 entsize; // sizeof(struct _ivar_t) 3785/// uint32 count; 3786/// struct _iver_t list[count]; 3787/// } 3788/// 3789llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( 3790 const ObjCImplementationDecl *ID) { 3791 3792 std::vector<llvm::Constant*> Ivars, Ivar(5); 3793 3794 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 3795 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface"); 3796 3797 // FIXME. Consolidate this with similar code in GenerateClass. 3798 const llvm::Type *InterfaceTy = 3799 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType( 3800 const_cast<ObjCInterfaceDecl*>(OID))); 3801 const llvm::StructLayout *Layout = 3802 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); 3803 3804 RecordDecl::field_iterator i,p; 3805 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p); 3806 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(); 3807 3808 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) { 3809 FieldDecl *Field = *i; 3810 unsigned long offset = Layout->getElementOffset(CGM.getTypes(). 3811 getLLVMFieldNo(Field)); 3812 const ObjCIvarDecl *ivarDecl = *I++; 3813 Ivar[0] = EmitIvarOffsetVar(ID, ivarDecl, offset); 3814 if (Field->getIdentifier()) 3815 Ivar[1] = GetMethodVarName(Field->getIdentifier()); 3816 else 3817 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 3818 std::string TypeStr; 3819 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); 3820 Ivar[2] = GetMethodVarType(TypeStr); 3821 const llvm::Type *FieldTy = 3822 CGM.getTypes().ConvertTypeForMem(Field->getType()); 3823 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); 3824 unsigned Align = CGM.getContext().getPreferredTypeAlign( 3825 Field->getType().getTypePtr()) >> 3; 3826 Align = llvm::Log2_32(Align); 3827 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align); 3828 // NOTE. Size of a bitfield does not match gcc's, because of the way 3829 // bitfields are treated special in each. But I am told that 'size' 3830 // for bitfield ivars is ignored by the runtime so it does not matter. 3831 // (even if it matters, some day, there is enough info. to get the bitfield 3832 // right! 3833 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 3834 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar)); 3835 } 3836 // Return null for empty list. 3837 if (Ivars.empty()) 3838 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 3839 std::vector<llvm::Constant*> Values(3); 3840 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy); 3841 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 3842 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 3843 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy, 3844 Ivars.size()); 3845 Values[2] = llvm::ConstantArray::get(AT, Ivars); 3846 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 3847 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_"; 3848 llvm::GlobalVariable *GV = 3849 new llvm::GlobalVariable(Init->getType(), false, 3850 llvm::GlobalValue::InternalLinkage, 3851 Init, 3852 Prefix + OID->getNameAsString(), 3853 &CGM.getModule()); 3854 GV->setAlignment( 3855 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 3856 GV->setSection("__DATA, __objc_const"); 3857 3858 UsedGlobals.push_back(GV); 3859 return llvm::ConstantExpr::getBitCast(GV, 3860 ObjCTypes.IvarListnfABIPtrTy); 3861} 3862 3863llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef( 3864 const ObjCProtocolDecl *PD) { 3865 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 3866 3867 if (!Entry) { 3868 // We use the initializer as a marker of whether this is a forward 3869 // reference or not. At module finalization we add the empty 3870 // contents for protocols which were referenced but never defined. 3871 Entry = 3872 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, 3873 llvm::GlobalValue::ExternalLinkage, 3874 0, 3875 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(), 3876 &CGM.getModule()); 3877 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 3878 UsedGlobals.push_back(Entry); 3879 } 3880 3881 return Entry; 3882} 3883 3884/// GetOrEmitProtocol - Generate the protocol meta-data: 3885/// @code 3886/// struct _protocol_t { 3887/// id isa; // NULL 3888/// const char * const protocol_name; 3889/// const struct _protocol_list_t * protocol_list; // super protocols 3890/// const struct method_list_t * const instance_methods; 3891/// const struct method_list_t * const class_methods; 3892/// const struct method_list_t *optionalInstanceMethods; 3893/// const struct method_list_t *optionalClassMethods; 3894/// const struct _prop_list_t * properties; 3895/// const uint32_t size; // sizeof(struct _protocol_t) 3896/// const uint32_t flags; // = 0 3897/// } 3898/// @endcode 3899/// 3900 3901llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( 3902 const ObjCProtocolDecl *PD) { 3903 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 3904 3905 // Early exit if a defining object has already been generated. 3906 if (Entry && Entry->hasInitializer()) 3907 return Entry; 3908 3909 const char *ProtocolName = PD->getNameAsCString(); 3910 3911 // Construct method lists. 3912 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 3913 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 3914 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(), 3915 e = PD->instmeth_end(); i != e; ++i) { 3916 ObjCMethodDecl *MD = *i; 3917 llvm::Constant *C = GetMethodDescriptionConstant(MD); 3918 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 3919 OptInstanceMethods.push_back(C); 3920 } else { 3921 InstanceMethods.push_back(C); 3922 } 3923 } 3924 3925 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(), 3926 e = PD->classmeth_end(); i != e; ++i) { 3927 ObjCMethodDecl *MD = *i; 3928 llvm::Constant *C = GetMethodDescriptionConstant(MD); 3929 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 3930 OptClassMethods.push_back(C); 3931 } else { 3932 ClassMethods.push_back(C); 3933 } 3934 } 3935 3936 std::vector<llvm::Constant*> Values(10); 3937 // isa is NULL 3938 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy); 3939 Values[1] = GetClassName(PD->getIdentifier()); 3940 Values[2] = EmitProtocolList( 3941 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(), 3942 PD->protocol_begin(), 3943 PD->protocol_end()); 3944 3945 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_" 3946 + PD->getNameAsString(), 3947 "__DATA, __objc_const", 3948 InstanceMethods); 3949 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_" 3950 + PD->getNameAsString(), 3951 "__DATA, __objc_const", 3952 ClassMethods); 3953 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_" 3954 + PD->getNameAsString(), 3955 "__DATA, __objc_const", 3956 OptInstanceMethods); 3957 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_" 3958 + PD->getNameAsString(), 3959 "__DATA, __objc_const", 3960 OptClassMethods); 3961 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(), 3962 0, PD, ObjCTypes); 3963 uint32_t Size = 3964 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy); 3965 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 3966 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy); 3967 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy, 3968 Values); 3969 3970 if (Entry) { 3971 // Already created, fix the linkage and update the initializer. 3972 Entry->setLinkage(llvm::GlobalValue::WeakLinkage); 3973 Entry->setInitializer(Init); 3974 } else { 3975 Entry = 3976 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, 3977 llvm::GlobalValue::WeakLinkage, 3978 Init, 3979 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName, 3980 &CGM.getModule()); 3981 Entry->setAlignment( 3982 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy)); 3983 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 3984 } 3985 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 3986 3987 // Use this protocol meta-data to build protocol list table in section 3988 // __DATA, __objc_protolist 3989 llvm::Type *ptype = llvm::PointerType::getUnqual(ObjCTypes.ProtocolnfABITy); 3990 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable( 3991 ptype, false, 3992 llvm::GlobalValue::WeakLinkage, 3993 Entry, 3994 std::string("\01l_OBJC_LABEL_PROTOCOL_$_") 3995 +ProtocolName, 3996 &CGM.getModule()); 3997 PTGV->setAlignment( 3998 CGM.getTargetData().getPrefTypeAlignment(ptype)); 3999 PTGV->setSection("__DATA, __objc_protolist"); 4000 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4001 UsedGlobals.push_back(PTGV); 4002 return Entry; 4003} 4004 4005/// EmitProtocolList - Generate protocol list meta-data: 4006/// @code 4007/// struct _protocol_list_t { 4008/// long protocol_count; // Note, this is 32/64 bit 4009/// struct _protocol_t[protocol_count]; 4010/// } 4011/// @endcode 4012/// 4013llvm::Constant * 4014CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name, 4015 ObjCProtocolDecl::protocol_iterator begin, 4016 ObjCProtocolDecl::protocol_iterator end) { 4017 std::vector<llvm::Constant*> ProtocolRefs; 4018 4019 for (; begin != end; ++begin) 4020 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented??? 4021 4022 // Just return null for empty protocol lists 4023 if (ProtocolRefs.empty()) 4024 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 4025 4026 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 4027 if (GV) 4028 return GV; 4029 // This list is null terminated. 4030 ProtocolRefs.push_back(llvm::Constant::getNullValue( 4031 ObjCTypes.ProtocolListnfABIPtrTy)); 4032 4033 std::vector<llvm::Constant*> Values(2); 4034 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 4035 Values[1] = 4036 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolListnfABIPtrTy, 4037 ProtocolRefs.size()), 4038 ProtocolRefs); 4039 4040 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4041 GV = new llvm::GlobalVariable(Init->getType(), false, 4042 llvm::GlobalValue::InternalLinkage, 4043 Init, 4044 Name, 4045 &CGM.getModule()); 4046 GV->setSection("__DATA, __objc_const"); 4047 GV->setAlignment( 4048 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4049 UsedGlobals.push_back(GV); 4050 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy); 4051} 4052 4053/// GetMethodDescriptionConstant - This routine build following meta-data: 4054/// struct _objc_method { 4055/// SEL _cmd; 4056/// char *method_type; 4057/// char *_imp; 4058/// } 4059 4060llvm::Constant * 4061CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 4062 std::vector<llvm::Constant*> Desc(3); 4063 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 4064 ObjCTypes.SelectorPtrTy); 4065 Desc[1] = GetMethodVarType(MD); 4066 // Protocol methods have no implementation. So, this entry is always NULL. 4067 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 4068 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc); 4069} 4070/* *** */ 4071 4072CodeGen::CGObjCRuntime * 4073CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { 4074 return new CGObjCMac(CGM); 4075} 4076 4077CodeGen::CGObjCRuntime * 4078CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) { 4079 return new CGObjCNonFragileABIMac(CGM); 4080} 4081