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