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