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