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