CGObjCMac.cpp revision d55b6fc5f3304e97621b4d5a2d9376ad63d74179
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This provides Objective-C code generation targetting the Apple runtime. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CGObjCRuntime.h" 15 16#include "CodeGenModule.h" 17#include "CodeGenFunction.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/Basic/LangOptions.h" 22 23#include "llvm/Module.h" 24#include "llvm/ADT/DenseSet.h" 25#include "llvm/Target/TargetData.h" 26#include <sstream> 27 28using namespace clang; 29using namespace CodeGen; 30 31namespace { 32 33 typedef std::vector<llvm::Constant*> ConstantVector; 34 35 // FIXME: We should find a nicer way to make the labels for 36 // metadata, string concatenation is lame. 37 38class ObjCCommonTypesHelper { 39protected: 40 CodeGen::CodeGenModule &CGM; 41 42public: 43 const llvm::Type *ShortTy, *IntTy, *LongTy; 44 const llvm::Type *Int8PtrTy; 45 46 /// ObjectPtrTy - LLVM type for object handles (typeof(id)) 47 const llvm::Type *ObjectPtrTy; 48 49 /// PtrObjectPtrTy - LLVM type for id * 50 const llvm::Type *PtrObjectPtrTy; 51 52 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) 53 const llvm::Type *SelectorPtrTy; 54 /// ProtocolPtrTy - LLVM type for external protocol handles 55 /// (typeof(Protocol)) 56 const llvm::Type *ExternalProtocolPtrTy; 57 58 // SuperCTy - clang type for struct objc_super. 59 QualType SuperCTy; 60 // SuperPtrCTy - clang type for struct objc_super *. 61 QualType SuperPtrCTy; 62 63 /// SuperTy - LLVM type for struct objc_super. 64 const llvm::StructType *SuperTy; 65 /// SuperPtrTy - LLVM type for struct objc_super *. 66 const llvm::Type *SuperPtrTy; 67 68 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t 69 /// in GCC parlance). 70 const llvm::StructType *PropertyTy; 71 72 /// PropertyListTy - LLVM type for struct objc_property_list 73 /// (_prop_list_t in GCC parlance). 74 const llvm::StructType *PropertyListTy; 75 /// PropertyListPtrTy - LLVM type for struct objc_property_list*. 76 const llvm::Type *PropertyListPtrTy; 77 78 // MethodTy - LLVM type for struct objc_method. 79 const llvm::StructType *MethodTy; 80 81 /// CacheTy - LLVM type for struct objc_cache. 82 const llvm::Type *CacheTy; 83 /// CachePtrTy - LLVM type for struct objc_cache *. 84 const llvm::Type *CachePtrTy; 85 86 llvm::Function *GetPropertyFn, *SetPropertyFn; 87 88 llvm::Function *EnumerationMutationFn; 89 90 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. 91 llvm::Function *GcReadWeakFn; 92 93 /// GcAssignWeakFn -- LLVM objc_assign_weak function. 94 llvm::Function *GcAssignWeakFn; 95 96 /// GcAssignGlobalFn -- LLVM objc_assign_global function. 97 llvm::Function *GcAssignGlobalFn; 98 99 /// GcAssignIvarFn -- LLVM objc_assign_ivar function. 100 llvm::Function *GcAssignIvarFn; 101 102 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. 103 llvm::Function *GcAssignStrongCastFn; 104 105 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); 106 ~ObjCCommonTypesHelper(){} 107}; 108 109/// ObjCTypesHelper - Helper class that encapsulates lazy 110/// construction of varies types used during ObjC generation. 111class ObjCTypesHelper : public ObjCCommonTypesHelper { 112private: 113 114 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn; 115 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn, 116 *MessageSendSuperFpretFn; 117 118public: 119 /// SymtabTy - LLVM type for struct objc_symtab. 120 const llvm::StructType *SymtabTy; 121 /// SymtabPtrTy - LLVM type for struct objc_symtab *. 122 const llvm::Type *SymtabPtrTy; 123 /// ModuleTy - LLVM type for struct objc_module. 124 const llvm::StructType *ModuleTy; 125 126 /// ProtocolTy - LLVM type for struct objc_protocol. 127 const llvm::StructType *ProtocolTy; 128 /// ProtocolPtrTy - LLVM type for struct objc_protocol *. 129 const llvm::Type *ProtocolPtrTy; 130 /// ProtocolExtensionTy - LLVM type for struct 131 /// objc_protocol_extension. 132 const llvm::StructType *ProtocolExtensionTy; 133 /// ProtocolExtensionTy - LLVM type for struct 134 /// objc_protocol_extension *. 135 const llvm::Type *ProtocolExtensionPtrTy; 136 /// MethodDescriptionTy - LLVM type for struct 137 /// objc_method_description. 138 const llvm::StructType *MethodDescriptionTy; 139 /// MethodDescriptionListTy - LLVM type for struct 140 /// objc_method_description_list. 141 const llvm::StructType *MethodDescriptionListTy; 142 /// MethodDescriptionListPtrTy - LLVM type for struct 143 /// objc_method_description_list *. 144 const llvm::Type *MethodDescriptionListPtrTy; 145 /// ProtocolListTy - LLVM type for struct objc_property_list. 146 const llvm::Type *ProtocolListTy; 147 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. 148 const llvm::Type *ProtocolListPtrTy; 149 /// CategoryTy - LLVM type for struct objc_category. 150 const llvm::StructType *CategoryTy; 151 /// ClassTy - LLVM type for struct objc_class. 152 const llvm::StructType *ClassTy; 153 /// ClassPtrTy - LLVM type for struct objc_class *. 154 const llvm::Type *ClassPtrTy; 155 /// ClassExtensionTy - LLVM type for struct objc_class_ext. 156 const llvm::StructType *ClassExtensionTy; 157 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. 158 const llvm::Type *ClassExtensionPtrTy; 159 // IvarTy - LLVM type for struct objc_ivar. 160 const llvm::StructType *IvarTy; 161 /// IvarListTy - LLVM type for struct objc_ivar_list. 162 const llvm::Type *IvarListTy; 163 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. 164 const llvm::Type *IvarListPtrTy; 165 /// MethodListTy - LLVM type for struct objc_method_list. 166 const llvm::Type *MethodListTy; 167 /// MethodListPtrTy - LLVM type for struct objc_method_list *. 168 const llvm::Type *MethodListPtrTy; 169 170 /// ExceptionDataTy - LLVM type for struct _objc_exception_data. 171 const llvm::Type *ExceptionDataTy; 172 173 /// ExceptionThrowFn - LLVM objc_exception_throw function. 174 llvm::Function *ExceptionThrowFn; 175 176 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. 177 llvm::Function *ExceptionTryEnterFn; 178 179 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. 180 llvm::Function *ExceptionTryExitFn; 181 182 /// ExceptionExtractFn - LLVM objc_exception_extract function. 183 llvm::Function *ExceptionExtractFn; 184 185 /// ExceptionMatchFn - LLVM objc_exception_match function. 186 llvm::Function *ExceptionMatchFn; 187 188 /// SetJmpFn - LLVM _setjmp function. 189 llvm::Function *SetJmpFn; 190 191 /// SyncEnterFn - LLVM object_sync_enter function. 192 llvm::Function *SyncEnterFn; 193 194 /// SyncExitFn - LLVM object_sync_exit function. 195 llvm::Function *SyncExitFn; 196 197public: 198 ObjCTypesHelper(CodeGen::CodeGenModule &cgm); 199 ~ObjCTypesHelper() {} 200 201 202 llvm::Function *getSendFn(bool IsSuper) { 203 return IsSuper ? MessageSendSuperFn : MessageSendFn; 204 } 205 206 llvm::Function *getSendStretFn(bool IsSuper) { 207 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn; 208 } 209 210 llvm::Function *getSendFpretFn(bool IsSuper) { 211 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn; 212 } 213}; 214 215/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's 216/// modern abi 217class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { 218public: 219 // MethodListnfABITy - LLVM for struct _method_list_t 220 const llvm::StructType *MethodListnfABITy; 221 222 // MethodListnfABIPtrTy - LLVM for struct _method_list_t* 223 const llvm::Type *MethodListnfABIPtrTy; 224 225 // ProtocolnfABITy = LLVM for struct _protocol_t 226 const llvm::StructType *ProtocolnfABITy; 227 228 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list 229 const llvm::StructType *ProtocolListnfABITy; 230 231 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* 232 const llvm::Type *ProtocolListnfABIPtrTy; 233 234 // ClassnfABITy - LLVM for struct _class_t 235 const llvm::StructType *ClassnfABITy; 236 237 // IvarnfABITy - LLVM for struct _ivar_t 238 const llvm::StructType *IvarnfABITy; 239 240 // IvarListnfABITy - LLVM for struct _ivar_list_t 241 const llvm::StructType *IvarListnfABITy; 242 243 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* 244 const llvm::Type *IvarListnfABIPtrTy; 245 246 // ClassRonfABITy - LLVM for struct _class_ro_t 247 const llvm::StructType *ClassRonfABITy; 248 249 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 250 const llvm::Type *ImpnfABITy; 251 252 // CategorynfABITy - LLVM for struct _category_t 253 const llvm::StructType *CategorynfABITy; 254 255 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); 256 ~ObjCNonFragileABITypesHelper(){} 257}; 258 259class CGObjCCommonMac : public CodeGen::CGObjCRuntime { 260protected: 261 CodeGen::CodeGenModule &CGM; 262 // FIXME! May not be needing this after all. 263 unsigned ObjCABI; 264 265 /// LazySymbols - Symbols to generate a lazy reference for. See 266 /// DefinedSymbols and FinishModule(). 267 std::set<IdentifierInfo*> LazySymbols; 268 269 /// DefinedSymbols - External symbols which are defined by this 270 /// module. The symbols in this list and LazySymbols are used to add 271 /// special linker symbols which ensure that Objective-C modules are 272 /// linked properly. 273 std::set<IdentifierInfo*> DefinedSymbols; 274 275 /// ClassNames - uniqued class names. 276 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames; 277 278 /// MethodVarNames - uniqued method variable names. 279 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; 280 281 /// MethodVarTypes - uniqued method type signatures. We have to use 282 /// a StringMap here because have no other unique reference. 283 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; 284 285 /// MethodDefinitions - map of methods which have been defined in 286 /// this translation unit. 287 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; 288 289 /// PropertyNames - uniqued method variable names. 290 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; 291 292 /// ClassReferences - uniqued class references. 293 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; 294 295 /// SelectorReferences - uniqued selector references. 296 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; 297 298 /// Protocols - Protocols for which an objc_protocol structure has 299 /// been emitted. Forward declarations are handled by creating an 300 /// empty structure whose initializer is filled in when/if defined. 301 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; 302 303 /// DefinedProtocols - Protocols which have actually been 304 /// defined. We should not need this, see FIXME in GenerateProtocol. 305 llvm::DenseSet<IdentifierInfo*> DefinedProtocols; 306 307 /// DefinedClasses - List of defined classes. 308 std::vector<llvm::GlobalValue*> DefinedClasses; 309 310 /// DefinedCategories - List of defined categories. 311 std::vector<llvm::GlobalValue*> DefinedCategories; 312 313 /// UsedGlobals - List of globals to pack into the llvm.used metadata 314 /// to prevent them from being clobbered. 315 std::vector<llvm::GlobalVariable*> UsedGlobals; 316 317 /// GetNameForMethod - Return a name for the given method. 318 /// \param[out] NameOut - The return value. 319 void GetNameForMethod(const ObjCMethodDecl *OMD, 320 const ObjCContainerDecl *CD, 321 std::string &NameOut); 322 323 /// GetMethodVarName - Return a unique constant for the given 324 /// selector's name. The return value has type char *. 325 llvm::Constant *GetMethodVarName(Selector Sel); 326 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); 327 llvm::Constant *GetMethodVarName(const std::string &Name); 328 329 /// GetMethodVarType - Return a unique constant for the given 330 /// selector's name. The return value has type char *. 331 332 // FIXME: This is a horrible name. 333 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D); 334 llvm::Constant *GetMethodVarType(const std::string &Name); 335 336 /// GetPropertyName - Return a unique constant for the given 337 /// name. The return value has type char *. 338 llvm::Constant *GetPropertyName(IdentifierInfo *Ident); 339 340 // FIXME: This can be dropped once string functions are unified. 341 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, 342 const Decl *Container); 343 344public: 345 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm) 346 { } 347}; 348 349class CGObjCMac : public CGObjCCommonMac { 350private: 351 ObjCTypesHelper ObjCTypes; 352 /// EmitImageInfo - Emit the image info marker used to encode some module 353 /// level information. 354 void EmitImageInfo(); 355 356 /// EmitModuleInfo - Another marker encoding module level 357 /// information. 358 void EmitModuleInfo(); 359 360 /// EmitModuleSymols - Emit module symbols, the list of defined 361 /// classes and categories. The result has type SymtabPtrTy. 362 llvm::Constant *EmitModuleSymbols(); 363 364 /// FinishModule - Write out global data structures at the end of 365 /// processing a translation unit. 366 void FinishModule(); 367 368 /// EmitClassExtension - Generate the class extension structure used 369 /// to store the weak ivar layout and properties. The return value 370 /// has type ClassExtensionPtrTy. 371 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID); 372 373 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 374 /// for the given class. 375 llvm::Value *EmitClassRef(CGBuilderTy &Builder, 376 const ObjCInterfaceDecl *ID); 377 378 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 379 QualType ResultType, 380 Selector Sel, 381 llvm::Value *Arg0, 382 QualType Arg0Ty, 383 bool IsSuper, 384 const CallArgList &CallArgs); 385 386 /// EmitIvarList - Emit the ivar list for the given 387 /// implementation. If ForClass is true the list of class ivars 388 /// (i.e. metaclass ivars) is emitted, otherwise the list of 389 /// interface ivars will be emitted. The return value has type 390 /// IvarListPtrTy. 391 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, 392 bool ForClass, 393 const llvm::Type *InterfaceTy); 394 395 /// EmitMetaClass - Emit a forward reference to the class structure 396 /// for the metaclass of the given interface. The return value has 397 /// type ClassPtrTy. 398 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); 399 400 /// EmitMetaClass - Emit a class structure for the metaclass of the 401 /// given implementation. The return value has type ClassPtrTy. 402 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, 403 llvm::Constant *Protocols, 404 const llvm::Type *InterfaceTy, 405 const ConstantVector &Methods); 406 407 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 408 409 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 410 411 /// EmitMethodList - Emit the method list for the given 412 /// implementation. The return value has type MethodListPtrTy. 413 llvm::Constant *EmitMethodList(const std::string &Name, 414 const char *Section, 415 const ConstantVector &Methods); 416 417 /// EmitMethodDescList - Emit a method description list for a list of 418 /// method declarations. 419 /// - TypeName: The name for the type containing the methods. 420 /// - IsProtocol: True iff these methods are for a protocol. 421 /// - ClassMethds: True iff these are class methods. 422 /// - Required: When true, only "required" methods are 423 /// listed. Similarly, when false only "optional" methods are 424 /// listed. For classes this should always be true. 425 /// - begin, end: The method list to output. 426 /// 427 /// The return value has type MethodDescriptionListPtrTy. 428 llvm::Constant *EmitMethodDescList(const std::string &Name, 429 const char *Section, 430 const ConstantVector &Methods); 431 432 /// EmitPropertyList - Emit the given property list. The return 433 /// value has type PropertyListPtrTy. 434 llvm::Constant *EmitPropertyList(const std::string &Name, 435 const Decl *Container, 436 const ObjCContainerDecl *OCD); 437 438 /// GetOrEmitProtocol - Get the protocol object for the given 439 /// declaration, emitting it if necessary. The return value has type 440 /// ProtocolPtrTy. 441 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 442 443 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 444 /// object for the given declaration, emitting it if needed. These 445 /// forward references will be filled in with empty bodies if no 446 /// definition is seen. The return value has type ProtocolPtrTy. 447 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 448 449 /// EmitProtocolExtension - Generate the protocol extension 450 /// structure used to store optional instance and class methods, and 451 /// protocol properties. The return value has type 452 /// ProtocolExtensionPtrTy. 453 llvm::Constant * 454 EmitProtocolExtension(const ObjCProtocolDecl *PD, 455 const ConstantVector &OptInstanceMethods, 456 const ConstantVector &OptClassMethods); 457 458 /// EmitProtocolList - Generate the list of referenced 459 /// protocols. The return value has type ProtocolListPtrTy. 460 llvm::Constant *EmitProtocolList(const std::string &Name, 461 ObjCProtocolDecl::protocol_iterator begin, 462 ObjCProtocolDecl::protocol_iterator end); 463 464 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 465 /// for the given selector. 466 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); 467 468 /// GetProtocolRef - Return a reference to the internal protocol 469 /// description, creating an empty one if it has not been 470 /// defined. The return value has type ProtocolPtrTy. 471 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); 472 473 /// GetClassName - Return a unique constant for the given selector's 474 /// name. The return value has type char *. 475 llvm::Constant *GetClassName(IdentifierInfo *Ident); 476 477public: 478 CGObjCMac(CodeGen::CodeGenModule &cgm); 479 virtual llvm::Constant *GenerateConstantString(const std::string &String); 480 481 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 482 QualType ResultType, 483 Selector Sel, 484 llvm::Value *Receiver, 485 bool IsClassMessage, 486 const CallArgList &CallArgs); 487 488 virtual CodeGen::RValue 489 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 490 QualType ResultType, 491 Selector Sel, 492 const ObjCInterfaceDecl *Class, 493 llvm::Value *Receiver, 494 bool IsClassMessage, 495 const CallArgList &CallArgs); 496 497 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 498 const ObjCInterfaceDecl *ID); 499 500 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); 501 502 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 503 const ObjCContainerDecl *CD=0); 504 505 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 506 507 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 508 509 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 510 const ObjCProtocolDecl *PD); 511 512 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 513 514 virtual llvm::Function *ModuleInitFunction(); 515 virtual llvm::Function *GetPropertyGetFunction(); 516 virtual llvm::Function *GetPropertySetFunction(); 517 virtual llvm::Function *EnumerationMutationFunction(); 518 519 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 520 const Stmt &S); 521 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 522 const ObjCAtThrowStmt &S); 523 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 524 llvm::Value *AddrWeakObj); 525 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 526 llvm::Value *src, llvm::Value *dst); 527 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 528 llvm::Value *src, llvm::Value *dest); 529 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 530 llvm::Value *src, llvm::Value *dest); 531 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 532 llvm::Value *src, llvm::Value *dest); 533}; 534 535class CGObjCNonFragileABIMac : public CGObjCCommonMac { 536private: 537 ObjCNonFragileABITypesHelper ObjCTypes; 538public: 539 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); 540}; 541 542} // end anonymous namespace 543 544/* *** Helper Functions *** */ 545 546/// getConstantGEP() - Help routine to construct simple GEPs. 547static llvm::Constant *getConstantGEP(llvm::Constant *C, 548 unsigned idx0, 549 unsigned idx1) { 550 llvm::Value *Idxs[] = { 551 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0), 552 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1) 553 }; 554 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2); 555} 556 557/* *** CGObjCMac Public Interface *** */ 558 559CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), 560 ObjCTypes(cgm) 561{ 562 ObjCABI = 1; 563 EmitImageInfo(); 564} 565 566/// GetClass - Return a reference to the class for the given interface 567/// decl. 568llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder, 569 const ObjCInterfaceDecl *ID) { 570 return EmitClassRef(Builder, ID); 571} 572 573/// GetSelector - Return the pointer to the unique'd string for this selector. 574llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) { 575 return EmitSelector(Builder, Sel); 576} 577 578/// Generate a constant CFString object. 579/* 580 struct __builtin_CFString { 581 const int *isa; // point to __CFConstantStringClassReference 582 int flags; 583 const char *str; 584 long length; 585 }; 586*/ 587 588llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) { 589 return CGM.GetAddrOfConstantCFString(String); 590} 591 592/// Generates a message send where the super is the receiver. This is 593/// a message send to self with special delivery semantics indicating 594/// which class's method should be called. 595CodeGen::RValue 596CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 597 QualType ResultType, 598 Selector Sel, 599 const ObjCInterfaceDecl *Class, 600 llvm::Value *Receiver, 601 bool IsClassMessage, 602 const CodeGen::CallArgList &CallArgs) { 603 // Create and init a super structure; this is a (receiver, class) 604 // pair we will pass to objc_msgSendSuper. 605 llvm::Value *ObjCSuper = 606 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 607 llvm::Value *ReceiverAsObject = 608 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 609 CGF.Builder.CreateStore(ReceiverAsObject, 610 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 611 612 // If this is a class message the metaclass is passed as the target. 613 llvm::Value *Target; 614 if (IsClassMessage) { 615 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class); 616 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1); 617 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr); 618 Target = Super; 619 } else { 620 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 621 } 622 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 623 // and ObjCTypes types. 624 const llvm::Type *ClassTy = 625 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 626 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 627 CGF.Builder.CreateStore(Target, 628 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 629 630 return EmitMessageSend(CGF, ResultType, Sel, 631 ObjCSuper, ObjCTypes.SuperPtrCTy, 632 true, CallArgs); 633} 634 635/// Generate code for a message send expression. 636CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 637 QualType ResultType, 638 Selector Sel, 639 llvm::Value *Receiver, 640 bool IsClassMessage, 641 const CallArgList &CallArgs) { 642 llvm::Value *Arg0 = 643 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp"); 644 return EmitMessageSend(CGF, ResultType, Sel, 645 Arg0, CGF.getContext().getObjCIdType(), 646 false, CallArgs); 647} 648 649CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, 650 QualType ResultType, 651 Selector Sel, 652 llvm::Value *Arg0, 653 QualType Arg0Ty, 654 bool IsSuper, 655 const CallArgList &CallArgs) { 656 CallArgList ActualArgs; 657 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 658 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder, 659 Sel)), 660 CGF.getContext().getObjCSelType())); 661 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 662 663 const llvm::FunctionType *FTy = 664 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs), 665 false); 666 667 llvm::Constant *Fn; 668 if (CGM.ReturnTypeUsesSret(ResultType)) { 669 Fn = ObjCTypes.getSendStretFn(IsSuper); 670 } else if (ResultType->isFloatingType()) { 671 // FIXME: Sadly, this is wrong. This actually depends on the 672 // architecture. This happens to be right for x86-32 though. 673 Fn = ObjCTypes.getSendFpretFn(IsSuper); 674 } else { 675 Fn = ObjCTypes.getSendFn(IsSuper); 676 } 677 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy)); 678 return CGF.EmitCall(Fn, ResultType, ActualArgs); 679} 680 681llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder, 682 const ObjCProtocolDecl *PD) { 683 // FIXME: I don't understand why gcc generates this, or where it is 684 // resolved. Investigate. Its also wasteful to look this up over and 685 // over. 686 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 687 688 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 689 ObjCTypes.ExternalProtocolPtrTy); 690} 691 692void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) { 693 // FIXME: We shouldn't need this, the protocol decl should contain 694 // enough information to tell us whether this was a declaration or a 695 // definition. 696 DefinedProtocols.insert(PD->getIdentifier()); 697 698 // If we have generated a forward reference to this protocol, emit 699 // it now. Otherwise do nothing, the protocol objects are lazily 700 // emitted. 701 if (Protocols.count(PD->getIdentifier())) 702 GetOrEmitProtocol(PD); 703} 704 705llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) { 706 if (DefinedProtocols.count(PD->getIdentifier())) 707 return GetOrEmitProtocol(PD); 708 return GetOrEmitProtocolRef(PD); 709} 710 711/* 712 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions 713 struct _objc_protocol { 714 struct _objc_protocol_extension *isa; 715 char *protocol_name; 716 struct _objc_protocol_list *protocol_list; 717 struct _objc__method_prototype_list *instance_methods; 718 struct _objc__method_prototype_list *class_methods 719 }; 720 721 See EmitProtocolExtension(). 722*/ 723llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { 724 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 725 726 // Early exit if a defining object has already been generated. 727 if (Entry && Entry->hasInitializer()) 728 return Entry; 729 730 // FIXME: I don't understand why gcc generates this, or where it is 731 // resolved. Investigate. Its also wasteful to look this up over and 732 // over. 733 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 734 735 const char *ProtocolName = PD->getNameAsCString(); 736 737 // Construct method lists. 738 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 739 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 740 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(), 741 e = PD->instmeth_end(); i != e; ++i) { 742 ObjCMethodDecl *MD = *i; 743 llvm::Constant *C = GetMethodDescriptionConstant(MD); 744 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 745 OptInstanceMethods.push_back(C); 746 } else { 747 InstanceMethods.push_back(C); 748 } 749 } 750 751 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(), 752 e = PD->classmeth_end(); i != e; ++i) { 753 ObjCMethodDecl *MD = *i; 754 llvm::Constant *C = GetMethodDescriptionConstant(MD); 755 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 756 OptClassMethods.push_back(C); 757 } else { 758 ClassMethods.push_back(C); 759 } 760 } 761 762 std::vector<llvm::Constant*> Values(5); 763 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods); 764 Values[1] = GetClassName(PD->getIdentifier()); 765 Values[2] = 766 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(), 767 PD->protocol_begin(), 768 PD->protocol_end()); 769 Values[3] = 770 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" 771 + PD->getNameAsString(), 772 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 773 InstanceMethods); 774 Values[4] = 775 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" 776 + PD->getNameAsString(), 777 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 778 ClassMethods); 779 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 780 Values); 781 782 if (Entry) { 783 // Already created, fix the linkage and update the initializer. 784 Entry->setLinkage(llvm::GlobalValue::InternalLinkage); 785 Entry->setInitializer(Init); 786 } else { 787 Entry = 788 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 789 llvm::GlobalValue::InternalLinkage, 790 Init, 791 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName, 792 &CGM.getModule()); 793 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 794 UsedGlobals.push_back(Entry); 795 // FIXME: Is this necessary? Why only for protocol? 796 Entry->setAlignment(4); 797 } 798 799 return Entry; 800} 801 802llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { 803 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 804 805 if (!Entry) { 806 // We use the initializer as a marker of whether this is a forward 807 // reference or not. At module finalization we add the empty 808 // contents for protocols which were referenced but never defined. 809 Entry = 810 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 811 llvm::GlobalValue::ExternalLinkage, 812 0, 813 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(), 814 &CGM.getModule()); 815 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 816 UsedGlobals.push_back(Entry); 817 // FIXME: Is this necessary? Why only for protocol? 818 Entry->setAlignment(4); 819 } 820 821 return Entry; 822} 823 824/* 825 struct _objc_protocol_extension { 826 uint32_t size; 827 struct objc_method_description_list *optional_instance_methods; 828 struct objc_method_description_list *optional_class_methods; 829 struct objc_property_list *instance_properties; 830 }; 831*/ 832llvm::Constant * 833CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, 834 const ConstantVector &OptInstanceMethods, 835 const ConstantVector &OptClassMethods) { 836 uint64_t Size = 837 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy); 838 std::vector<llvm::Constant*> Values(4); 839 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 840 Values[1] = 841 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" 842 + PD->getNameAsString(), 843 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 844 OptInstanceMethods); 845 Values[2] = 846 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" 847 + PD->getNameAsString(), 848 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 849 OptClassMethods); 850 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + 851 PD->getNameAsString(), 852 0, PD); 853 854 // Return null if no extension bits are used. 855 if (Values[1]->isNullValue() && Values[2]->isNullValue() && 856 Values[3]->isNullValue()) 857 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 858 859 llvm::Constant *Init = 860 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); 861 llvm::GlobalVariable *GV = 862 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false, 863 llvm::GlobalValue::InternalLinkage, 864 Init, 865 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(), 866 &CGM.getModule()); 867 // No special section, but goes in llvm.used 868 UsedGlobals.push_back(GV); 869 870 return GV; 871} 872 873/* 874 struct objc_protocol_list { 875 struct objc_protocol_list *next; 876 long count; 877 Protocol *list[]; 878 }; 879*/ 880llvm::Constant * 881CGObjCMac::EmitProtocolList(const std::string &Name, 882 ObjCProtocolDecl::protocol_iterator begin, 883 ObjCProtocolDecl::protocol_iterator end) { 884 std::vector<llvm::Constant*> ProtocolRefs; 885 886 for (; begin != end; ++begin) 887 ProtocolRefs.push_back(GetProtocolRef(*begin)); 888 889 // Just return null for empty protocol lists 890 if (ProtocolRefs.empty()) 891 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 892 893 // This list is null terminated. 894 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); 895 896 std::vector<llvm::Constant*> Values(3); 897 // This field is only used by the runtime. 898 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 899 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 900 Values[2] = 901 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, 902 ProtocolRefs.size()), 903 ProtocolRefs); 904 905 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 906 llvm::GlobalVariable *GV = 907 new llvm::GlobalVariable(Init->getType(), false, 908 llvm::GlobalValue::InternalLinkage, 909 Init, 910 Name, 911 &CGM.getModule()); 912 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip"); 913 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); 914} 915 916/* 917 struct _objc_property { 918 const char * const name; 919 const char * const attributes; 920 }; 921 922 struct _objc_property_list { 923 uint32_t entsize; // sizeof (struct _objc_property) 924 uint32_t prop_count; 925 struct _objc_property[prop_count]; 926 }; 927*/ 928llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name, 929 const Decl *Container, 930 const ObjCContainerDecl *OCD) { 931 std::vector<llvm::Constant*> Properties, Prop(2); 932 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(), 933 E = OCD->prop_end(); I != E; ++I) { 934 const ObjCPropertyDecl *PD = *I; 935 Prop[0] = GetPropertyName(PD->getIdentifier()); 936 Prop[1] = GetPropertyTypeString(PD, Container); 937 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, 938 Prop)); 939 } 940 941 // Return null for empty list. 942 if (Properties.empty()) 943 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 944 945 unsigned PropertySize = 946 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy); 947 std::vector<llvm::Constant*> Values(3); 948 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); 949 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); 950 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, 951 Properties.size()); 952 Values[2] = llvm::ConstantArray::get(AT, Properties); 953 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 954 955 llvm::GlobalVariable *GV = 956 new llvm::GlobalVariable(Init->getType(), false, 957 llvm::GlobalValue::InternalLinkage, 958 Init, 959 Name, 960 &CGM.getModule()); 961 // No special section on property lists? 962 UsedGlobals.push_back(GV); 963 return llvm::ConstantExpr::getBitCast(GV, 964 ObjCTypes.PropertyListPtrTy); 965 966} 967 968/* 969 struct objc_method_description_list { 970 int count; 971 struct objc_method_description list[]; 972 }; 973*/ 974llvm::Constant * 975CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 976 std::vector<llvm::Constant*> Desc(2); 977 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 978 ObjCTypes.SelectorPtrTy); 979 Desc[1] = GetMethodVarType(MD); 980 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, 981 Desc); 982} 983 984llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name, 985 const char *Section, 986 const ConstantVector &Methods) { 987 // Return null for empty list. 988 if (Methods.empty()) 989 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 990 991 std::vector<llvm::Constant*> Values(2); 992 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 993 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, 994 Methods.size()); 995 Values[1] = llvm::ConstantArray::get(AT, Methods); 996 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 997 998 llvm::GlobalVariable *GV = 999 new llvm::GlobalVariable(Init->getType(), false, 1000 llvm::GlobalValue::InternalLinkage, 1001 Init, Name, &CGM.getModule()); 1002 GV->setSection(Section); 1003 UsedGlobals.push_back(GV); 1004 return llvm::ConstantExpr::getBitCast(GV, 1005 ObjCTypes.MethodDescriptionListPtrTy); 1006} 1007 1008/* 1009 struct _objc_category { 1010 char *category_name; 1011 char *class_name; 1012 struct _objc_method_list *instance_methods; 1013 struct _objc_method_list *class_methods; 1014 struct _objc_protocol_list *protocols; 1015 uint32_t size; // <rdar://4585769> 1016 struct _objc_property_list *instance_properties; 1017 }; 1018 */ 1019void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 1020 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy); 1021 1022 // FIXME: This is poor design, the OCD should have a pointer to the 1023 // category decl. Additionally, note that Category can be null for 1024 // the @implementation w/o an @interface case. Sema should just 1025 // create one for us as it does for @implementation so everyone else 1026 // can live life under a clear blue sky. 1027 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 1028 const ObjCCategoryDecl *Category = 1029 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 1030 std::string ExtName(Interface->getNameAsString() + "_" + 1031 OCD->getNameAsString()); 1032 1033 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1034 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), 1035 e = OCD->instmeth_end(); i != e; ++i) { 1036 // Instance methods should always be defined. 1037 InstanceMethods.push_back(GetMethodConstant(*i)); 1038 } 1039 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), 1040 e = OCD->classmeth_end(); i != e; ++i) { 1041 // Class methods should always be defined. 1042 ClassMethods.push_back(GetMethodConstant(*i)); 1043 } 1044 1045 std::vector<llvm::Constant*> Values(7); 1046 Values[0] = GetClassName(OCD->getIdentifier()); 1047 Values[1] = GetClassName(Interface->getIdentifier()); 1048 Values[2] = 1049 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") + 1050 ExtName, 1051 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1052 InstanceMethods); 1053 Values[3] = 1054 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName, 1055 "__OBJC,__cat_class_meth,regular,no_dead_strip", 1056 ClassMethods); 1057 if (Category) { 1058 Values[4] = 1059 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName, 1060 Category->protocol_begin(), 1061 Category->protocol_end()); 1062 } else { 1063 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1064 } 1065 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1066 1067 // If there is no category @interface then there can be no properties. 1068 if (Category) { 1069 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName, 1070 OCD, Category); 1071 } else { 1072 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1073 } 1074 1075 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, 1076 Values); 1077 1078 llvm::GlobalVariable *GV = 1079 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false, 1080 llvm::GlobalValue::InternalLinkage, 1081 Init, 1082 std::string("\01L_OBJC_CATEGORY_")+ExtName, 1083 &CGM.getModule()); 1084 GV->setSection("__OBJC,__category,regular,no_dead_strip"); 1085 UsedGlobals.push_back(GV); 1086 DefinedCategories.push_back(GV); 1087} 1088 1089// FIXME: Get from somewhere? 1090enum ClassFlags { 1091 eClassFlags_Factory = 0x00001, 1092 eClassFlags_Meta = 0x00002, 1093 // <rdr://5142207> 1094 eClassFlags_HasCXXStructors = 0x02000, 1095 eClassFlags_Hidden = 0x20000, 1096 eClassFlags_ABI2_Hidden = 0x00010, 1097 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634> 1098}; 1099 1100// <rdr://5142207&4705298&4843145> 1101static bool IsClassHidden(const ObjCInterfaceDecl *ID) { 1102 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) { 1103 // FIXME: Support -fvisibility 1104 switch (attr->getVisibility()) { 1105 default: 1106 assert(0 && "Unknown visibility"); 1107 return false; 1108 case VisibilityAttr::DefaultVisibility: 1109 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here? 1110 return false; 1111 case VisibilityAttr::HiddenVisibility: 1112 return true; 1113 } 1114 } else { 1115 return false; // FIXME: Support -fvisibility 1116 } 1117} 1118 1119/* 1120 struct _objc_class { 1121 Class isa; 1122 Class super_class; 1123 const char *name; 1124 long version; 1125 long info; 1126 long instance_size; 1127 struct _objc_ivar_list *ivars; 1128 struct _objc_method_list *methods; 1129 struct _objc_cache *cache; 1130 struct _objc_protocol_list *protocols; 1131 // Objective-C 1.0 extensions (<rdr://4585769>) 1132 const char *ivar_layout; 1133 struct _objc_class_ext *ext; 1134 }; 1135 1136 See EmitClassExtension(); 1137 */ 1138void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { 1139 DefinedSymbols.insert(ID->getIdentifier()); 1140 1141 std::string ClassName = ID->getNameAsString(); 1142 // FIXME: Gross 1143 ObjCInterfaceDecl *Interface = 1144 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 1145 llvm::Constant *Protocols = 1146 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(), 1147 Interface->protocol_begin(), 1148 Interface->protocol_end()); 1149 const llvm::Type *InterfaceTy = 1150 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface)); 1151 unsigned Flags = eClassFlags_Factory; 1152 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy); 1153 1154 // FIXME: Set CXX-structors flag. 1155 if (IsClassHidden(ID->getClassInterface())) 1156 Flags |= eClassFlags_Hidden; 1157 1158 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1159 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), 1160 e = ID->instmeth_end(); i != e; ++i) { 1161 // Instance methods should always be defined. 1162 InstanceMethods.push_back(GetMethodConstant(*i)); 1163 } 1164 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), 1165 e = ID->classmeth_end(); i != e; ++i) { 1166 // Class methods should always be defined. 1167 ClassMethods.push_back(GetMethodConstant(*i)); 1168 } 1169 1170 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), 1171 e = ID->propimpl_end(); i != e; ++i) { 1172 ObjCPropertyImplDecl *PID = *i; 1173 1174 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1175 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1176 1177 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 1178 if (llvm::Constant *C = GetMethodConstant(MD)) 1179 InstanceMethods.push_back(C); 1180 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 1181 if (llvm::Constant *C = GetMethodConstant(MD)) 1182 InstanceMethods.push_back(C); 1183 } 1184 } 1185 1186 std::vector<llvm::Constant*> Values(12); 1187 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods); 1188 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { 1189 // Record a reference to the super class. 1190 LazySymbols.insert(Super->getIdentifier()); 1191 1192 Values[ 1] = 1193 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1194 ObjCTypes.ClassPtrTy); 1195 } else { 1196 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1197 } 1198 Values[ 2] = GetClassName(ID->getIdentifier()); 1199 // Version is always 0. 1200 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1201 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1202 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1203 Values[ 6] = EmitIvarList(ID, false, InterfaceTy); 1204 Values[ 7] = 1205 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(), 1206 "__OBJC,__inst_meth,regular,no_dead_strip", 1207 InstanceMethods); 1208 // cache is always NULL. 1209 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1210 Values[ 9] = Protocols; 1211 // FIXME: Set ivar_layout 1212 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1213 Values[11] = EmitClassExtension(ID); 1214 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1215 Values); 1216 1217 llvm::GlobalVariable *GV = 1218 new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1219 llvm::GlobalValue::InternalLinkage, 1220 Init, 1221 std::string("\01L_OBJC_CLASS_")+ClassName, 1222 &CGM.getModule()); 1223 GV->setSection("__OBJC,__class,regular,no_dead_strip"); 1224 UsedGlobals.push_back(GV); 1225 // FIXME: Why? 1226 GV->setAlignment(32); 1227 DefinedClasses.push_back(GV); 1228} 1229 1230llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, 1231 llvm::Constant *Protocols, 1232 const llvm::Type *InterfaceTy, 1233 const ConstantVector &Methods) { 1234 unsigned Flags = eClassFlags_Meta; 1235 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy); 1236 1237 if (IsClassHidden(ID->getClassInterface())) 1238 Flags |= eClassFlags_Hidden; 1239 1240 std::vector<llvm::Constant*> Values(12); 1241 // The isa for the metaclass is the root of the hierarchy. 1242 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 1243 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 1244 Root = Super; 1245 Values[ 0] = 1246 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()), 1247 ObjCTypes.ClassPtrTy); 1248 // The super class for the metaclass is emitted as the name of the 1249 // super class. The runtime fixes this up to point to the 1250 // *metaclass* for the super class. 1251 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { 1252 Values[ 1] = 1253 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1254 ObjCTypes.ClassPtrTy); 1255 } else { 1256 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1257 } 1258 Values[ 2] = GetClassName(ID->getIdentifier()); 1259 // Version is always 0. 1260 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1261 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1262 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1263 Values[ 6] = EmitIvarList(ID, true, InterfaceTy); 1264 Values[ 7] = 1265 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(), 1266 "__OBJC,__inst_meth,regular,no_dead_strip", 1267 Methods); 1268 // cache is always NULL. 1269 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1270 Values[ 9] = Protocols; 1271 // ivar_layout for metaclass is always NULL. 1272 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1273 // The class extension is always unused for metaclasses. 1274 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1275 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1276 Values); 1277 1278 std::string Name("\01L_OBJC_METACLASS_"); 1279 Name += ID->getNameAsCString(); 1280 1281 // Check for a forward reference. 1282 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 1283 if (GV) { 1284 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1285 "Forward metaclass reference has incorrect type."); 1286 GV->setLinkage(llvm::GlobalValue::InternalLinkage); 1287 GV->setInitializer(Init); 1288 } else { 1289 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1290 llvm::GlobalValue::InternalLinkage, 1291 Init, Name, 1292 &CGM.getModule()); 1293 } 1294 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); 1295 UsedGlobals.push_back(GV); 1296 // FIXME: Why? 1297 GV->setAlignment(32); 1298 1299 return GV; 1300} 1301 1302llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { 1303 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString(); 1304 1305 // FIXME: Should we look these up somewhere other than the 1306 // module. Its a bit silly since we only generate these while 1307 // processing an implementation, so exactly one pointer would work 1308 // if know when we entered/exitted an implementation block. 1309 1310 // Check for an existing forward reference. 1311 // Previously, metaclass with internal linkage may have been defined. 1312 // pass 'true' as 2nd argument so it is returned. 1313 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) { 1314 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1315 "Forward metaclass reference has incorrect type."); 1316 return GV; 1317 } else { 1318 // Generate as an external reference to keep a consistent 1319 // module. This will be patched up when we emit the metaclass. 1320 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1321 llvm::GlobalValue::ExternalLinkage, 1322 0, 1323 Name, 1324 &CGM.getModule()); 1325 } 1326} 1327 1328/* 1329 struct objc_class_ext { 1330 uint32_t size; 1331 const char *weak_ivar_layout; 1332 struct _objc_property_list *properties; 1333 }; 1334*/ 1335llvm::Constant * 1336CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) { 1337 uint64_t Size = 1338 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy); 1339 1340 std::vector<llvm::Constant*> Values(3); 1341 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1342 // FIXME: Output weak_ivar_layout string. 1343 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1344 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 1345 ID, ID->getClassInterface()); 1346 1347 // Return null if no extension bits are used. 1348 if (Values[1]->isNullValue() && Values[2]->isNullValue()) 1349 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1350 1351 llvm::Constant *Init = 1352 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); 1353 llvm::GlobalVariable *GV = 1354 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false, 1355 llvm::GlobalValue::InternalLinkage, 1356 Init, 1357 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(), 1358 &CGM.getModule()); 1359 // No special section, but goes in llvm.used 1360 UsedGlobals.push_back(GV); 1361 1362 return GV; 1363} 1364 1365/// countInheritedIvars - count number of ivars in class and its super class(s) 1366/// 1367static int countInheritedIvars(const ObjCInterfaceDecl *OI) { 1368 int count = 0; 1369 if (!OI) 1370 return 0; 1371 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass(); 1372 if (SuperClass) 1373 count += countInheritedIvars(SuperClass); 1374 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1375 E = OI->ivar_end(); I != E; ++I) 1376 ++count; 1377 return count; 1378} 1379 1380/* 1381 struct objc_ivar { 1382 char *ivar_name; 1383 char *ivar_type; 1384 int ivar_offset; 1385 }; 1386 1387 struct objc_ivar_list { 1388 int ivar_count; 1389 struct objc_ivar list[count]; 1390 }; 1391 */ 1392llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, 1393 bool ForClass, 1394 const llvm::Type *InterfaceTy) { 1395 std::vector<llvm::Constant*> Ivars, Ivar(3); 1396 1397 // When emitting the root class GCC emits ivar entries for the 1398 // actual class structure. It is not clear if we need to follow this 1399 // behavior; for now lets try and get away with not doing it. If so, 1400 // the cleanest solution would be to make up an ObjCInterfaceDecl 1401 // for the class. 1402 if (ForClass) 1403 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1404 1405 const llvm::StructLayout *Layout = 1406 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); 1407 ObjCInterfaceDecl *OID = 1408 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface()); 1409 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass()); 1410 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID); 1411 RecordDecl::field_iterator ifield = RD->field_begin(); 1412 while (countSuperClassIvars-- > 0) 1413 ++ifield; 1414 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) { 1415 FieldDecl *Field = *ifield; 1416 unsigned Offset = Layout->getElementOffset(CGM.getTypes(). 1417 getLLVMFieldNo(Field)); 1418 if (Field->getIdentifier()) 1419 Ivar[0] = GetMethodVarName(Field->getIdentifier()); 1420 else 1421 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1422 std::string TypeStr; 1423 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); 1424 Ivar[1] = GetMethodVarType(TypeStr); 1425 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset); 1426 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar)); 1427 } 1428 1429 // Return null for empty list. 1430 if (Ivars.empty()) 1431 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1432 1433 std::vector<llvm::Constant*> Values(2); 1434 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 1435 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, 1436 Ivars.size()); 1437 Values[1] = llvm::ConstantArray::get(AT, Ivars); 1438 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1439 1440 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" : 1441 "\01L_OBJC_INSTANCE_VARIABLES_"); 1442 llvm::GlobalVariable *GV = 1443 new llvm::GlobalVariable(Init->getType(), false, 1444 llvm::GlobalValue::InternalLinkage, 1445 Init, 1446 Prefix + ID->getNameAsString(), 1447 &CGM.getModule()); 1448 if (ForClass) { 1449 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip"); 1450 // FIXME: Why is this only here? 1451 GV->setAlignment(32); 1452 } else { 1453 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip"); 1454 } 1455 UsedGlobals.push_back(GV); 1456 return llvm::ConstantExpr::getBitCast(GV, 1457 ObjCTypes.IvarListPtrTy); 1458} 1459 1460/* 1461 struct objc_method { 1462 SEL method_name; 1463 char *method_types; 1464 void *method; 1465 }; 1466 1467 struct objc_method_list { 1468 struct objc_method_list *obsolete; 1469 int count; 1470 struct objc_method methods_list[count]; 1471 }; 1472*/ 1473 1474/// GetMethodConstant - Return a struct objc_method constant for the 1475/// given method if it has been defined. The result is null if the 1476/// method has not been defined. The return value has type MethodPtrTy. 1477llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { 1478 // FIXME: Use DenseMap::lookup 1479 llvm::Function *Fn = MethodDefinitions[MD]; 1480 if (!Fn) 1481 return 0; 1482 1483 std::vector<llvm::Constant*> Method(3); 1484 Method[0] = 1485 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1486 ObjCTypes.SelectorPtrTy); 1487 Method[1] = GetMethodVarType(MD); 1488 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 1489 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 1490} 1491 1492llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name, 1493 const char *Section, 1494 const ConstantVector &Methods) { 1495 // Return null for empty list. 1496 if (Methods.empty()) 1497 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); 1498 1499 std::vector<llvm::Constant*> Values(3); 1500 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1501 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1502 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 1503 Methods.size()); 1504 Values[2] = llvm::ConstantArray::get(AT, Methods); 1505 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1506 1507 llvm::GlobalVariable *GV = 1508 new llvm::GlobalVariable(Init->getType(), false, 1509 llvm::GlobalValue::InternalLinkage, 1510 Init, 1511 Name, 1512 &CGM.getModule()); 1513 GV->setSection(Section); 1514 UsedGlobals.push_back(GV); 1515 return llvm::ConstantExpr::getBitCast(GV, 1516 ObjCTypes.MethodListPtrTy); 1517} 1518 1519llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD, 1520 const ObjCContainerDecl *CD) { 1521 std::string Name; 1522 GetNameForMethod(OMD, CD, Name); 1523 1524 const llvm::FunctionType *MethodTy = 1525 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext())); 1526 llvm::Function *Method = 1527 llvm::Function::Create(MethodTy, 1528 llvm::GlobalValue::InternalLinkage, 1529 Name, 1530 &CGM.getModule()); 1531 MethodDefinitions.insert(std::make_pair(OMD, Method)); 1532 1533 return Method; 1534} 1535 1536llvm::Function *CGObjCMac::ModuleInitFunction() { 1537 // Abuse this interface function as a place to finalize. 1538 FinishModule(); 1539 1540 return NULL; 1541} 1542 1543llvm::Function *CGObjCMac::GetPropertyGetFunction() { 1544 return ObjCTypes.GetPropertyFn; 1545} 1546 1547llvm::Function *CGObjCMac::GetPropertySetFunction() { 1548 return ObjCTypes.SetPropertyFn; 1549} 1550 1551llvm::Function *CGObjCMac::EnumerationMutationFunction() 1552{ 1553 return ObjCTypes.EnumerationMutationFn; 1554} 1555 1556/* 1557 1558Objective-C setjmp-longjmp (sjlj) Exception Handling 1559-- 1560 1561The basic framework for a @try-catch-finally is as follows: 1562{ 1563 objc_exception_data d; 1564 id _rethrow = null; 1565 1566 objc_exception_try_enter(&d); 1567 if (!setjmp(d.jmp_buf)) { 1568 ... try body ... 1569 } else { 1570 // exception path 1571 id _caught = objc_exception_extract(&d); 1572 1573 // enter new try scope for handlers 1574 if (!setjmp(d.jmp_buf)) { 1575 ... match exception and execute catch blocks ... 1576 1577 // fell off end, rethrow. 1578 _rethrow = _caught; 1579 ... jump-through-finally to finally_rethrow ... 1580 } else { 1581 // exception in catch block 1582 _rethrow = objc_exception_extract(&d); 1583 ... jump-through-finally_no_exit to finally_rethrow ... 1584 } 1585 } 1586 ... jump-through-finally to finally_end ... 1587 1588finally: 1589 // match either the initial try_enter or the catch try_enter, 1590 // depending on the path followed. 1591 objc_exception_try_exit(&d); 1592finally_no_exit: 1593 ... finally block .... 1594 ... dispatch to finally destination ... 1595 1596finally_rethrow: 1597 objc_exception_throw(_rethrow); 1598 1599finally_end: 1600} 1601 1602This framework differs slightly from the one gcc uses, in that gcc 1603uses _rethrow to determine if objc_exception_try_exit should be called 1604and if the object should be rethrown. This breaks in the face of 1605throwing nil and introduces unnecessary branches. 1606 1607We specialize this framework for a few particular circumstances: 1608 1609 - If there are no catch blocks, then we avoid emitting the second 1610 exception handling context. 1611 1612 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id 1613 e)) we avoid emitting the code to rethrow an uncaught exception. 1614 1615 - FIXME: If there is no @finally block we can do a few more 1616 simplifications. 1617 1618Rethrows and Jumps-Through-Finally 1619-- 1620 1621Support for implicit rethrows and jumping through the finally block is 1622handled by storing the current exception-handling context in 1623ObjCEHStack. 1624 1625In order to implement proper @finally semantics, we support one basic 1626mechanism for jumping through the finally block to an arbitrary 1627destination. Constructs which generate exits from a @try or @catch 1628block use this mechanism to implement the proper semantics by chaining 1629jumps, as necessary. 1630 1631This mechanism works like the one used for indirect goto: we 1632arbitrarily assign an ID to each destination and store the ID for the 1633destination in a variable prior to entering the finally block. At the 1634end of the finally block we simply create a switch to the proper 1635destination. 1636 1637Code gen for @synchronized(expr) stmt; 1638Effectively generating code for: 1639objc_sync_enter(expr); 1640@try stmt @finally { objc_sync_exit(expr); } 1641*/ 1642 1643void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1644 const Stmt &S) { 1645 bool isTry = isa<ObjCAtTryStmt>(S); 1646 // Create various blocks we refer to for handling @finally. 1647 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 1648 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit"); 1649 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 1650 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 1651 llvm::Value *DestCode = 1652 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst"); 1653 1654 // Generate jump code. Done here so we can directly add things to 1655 // the switch instruction. 1656 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump"); 1657 llvm::SwitchInst *FinallySwitch = 1658 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump), 1659 FinallyEnd, 10, FinallyJump); 1660 1661 // Push an EH context entry, used for handling rethrows and jumps 1662 // through finally. 1663 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit, 1664 FinallySwitch, DestCode); 1665 CGF.ObjCEHStack.push_back(&EHEntry); 1666 1667 // Allocate memory for the exception data and rethrow pointer. 1668 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, 1669 "exceptiondata.ptr"); 1670 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, 1671 "_rethrow"); 1672 if (!isTry) { 1673 // For @synchronized, call objc_sync_enter(sync.expr) 1674 llvm::Value *Arg = CGF.EmitScalarExpr( 1675 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1676 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy); 1677 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg); 1678 } 1679 1680 // Enter a new try block and call setjmp. 1681 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); 1682 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0, 1683 "jmpbufarray"); 1684 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp"); 1685 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, 1686 JmpBufPtr, "result"); 1687 1688 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 1689 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 1690 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"), 1691 TryHandler, TryBlock); 1692 1693 // Emit the @try block. 1694 CGF.EmitBlock(TryBlock); 1695 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 1696 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 1697 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd); 1698 1699 // Emit the "exception in @try" block. 1700 CGF.EmitBlock(TryHandler); 1701 1702 // Retrieve the exception object. We may emit multiple blocks but 1703 // nothing can cross this so the value is already in SSA form. 1704 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, 1705 ExceptionData, 1706 "caught"); 1707 EHEntry.Exception = Caught; 1708 if (!isTry) 1709 { 1710 CGF.Builder.CreateStore(Caught, RethrowPtr); 1711 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false); 1712 } 1713 else if (const ObjCAtCatchStmt* CatchStmt = 1714 cast<ObjCAtTryStmt>(S).getCatchStmts()) 1715 { 1716 // Enter a new exception try block (in case a @catch block throws 1717 // an exception). 1718 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); 1719 1720 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, 1721 JmpBufPtr, "result"); 1722 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"); 1723 1724 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch"); 1725 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler"); 1726 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); 1727 1728 CGF.EmitBlock(CatchBlock); 1729 1730 // Handle catch list. As a special case we check if everything is 1731 // matched and avoid generating code for falling off the end if 1732 // so. 1733 bool AllMatched = false; 1734 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 1735 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch"); 1736 1737 const DeclStmt *CatchParam = 1738 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt()); 1739 const VarDecl *VD = 0; 1740 const PointerType *PT = 0; 1741 1742 // catch(...) always matches. 1743 if (!CatchParam) { 1744 AllMatched = true; 1745 } else { 1746 VD = cast<VarDecl>(CatchParam->getSolitaryDecl()); 1747 PT = VD->getType()->getAsPointerType(); 1748 1749 // catch(id e) always matches. 1750 // FIXME: For the time being we also match id<X>; this should 1751 // be rejected by Sema instead. 1752 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) || 1753 VD->getType()->isObjCQualifiedIdType()) 1754 AllMatched = true; 1755 } 1756 1757 if (AllMatched) { 1758 if (CatchParam) { 1759 CGF.EmitStmt(CatchParam); 1760 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 1761 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD)); 1762 } 1763 1764 CGF.EmitStmt(CatchStmt->getCatchBody()); 1765 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd); 1766 break; 1767 } 1768 1769 assert(PT && "Unexpected non-pointer type in @catch"); 1770 QualType T = PT->getPointeeType(); 1771 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType(); 1772 assert(ObjCType && "Catch parameter must have Objective-C type!"); 1773 1774 // Check if the @catch block matches the exception object. 1775 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl()); 1776 1777 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn, 1778 Class, Caught, "match"); 1779 1780 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched"); 1781 1782 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), 1783 MatchedBlock, NextCatchBlock); 1784 1785 // Emit the @catch block. 1786 CGF.EmitBlock(MatchedBlock); 1787 CGF.EmitStmt(CatchParam); 1788 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 1789 1790 llvm::Value *Tmp = 1791 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()), 1792 "tmp"); 1793 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD)); 1794 1795 CGF.EmitStmt(CatchStmt->getCatchBody()); 1796 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd); 1797 1798 CGF.EmitBlock(NextCatchBlock); 1799 } 1800 1801 if (!AllMatched) { 1802 // None of the handlers caught the exception, so store it to be 1803 // rethrown at the end of the @finally block. 1804 CGF.Builder.CreateStore(Caught, RethrowPtr); 1805 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow); 1806 } 1807 1808 // Emit the exception handler for the @catch blocks. 1809 CGF.EmitBlock(CatchHandler); 1810 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, 1811 ExceptionData), 1812 RethrowPtr); 1813 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false); 1814 } else { 1815 CGF.Builder.CreateStore(Caught, RethrowPtr); 1816 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false); 1817 } 1818 1819 // Pop the exception-handling stack entry. It is important to do 1820 // this now, because the code in the @finally block is not in this 1821 // context. 1822 CGF.ObjCEHStack.pop_back(); 1823 1824 // Emit the @finally block. 1825 CGF.EmitBlock(FinallyBlock); 1826 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData); 1827 1828 CGF.EmitBlock(FinallyNoExit); 1829 if (isTry) { 1830 if (const ObjCAtFinallyStmt* FinallyStmt = 1831 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 1832 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 1833 } 1834 else { 1835 // For @synchronized objc_sync_exit(expr); As finally's sole statement. 1836 // For @synchronized, call objc_sync_enter(sync.expr) 1837 llvm::Value *Arg = CGF.EmitScalarExpr( 1838 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1839 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy); 1840 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg); 1841 } 1842 1843 CGF.EmitBlock(FinallyJump); 1844 1845 CGF.EmitBlock(FinallyRethrow); 1846 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, 1847 CGF.Builder.CreateLoad(RethrowPtr)); 1848 CGF.Builder.CreateUnreachable(); 1849 1850 CGF.EmitBlock(FinallyEnd); 1851} 1852 1853void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 1854 const ObjCAtThrowStmt &S) { 1855 llvm::Value *ExceptionAsObject; 1856 1857 if (const Expr *ThrowExpr = S.getThrowExpr()) { 1858 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 1859 ExceptionAsObject = 1860 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); 1861 } else { 1862 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) && 1863 "Unexpected rethrow outside @catch block."); 1864 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception; 1865 } 1866 1867 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject); 1868 CGF.Builder.CreateUnreachable(); 1869 1870 // Clear the insertion point to indicate we are in unreachable code. 1871 CGF.Builder.ClearInsertionPoint(); 1872} 1873 1874void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E, 1875 llvm::BasicBlock *Dst, 1876 bool ExecuteTryExit) { 1877 if (!HaveInsertPoint()) 1878 return; 1879 1880 // Find the destination code for this block. We always use 0 for the 1881 // fallthrough block (default destination). 1882 llvm::SwitchInst *SI = E->FinallySwitch; 1883 llvm::ConstantInt *ID; 1884 if (Dst == SI->getDefaultDest()) { 1885 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0); 1886 } else { 1887 ID = SI->findCaseDest(Dst); 1888 if (!ID) { 1889 // No code found, get a new unique one by just using the number 1890 // of switch successors. 1891 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors()); 1892 SI->addCase(ID, Dst); 1893 } 1894 } 1895 1896 // Set the destination code and branch. 1897 Builder.CreateStore(ID, E->DestCode); 1898 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit); 1899} 1900 1901/// EmitObjCWeakRead - Code gen for loading value of a __weak 1902/// object: objc_read_weak (id *src) 1903/// 1904llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1905 llvm::Value *AddrWeakObj) 1906{ 1907 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 1908 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn, 1909 AddrWeakObj, "weakread"); 1910 return read_weak; 1911} 1912 1913/// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 1914/// objc_assign_weak (id src, id *dst) 1915/// 1916void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1917 llvm::Value *src, llvm::Value *dst) 1918{ 1919 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 1920 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 1921 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn, 1922 src, dst, "weakassign"); 1923 return; 1924} 1925 1926/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 1927/// objc_assign_global (id src, id *dst) 1928/// 1929void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1930 llvm::Value *src, llvm::Value *dst) 1931{ 1932 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 1933 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 1934 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn, 1935 src, dst, "globalassign"); 1936 return; 1937} 1938 1939/// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 1940/// objc_assign_ivar (id src, id *dst) 1941/// 1942void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1943 llvm::Value *src, llvm::Value *dst) 1944{ 1945 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 1946 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 1947 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn, 1948 src, dst, "assignivar"); 1949 return; 1950} 1951 1952/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 1953/// objc_assign_strongCast (id src, id *dst) 1954/// 1955void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1956 llvm::Value *src, llvm::Value *dst) 1957{ 1958 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 1959 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 1960 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn, 1961 src, dst, "weakassign"); 1962 return; 1963} 1964 1965/* *** Private Interface *** */ 1966 1967/// EmitImageInfo - Emit the image info marker used to encode some module 1968/// level information. 1969/// 1970/// See: <rdr://4810609&4810587&4810587> 1971/// struct IMAGE_INFO { 1972/// unsigned version; 1973/// unsigned flags; 1974/// }; 1975enum ImageInfoFlags { 1976 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies 1977 eImageInfo_GarbageCollected = (1 << 1), 1978 eImageInfo_GCOnly = (1 << 2) 1979}; 1980 1981void CGObjCMac::EmitImageInfo() { 1982 unsigned version = 0; // Version is unused? 1983 unsigned flags = 0; 1984 1985 // FIXME: Fix and continue? 1986 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 1987 flags |= eImageInfo_GarbageCollected; 1988 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 1989 flags |= eImageInfo_GCOnly; 1990 1991 // Emitted as int[2]; 1992 llvm::Constant *values[2] = { 1993 llvm::ConstantInt::get(llvm::Type::Int32Ty, version), 1994 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags) 1995 }; 1996 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2); 1997 llvm::GlobalVariable *GV = 1998 new llvm::GlobalVariable(AT, true, 1999 llvm::GlobalValue::InternalLinkage, 2000 llvm::ConstantArray::get(AT, values, 2), 2001 "\01L_OBJC_IMAGE_INFO", 2002 &CGM.getModule()); 2003 2004 if (ObjCABI == 1) { 2005 GV->setSection("__OBJC, __image_info,regular"); 2006 } else { 2007 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); 2008 } 2009 2010 UsedGlobals.push_back(GV); 2011} 2012 2013 2014// struct objc_module { 2015// unsigned long version; 2016// unsigned long size; 2017// const char *name; 2018// Symtab symtab; 2019// }; 2020 2021// FIXME: Get from somewhere 2022static const int ModuleVersion = 7; 2023 2024void CGObjCMac::EmitModuleInfo() { 2025 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy); 2026 2027 std::vector<llvm::Constant*> Values(4); 2028 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion); 2029 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 2030 // This used to be the filename, now it is unused. <rdr://4327263> 2031 Values[2] = GetClassName(&CGM.getContext().Idents.get("")); 2032 Values[3] = EmitModuleSymbols(); 2033 2034 llvm::GlobalVariable *GV = 2035 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false, 2036 llvm::GlobalValue::InternalLinkage, 2037 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, 2038 Values), 2039 "\01L_OBJC_MODULES", 2040 &CGM.getModule()); 2041 GV->setSection("__OBJC,__module_info,regular,no_dead_strip"); 2042 UsedGlobals.push_back(GV); 2043} 2044 2045llvm::Constant *CGObjCMac::EmitModuleSymbols() { 2046 unsigned NumClasses = DefinedClasses.size(); 2047 unsigned NumCategories = DefinedCategories.size(); 2048 2049 // Return null if no symbols were defined. 2050 if (!NumClasses && !NumCategories) 2051 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); 2052 2053 std::vector<llvm::Constant*> Values(5); 2054 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 2055 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); 2056 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); 2057 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); 2058 2059 // The runtime expects exactly the list of defined classes followed 2060 // by the list of defined categories, in a single array. 2061 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories); 2062 for (unsigned i=0; i<NumClasses; i++) 2063 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 2064 ObjCTypes.Int8PtrTy); 2065 for (unsigned i=0; i<NumCategories; i++) 2066 Symbols[NumClasses + i] = 2067 llvm::ConstantExpr::getBitCast(DefinedCategories[i], 2068 ObjCTypes.Int8PtrTy); 2069 2070 Values[4] = 2071 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 2072 NumClasses + NumCategories), 2073 Symbols); 2074 2075 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 2076 2077 llvm::GlobalVariable *GV = 2078 new llvm::GlobalVariable(Init->getType(), false, 2079 llvm::GlobalValue::InternalLinkage, 2080 Init, 2081 "\01L_OBJC_SYMBOLS", 2082 &CGM.getModule()); 2083 GV->setSection("__OBJC,__symbols,regular,no_dead_strip"); 2084 UsedGlobals.push_back(GV); 2085 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); 2086} 2087 2088llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder, 2089 const ObjCInterfaceDecl *ID) { 2090 LazySymbols.insert(ID->getIdentifier()); 2091 2092 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 2093 2094 if (!Entry) { 2095 llvm::Constant *Casted = 2096 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()), 2097 ObjCTypes.ClassPtrTy); 2098 Entry = 2099 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false, 2100 llvm::GlobalValue::InternalLinkage, 2101 Casted, "\01L_OBJC_CLASS_REFERENCES_", 2102 &CGM.getModule()); 2103 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip"); 2104 UsedGlobals.push_back(Entry); 2105 } 2106 2107 return Builder.CreateLoad(Entry, false, "tmp"); 2108} 2109 2110llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) { 2111 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 2112 2113 if (!Entry) { 2114 llvm::Constant *Casted = 2115 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 2116 ObjCTypes.SelectorPtrTy); 2117 Entry = 2118 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false, 2119 llvm::GlobalValue::InternalLinkage, 2120 Casted, "\01L_OBJC_SELECTOR_REFERENCES_", 2121 &CGM.getModule()); 2122 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip"); 2123 UsedGlobals.push_back(Entry); 2124 } 2125 2126 return Builder.CreateLoad(Entry, false, "tmp"); 2127} 2128 2129llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) { 2130 llvm::GlobalVariable *&Entry = ClassNames[Ident]; 2131 2132 if (!Entry) { 2133 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName()); 2134 Entry = 2135 new llvm::GlobalVariable(C->getType(), false, 2136 llvm::GlobalValue::InternalLinkage, 2137 C, "\01L_OBJC_CLASS_NAME_", 2138 &CGM.getModule()); 2139 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2140 UsedGlobals.push_back(Entry); 2141 } 2142 2143 return getConstantGEP(Entry, 0, 0); 2144} 2145 2146llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { 2147 llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; 2148 2149 if (!Entry) { 2150 // FIXME: Avoid std::string copying. 2151 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString()); 2152 Entry = 2153 new llvm::GlobalVariable(C->getType(), false, 2154 llvm::GlobalValue::InternalLinkage, 2155 C, "\01L_OBJC_METH_VAR_NAME_", 2156 &CGM.getModule()); 2157 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2158 UsedGlobals.push_back(Entry); 2159 } 2160 2161 return getConstantGEP(Entry, 0, 0); 2162} 2163 2164// FIXME: Merge into a single cstring creation function. 2165llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { 2166 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); 2167} 2168 2169// FIXME: Merge into a single cstring creation function. 2170llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) { 2171 return GetMethodVarName(&CGM.getContext().Idents.get(Name)); 2172} 2173 2174llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) { 2175 llvm::GlobalVariable *&Entry = MethodVarTypes[Name]; 2176 2177 if (!Entry) { 2178 llvm::Constant *C = llvm::ConstantArray::get(Name); 2179 Entry = 2180 new llvm::GlobalVariable(C->getType(), false, 2181 llvm::GlobalValue::InternalLinkage, 2182 C, "\01L_OBJC_METH_VAR_TYPE_", 2183 &CGM.getModule()); 2184 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2185 UsedGlobals.push_back(Entry); 2186 } 2187 2188 return getConstantGEP(Entry, 0, 0); 2189} 2190 2191// FIXME: Merge into a single cstring creation function. 2192llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) { 2193 std::string TypeStr; 2194 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D), 2195 TypeStr); 2196 return GetMethodVarType(TypeStr); 2197} 2198 2199// FIXME: Merge into a single cstring creation function. 2200llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { 2201 llvm::GlobalVariable *&Entry = PropertyNames[Ident]; 2202 2203 if (!Entry) { 2204 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName()); 2205 Entry = 2206 new llvm::GlobalVariable(C->getType(), false, 2207 llvm::GlobalValue::InternalLinkage, 2208 C, "\01L_OBJC_PROP_NAME_ATTR_", 2209 &CGM.getModule()); 2210 Entry->setSection("__TEXT,__cstring,cstring_literals"); 2211 UsedGlobals.push_back(Entry); 2212 } 2213 2214 return getConstantGEP(Entry, 0, 0); 2215} 2216 2217// FIXME: Merge into a single cstring creation function. 2218// FIXME: This Decl should be more precise. 2219llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, 2220 const Decl *Container) { 2221 std::string TypeStr; 2222 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 2223 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); 2224} 2225 2226void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, 2227 const ObjCContainerDecl *CD, 2228 std::string &NameOut) { 2229 // FIXME: Find the mangling GCC uses. 2230 NameOut = (D->isInstanceMethod() ? "-" : "+"); 2231 NameOut += '['; 2232 assert (CD && "Missing container decl in GetNameForMethod"); 2233 NameOut += CD->getNameAsString(); 2234 NameOut += ' '; 2235 NameOut += D->getSelector().getAsString(); 2236 NameOut += ']'; 2237} 2238 2239void CGObjCMac::FinishModule() { 2240 EmitModuleInfo(); 2241 2242 // Emit the dummy bodies for any protocols which were referenced but 2243 // never defined. 2244 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator 2245 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) { 2246 if (i->second->hasInitializer()) 2247 continue; 2248 2249 std::vector<llvm::Constant*> Values(5); 2250 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 2251 Values[1] = GetClassName(i->first); 2252 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 2253 Values[3] = Values[4] = 2254 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 2255 i->second->setLinkage(llvm::GlobalValue::InternalLinkage); 2256 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 2257 Values)); 2258 } 2259 2260 std::vector<llvm::Constant*> Used; 2261 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 2262 e = UsedGlobals.end(); i != e; ++i) { 2263 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 2264 } 2265 2266 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 2267 llvm::GlobalValue *GV = 2268 new llvm::GlobalVariable(AT, false, 2269 llvm::GlobalValue::AppendingLinkage, 2270 llvm::ConstantArray::get(AT, Used), 2271 "llvm.used", 2272 &CGM.getModule()); 2273 2274 GV->setSection("llvm.metadata"); 2275 2276 // Add assembler directives to add lazy undefined symbol references 2277 // for classes which are referenced but not defined. This is 2278 // important for correct linker interaction. 2279 2280 // FIXME: Uh, this isn't particularly portable. 2281 std::stringstream s; 2282 2283 if (!CGM.getModule().getModuleInlineAsm().empty()) 2284 s << "\n"; 2285 2286 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(), 2287 e = LazySymbols.end(); i != e; ++i) { 2288 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n"; 2289 } 2290 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(), 2291 e = DefinedSymbols.end(); i != e; ++i) { 2292 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n" 2293 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n"; 2294 } 2295 2296 CGM.getModule().appendModuleInlineAsm(s.str()); 2297} 2298 2299CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) 2300 : CGObjCCommonMac(cgm), 2301 ObjCTypes(cgm) 2302{ 2303 ObjCABI = 2; 2304} 2305 2306/* *** */ 2307 2308ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) 2309: CGM(cgm) 2310{ 2311 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 2312 ASTContext &Ctx = CGM.getContext(); 2313 2314 ShortTy = Types.ConvertType(Ctx.ShortTy); 2315 IntTy = Types.ConvertType(Ctx.IntTy); 2316 LongTy = Types.ConvertType(Ctx.LongTy); 2317 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 2318 2319 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); 2320 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); 2321 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); 2322 2323 // FIXME: It would be nice to unify this with the opaque type, so 2324 // that the IR comes out a bit cleaner. 2325 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); 2326 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); 2327 2328 // I'm not sure I like this. The implicit coordination is a bit 2329 // gross. We should solve this in a reasonable fashion because this 2330 // is a pretty common task (match some runtime data structure with 2331 // an LLVM data structure). 2332 2333 // FIXME: This is leaked. 2334 // FIXME: Merge with rewriter code? 2335 2336 // struct _objc_super { 2337 // id self; 2338 // Class cls; 2339 // } 2340 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 2341 SourceLocation(), 2342 &Ctx.Idents.get("_objc_super")); 2343 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 2344 Ctx.getObjCIdType(), 0, false)); 2345 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 2346 Ctx.getObjCClassType(), 0, false)); 2347 RD->completeDefinition(Ctx); 2348 2349 SuperCTy = Ctx.getTagDeclType(RD); 2350 SuperPtrCTy = Ctx.getPointerType(SuperCTy); 2351 2352 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); 2353 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); 2354 2355 // struct _prop_t { 2356 // char *name; 2357 // char *attributes; 2358 // } 2359 PropertyTy = llvm::StructType::get(Int8PtrTy, 2360 Int8PtrTy, 2361 NULL); 2362 CGM.getModule().addTypeName("struct._prop_t", 2363 PropertyTy); 2364 2365 // struct _prop_list_t { 2366 // uint32_t entsize; // sizeof(struct _prop_t) 2367 // uint32_t count_of_properties; 2368 // struct _prop_t prop_list[count_of_properties]; 2369 // } 2370 PropertyListTy = llvm::StructType::get(IntTy, 2371 IntTy, 2372 llvm::ArrayType::get(PropertyTy, 0), 2373 NULL); 2374 CGM.getModule().addTypeName("struct._prop_list_t", 2375 PropertyListTy); 2376 // struct _prop_list_t * 2377 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); 2378 2379 // struct _objc_method { 2380 // SEL _cmd; 2381 // char *method_type; 2382 // char *_imp; 2383 // } 2384 MethodTy = llvm::StructType::get(SelectorPtrTy, 2385 Int8PtrTy, 2386 Int8PtrTy, 2387 NULL); 2388 CGM.getModule().addTypeName("struct._objc_method", MethodTy); 2389 2390 // struct _objc_cache * 2391 CacheTy = llvm::OpaqueType::get(); 2392 CGM.getModule().addTypeName("struct._objc_cache", CacheTy); 2393 CachePtrTy = llvm::PointerType::getUnqual(CacheTy); 2394 2395 // Property manipulation functions. 2396 2397 // id objc_getProperty (id, SEL, ptrdiff_t, bool) 2398 std::vector<const llvm::Type*> Params; 2399 Params.push_back(ObjectPtrTy); 2400 Params.push_back(SelectorPtrTy); 2401 Params.push_back(LongTy); 2402 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy)); 2403 GetPropertyFn = 2404 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2405 Params, 2406 false), 2407 "objc_getProperty"); 2408 2409 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 2410 Params.clear(); 2411 Params.push_back(ObjectPtrTy); 2412 Params.push_back(SelectorPtrTy); 2413 Params.push_back(LongTy); 2414 Params.push_back(ObjectPtrTy); 2415 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy)); 2416 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy)); 2417 SetPropertyFn = 2418 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2419 Params, 2420 false), 2421 "objc_setProperty"); 2422 // Enumeration mutation. 2423 2424 Params.clear(); 2425 Params.push_back(ObjectPtrTy); 2426 EnumerationMutationFn = 2427 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2428 Params, 2429 false), 2430 "objc_enumerationMutation"); 2431 2432 // gc's API 2433 // id objc_read_weak (id *) 2434 Params.clear(); 2435 Params.push_back(PtrObjectPtrTy); 2436 GcReadWeakFn = 2437 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2438 Params, 2439 false), 2440 "objc_read_weak"); 2441 // id objc_assign_weak (id, id *) 2442 Params.clear(); 2443 Params.push_back(ObjectPtrTy); 2444 Params.push_back(PtrObjectPtrTy); 2445 GcAssignWeakFn = 2446 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2447 Params, 2448 false), 2449 "objc_assign_weak"); 2450 GcAssignGlobalFn = 2451 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2452 Params, 2453 false), 2454 "objc_assign_global"); 2455 GcAssignIvarFn = 2456 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2457 Params, 2458 false), 2459 "objc_assign_ivar"); 2460 GcAssignStrongCastFn = 2461 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2462 Params, 2463 false), 2464 "objc_assign_strongCast"); 2465} 2466 2467ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) 2468 : ObjCCommonTypesHelper(cgm) 2469{ 2470 // struct _objc_method_description { 2471 // SEL name; 2472 // char *types; 2473 // } 2474 MethodDescriptionTy = 2475 llvm::StructType::get(SelectorPtrTy, 2476 Int8PtrTy, 2477 NULL); 2478 CGM.getModule().addTypeName("struct._objc_method_description", 2479 MethodDescriptionTy); 2480 2481 // struct _objc_method_description_list { 2482 // int count; 2483 // struct _objc_method_description[1]; 2484 // } 2485 MethodDescriptionListTy = 2486 llvm::StructType::get(IntTy, 2487 llvm::ArrayType::get(MethodDescriptionTy, 0), 2488 NULL); 2489 CGM.getModule().addTypeName("struct._objc_method_description_list", 2490 MethodDescriptionListTy); 2491 2492 // struct _objc_method_description_list * 2493 MethodDescriptionListPtrTy = 2494 llvm::PointerType::getUnqual(MethodDescriptionListTy); 2495 2496 // Protocol description structures 2497 2498 // struct _objc_protocol_extension { 2499 // uint32_t size; // sizeof(struct _objc_protocol_extension) 2500 // struct _objc_method_description_list *optional_instance_methods; 2501 // struct _objc_method_description_list *optional_class_methods; 2502 // struct _objc_property_list *instance_properties; 2503 // } 2504 ProtocolExtensionTy = 2505 llvm::StructType::get(IntTy, 2506 MethodDescriptionListPtrTy, 2507 MethodDescriptionListPtrTy, 2508 PropertyListPtrTy, 2509 NULL); 2510 CGM.getModule().addTypeName("struct._objc_protocol_extension", 2511 ProtocolExtensionTy); 2512 2513 // struct _objc_protocol_extension * 2514 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); 2515 2516 // Handle recursive construction of Protocol and ProtocolList types 2517 2518 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get(); 2519 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 2520 2521 const llvm::Type *T = 2522 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder), 2523 LongTy, 2524 llvm::ArrayType::get(ProtocolTyHolder, 0), 2525 NULL); 2526 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T); 2527 2528 // struct _objc_protocol { 2529 // struct _objc_protocol_extension *isa; 2530 // char *protocol_name; 2531 // struct _objc_protocol **_objc_protocol_list; 2532 // struct _objc_method_description_list *instance_methods; 2533 // struct _objc_method_description_list *class_methods; 2534 // } 2535 T = llvm::StructType::get(ProtocolExtensionPtrTy, 2536 Int8PtrTy, 2537 llvm::PointerType::getUnqual(ProtocolListTyHolder), 2538 MethodDescriptionListPtrTy, 2539 MethodDescriptionListPtrTy, 2540 NULL); 2541 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T); 2542 2543 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get()); 2544 CGM.getModule().addTypeName("struct._objc_protocol_list", 2545 ProtocolListTy); 2546 // struct _objc_protocol_list * 2547 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); 2548 2549 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get()); 2550 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy); 2551 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); 2552 2553 // Class description structures 2554 2555 // struct _objc_ivar { 2556 // char *ivar_name; 2557 // char *ivar_type; 2558 // int ivar_offset; 2559 // } 2560 IvarTy = llvm::StructType::get(Int8PtrTy, 2561 Int8PtrTy, 2562 IntTy, 2563 NULL); 2564 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy); 2565 2566 // struct _objc_ivar_list * 2567 IvarListTy = llvm::OpaqueType::get(); 2568 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy); 2569 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); 2570 2571 // struct _objc_method_list * 2572 MethodListTy = llvm::OpaqueType::get(); 2573 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy); 2574 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); 2575 2576 // struct _objc_class_extension * 2577 ClassExtensionTy = 2578 llvm::StructType::get(IntTy, 2579 Int8PtrTy, 2580 PropertyListPtrTy, 2581 NULL); 2582 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy); 2583 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); 2584 2585 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 2586 2587 // struct _objc_class { 2588 // Class isa; 2589 // Class super_class; 2590 // char *name; 2591 // long version; 2592 // long info; 2593 // long instance_size; 2594 // struct _objc_ivar_list *ivars; 2595 // struct _objc_method_list *methods; 2596 // struct _objc_cache *cache; 2597 // struct _objc_protocol_list *protocols; 2598 // char *ivar_layout; 2599 // struct _objc_class_ext *ext; 2600 // }; 2601 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 2602 llvm::PointerType::getUnqual(ClassTyHolder), 2603 Int8PtrTy, 2604 LongTy, 2605 LongTy, 2606 LongTy, 2607 IvarListPtrTy, 2608 MethodListPtrTy, 2609 CachePtrTy, 2610 ProtocolListPtrTy, 2611 Int8PtrTy, 2612 ClassExtensionPtrTy, 2613 NULL); 2614 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T); 2615 2616 ClassTy = cast<llvm::StructType>(ClassTyHolder.get()); 2617 CGM.getModule().addTypeName("struct._objc_class", ClassTy); 2618 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); 2619 2620 // struct _objc_category { 2621 // char *category_name; 2622 // char *class_name; 2623 // struct _objc_method_list *instance_method; 2624 // struct _objc_method_list *class_method; 2625 // uint32_t size; // sizeof(struct _objc_category) 2626 // struct _objc_property_list *instance_properties;// category's @property 2627 // } 2628 CategoryTy = llvm::StructType::get(Int8PtrTy, 2629 Int8PtrTy, 2630 MethodListPtrTy, 2631 MethodListPtrTy, 2632 ProtocolListPtrTy, 2633 IntTy, 2634 PropertyListPtrTy, 2635 NULL); 2636 CGM.getModule().addTypeName("struct._objc_category", CategoryTy); 2637 2638 // Global metadata structures 2639 2640 // struct _objc_symtab { 2641 // long sel_ref_cnt; 2642 // SEL *refs; 2643 // short cls_def_cnt; 2644 // short cat_def_cnt; 2645 // char *defs[cls_def_cnt + cat_def_cnt]; 2646 // } 2647 SymtabTy = llvm::StructType::get(LongTy, 2648 SelectorPtrTy, 2649 ShortTy, 2650 ShortTy, 2651 llvm::ArrayType::get(Int8PtrTy, 0), 2652 NULL); 2653 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy); 2654 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); 2655 2656 // struct _objc_module { 2657 // long version; 2658 // long size; // sizeof(struct _objc_module) 2659 // char *name; 2660 // struct _objc_symtab* symtab; 2661 // } 2662 ModuleTy = 2663 llvm::StructType::get(LongTy, 2664 LongTy, 2665 Int8PtrTy, 2666 SymtabPtrTy, 2667 NULL); 2668 CGM.getModule().addTypeName("struct._objc_module", ModuleTy); 2669 2670 // Message send functions. 2671 2672 // id objc_msgSend (id, SEL, ...) 2673 std::vector<const llvm::Type*> Params; 2674 Params.push_back(ObjectPtrTy); 2675 Params.push_back(SelectorPtrTy); 2676 MessageSendFn = 2677 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2678 Params, 2679 true), 2680 "objc_msgSend"); 2681 2682 // id objc_msgSend_stret (id, SEL, ...) 2683 Params.clear(); 2684 Params.push_back(ObjectPtrTy); 2685 Params.push_back(SelectorPtrTy); 2686 MessageSendStretFn = 2687 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2688 Params, 2689 true), 2690 "objc_msgSend_stret"); 2691 2692 // 2693 Params.clear(); 2694 Params.push_back(ObjectPtrTy); 2695 Params.push_back(SelectorPtrTy); 2696 // FIXME: This should be long double on x86_64? 2697 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...) 2698 MessageSendFpretFn = 2699 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy, 2700 Params, 2701 true), 2702 "objc_msgSend_fpret"); 2703 2704 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...) 2705 Params.clear(); 2706 Params.push_back(SuperPtrTy); 2707 Params.push_back(SelectorPtrTy); 2708 MessageSendSuperFn = 2709 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2710 Params, 2711 true), 2712 "objc_msgSendSuper"); 2713 2714 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super, 2715 // SEL op, ...) 2716 Params.clear(); 2717 Params.push_back(Int8PtrTy); 2718 Params.push_back(SuperPtrTy); 2719 Params.push_back(SelectorPtrTy); 2720 MessageSendSuperStretFn = 2721 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2722 Params, 2723 true), 2724 "objc_msgSendSuper_stret"); 2725 2726 // There is no objc_msgSendSuper_fpret? How can that work? 2727 MessageSendSuperFpretFn = MessageSendSuperFn; 2728 2729 // FIXME: This is the size of the setjmp buffer and should be 2730 // target specific. 18 is what's used on 32-bit X86. 2731 uint64_t SetJmpBufferSize = 18; 2732 2733 // Exceptions 2734 const llvm::Type *StackPtrTy = 2735 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4); 2736 2737 ExceptionDataTy = 2738 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty, 2739 SetJmpBufferSize), 2740 StackPtrTy, NULL); 2741 CGM.getModule().addTypeName("struct._objc_exception_data", 2742 ExceptionDataTy); 2743 2744 Params.clear(); 2745 Params.push_back(ObjectPtrTy); 2746 ExceptionThrowFn = 2747 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2748 Params, 2749 false), 2750 "objc_exception_throw"); 2751 2752 Params.clear(); 2753 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); 2754 ExceptionTryEnterFn = 2755 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2756 Params, 2757 false), 2758 "objc_exception_try_enter"); 2759 ExceptionTryExitFn = 2760 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2761 Params, 2762 false), 2763 "objc_exception_try_exit"); 2764 ExceptionExtractFn = 2765 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 2766 Params, 2767 false), 2768 "objc_exception_extract"); 2769 2770 Params.clear(); 2771 Params.push_back(ClassPtrTy); 2772 Params.push_back(ObjectPtrTy); 2773 ExceptionMatchFn = 2774 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 2775 Params, 2776 false), 2777 "objc_exception_match"); 2778 2779 // synchronized APIs 2780 // void objc_sync_enter (id) 2781 Params.clear(); 2782 Params.push_back(ObjectPtrTy); 2783 SyncEnterFn = 2784 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2785 Params, 2786 false), 2787 "objc_sync_enter"); 2788 // void objc_sync_exit (id) 2789 SyncExitFn = 2790 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 2791 Params, 2792 false), 2793 "objc_sync_exit"); 2794 2795 2796 Params.clear(); 2797 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty)); 2798 SetJmpFn = 2799 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 2800 Params, 2801 false), 2802 "_setjmp"); 2803 2804} 2805 2806ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) 2807: ObjCCommonTypesHelper(cgm) 2808{ 2809 // struct _method_list_t { 2810 // uint32_t entsize; // sizeof(struct _objc_method) 2811 // uint32_t method_count; 2812 // struct _objc_method method_list[method_count]; 2813 // } 2814 MethodListnfABITy = llvm::StructType::get(IntTy, 2815 IntTy, 2816 llvm::ArrayType::get(MethodTy, 0), 2817 NULL); 2818 CGM.getModule().addTypeName("struct.__method_list_t", 2819 MethodListnfABITy); 2820 // struct method_list_t * 2821 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); 2822 2823 // struct _protocol_t { 2824 // id isa; // NULL 2825 // const char * const protocol_name; 2826 // const struct _protocol_list_t * protocol_list; // super protocols 2827 // const struct method_list_t * const instance_methods; 2828 // const struct method_list_t * const class_methods; 2829 // const struct method_list_t *optionalInstanceMethods; 2830 // const struct method_list_t *optionalClassMethods; 2831 // const struct _prop_list_t * properties; 2832 // const uint32_t size; // sizeof(struct _protocol_t) 2833 // const uint32_t flags; // = 0 2834 // } 2835 2836 // Holder for struct _protocol_list_t * 2837 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 2838 2839 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy, 2840 Int8PtrTy, 2841 llvm::PointerType::getUnqual( 2842 ProtocolListTyHolder), 2843 MethodListnfABIPtrTy, 2844 MethodListnfABIPtrTy, 2845 MethodListnfABIPtrTy, 2846 MethodListnfABIPtrTy, 2847 PropertyListPtrTy, 2848 IntTy, 2849 IntTy, 2850 NULL); 2851 CGM.getModule().addTypeName("struct._protocol_t", 2852 ProtocolnfABITy); 2853 2854 // struct _objc_protocol_list { 2855 // long protocol_count; // Note, this is 32/64 bit 2856 // struct _protocol_t[protocol_count]; 2857 // } 2858 ProtocolListnfABITy = llvm::StructType::get(LongTy, 2859 llvm::ArrayType::get( 2860 ProtocolnfABITy, 0), 2861 NULL); 2862 CGM.getModule().addTypeName("struct._objc_protocol_list", 2863 ProtocolListnfABITy); 2864 2865 // FIXME! Is this doing the right thing? 2866 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo( 2867 ProtocolListnfABITy); 2868 2869 // struct _objc_protocol_list* 2870 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); 2871 2872 // struct _ivar_t { 2873 // unsigned long int *offset; // pointer to ivar offset location 2874 // char *name; 2875 // char *type; 2876 // uint32_t alignment; 2877 // uint32_t size; 2878 // } 2879 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy), 2880 Int8PtrTy, 2881 Int8PtrTy, 2882 IntTy, 2883 IntTy, 2884 NULL); 2885 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy); 2886 2887 // struct _ivar_list_t { 2888 // uint32 entsize; // sizeof(struct _ivar_t) 2889 // uint32 count; 2890 // struct _iver_t list[count]; 2891 // } 2892 IvarListnfABIPtrTy = llvm::StructType::get(IntTy, 2893 IntTy, 2894 llvm::ArrayType::get( 2895 IvarnfABITy, 0), 2896 NULL); 2897 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABIPtrTy); 2898 2899 // struct _class_ro_t { 2900 // uint32_t const flags; 2901 // uint32_t const instanceStart; 2902 // uint32_t const instanceSize; 2903 // uint32_t const reserved; // only when building for 64bit targets 2904 // const uint8_t * const ivarLayout; 2905 // const char *const name; 2906 // const struct _method_list_t * const baseMethods; 2907 // const struct _objc_protocol_list *const baseProtocols; 2908 // const struct _ivar_list_t *const ivars; 2909 // const uint8_t * const weakIvarLayout; 2910 // const struct _prop_list_t * const properties; 2911 // } 2912 2913 // FIXME. Add 'reserved' field in 64bit abi mode! 2914 ClassRonfABITy = llvm::StructType::get(IntTy, 2915 IntTy, 2916 IntTy, 2917 Int8PtrTy, 2918 Int8PtrTy, 2919 MethodListnfABIPtrTy, 2920 ProtocolListnfABIPtrTy, 2921 IvarListnfABIPtrTy, 2922 Int8PtrTy, 2923 PropertyListPtrTy, 2924 NULL); 2925 CGM.getModule().addTypeName("struct._class_ro_t", 2926 ClassRonfABITy); 2927 2928 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 2929 std::vector<const llvm::Type*> Params; 2930 Params.push_back(ObjectPtrTy); 2931 Params.push_back(SelectorPtrTy); 2932 ImpnfABITy = llvm::PointerType::getUnqual( 2933 llvm::FunctionType::get(ObjectPtrTy, Params, false)); 2934 2935 // struct _class_t { 2936 // struct _class_t *isa; 2937 // struct _class_t * const superclass; 2938 // void *cache; 2939 // IMP *vtable; 2940 // struct class_ro_t *ro; 2941 // } 2942 2943 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 2944 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 2945 llvm::PointerType::getUnqual(ClassTyHolder), 2946 CachePtrTy, 2947 llvm::PointerType::getUnqual(ImpnfABITy), 2948 llvm::PointerType::getUnqual( 2949 ClassRonfABITy), 2950 NULL); 2951 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy); 2952 2953 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo( 2954 ClassnfABITy); 2955 2956 // struct _category_t { 2957 // const char * const name; 2958 // struct _class_t *const cls; 2959 // const struct _method_list_t * const instance_methods; 2960 // const struct _method_list_t * const class_methods; 2961 // const struct _protocol_list_t * const protocols; 2962 // const struct _prop_list_t * const properties; 2963 // } 2964} 2965 2966/* *** */ 2967 2968CodeGen::CGObjCRuntime * 2969CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { 2970 return new CGObjCMac(CGM); 2971} 2972 2973CodeGen::CGObjCRuntime * 2974CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) { 2975 return 0; 2976 // return new CGObjCNonFragileABIMac(CGM); 2977} 2978