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