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