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