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