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