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