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