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