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 targeting the Apple runtime. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGBlocks.h" 15 #include "CGCleanup.h" 16 #include "CGObjCRuntime.h" 17 #include "CGRecordLayout.h" 18 #include "CodeGenFunction.h" 19 #include "CodeGenModule.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/Decl.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/StmtObjC.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/CodeGen/CGFunctionInfo.h" 27 #include "clang/Frontend/CodeGenOptions.h" 28 #include "llvm/ADT/CachedHashString.h" 29 #include "llvm/ADT/DenseSet.h" 30 #include "llvm/ADT/SetVector.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallString.h" 33 #include "llvm/IR/CallSite.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/InlineAsm.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/LLVMContext.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <cstdio> 41 42 using namespace clang; 43 using namespace CodeGen; 44 45 namespace { 46 47 // FIXME: We should find a nicer way to make the labels for metadata, string 48 // concatenation is lame. 49 50 class ObjCCommonTypesHelper { 51 protected: 52 llvm::LLVMContext &VMContext; 53 54 private: 55 // The types of these functions don't really matter because we 56 // should always bitcast before calling them. 57 58 /// id objc_msgSend (id, SEL, ...) 59 /// 60 /// The default messenger, used for sends whose ABI is unchanged from 61 /// the all-integer/pointer case. 62 llvm::Constant *getMessageSendFn() const { 63 // Add the non-lazy-bind attribute, since objc_msgSend is likely to 64 // be called a lot. 65 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; 66 return 67 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 68 params, true), 69 "objc_msgSend", 70 llvm::AttributeSet::get(CGM.getLLVMContext(), 71 llvm::AttributeSet::FunctionIndex, 72 llvm::Attribute::NonLazyBind)); 73 } 74 75 /// void objc_msgSend_stret (id, SEL, ...) 76 /// 77 /// The messenger used when the return value is an aggregate returned 78 /// by indirect reference in the first argument, and therefore the 79 /// self and selector parameters are shifted over by one. 80 llvm::Constant *getMessageSendStretFn() const { 81 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; 82 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, 83 params, true), 84 "objc_msgSend_stret"); 85 86 } 87 88 /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...) 89 /// 90 /// The messenger used when the return value is returned on the x87 91 /// floating-point stack; without a special entrypoint, the nil case 92 /// would be unbalanced. 93 llvm::Constant *getMessageSendFpretFn() const { 94 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; 95 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy, 96 params, true), 97 "objc_msgSend_fpret"); 98 99 } 100 101 /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...) 102 /// 103 /// The messenger used when the return value is returned in two values on the 104 /// x87 floating point stack; without a special entrypoint, the nil case 105 /// would be unbalanced. Only used on 64-bit X86. 106 llvm::Constant *getMessageSendFp2retFn() const { 107 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; 108 llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext); 109 llvm::Type *resultType = 110 llvm::StructType::get(longDoubleType, longDoubleType, nullptr); 111 112 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType, 113 params, true), 114 "objc_msgSend_fp2ret"); 115 } 116 117 /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...) 118 /// 119 /// The messenger used for super calls, which have different dispatch 120 /// semantics. The class passed is the superclass of the current 121 /// class. 122 llvm::Constant *getMessageSendSuperFn() const { 123 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy }; 124 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 125 params, true), 126 "objc_msgSendSuper"); 127 } 128 129 /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...) 130 /// 131 /// A slightly different messenger used for super calls. The class 132 /// passed is the current class. 133 llvm::Constant *getMessageSendSuperFn2() const { 134 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy }; 135 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 136 params, true), 137 "objc_msgSendSuper2"); 138 } 139 140 /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super, 141 /// SEL op, ...) 142 /// 143 /// The messenger used for super calls which return an aggregate indirectly. 144 llvm::Constant *getMessageSendSuperStretFn() const { 145 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy }; 146 return CGM.CreateRuntimeFunction( 147 llvm::FunctionType::get(CGM.VoidTy, params, true), 148 "objc_msgSendSuper_stret"); 149 } 150 151 /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super, 152 /// SEL op, ...) 153 /// 154 /// objc_msgSendSuper_stret with the super2 semantics. 155 llvm::Constant *getMessageSendSuperStretFn2() const { 156 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy }; 157 return CGM.CreateRuntimeFunction( 158 llvm::FunctionType::get(CGM.VoidTy, params, true), 159 "objc_msgSendSuper2_stret"); 160 } 161 162 llvm::Constant *getMessageSendSuperFpretFn() const { 163 // There is no objc_msgSendSuper_fpret? How can that work? 164 return getMessageSendSuperFn(); 165 } 166 167 llvm::Constant *getMessageSendSuperFpretFn2() const { 168 // There is no objc_msgSendSuper_fpret? How can that work? 169 return getMessageSendSuperFn2(); 170 } 171 172 protected: 173 CodeGen::CodeGenModule &CGM; 174 175 public: 176 llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy; 177 llvm::Type *Int8PtrTy, *Int8PtrPtrTy; 178 llvm::Type *IvarOffsetVarTy; 179 180 /// ObjectPtrTy - LLVM type for object handles (typeof(id)) 181 llvm::Type *ObjectPtrTy; 182 183 /// PtrObjectPtrTy - LLVM type for id * 184 llvm::Type *PtrObjectPtrTy; 185 186 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) 187 llvm::Type *SelectorPtrTy; 188 189 private: 190 /// ProtocolPtrTy - LLVM type for external protocol handles 191 /// (typeof(Protocol)) 192 llvm::Type *ExternalProtocolPtrTy; 193 194 public: 195 llvm::Type *getExternalProtocolPtrTy() { 196 if (!ExternalProtocolPtrTy) { 197 // FIXME: It would be nice to unify this with the opaque type, so that the 198 // IR comes out a bit cleaner. 199 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 200 ASTContext &Ctx = CGM.getContext(); 201 llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); 202 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); 203 } 204 205 return ExternalProtocolPtrTy; 206 } 207 208 // SuperCTy - clang type for struct objc_super. 209 QualType SuperCTy; 210 // SuperPtrCTy - clang type for struct objc_super *. 211 QualType SuperPtrCTy; 212 213 /// SuperTy - LLVM type for struct objc_super. 214 llvm::StructType *SuperTy; 215 /// SuperPtrTy - LLVM type for struct objc_super *. 216 llvm::Type *SuperPtrTy; 217 218 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t 219 /// in GCC parlance). 220 llvm::StructType *PropertyTy; 221 222 /// PropertyListTy - LLVM type for struct objc_property_list 223 /// (_prop_list_t in GCC parlance). 224 llvm::StructType *PropertyListTy; 225 /// PropertyListPtrTy - LLVM type for struct objc_property_list*. 226 llvm::Type *PropertyListPtrTy; 227 228 // MethodTy - LLVM type for struct objc_method. 229 llvm::StructType *MethodTy; 230 231 /// CacheTy - LLVM type for struct objc_cache. 232 llvm::Type *CacheTy; 233 /// CachePtrTy - LLVM type for struct objc_cache *. 234 llvm::Type *CachePtrTy; 235 236 llvm::Constant *getGetPropertyFn() { 237 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 238 ASTContext &Ctx = CGM.getContext(); 239 // id objc_getProperty (id, SEL, ptrdiff_t, bool) 240 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); 241 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); 242 CanQualType Params[] = { 243 IdType, SelType, 244 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy}; 245 llvm::FunctionType *FTy = 246 Types.GetFunctionType( 247 Types.arrangeBuiltinFunctionDeclaration(IdType, Params)); 248 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty"); 249 } 250 251 llvm::Constant *getSetPropertyFn() { 252 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 253 ASTContext &Ctx = CGM.getContext(); 254 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 255 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); 256 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); 257 CanQualType Params[] = { 258 IdType, 259 SelType, 260 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), 261 IdType, 262 Ctx.BoolTy, 263 Ctx.BoolTy}; 264 llvm::FunctionType *FTy = 265 Types.GetFunctionType( 266 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); 267 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty"); 268 } 269 270 llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) { 271 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 272 ASTContext &Ctx = CGM.getContext(); 273 // void objc_setProperty_atomic(id self, SEL _cmd, 274 // id newValue, ptrdiff_t offset); 275 // void objc_setProperty_nonatomic(id self, SEL _cmd, 276 // id newValue, ptrdiff_t offset); 277 // void objc_setProperty_atomic_copy(id self, SEL _cmd, 278 // id newValue, ptrdiff_t offset); 279 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, 280 // id newValue, ptrdiff_t offset); 281 282 SmallVector<CanQualType,4> Params; 283 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); 284 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); 285 Params.push_back(IdType); 286 Params.push_back(SelType); 287 Params.push_back(IdType); 288 Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified()); 289 llvm::FunctionType *FTy = 290 Types.GetFunctionType( 291 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); 292 const char *name; 293 if (atomic && copy) 294 name = "objc_setProperty_atomic_copy"; 295 else if (atomic && !copy) 296 name = "objc_setProperty_atomic"; 297 else if (!atomic && copy) 298 name = "objc_setProperty_nonatomic_copy"; 299 else 300 name = "objc_setProperty_nonatomic"; 301 302 return CGM.CreateRuntimeFunction(FTy, name); 303 } 304 305 llvm::Constant *getCopyStructFn() { 306 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 307 ASTContext &Ctx = CGM.getContext(); 308 // void objc_copyStruct (void *, const void *, size_t, bool, bool) 309 SmallVector<CanQualType,5> Params; 310 Params.push_back(Ctx.VoidPtrTy); 311 Params.push_back(Ctx.VoidPtrTy); 312 Params.push_back(Ctx.LongTy); 313 Params.push_back(Ctx.BoolTy); 314 Params.push_back(Ctx.BoolTy); 315 llvm::FunctionType *FTy = 316 Types.GetFunctionType( 317 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); 318 return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct"); 319 } 320 321 /// This routine declares and returns address of: 322 /// void objc_copyCppObjectAtomic( 323 /// void *dest, const void *src, 324 /// void (*copyHelper) (void *dest, const void *source)); 325 llvm::Constant *getCppAtomicObjectFunction() { 326 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 327 ASTContext &Ctx = CGM.getContext(); 328 /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper); 329 SmallVector<CanQualType,3> Params; 330 Params.push_back(Ctx.VoidPtrTy); 331 Params.push_back(Ctx.VoidPtrTy); 332 Params.push_back(Ctx.VoidPtrTy); 333 llvm::FunctionType *FTy = 334 Types.GetFunctionType( 335 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); 336 return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic"); 337 } 338 339 llvm::Constant *getEnumerationMutationFn() { 340 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 341 ASTContext &Ctx = CGM.getContext(); 342 // void objc_enumerationMutation (id) 343 SmallVector<CanQualType,1> Params; 344 Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType())); 345 llvm::FunctionType *FTy = 346 Types.GetFunctionType( 347 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); 348 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation"); 349 } 350 351 llvm::Constant *getLookUpClassFn() { 352 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 353 ASTContext &Ctx = CGM.getContext(); 354 // Class objc_lookUpClass (const char *) 355 SmallVector<CanQualType,1> Params; 356 Params.push_back( 357 Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst()))); 358 llvm::FunctionType *FTy = 359 Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration( 360 Ctx.getCanonicalType(Ctx.getObjCClassType()), 361 Params)); 362 return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass"); 363 } 364 365 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. 366 llvm::Constant *getGcReadWeakFn() { 367 // id objc_read_weak (id *) 368 llvm::Type *args[] = { ObjectPtrTy->getPointerTo() }; 369 llvm::FunctionType *FTy = 370 llvm::FunctionType::get(ObjectPtrTy, args, false); 371 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak"); 372 } 373 374 /// GcAssignWeakFn -- LLVM objc_assign_weak function. 375 llvm::Constant *getGcAssignWeakFn() { 376 // id objc_assign_weak (id, id *) 377 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; 378 llvm::FunctionType *FTy = 379 llvm::FunctionType::get(ObjectPtrTy, args, false); 380 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak"); 381 } 382 383 /// GcAssignGlobalFn -- LLVM objc_assign_global function. 384 llvm::Constant *getGcAssignGlobalFn() { 385 // id objc_assign_global(id, id *) 386 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; 387 llvm::FunctionType *FTy = 388 llvm::FunctionType::get(ObjectPtrTy, args, false); 389 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global"); 390 } 391 392 /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function. 393 llvm::Constant *getGcAssignThreadLocalFn() { 394 // id objc_assign_threadlocal(id src, id * dest) 395 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; 396 llvm::FunctionType *FTy = 397 llvm::FunctionType::get(ObjectPtrTy, args, false); 398 return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal"); 399 } 400 401 /// GcAssignIvarFn -- LLVM objc_assign_ivar function. 402 llvm::Constant *getGcAssignIvarFn() { 403 // id objc_assign_ivar(id, id *, ptrdiff_t) 404 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(), 405 CGM.PtrDiffTy }; 406 llvm::FunctionType *FTy = 407 llvm::FunctionType::get(ObjectPtrTy, args, false); 408 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar"); 409 } 410 411 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function. 412 llvm::Constant *GcMemmoveCollectableFn() { 413 // void *objc_memmove_collectable(void *dst, const void *src, size_t size) 414 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy }; 415 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false); 416 return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable"); 417 } 418 419 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. 420 llvm::Constant *getGcAssignStrongCastFn() { 421 // id objc_assign_strongCast(id, id *) 422 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; 423 llvm::FunctionType *FTy = 424 llvm::FunctionType::get(ObjectPtrTy, args, false); 425 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast"); 426 } 427 428 /// ExceptionThrowFn - LLVM objc_exception_throw function. 429 llvm::Constant *getExceptionThrowFn() { 430 // void objc_exception_throw(id) 431 llvm::Type *args[] = { ObjectPtrTy }; 432 llvm::FunctionType *FTy = 433 llvm::FunctionType::get(CGM.VoidTy, args, false); 434 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 435 } 436 437 /// ExceptionRethrowFn - LLVM objc_exception_rethrow function. 438 llvm::Constant *getExceptionRethrowFn() { 439 // void objc_exception_rethrow(void) 440 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false); 441 return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow"); 442 } 443 444 /// SyncEnterFn - LLVM object_sync_enter function. 445 llvm::Constant *getSyncEnterFn() { 446 // int objc_sync_enter (id) 447 llvm::Type *args[] = { ObjectPtrTy }; 448 llvm::FunctionType *FTy = 449 llvm::FunctionType::get(CGM.IntTy, args, false); 450 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); 451 } 452 453 /// SyncExitFn - LLVM object_sync_exit function. 454 llvm::Constant *getSyncExitFn() { 455 // int objc_sync_exit (id) 456 llvm::Type *args[] = { ObjectPtrTy }; 457 llvm::FunctionType *FTy = 458 llvm::FunctionType::get(CGM.IntTy, args, false); 459 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); 460 } 461 462 llvm::Constant *getSendFn(bool IsSuper) const { 463 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn(); 464 } 465 466 llvm::Constant *getSendFn2(bool IsSuper) const { 467 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn(); 468 } 469 470 llvm::Constant *getSendStretFn(bool IsSuper) const { 471 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn(); 472 } 473 474 llvm::Constant *getSendStretFn2(bool IsSuper) const { 475 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn(); 476 } 477 478 llvm::Constant *getSendFpretFn(bool IsSuper) const { 479 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn(); 480 } 481 482 llvm::Constant *getSendFpretFn2(bool IsSuper) const { 483 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn(); 484 } 485 486 llvm::Constant *getSendFp2retFn(bool IsSuper) const { 487 return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn(); 488 } 489 490 llvm::Constant *getSendFp2RetFn2(bool IsSuper) const { 491 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn(); 492 } 493 494 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); 495 }; 496 497 /// ObjCTypesHelper - Helper class that encapsulates lazy 498 /// construction of varies types used during ObjC generation. 499 class ObjCTypesHelper : public ObjCCommonTypesHelper { 500 public: 501 /// SymtabTy - LLVM type for struct objc_symtab. 502 llvm::StructType *SymtabTy; 503 /// SymtabPtrTy - LLVM type for struct objc_symtab *. 504 llvm::Type *SymtabPtrTy; 505 /// ModuleTy - LLVM type for struct objc_module. 506 llvm::StructType *ModuleTy; 507 508 /// ProtocolTy - LLVM type for struct objc_protocol. 509 llvm::StructType *ProtocolTy; 510 /// ProtocolPtrTy - LLVM type for struct objc_protocol *. 511 llvm::Type *ProtocolPtrTy; 512 /// ProtocolExtensionTy - LLVM type for struct 513 /// objc_protocol_extension. 514 llvm::StructType *ProtocolExtensionTy; 515 /// ProtocolExtensionTy - LLVM type for struct 516 /// objc_protocol_extension *. 517 llvm::Type *ProtocolExtensionPtrTy; 518 /// MethodDescriptionTy - LLVM type for struct 519 /// objc_method_description. 520 llvm::StructType *MethodDescriptionTy; 521 /// MethodDescriptionListTy - LLVM type for struct 522 /// objc_method_description_list. 523 llvm::StructType *MethodDescriptionListTy; 524 /// MethodDescriptionListPtrTy - LLVM type for struct 525 /// objc_method_description_list *. 526 llvm::Type *MethodDescriptionListPtrTy; 527 /// ProtocolListTy - LLVM type for struct objc_property_list. 528 llvm::StructType *ProtocolListTy; 529 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. 530 llvm::Type *ProtocolListPtrTy; 531 /// CategoryTy - LLVM type for struct objc_category. 532 llvm::StructType *CategoryTy; 533 /// ClassTy - LLVM type for struct objc_class. 534 llvm::StructType *ClassTy; 535 /// ClassPtrTy - LLVM type for struct objc_class *. 536 llvm::Type *ClassPtrTy; 537 /// ClassExtensionTy - LLVM type for struct objc_class_ext. 538 llvm::StructType *ClassExtensionTy; 539 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. 540 llvm::Type *ClassExtensionPtrTy; 541 // IvarTy - LLVM type for struct objc_ivar. 542 llvm::StructType *IvarTy; 543 /// IvarListTy - LLVM type for struct objc_ivar_list. 544 llvm::Type *IvarListTy; 545 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. 546 llvm::Type *IvarListPtrTy; 547 /// MethodListTy - LLVM type for struct objc_method_list. 548 llvm::Type *MethodListTy; 549 /// MethodListPtrTy - LLVM type for struct objc_method_list *. 550 llvm::Type *MethodListPtrTy; 551 552 /// ExceptionDataTy - LLVM type for struct _objc_exception_data. 553 llvm::Type *ExceptionDataTy; 554 555 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. 556 llvm::Constant *getExceptionTryEnterFn() { 557 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; 558 return CGM.CreateRuntimeFunction( 559 llvm::FunctionType::get(CGM.VoidTy, params, false), 560 "objc_exception_try_enter"); 561 } 562 563 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. 564 llvm::Constant *getExceptionTryExitFn() { 565 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; 566 return CGM.CreateRuntimeFunction( 567 llvm::FunctionType::get(CGM.VoidTy, params, false), 568 "objc_exception_try_exit"); 569 } 570 571 /// ExceptionExtractFn - LLVM objc_exception_extract function. 572 llvm::Constant *getExceptionExtractFn() { 573 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; 574 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 575 params, false), 576 "objc_exception_extract"); 577 } 578 579 /// ExceptionMatchFn - LLVM objc_exception_match function. 580 llvm::Constant *getExceptionMatchFn() { 581 llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy }; 582 return CGM.CreateRuntimeFunction( 583 llvm::FunctionType::get(CGM.Int32Ty, params, false), 584 "objc_exception_match"); 585 } 586 587 /// SetJmpFn - LLVM _setjmp function. 588 llvm::Constant *getSetJmpFn() { 589 // This is specifically the prototype for x86. 590 llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() }; 591 return 592 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, 593 params, false), 594 "_setjmp", 595 llvm::AttributeSet::get(CGM.getLLVMContext(), 596 llvm::AttributeSet::FunctionIndex, 597 llvm::Attribute::NonLazyBind)); 598 } 599 600 public: 601 ObjCTypesHelper(CodeGen::CodeGenModule &cgm); 602 }; 603 604 /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's 605 /// modern abi 606 class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { 607 public: 608 // MethodListnfABITy - LLVM for struct _method_list_t 609 llvm::StructType *MethodListnfABITy; 610 611 // MethodListnfABIPtrTy - LLVM for struct _method_list_t* 612 llvm::Type *MethodListnfABIPtrTy; 613 614 // ProtocolnfABITy = LLVM for struct _protocol_t 615 llvm::StructType *ProtocolnfABITy; 616 617 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t* 618 llvm::Type *ProtocolnfABIPtrTy; 619 620 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list 621 llvm::StructType *ProtocolListnfABITy; 622 623 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* 624 llvm::Type *ProtocolListnfABIPtrTy; 625 626 // ClassnfABITy - LLVM for struct _class_t 627 llvm::StructType *ClassnfABITy; 628 629 // ClassnfABIPtrTy - LLVM for struct _class_t* 630 llvm::Type *ClassnfABIPtrTy; 631 632 // IvarnfABITy - LLVM for struct _ivar_t 633 llvm::StructType *IvarnfABITy; 634 635 // IvarListnfABITy - LLVM for struct _ivar_list_t 636 llvm::StructType *IvarListnfABITy; 637 638 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* 639 llvm::Type *IvarListnfABIPtrTy; 640 641 // ClassRonfABITy - LLVM for struct _class_ro_t 642 llvm::StructType *ClassRonfABITy; 643 644 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 645 llvm::Type *ImpnfABITy; 646 647 // CategorynfABITy - LLVM for struct _category_t 648 llvm::StructType *CategorynfABITy; 649 650 // New types for nonfragile abi messaging. 651 652 // MessageRefTy - LLVM for: 653 // struct _message_ref_t { 654 // IMP messenger; 655 // SEL name; 656 // }; 657 llvm::StructType *MessageRefTy; 658 // MessageRefCTy - clang type for struct _message_ref_t 659 QualType MessageRefCTy; 660 661 // MessageRefPtrTy - LLVM for struct _message_ref_t* 662 llvm::Type *MessageRefPtrTy; 663 // MessageRefCPtrTy - clang type for struct _message_ref_t* 664 QualType MessageRefCPtrTy; 665 666 // SuperMessageRefTy - LLVM for: 667 // struct _super_message_ref_t { 668 // SUPER_IMP messenger; 669 // SEL name; 670 // }; 671 llvm::StructType *SuperMessageRefTy; 672 673 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* 674 llvm::Type *SuperMessageRefPtrTy; 675 676 llvm::Constant *getMessageSendFixupFn() { 677 // id objc_msgSend_fixup(id, struct message_ref_t*, ...) 678 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy }; 679 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 680 params, true), 681 "objc_msgSend_fixup"); 682 } 683 684 llvm::Constant *getMessageSendFpretFixupFn() { 685 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...) 686 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy }; 687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 688 params, true), 689 "objc_msgSend_fpret_fixup"); 690 } 691 692 llvm::Constant *getMessageSendStretFixupFn() { 693 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...) 694 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy }; 695 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 696 params, true), 697 "objc_msgSend_stret_fixup"); 698 } 699 700 llvm::Constant *getMessageSendSuper2FixupFn() { 701 // id objc_msgSendSuper2_fixup (struct objc_super *, 702 // struct _super_message_ref_t*, ...) 703 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy }; 704 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 705 params, true), 706 "objc_msgSendSuper2_fixup"); 707 } 708 709 llvm::Constant *getMessageSendSuper2StretFixupFn() { 710 // id objc_msgSendSuper2_stret_fixup(struct objc_super *, 711 // struct _super_message_ref_t*, ...) 712 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy }; 713 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 714 params, true), 715 "objc_msgSendSuper2_stret_fixup"); 716 } 717 718 llvm::Constant *getObjCEndCatchFn() { 719 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false), 720 "objc_end_catch"); 721 722 } 723 724 llvm::Constant *getObjCBeginCatchFn() { 725 llvm::Type *params[] = { Int8PtrTy }; 726 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy, 727 params, false), 728 "objc_begin_catch"); 729 } 730 731 llvm::StructType *EHTypeTy; 732 llvm::Type *EHTypePtrTy; 733 734 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); 735 }; 736 737 enum class ObjCLabelType { 738 ClassName, 739 MethodVarName, 740 MethodVarType, 741 PropertyName, 742 }; 743 744 class CGObjCCommonMac : public CodeGen::CGObjCRuntime { 745 public: 746 class SKIP_SCAN { 747 public: 748 unsigned skip; 749 unsigned scan; 750 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0) 751 : skip(_skip), scan(_scan) {} 752 }; 753 754 /// opcode for captured block variables layout 'instructions'. 755 /// In the following descriptions, 'I' is the value of the immediate field. 756 /// (field following the opcode). 757 /// 758 enum BLOCK_LAYOUT_OPCODE { 759 /// An operator which affects how the following layout should be 760 /// interpreted. 761 /// I == 0: Halt interpretation and treat everything else as 762 /// a non-pointer. Note that this instruction is equal 763 /// to '\0'. 764 /// I != 0: Currently unused. 765 BLOCK_LAYOUT_OPERATOR = 0, 766 767 /// The next I+1 bytes do not contain a value of object pointer type. 768 /// Note that this can leave the stream unaligned, meaning that 769 /// subsequent word-size instructions do not begin at a multiple of 770 /// the pointer size. 771 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1, 772 773 /// The next I+1 words do not contain a value of object pointer type. 774 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for 775 /// when the required skip quantity is a multiple of the pointer size. 776 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2, 777 778 /// The next I+1 words are __strong pointers to Objective-C 779 /// objects or blocks. 780 BLOCK_LAYOUT_STRONG = 3, 781 782 /// The next I+1 words are pointers to __block variables. 783 BLOCK_LAYOUT_BYREF = 4, 784 785 /// The next I+1 words are __weak pointers to Objective-C 786 /// objects or blocks. 787 BLOCK_LAYOUT_WEAK = 5, 788 789 /// The next I+1 words are __unsafe_unretained pointers to 790 /// Objective-C objects or blocks. 791 BLOCK_LAYOUT_UNRETAINED = 6 792 793 /// The next I+1 words are block or object pointers with some 794 /// as-yet-unspecified ownership semantics. If we add more 795 /// flavors of ownership semantics, values will be taken from 796 /// this range. 797 /// 798 /// This is included so that older tools can at least continue 799 /// processing the layout past such things. 800 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10, 801 802 /// All other opcodes are reserved. Halt interpretation and 803 /// treat everything else as opaque. 804 }; 805 806 class RUN_SKIP { 807 public: 808 enum BLOCK_LAYOUT_OPCODE opcode; 809 CharUnits block_var_bytepos; 810 CharUnits block_var_size; 811 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR, 812 CharUnits BytePos = CharUnits::Zero(), 813 CharUnits Size = CharUnits::Zero()) 814 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {} 815 816 // Allow sorting based on byte pos. 817 bool operator<(const RUN_SKIP &b) const { 818 return block_var_bytepos < b.block_var_bytepos; 819 } 820 }; 821 822 protected: 823 llvm::LLVMContext &VMContext; 824 // FIXME! May not be needing this after all. 825 unsigned ObjCABI; 826 827 // arc/mrr layout of captured block literal variables. 828 SmallVector<RUN_SKIP, 16> RunSkipBlockVars; 829 830 /// LazySymbols - Symbols to generate a lazy reference for. See 831 /// DefinedSymbols and FinishModule(). 832 llvm::SetVector<IdentifierInfo*> LazySymbols; 833 834 /// DefinedSymbols - External symbols which are defined by this 835 /// module. The symbols in this list and LazySymbols are used to add 836 /// special linker symbols which ensure that Objective-C modules are 837 /// linked properly. 838 llvm::SetVector<IdentifierInfo*> DefinedSymbols; 839 840 /// ClassNames - uniqued class names. 841 llvm::StringMap<llvm::GlobalVariable*> ClassNames; 842 843 /// MethodVarNames - uniqued method variable names. 844 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; 845 846 /// DefinedCategoryNames - list of category names in form Class_Category. 847 llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames; 848 849 /// MethodVarTypes - uniqued method type signatures. We have to use 850 /// a StringMap here because have no other unique reference. 851 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; 852 853 /// MethodDefinitions - map of methods which have been defined in 854 /// this translation unit. 855 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; 856 857 /// PropertyNames - uniqued method variable names. 858 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; 859 860 /// ClassReferences - uniqued class references. 861 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; 862 863 /// SelectorReferences - uniqued selector references. 864 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; 865 866 /// Protocols - Protocols for which an objc_protocol structure has 867 /// been emitted. Forward declarations are handled by creating an 868 /// empty structure whose initializer is filled in when/if defined. 869 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; 870 871 /// DefinedProtocols - Protocols which have actually been 872 /// defined. We should not need this, see FIXME in GenerateProtocol. 873 llvm::DenseSet<IdentifierInfo*> DefinedProtocols; 874 875 /// DefinedClasses - List of defined classes. 876 SmallVector<llvm::GlobalValue*, 16> DefinedClasses; 877 878 /// ImplementedClasses - List of @implemented classes. 879 SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses; 880 881 /// DefinedNonLazyClasses - List of defined "non-lazy" classes. 882 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses; 883 884 /// DefinedCategories - List of defined categories. 885 SmallVector<llvm::GlobalValue*, 16> DefinedCategories; 886 887 /// DefinedNonLazyCategories - List of defined "non-lazy" categories. 888 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories; 889 890 /// GetNameForMethod - Return a name for the given method. 891 /// \param[out] NameOut - The return value. 892 void GetNameForMethod(const ObjCMethodDecl *OMD, 893 const ObjCContainerDecl *CD, 894 SmallVectorImpl<char> &NameOut); 895 896 /// GetMethodVarName - Return a unique constant for the given 897 /// selector's name. The return value has type char *. 898 llvm::Constant *GetMethodVarName(Selector Sel); 899 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); 900 901 /// GetMethodVarType - Return a unique constant for the given 902 /// method's type encoding string. The return value has type char *. 903 904 // FIXME: This is a horrible name. 905 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D, 906 bool Extended = false); 907 llvm::Constant *GetMethodVarType(const FieldDecl *D); 908 909 /// GetPropertyName - Return a unique constant for the given 910 /// name. The return value has type char *. 911 llvm::Constant *GetPropertyName(IdentifierInfo *Ident); 912 913 // FIXME: This can be dropped once string functions are unified. 914 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, 915 const Decl *Container); 916 917 /// GetClassName - Return a unique constant for the given selector's 918 /// runtime name (which may change via use of objc_runtime_name attribute on 919 /// class or protocol definition. The return value has type char *. 920 llvm::Constant *GetClassName(StringRef RuntimeName); 921 922 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD); 923 924 /// BuildIvarLayout - Builds ivar layout bitmap for the class 925 /// implementation for the __strong or __weak case. 926 /// 927 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there 928 /// are any weak ivars defined directly in the class. Meaningless unless 929 /// building a weak layout. Does not guarantee that the layout will 930 /// actually have any entries, because the ivar might be under-aligned. 931 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI, 932 CharUnits beginOffset, 933 CharUnits endOffset, 934 bool forStrongLayout, 935 bool hasMRCWeakIvars); 936 937 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI, 938 CharUnits beginOffset, 939 CharUnits endOffset) { 940 return BuildIvarLayout(OI, beginOffset, endOffset, true, false); 941 } 942 943 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI, 944 CharUnits beginOffset, 945 CharUnits endOffset, 946 bool hasMRCWeakIvars) { 947 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars); 948 } 949 950 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout); 951 952 void UpdateRunSkipBlockVars(bool IsByref, 953 Qualifiers::ObjCLifetime LifeTime, 954 CharUnits FieldOffset, 955 CharUnits FieldSize); 956 957 void BuildRCBlockVarRecordLayout(const RecordType *RT, 958 CharUnits BytePos, bool &HasUnion, 959 bool ByrefLayout=false); 960 961 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout, 962 const RecordDecl *RD, 963 ArrayRef<const FieldDecl*> RecFields, 964 CharUnits BytePos, bool &HasUnion, 965 bool ByrefLayout); 966 967 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout); 968 969 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout); 970 971 /// GetIvarLayoutName - Returns a unique constant for the given 972 /// ivar layout bitmap. 973 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, 974 const ObjCCommonTypesHelper &ObjCTypes); 975 976 /// EmitPropertyList - Emit the given property list. The return 977 /// value has type PropertyListPtrTy. 978 llvm::Constant *EmitPropertyList(Twine Name, 979 const Decl *Container, 980 const ObjCContainerDecl *OCD, 981 const ObjCCommonTypesHelper &ObjCTypes, 982 bool IsClassProperty); 983 984 /// EmitProtocolMethodTypes - Generate the array of extended method type 985 /// strings. The return value has type Int8PtrPtrTy. 986 llvm::Constant *EmitProtocolMethodTypes(Twine Name, 987 ArrayRef<llvm::Constant*> MethodTypes, 988 const ObjCCommonTypesHelper &ObjCTypes); 989 990 /// PushProtocolProperties - Push protocol's property on the input stack. 991 void PushProtocolProperties( 992 llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet, 993 SmallVectorImpl<llvm::Constant*> &Properties, 994 const Decl *Container, 995 const ObjCProtocolDecl *Proto, 996 const ObjCCommonTypesHelper &ObjCTypes, 997 bool IsClassProperty); 998 999 /// GetProtocolRef - Return a reference to the internal protocol 1000 /// description, creating an empty one if it has not been 1001 /// defined. The return value has type ProtocolPtrTy. 1002 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); 1003 1004 /// Return a reference to the given Class using runtime calls rather than 1005 /// by a symbol reference. 1006 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF, 1007 const ObjCInterfaceDecl *ID, 1008 ObjCCommonTypesHelper &ObjCTypes); 1009 1010 public: 1011 /// CreateMetadataVar - Create a global variable with internal 1012 /// linkage for use by the Objective-C runtime. 1013 /// 1014 /// This is a convenience wrapper which not only creates the 1015 /// variable, but also sets the section and alignment and adds the 1016 /// global to the "llvm.used" list. 1017 /// 1018 /// \param Name - The variable name. 1019 /// \param Init - The variable initializer; this is also used to 1020 /// define the type of the variable. 1021 /// \param Section - The section the variable should go into, or empty. 1022 /// \param Align - The alignment for the variable, or 0. 1023 /// \param AddToUsed - Whether the variable should be added to 1024 /// "llvm.used". 1025 llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init, 1026 StringRef Section, CharUnits Align, 1027 bool AddToUsed); 1028 1029 llvm::GlobalVariable *CreateCStringLiteral(StringRef Name, 1030 ObjCLabelType LabelType, 1031 bool ForceNonFragileABI = false, 1032 bool NullTerminate = true); 1033 1034 protected: 1035 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 1036 ReturnValueSlot Return, 1037 QualType ResultType, 1038 llvm::Value *Sel, 1039 llvm::Value *Arg0, 1040 QualType Arg0Ty, 1041 bool IsSuper, 1042 const CallArgList &CallArgs, 1043 const ObjCMethodDecl *OMD, 1044 const ObjCInterfaceDecl *ClassReceiver, 1045 const ObjCCommonTypesHelper &ObjCTypes); 1046 1047 /// EmitImageInfo - Emit the image info marker used to encode some module 1048 /// level information. 1049 void EmitImageInfo(); 1050 1051 public: 1052 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : 1053 CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { } 1054 1055 bool isNonFragileABI() const { 1056 return ObjCABI == 2; 1057 } 1058 1059 ConstantAddress GenerateConstantString(const StringLiteral *SL) override; 1060 1061 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 1062 const ObjCContainerDecl *CD=nullptr) override; 1063 1064 void GenerateProtocol(const ObjCProtocolDecl *PD) override; 1065 1066 /// GetOrEmitProtocol - Get the protocol object for the given 1067 /// declaration, emitting it if necessary. The return value has type 1068 /// ProtocolPtrTy. 1069 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0; 1070 1071 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 1072 /// object for the given declaration, emitting it if needed. These 1073 /// forward references will be filled in with empty bodies if no 1074 /// definition is seen. The return value has type ProtocolPtrTy. 1075 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0; 1076 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM, 1077 const CGBlockInfo &blockInfo) override; 1078 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM, 1079 const CGBlockInfo &blockInfo) override; 1080 1081 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM, 1082 QualType T) override; 1083 }; 1084 1085 class CGObjCMac : public CGObjCCommonMac { 1086 private: 1087 ObjCTypesHelper ObjCTypes; 1088 1089 /// EmitModuleInfo - Another marker encoding module level 1090 /// information. 1091 void EmitModuleInfo(); 1092 1093 /// EmitModuleSymols - Emit module symbols, the list of defined 1094 /// classes and categories. The result has type SymtabPtrTy. 1095 llvm::Constant *EmitModuleSymbols(); 1096 1097 /// FinishModule - Write out global data structures at the end of 1098 /// processing a translation unit. 1099 void FinishModule(); 1100 1101 /// EmitClassExtension - Generate the class extension structure used 1102 /// to store the weak ivar layout and properties. The return value 1103 /// has type ClassExtensionPtrTy. 1104 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID, 1105 CharUnits instanceSize, 1106 bool hasMRCWeakIvars, 1107 bool isClassProperty); 1108 1109 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 1110 /// for the given class. 1111 llvm::Value *EmitClassRef(CodeGenFunction &CGF, 1112 const ObjCInterfaceDecl *ID); 1113 1114 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, 1115 IdentifierInfo *II); 1116 1117 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; 1118 1119 /// EmitSuperClassRef - Emits reference to class's main metadata class. 1120 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID); 1121 1122 /// EmitIvarList - Emit the ivar list for the given 1123 /// implementation. If ForClass is true the list of class ivars 1124 /// (i.e. metaclass ivars) is emitted, otherwise the list of 1125 /// interface ivars will be emitted. The return value has type 1126 /// IvarListPtrTy. 1127 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, 1128 bool ForClass); 1129 1130 /// EmitMetaClass - Emit a forward reference to the class structure 1131 /// for the metaclass of the given interface. The return value has 1132 /// type ClassPtrTy. 1133 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); 1134 1135 /// EmitMetaClass - Emit a class structure for the metaclass of the 1136 /// given implementation. The return value has type ClassPtrTy. 1137 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, 1138 llvm::Constant *Protocols, 1139 ArrayRef<llvm::Constant*> Methods); 1140 1141 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 1142 1143 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 1144 1145 /// EmitMethodList - Emit the method list for the given 1146 /// implementation. The return value has type MethodListPtrTy. 1147 llvm::Constant *EmitMethodList(Twine Name, StringRef Section, 1148 ArrayRef<llvm::Constant *> Methods); 1149 1150 /// EmitMethodDescList - Emit a method description list for a list of 1151 /// method declarations. 1152 /// - TypeName: The name for the type containing the methods. 1153 /// - IsProtocol: True iff these methods are for a protocol. 1154 /// - ClassMethds: True iff these are class methods. 1155 /// - Required: When true, only "required" methods are 1156 /// listed. Similarly, when false only "optional" methods are 1157 /// listed. For classes this should always be true. 1158 /// - begin, end: The method list to output. 1159 /// 1160 /// The return value has type MethodDescriptionListPtrTy. 1161 llvm::Constant *EmitMethodDescList(Twine Name, StringRef Section, 1162 ArrayRef<llvm::Constant *> Methods); 1163 1164 /// GetOrEmitProtocol - Get the protocol object for the given 1165 /// declaration, emitting it if necessary. The return value has type 1166 /// ProtocolPtrTy. 1167 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override; 1168 1169 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 1170 /// object for the given declaration, emitting it if needed. These 1171 /// forward references will be filled in with empty bodies if no 1172 /// definition is seen. The return value has type ProtocolPtrTy. 1173 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override; 1174 1175 /// EmitProtocolExtension - Generate the protocol extension 1176 /// structure used to store optional instance and class methods, and 1177 /// protocol properties. The return value has type 1178 /// ProtocolExtensionPtrTy. 1179 llvm::Constant * 1180 EmitProtocolExtension(const ObjCProtocolDecl *PD, 1181 ArrayRef<llvm::Constant*> OptInstanceMethods, 1182 ArrayRef<llvm::Constant*> OptClassMethods, 1183 ArrayRef<llvm::Constant*> MethodTypesExt); 1184 1185 /// EmitProtocolList - Generate the list of referenced 1186 /// protocols. The return value has type ProtocolListPtrTy. 1187 llvm::Constant *EmitProtocolList(Twine Name, 1188 ObjCProtocolDecl::protocol_iterator begin, 1189 ObjCProtocolDecl::protocol_iterator end); 1190 1191 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 1192 /// for the given selector. 1193 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel); 1194 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel); 1195 1196 public: 1197 CGObjCMac(CodeGen::CodeGenModule &cgm); 1198 1199 llvm::Function *ModuleInitFunction() override; 1200 1201 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1202 ReturnValueSlot Return, 1203 QualType ResultType, 1204 Selector Sel, llvm::Value *Receiver, 1205 const CallArgList &CallArgs, 1206 const ObjCInterfaceDecl *Class, 1207 const ObjCMethodDecl *Method) override; 1208 1209 CodeGen::RValue 1210 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 1211 ReturnValueSlot Return, QualType ResultType, 1212 Selector Sel, const ObjCInterfaceDecl *Class, 1213 bool isCategoryImpl, llvm::Value *Receiver, 1214 bool IsClassMessage, const CallArgList &CallArgs, 1215 const ObjCMethodDecl *Method) override; 1216 1217 llvm::Value *GetClass(CodeGenFunction &CGF, 1218 const ObjCInterfaceDecl *ID) override; 1219 1220 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override; 1221 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override; 1222 1223 /// The NeXT/Apple runtimes do not support typed selectors; just emit an 1224 /// untyped one. 1225 llvm::Value *GetSelector(CodeGenFunction &CGF, 1226 const ObjCMethodDecl *Method) override; 1227 1228 llvm::Constant *GetEHType(QualType T) override; 1229 1230 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; 1231 1232 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; 1233 1234 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {} 1235 1236 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 1237 const ObjCProtocolDecl *PD) override; 1238 1239 llvm::Constant *GetPropertyGetFunction() override; 1240 llvm::Constant *GetPropertySetFunction() override; 1241 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, 1242 bool copy) override; 1243 llvm::Constant *GetGetStructFunction() override; 1244 llvm::Constant *GetSetStructFunction() override; 1245 llvm::Constant *GetCppAtomicObjectGetFunction() override; 1246 llvm::Constant *GetCppAtomicObjectSetFunction() override; 1247 llvm::Constant *EnumerationMutationFunction() override; 1248 1249 void EmitTryStmt(CodeGen::CodeGenFunction &CGF, 1250 const ObjCAtTryStmt &S) override; 1251 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1252 const ObjCAtSynchronizedStmt &S) override; 1253 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S); 1254 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, 1255 bool ClearInsertionPoint=true) override; 1256 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1257 Address AddrWeakObj) override; 1258 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1259 llvm::Value *src, Address dst) override; 1260 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1261 llvm::Value *src, Address dest, 1262 bool threadlocal = false) override; 1263 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1264 llvm::Value *src, Address dest, 1265 llvm::Value *ivarOffset) override; 1266 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1267 llvm::Value *src, Address dest) override; 1268 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 1269 Address dest, Address src, 1270 llvm::Value *size) override; 1271 1272 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, 1273 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, 1274 unsigned CVRQualifiers) override; 1275 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 1276 const ObjCInterfaceDecl *Interface, 1277 const ObjCIvarDecl *Ivar) override; 1278 1279 /// GetClassGlobal - Return the global variable for the Objective-C 1280 /// class of the given name. 1281 llvm::GlobalVariable *GetClassGlobal(StringRef Name, 1282 bool Weak = false) override { 1283 llvm_unreachable("CGObjCMac::GetClassGlobal"); 1284 } 1285 }; 1286 1287 class CGObjCNonFragileABIMac : public CGObjCCommonMac { 1288 private: 1289 ObjCNonFragileABITypesHelper ObjCTypes; 1290 llvm::GlobalVariable* ObjCEmptyCacheVar; 1291 llvm::GlobalVariable* ObjCEmptyVtableVar; 1292 1293 /// SuperClassReferences - uniqued super class references. 1294 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences; 1295 1296 /// MetaClassReferences - uniqued meta class references. 1297 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences; 1298 1299 /// EHTypeReferences - uniqued class ehtype references. 1300 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences; 1301 1302 /// VTableDispatchMethods - List of methods for which we generate 1303 /// vtable-based message dispatch. 1304 llvm::DenseSet<Selector> VTableDispatchMethods; 1305 1306 /// DefinedMetaClasses - List of defined meta-classes. 1307 std::vector<llvm::GlobalValue*> DefinedMetaClasses; 1308 1309 /// isVTableDispatchedSelector - Returns true if SEL is a 1310 /// vtable-based selector. 1311 bool isVTableDispatchedSelector(Selector Sel); 1312 1313 /// FinishNonFragileABIModule - Write out global data structures at the end of 1314 /// processing a translation unit. 1315 void FinishNonFragileABIModule(); 1316 1317 /// AddModuleClassList - Add the given list of class pointers to the 1318 /// module with the provided symbol and section names. 1319 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container, 1320 StringRef SymbolName, StringRef SectionName); 1321 1322 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags, 1323 unsigned InstanceStart, 1324 unsigned InstanceSize, 1325 const ObjCImplementationDecl *ID); 1326 llvm::GlobalVariable * BuildClassMetaData(const std::string &ClassName, 1327 llvm::Constant *IsAGV, 1328 llvm::Constant *SuperClassGV, 1329 llvm::Constant *ClassRoGV, 1330 bool HiddenVisibility, 1331 bool Weak); 1332 1333 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 1334 1335 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 1336 1337 /// EmitMethodList - Emit the method list for the given 1338 /// implementation. The return value has type MethodListnfABITy. 1339 llvm::Constant *EmitMethodList(Twine Name, StringRef Section, 1340 ArrayRef<llvm::Constant *> Methods); 1341 /// EmitIvarList - Emit the ivar list for the given 1342 /// implementation. If ForClass is true the list of class ivars 1343 /// (i.e. metaclass ivars) is emitted, otherwise the list of 1344 /// interface ivars will be emitted. The return value has type 1345 /// IvarListnfABIPtrTy. 1346 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID); 1347 1348 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, 1349 const ObjCIvarDecl *Ivar, 1350 unsigned long int offset); 1351 1352 /// GetOrEmitProtocol - Get the protocol object for the given 1353 /// declaration, emitting it if necessary. The return value has type 1354 /// ProtocolPtrTy. 1355 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override; 1356 1357 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 1358 /// object for the given declaration, emitting it if needed. These 1359 /// forward references will be filled in with empty bodies if no 1360 /// definition is seen. The return value has type ProtocolPtrTy. 1361 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override; 1362 1363 /// EmitProtocolList - Generate the list of referenced 1364 /// protocols. The return value has type ProtocolListPtrTy. 1365 llvm::Constant *EmitProtocolList(Twine Name, 1366 ObjCProtocolDecl::protocol_iterator begin, 1367 ObjCProtocolDecl::protocol_iterator end); 1368 1369 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF, 1370 ReturnValueSlot Return, 1371 QualType ResultType, 1372 Selector Sel, 1373 llvm::Value *Receiver, 1374 QualType Arg0Ty, 1375 bool IsSuper, 1376 const CallArgList &CallArgs, 1377 const ObjCMethodDecl *Method); 1378 1379 /// GetClassGlobal - Return the global variable for the Objective-C 1380 /// class of the given name. 1381 llvm::GlobalVariable *GetClassGlobal(StringRef Name, 1382 bool Weak = false) override; 1383 1384 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 1385 /// for the given class reference. 1386 llvm::Value *EmitClassRef(CodeGenFunction &CGF, 1387 const ObjCInterfaceDecl *ID); 1388 1389 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, 1390 IdentifierInfo *II, bool Weak, 1391 const ObjCInterfaceDecl *ID); 1392 1393 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; 1394 1395 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 1396 /// for the given super class reference. 1397 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF, 1398 const ObjCInterfaceDecl *ID); 1399 1400 /// EmitMetaClassRef - Return a Value * of the address of _class_t 1401 /// meta-data 1402 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF, 1403 const ObjCInterfaceDecl *ID, bool Weak); 1404 1405 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for 1406 /// the given ivar. 1407 /// 1408 llvm::GlobalVariable * ObjCIvarOffsetVariable( 1409 const ObjCInterfaceDecl *ID, 1410 const ObjCIvarDecl *Ivar); 1411 1412 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 1413 /// for the given selector. 1414 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel); 1415 Address EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel); 1416 1417 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C 1418 /// interface. The return value has type EHTypePtrTy. 1419 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID, 1420 bool ForDefinition); 1421 1422 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; } 1423 1424 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; } 1425 1426 void GetClassSizeInfo(const ObjCImplementationDecl *OID, 1427 uint32_t &InstanceStart, 1428 uint32_t &InstanceSize); 1429 1430 // Shamelessly stolen from Analysis/CFRefCount.cpp 1431 Selector GetNullarySelector(const char* name) const { 1432 IdentifierInfo* II = &CGM.getContext().Idents.get(name); 1433 return CGM.getContext().Selectors.getSelector(0, &II); 1434 } 1435 1436 Selector GetUnarySelector(const char* name) const { 1437 IdentifierInfo* II = &CGM.getContext().Idents.get(name); 1438 return CGM.getContext().Selectors.getSelector(1, &II); 1439 } 1440 1441 /// ImplementationIsNonLazy - Check whether the given category or 1442 /// class implementation is "non-lazy". 1443 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const; 1444 1445 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF, 1446 const ObjCIvarDecl *IV) { 1447 // Annotate the load as an invariant load iff inside an instance method 1448 // and ivar belongs to instance method's class and one of its super class. 1449 // This check is needed because the ivar offset is a lazily 1450 // initialised value that may depend on objc_msgSend to perform a fixup on 1451 // the first message dispatch. 1452 // 1453 // An additional opportunity to mark the load as invariant arises when the 1454 // base of the ivar access is a parameter to an Objective C method. 1455 // However, because the parameters are not available in the current 1456 // interface, we cannot perform this check. 1457 if (const ObjCMethodDecl *MD = 1458 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl)) 1459 if (MD->isInstanceMethod()) 1460 if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) 1461 return IV->getContainingInterface()->isSuperClassOf(ID); 1462 return false; 1463 } 1464 1465 public: 1466 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); 1467 // FIXME. All stubs for now! 1468 llvm::Function *ModuleInitFunction() override; 1469 1470 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1471 ReturnValueSlot Return, 1472 QualType ResultType, Selector Sel, 1473 llvm::Value *Receiver, 1474 const CallArgList &CallArgs, 1475 const ObjCInterfaceDecl *Class, 1476 const ObjCMethodDecl *Method) override; 1477 1478 CodeGen::RValue 1479 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 1480 ReturnValueSlot Return, QualType ResultType, 1481 Selector Sel, const ObjCInterfaceDecl *Class, 1482 bool isCategoryImpl, llvm::Value *Receiver, 1483 bool IsClassMessage, const CallArgList &CallArgs, 1484 const ObjCMethodDecl *Method) override; 1485 1486 llvm::Value *GetClass(CodeGenFunction &CGF, 1487 const ObjCInterfaceDecl *ID) override; 1488 1489 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override 1490 { return EmitSelector(CGF, Sel); } 1491 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override 1492 { return EmitSelectorAddr(CGF, Sel); } 1493 1494 /// The NeXT/Apple runtimes do not support typed selectors; just emit an 1495 /// untyped one. 1496 llvm::Value *GetSelector(CodeGenFunction &CGF, 1497 const ObjCMethodDecl *Method) override 1498 { return EmitSelector(CGF, Method->getSelector()); } 1499 1500 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; 1501 1502 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; 1503 1504 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {} 1505 1506 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 1507 const ObjCProtocolDecl *PD) override; 1508 1509 llvm::Constant *GetEHType(QualType T) override; 1510 1511 llvm::Constant *GetPropertyGetFunction() override { 1512 return ObjCTypes.getGetPropertyFn(); 1513 } 1514 llvm::Constant *GetPropertySetFunction() override { 1515 return ObjCTypes.getSetPropertyFn(); 1516 } 1517 1518 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, 1519 bool copy) override { 1520 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy); 1521 } 1522 1523 llvm::Constant *GetSetStructFunction() override { 1524 return ObjCTypes.getCopyStructFn(); 1525 } 1526 1527 llvm::Constant *GetGetStructFunction() override { 1528 return ObjCTypes.getCopyStructFn(); 1529 } 1530 1531 llvm::Constant *GetCppAtomicObjectSetFunction() override { 1532 return ObjCTypes.getCppAtomicObjectFunction(); 1533 } 1534 1535 llvm::Constant *GetCppAtomicObjectGetFunction() override { 1536 return ObjCTypes.getCppAtomicObjectFunction(); 1537 } 1538 1539 llvm::Constant *EnumerationMutationFunction() override { 1540 return ObjCTypes.getEnumerationMutationFn(); 1541 } 1542 1543 void EmitTryStmt(CodeGen::CodeGenFunction &CGF, 1544 const ObjCAtTryStmt &S) override; 1545 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1546 const ObjCAtSynchronizedStmt &S) override; 1547 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, 1548 bool ClearInsertionPoint=true) override; 1549 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1550 Address AddrWeakObj) override; 1551 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1552 llvm::Value *src, Address edst) override; 1553 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1554 llvm::Value *src, Address dest, 1555 bool threadlocal = false) override; 1556 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1557 llvm::Value *src, Address dest, 1558 llvm::Value *ivarOffset) override; 1559 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1560 llvm::Value *src, Address dest) override; 1561 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 1562 Address dest, Address src, 1563 llvm::Value *size) override; 1564 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, 1565 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, 1566 unsigned CVRQualifiers) override; 1567 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 1568 const ObjCInterfaceDecl *Interface, 1569 const ObjCIvarDecl *Ivar) override; 1570 }; 1571 1572 /// A helper class for performing the null-initialization of a return 1573 /// value. 1574 struct NullReturnState { 1575 llvm::BasicBlock *NullBB; 1576 NullReturnState() : NullBB(nullptr) {} 1577 1578 /// Perform a null-check of the given receiver. 1579 void init(CodeGenFunction &CGF, llvm::Value *receiver) { 1580 // Make blocks for the null-receiver and call edges. 1581 NullBB = CGF.createBasicBlock("msgSend.null-receiver"); 1582 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call"); 1583 1584 // Check for a null receiver and, if there is one, jump to the 1585 // null-receiver block. There's no point in trying to avoid it: 1586 // we're always going to put *something* there, because otherwise 1587 // we shouldn't have done this null-check in the first place. 1588 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver); 1589 CGF.Builder.CreateCondBr(isNull, NullBB, callBB); 1590 1591 // Otherwise, start performing the call. 1592 CGF.EmitBlock(callBB); 1593 } 1594 1595 /// Complete the null-return operation. It is valid to call this 1596 /// regardless of whether 'init' has been called. 1597 RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType, 1598 const CallArgList &CallArgs, 1599 const ObjCMethodDecl *Method) { 1600 // If we never had to do a null-check, just use the raw result. 1601 if (!NullBB) return result; 1602 1603 // The continuation block. This will be left null if we don't have an 1604 // IP, which can happen if the method we're calling is marked noreturn. 1605 llvm::BasicBlock *contBB = nullptr; 1606 1607 // Finish the call path. 1608 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock(); 1609 if (callBB) { 1610 contBB = CGF.createBasicBlock("msgSend.cont"); 1611 CGF.Builder.CreateBr(contBB); 1612 } 1613 1614 // Okay, start emitting the null-receiver block. 1615 CGF.EmitBlock(NullBB); 1616 1617 // Release any consumed arguments we've got. 1618 if (Method) { 1619 CallArgList::const_iterator I = CallArgs.begin(); 1620 for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(), 1621 e = Method->param_end(); i != e; ++i, ++I) { 1622 const ParmVarDecl *ParamDecl = (*i); 1623 if (ParamDecl->hasAttr<NSConsumedAttr>()) { 1624 RValue RV = I->RV; 1625 assert(RV.isScalar() && 1626 "NullReturnState::complete - arg not on object"); 1627 CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime); 1628 } 1629 } 1630 } 1631 1632 // The phi code below assumes that we haven't needed any control flow yet. 1633 assert(CGF.Builder.GetInsertBlock() == NullBB); 1634 1635 // If we've got a void return, just jump to the continuation block. 1636 if (result.isScalar() && resultType->isVoidType()) { 1637 // No jumps required if the message-send was noreturn. 1638 if (contBB) CGF.EmitBlock(contBB); 1639 return result; 1640 } 1641 1642 // If we've got a scalar return, build a phi. 1643 if (result.isScalar()) { 1644 // Derive the null-initialization value. 1645 llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType); 1646 1647 // If no join is necessary, just flow out. 1648 if (!contBB) return RValue::get(null); 1649 1650 // Otherwise, build a phi. 1651 CGF.EmitBlock(contBB); 1652 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2); 1653 phi->addIncoming(result.getScalarVal(), callBB); 1654 phi->addIncoming(null, NullBB); 1655 return RValue::get(phi); 1656 } 1657 1658 // If we've got an aggregate return, null the buffer out. 1659 // FIXME: maybe we should be doing things differently for all the 1660 // cases where the ABI has us returning (1) non-agg values in 1661 // memory or (2) agg values in registers. 1662 if (result.isAggregate()) { 1663 assert(result.isAggregate() && "null init of non-aggregate result?"); 1664 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType); 1665 if (contBB) CGF.EmitBlock(contBB); 1666 return result; 1667 } 1668 1669 // Complex types. 1670 CGF.EmitBlock(contBB); 1671 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal(); 1672 1673 // Find the scalar type and its zero value. 1674 llvm::Type *scalarTy = callResult.first->getType(); 1675 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy); 1676 1677 // Build phis for both coordinates. 1678 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2); 1679 real->addIncoming(callResult.first, callBB); 1680 real->addIncoming(scalarZero, NullBB); 1681 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2); 1682 imag->addIncoming(callResult.second, callBB); 1683 imag->addIncoming(scalarZero, NullBB); 1684 return RValue::getComplex(real, imag); 1685 } 1686 }; 1687 1688 } // end anonymous namespace 1689 1690 /* *** Helper Functions *** */ 1691 1692 /// getConstantGEP() - Help routine to construct simple GEPs. 1693 static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext, 1694 llvm::GlobalVariable *C, unsigned idx0, 1695 unsigned idx1) { 1696 llvm::Value *Idxs[] = { 1697 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0), 1698 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1) 1699 }; 1700 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs); 1701 } 1702 1703 /// hasObjCExceptionAttribute - Return true if this class or any super 1704 /// class has the __objc_exception__ attribute. 1705 static bool hasObjCExceptionAttribute(ASTContext &Context, 1706 const ObjCInterfaceDecl *OID) { 1707 if (OID->hasAttr<ObjCExceptionAttr>()) 1708 return true; 1709 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 1710 return hasObjCExceptionAttribute(Context, Super); 1711 return false; 1712 } 1713 1714 /* *** CGObjCMac Public Interface *** */ 1715 1716 CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), 1717 ObjCTypes(cgm) { 1718 ObjCABI = 1; 1719 EmitImageInfo(); 1720 } 1721 1722 /// GetClass - Return a reference to the class for the given interface 1723 /// decl. 1724 llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF, 1725 const ObjCInterfaceDecl *ID) { 1726 return EmitClassRef(CGF, ID); 1727 } 1728 1729 /// GetSelector - Return the pointer to the unique'd string for this selector. 1730 llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) { 1731 return EmitSelector(CGF, Sel); 1732 } 1733 Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) { 1734 return EmitSelectorAddr(CGF, Sel); 1735 } 1736 llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl 1737 *Method) { 1738 return EmitSelector(CGF, Method->getSelector()); 1739 } 1740 1741 llvm::Constant *CGObjCMac::GetEHType(QualType T) { 1742 if (T->isObjCIdType() || 1743 T->isObjCQualifiedIdType()) { 1744 return CGM.GetAddrOfRTTIDescriptor( 1745 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true); 1746 } 1747 if (T->isObjCClassType() || 1748 T->isObjCQualifiedClassType()) { 1749 return CGM.GetAddrOfRTTIDescriptor( 1750 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true); 1751 } 1752 if (T->isObjCObjectPointerType()) 1753 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true); 1754 1755 llvm_unreachable("asking for catch type for ObjC type in fragile runtime"); 1756 } 1757 1758 /// Generate a constant CFString object. 1759 /* 1760 struct __builtin_CFString { 1761 const int *isa; // point to __CFConstantStringClassReference 1762 int flags; 1763 const char *str; 1764 long length; 1765 }; 1766 */ 1767 1768 /// or Generate a constant NSString object. 1769 /* 1770 struct __builtin_NSString { 1771 const int *isa; // point to __NSConstantStringClassReference 1772 const char *str; 1773 unsigned int length; 1774 }; 1775 */ 1776 1777 ConstantAddress CGObjCCommonMac::GenerateConstantString( 1778 const StringLiteral *SL) { 1779 return (CGM.getLangOpts().NoConstantCFStrings == 0 ? 1780 CGM.GetAddrOfConstantCFString(SL) : 1781 CGM.GetAddrOfConstantString(SL)); 1782 } 1783 1784 enum { 1785 kCFTaggedObjectID_Integer = (1 << 1) + 1 1786 }; 1787 1788 /// Generates a message send where the super is the receiver. This is 1789 /// a message send to self with special delivery semantics indicating 1790 /// which class's method should be called. 1791 CodeGen::RValue 1792 CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 1793 ReturnValueSlot Return, 1794 QualType ResultType, 1795 Selector Sel, 1796 const ObjCInterfaceDecl *Class, 1797 bool isCategoryImpl, 1798 llvm::Value *Receiver, 1799 bool IsClassMessage, 1800 const CodeGen::CallArgList &CallArgs, 1801 const ObjCMethodDecl *Method) { 1802 // Create and init a super structure; this is a (receiver, class) 1803 // pair we will pass to objc_msgSendSuper. 1804 Address ObjCSuper = 1805 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(), 1806 "objc_super"); 1807 llvm::Value *ReceiverAsObject = 1808 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 1809 CGF.Builder.CreateStore( 1810 ReceiverAsObject, 1811 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero())); 1812 1813 // If this is a class message the metaclass is passed as the target. 1814 llvm::Value *Target; 1815 if (IsClassMessage) { 1816 if (isCategoryImpl) { 1817 // Message sent to 'super' in a class method defined in a category 1818 // implementation requires an odd treatment. 1819 // If we are in a class method, we must retrieve the 1820 // _metaclass_ for the current class, pointed at by 1821 // the class's "isa" pointer. The following assumes that 1822 // isa" is the first ivar in a class (which it must be). 1823 Target = EmitClassRef(CGF, Class->getSuperClass()); 1824 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0); 1825 Target = CGF.Builder.CreateAlignedLoad(Target, CGF.getPointerAlign()); 1826 } else { 1827 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class); 1828 llvm::Value *SuperPtr = 1829 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1); 1830 llvm::Value *Super = 1831 CGF.Builder.CreateAlignedLoad(SuperPtr, CGF.getPointerAlign()); 1832 Target = Super; 1833 } 1834 } else if (isCategoryImpl) 1835 Target = EmitClassRef(CGF, Class->getSuperClass()); 1836 else { 1837 llvm::Value *ClassPtr = EmitSuperClassRef(Class); 1838 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1); 1839 Target = CGF.Builder.CreateAlignedLoad(ClassPtr, CGF.getPointerAlign()); 1840 } 1841 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and 1842 // ObjCTypes types. 1843 llvm::Type *ClassTy = 1844 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 1845 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 1846 CGF.Builder.CreateStore(Target, 1847 CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize())); 1848 return EmitMessageSend(CGF, Return, ResultType, 1849 EmitSelector(CGF, Sel), 1850 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy, 1851 true, CallArgs, Method, Class, ObjCTypes); 1852 } 1853 1854 /// Generate code for a message send expression. 1855 CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1856 ReturnValueSlot Return, 1857 QualType ResultType, 1858 Selector Sel, 1859 llvm::Value *Receiver, 1860 const CallArgList &CallArgs, 1861 const ObjCInterfaceDecl *Class, 1862 const ObjCMethodDecl *Method) { 1863 return EmitMessageSend(CGF, Return, ResultType, 1864 EmitSelector(CGF, Sel), 1865 Receiver, CGF.getContext().getObjCIdType(), 1866 false, CallArgs, Method, Class, ObjCTypes); 1867 } 1868 1869 static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) { 1870 do { 1871 if (ID->isWeakImported()) 1872 return true; 1873 } while ((ID = ID->getSuperClass())); 1874 1875 return false; 1876 } 1877 1878 CodeGen::RValue 1879 CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, 1880 ReturnValueSlot Return, 1881 QualType ResultType, 1882 llvm::Value *Sel, 1883 llvm::Value *Arg0, 1884 QualType Arg0Ty, 1885 bool IsSuper, 1886 const CallArgList &CallArgs, 1887 const ObjCMethodDecl *Method, 1888 const ObjCInterfaceDecl *ClassReceiver, 1889 const ObjCCommonTypesHelper &ObjCTypes) { 1890 CallArgList ActualArgs; 1891 if (!IsSuper) 1892 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy); 1893 ActualArgs.add(RValue::get(Arg0), Arg0Ty); 1894 ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType()); 1895 ActualArgs.addFrom(CallArgs); 1896 1897 // If we're calling a method, use the formal signature. 1898 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 1899 1900 if (Method) 1901 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) == 1902 CGM.getContext().getCanonicalType(ResultType) && 1903 "Result type mismatch!"); 1904 1905 bool ReceiverCanBeNull = true; 1906 1907 // Super dispatch assumes that self is non-null; even the messenger 1908 // doesn't have a null check internally. 1909 if (IsSuper) { 1910 ReceiverCanBeNull = false; 1911 1912 // If this is a direct dispatch of a class method, check whether the class, 1913 // or anything in its hierarchy, was weak-linked. 1914 } else if (ClassReceiver && Method && Method->isClassMethod()) { 1915 ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver); 1916 1917 // If we're emitting a method, and self is const (meaning just ARC, for now), 1918 // and the receiver is a load of self, then self is a valid object. 1919 } else if (auto CurMethod = 1920 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) { 1921 auto Self = CurMethod->getSelfDecl(); 1922 if (Self->getType().isConstQualified()) { 1923 if (auto LI = dyn_cast<llvm::LoadInst>(Arg0->stripPointerCasts())) { 1924 llvm::Value *SelfAddr = CGF.GetAddrOfLocalVar(Self).getPointer(); 1925 if (SelfAddr == LI->getPointerOperand()) { 1926 ReceiverCanBeNull = false; 1927 } 1928 } 1929 } 1930 } 1931 1932 NullReturnState nullReturn; 1933 1934 llvm::Constant *Fn = nullptr; 1935 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) { 1936 if (ReceiverCanBeNull) nullReturn.init(CGF, Arg0); 1937 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper) 1938 : ObjCTypes.getSendStretFn(IsSuper); 1939 } else if (CGM.ReturnTypeUsesFPRet(ResultType)) { 1940 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper) 1941 : ObjCTypes.getSendFpretFn(IsSuper); 1942 } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) { 1943 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper) 1944 : ObjCTypes.getSendFp2retFn(IsSuper); 1945 } else { 1946 // arm64 uses objc_msgSend for stret methods and yet null receiver check 1947 // must be made for it. 1948 if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 1949 nullReturn.init(CGF, Arg0); 1950 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper) 1951 : ObjCTypes.getSendFn(IsSuper); 1952 } 1953 1954 // Emit a null-check if there's a consumed argument other than the receiver. 1955 bool RequiresNullCheck = false; 1956 if (ReceiverCanBeNull && CGM.getLangOpts().ObjCAutoRefCount && Method) { 1957 for (const auto *ParamDecl : Method->parameters()) { 1958 if (ParamDecl->hasAttr<NSConsumedAttr>()) { 1959 if (!nullReturn.NullBB) 1960 nullReturn.init(CGF, Arg0); 1961 RequiresNullCheck = true; 1962 break; 1963 } 1964 } 1965 } 1966 1967 llvm::Instruction *CallSite; 1968 Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType); 1969 RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs, 1970 CGCalleeInfo(), &CallSite); 1971 1972 // Mark the call as noreturn if the method is marked noreturn and the 1973 // receiver cannot be null. 1974 if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) { 1975 llvm::CallSite(CallSite).setDoesNotReturn(); 1976 } 1977 1978 return nullReturn.complete(CGF, rvalue, ResultType, CallArgs, 1979 RequiresNullCheck ? Method : nullptr); 1980 } 1981 1982 static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT, 1983 bool pointee = false) { 1984 // Note that GC qualification applies recursively to C pointer types 1985 // that aren't otherwise decorated. This is weird, but it's probably 1986 // an intentional workaround to the unreliable placement of GC qualifiers. 1987 if (FQT.isObjCGCStrong()) 1988 return Qualifiers::Strong; 1989 1990 if (FQT.isObjCGCWeak()) 1991 return Qualifiers::Weak; 1992 1993 if (auto ownership = FQT.getObjCLifetime()) { 1994 // Ownership does not apply recursively to C pointer types. 1995 if (pointee) return Qualifiers::GCNone; 1996 switch (ownership) { 1997 case Qualifiers::OCL_Weak: return Qualifiers::Weak; 1998 case Qualifiers::OCL_Strong: return Qualifiers::Strong; 1999 case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone; 2000 case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?"); 2001 case Qualifiers::OCL_None: llvm_unreachable("known nonzero"); 2002 } 2003 llvm_unreachable("bad objc ownership"); 2004 } 2005 2006 // Treat unqualified retainable pointers as strong. 2007 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) 2008 return Qualifiers::Strong; 2009 2010 // Walk into C pointer types, but only in GC. 2011 if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) { 2012 if (const PointerType *PT = FQT->getAs<PointerType>()) 2013 return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true); 2014 } 2015 2016 return Qualifiers::GCNone; 2017 } 2018 2019 namespace { 2020 struct IvarInfo { 2021 CharUnits Offset; 2022 uint64_t SizeInWords; 2023 IvarInfo(CharUnits offset, uint64_t sizeInWords) 2024 : Offset(offset), SizeInWords(sizeInWords) {} 2025 2026 // Allow sorting based on byte pos. 2027 bool operator<(const IvarInfo &other) const { 2028 return Offset < other.Offset; 2029 } 2030 }; 2031 2032 /// A helper class for building GC layout strings. 2033 class IvarLayoutBuilder { 2034 CodeGenModule &CGM; 2035 2036 /// The start of the layout. Offsets will be relative to this value, 2037 /// and entries less than this value will be silently discarded. 2038 CharUnits InstanceBegin; 2039 2040 /// The end of the layout. Offsets will never exceed this value. 2041 CharUnits InstanceEnd; 2042 2043 /// Whether we're generating the strong layout or the weak layout. 2044 bool ForStrongLayout; 2045 2046 /// Whether the offsets in IvarsInfo might be out-of-order. 2047 bool IsDisordered = false; 2048 2049 llvm::SmallVector<IvarInfo, 8> IvarsInfo; 2050 2051 public: 2052 IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin, 2053 CharUnits instanceEnd, bool forStrongLayout) 2054 : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd), 2055 ForStrongLayout(forStrongLayout) { 2056 } 2057 2058 void visitRecord(const RecordType *RT, CharUnits offset); 2059 2060 template <class Iterator, class GetOffsetFn> 2061 void visitAggregate(Iterator begin, Iterator end, 2062 CharUnits aggrOffset, 2063 const GetOffsetFn &getOffset); 2064 2065 void visitField(const FieldDecl *field, CharUnits offset); 2066 2067 /// Add the layout of a block implementation. 2068 void visitBlock(const CGBlockInfo &blockInfo); 2069 2070 /// Is there any information for an interesting bitmap? 2071 bool hasBitmapData() const { return !IvarsInfo.empty(); } 2072 2073 llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC, 2074 llvm::SmallVectorImpl<unsigned char> &buffer); 2075 2076 static void dump(ArrayRef<unsigned char> buffer) { 2077 const unsigned char *s = buffer.data(); 2078 for (unsigned i = 0, e = buffer.size(); i < e; i++) 2079 if (!(s[i] & 0xf0)) 2080 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : ""); 2081 else 2082 printf("0x%x%s", s[i], s[i] != 0 ? ", " : ""); 2083 printf("\n"); 2084 } 2085 }; 2086 } // end anonymous namespace 2087 2088 llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM, 2089 const CGBlockInfo &blockInfo) { 2090 2091 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); 2092 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) 2093 return nullPtr; 2094 2095 IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize, 2096 /*for strong layout*/ true); 2097 2098 builder.visitBlock(blockInfo); 2099 2100 if (!builder.hasBitmapData()) 2101 return nullPtr; 2102 2103 llvm::SmallVector<unsigned char, 32> buffer; 2104 llvm::Constant *C = builder.buildBitmap(*this, buffer); 2105 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) { 2106 printf("\n block variable layout for block: "); 2107 builder.dump(buffer); 2108 } 2109 2110 return C; 2111 } 2112 2113 void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) { 2114 // __isa is the first field in block descriptor and must assume by runtime's 2115 // convention that it is GC'able. 2116 IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1)); 2117 2118 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 2119 2120 // Ignore the optional 'this' capture: C++ objects are not assumed 2121 // to be GC'ed. 2122 2123 CharUnits lastFieldOffset; 2124 2125 // Walk the captured variables. 2126 for (const auto &CI : blockDecl->captures()) { 2127 const VarDecl *variable = CI.getVariable(); 2128 QualType type = variable->getType(); 2129 2130 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 2131 2132 // Ignore constant captures. 2133 if (capture.isConstant()) continue; 2134 2135 CharUnits fieldOffset = capture.getOffset(); 2136 2137 // Block fields are not necessarily ordered; if we detect that we're 2138 // adding them out-of-order, make sure we sort later. 2139 if (fieldOffset < lastFieldOffset) 2140 IsDisordered = true; 2141 lastFieldOffset = fieldOffset; 2142 2143 // __block variables are passed by their descriptor address. 2144 if (CI.isByRef()) { 2145 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1)); 2146 continue; 2147 } 2148 2149 assert(!type->isArrayType() && "array variable should not be caught"); 2150 if (const RecordType *record = type->getAs<RecordType>()) { 2151 visitRecord(record, fieldOffset); 2152 continue; 2153 } 2154 2155 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type); 2156 2157 if (GCAttr == Qualifiers::Strong) { 2158 assert(CGM.getContext().getTypeSize(type) 2159 == CGM.getTarget().getPointerWidth(0)); 2160 IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1)); 2161 } 2162 } 2163 } 2164 2165 /// getBlockCaptureLifetime - This routine returns life time of the captured 2166 /// block variable for the purpose of block layout meta-data generation. FQT is 2167 /// the type of the variable captured in the block. 2168 Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT, 2169 bool ByrefLayout) { 2170 // If it has an ownership qualifier, we're done. 2171 if (auto lifetime = FQT.getObjCLifetime()) 2172 return lifetime; 2173 2174 // If it doesn't, and this is ARC, it has no ownership. 2175 if (CGM.getLangOpts().ObjCAutoRefCount) 2176 return Qualifiers::OCL_None; 2177 2178 // In MRC, retainable pointers are owned by non-__block variables. 2179 if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) 2180 return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong; 2181 2182 return Qualifiers::OCL_None; 2183 } 2184 2185 void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref, 2186 Qualifiers::ObjCLifetime LifeTime, 2187 CharUnits FieldOffset, 2188 CharUnits FieldSize) { 2189 // __block variables are passed by their descriptor address. 2190 if (IsByref) 2191 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset, 2192 FieldSize)); 2193 else if (LifeTime == Qualifiers::OCL_Strong) 2194 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset, 2195 FieldSize)); 2196 else if (LifeTime == Qualifiers::OCL_Weak) 2197 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset, 2198 FieldSize)); 2199 else if (LifeTime == Qualifiers::OCL_ExplicitNone) 2200 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset, 2201 FieldSize)); 2202 else 2203 RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES, 2204 FieldOffset, 2205 FieldSize)); 2206 } 2207 2208 void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, 2209 const RecordDecl *RD, 2210 ArrayRef<const FieldDecl*> RecFields, 2211 CharUnits BytePos, bool &HasUnion, 2212 bool ByrefLayout) { 2213 bool IsUnion = (RD && RD->isUnion()); 2214 CharUnits MaxUnionSize = CharUnits::Zero(); 2215 const FieldDecl *MaxField = nullptr; 2216 const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr; 2217 CharUnits MaxFieldOffset = CharUnits::Zero(); 2218 CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero(); 2219 2220 if (RecFields.empty()) 2221 return; 2222 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); 2223 2224 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 2225 const FieldDecl *Field = RecFields[i]; 2226 // Note that 'i' here is actually the field index inside RD of Field, 2227 // although this dependency is hidden. 2228 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2229 CharUnits FieldOffset = 2230 CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i)); 2231 2232 // Skip over unnamed or bitfields 2233 if (!Field->getIdentifier() || Field->isBitField()) { 2234 LastFieldBitfieldOrUnnamed = Field; 2235 LastBitfieldOrUnnamedOffset = FieldOffset; 2236 continue; 2237 } 2238 2239 LastFieldBitfieldOrUnnamed = nullptr; 2240 QualType FQT = Field->getType(); 2241 if (FQT->isRecordType() || FQT->isUnionType()) { 2242 if (FQT->isUnionType()) 2243 HasUnion = true; 2244 2245 BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(), 2246 BytePos + FieldOffset, HasUnion); 2247 continue; 2248 } 2249 2250 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { 2251 const ConstantArrayType *CArray = 2252 dyn_cast_or_null<ConstantArrayType>(Array); 2253 uint64_t ElCount = CArray->getSize().getZExtValue(); 2254 assert(CArray && "only array with known element size is supported"); 2255 FQT = CArray->getElementType(); 2256 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { 2257 const ConstantArrayType *CArray = 2258 dyn_cast_or_null<ConstantArrayType>(Array); 2259 ElCount *= CArray->getSize().getZExtValue(); 2260 FQT = CArray->getElementType(); 2261 } 2262 if (FQT->isRecordType() && ElCount) { 2263 int OldIndex = RunSkipBlockVars.size() - 1; 2264 const RecordType *RT = FQT->getAs<RecordType>(); 2265 BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset, 2266 HasUnion); 2267 2268 // Replicate layout information for each array element. Note that 2269 // one element is already done. 2270 uint64_t ElIx = 1; 2271 for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) { 2272 CharUnits Size = CGM.getContext().getTypeSizeInChars(RT); 2273 for (int i = OldIndex+1; i <= FirstIndex; ++i) 2274 RunSkipBlockVars.push_back( 2275 RUN_SKIP(RunSkipBlockVars[i].opcode, 2276 RunSkipBlockVars[i].block_var_bytepos + Size*ElIx, 2277 RunSkipBlockVars[i].block_var_size)); 2278 } 2279 continue; 2280 } 2281 } 2282 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType()); 2283 if (IsUnion) { 2284 CharUnits UnionIvarSize = FieldSize; 2285 if (UnionIvarSize > MaxUnionSize) { 2286 MaxUnionSize = UnionIvarSize; 2287 MaxField = Field; 2288 MaxFieldOffset = FieldOffset; 2289 } 2290 } else { 2291 UpdateRunSkipBlockVars(false, 2292 getBlockCaptureLifetime(FQT, ByrefLayout), 2293 BytePos + FieldOffset, 2294 FieldSize); 2295 } 2296 } 2297 2298 if (LastFieldBitfieldOrUnnamed) { 2299 if (LastFieldBitfieldOrUnnamed->isBitField()) { 2300 // Last field was a bitfield. Must update the info. 2301 uint64_t BitFieldSize 2302 = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext()); 2303 unsigned UnsSize = (BitFieldSize / ByteSizeInBits) + 2304 ((BitFieldSize % ByteSizeInBits) != 0); 2305 CharUnits Size = CharUnits::fromQuantity(UnsSize); 2306 Size += LastBitfieldOrUnnamedOffset; 2307 UpdateRunSkipBlockVars(false, 2308 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(), 2309 ByrefLayout), 2310 BytePos + LastBitfieldOrUnnamedOffset, 2311 Size); 2312 } else { 2313 assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed"); 2314 // Last field was unnamed. Must update skip info. 2315 CharUnits FieldSize 2316 = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType()); 2317 UpdateRunSkipBlockVars(false, 2318 getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(), 2319 ByrefLayout), 2320 BytePos + LastBitfieldOrUnnamedOffset, 2321 FieldSize); 2322 } 2323 } 2324 2325 if (MaxField) 2326 UpdateRunSkipBlockVars(false, 2327 getBlockCaptureLifetime(MaxField->getType(), ByrefLayout), 2328 BytePos + MaxFieldOffset, 2329 MaxUnionSize); 2330 } 2331 2332 void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT, 2333 CharUnits BytePos, 2334 bool &HasUnion, 2335 bool ByrefLayout) { 2336 const RecordDecl *RD = RT->getDecl(); 2337 SmallVector<const FieldDecl*, 16> Fields(RD->fields()); 2338 llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0)); 2339 const llvm::StructLayout *RecLayout = 2340 CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty)); 2341 2342 BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout); 2343 } 2344 2345 /// InlineLayoutInstruction - This routine produce an inline instruction for the 2346 /// block variable layout if it can. If not, it returns 0. Rules are as follow: 2347 /// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world, 2348 /// an inline layout of value 0x0000000000000xyz is interpreted as follows: 2349 /// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by 2350 /// y captured object of BLOCK_LAYOUT_BYREF. Followed by 2351 /// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero 2352 /// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no 2353 /// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured. 2354 uint64_t CGObjCCommonMac::InlineLayoutInstruction( 2355 SmallVectorImpl<unsigned char> &Layout) { 2356 uint64_t Result = 0; 2357 if (Layout.size() <= 3) { 2358 unsigned size = Layout.size(); 2359 unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0; 2360 unsigned char inst; 2361 enum BLOCK_LAYOUT_OPCODE opcode ; 2362 switch (size) { 2363 case 3: 2364 inst = Layout[0]; 2365 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2366 if (opcode == BLOCK_LAYOUT_STRONG) 2367 strong_word_count = (inst & 0xF)+1; 2368 else 2369 return 0; 2370 inst = Layout[1]; 2371 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2372 if (opcode == BLOCK_LAYOUT_BYREF) 2373 byref_word_count = (inst & 0xF)+1; 2374 else 2375 return 0; 2376 inst = Layout[2]; 2377 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2378 if (opcode == BLOCK_LAYOUT_WEAK) 2379 weak_word_count = (inst & 0xF)+1; 2380 else 2381 return 0; 2382 break; 2383 2384 case 2: 2385 inst = Layout[0]; 2386 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2387 if (opcode == BLOCK_LAYOUT_STRONG) { 2388 strong_word_count = (inst & 0xF)+1; 2389 inst = Layout[1]; 2390 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2391 if (opcode == BLOCK_LAYOUT_BYREF) 2392 byref_word_count = (inst & 0xF)+1; 2393 else if (opcode == BLOCK_LAYOUT_WEAK) 2394 weak_word_count = (inst & 0xF)+1; 2395 else 2396 return 0; 2397 } 2398 else if (opcode == BLOCK_LAYOUT_BYREF) { 2399 byref_word_count = (inst & 0xF)+1; 2400 inst = Layout[1]; 2401 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2402 if (opcode == BLOCK_LAYOUT_WEAK) 2403 weak_word_count = (inst & 0xF)+1; 2404 else 2405 return 0; 2406 } 2407 else 2408 return 0; 2409 break; 2410 2411 case 1: 2412 inst = Layout[0]; 2413 opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2414 if (opcode == BLOCK_LAYOUT_STRONG) 2415 strong_word_count = (inst & 0xF)+1; 2416 else if (opcode == BLOCK_LAYOUT_BYREF) 2417 byref_word_count = (inst & 0xF)+1; 2418 else if (opcode == BLOCK_LAYOUT_WEAK) 2419 weak_word_count = (inst & 0xF)+1; 2420 else 2421 return 0; 2422 break; 2423 2424 default: 2425 return 0; 2426 } 2427 2428 // Cannot inline when any of the word counts is 15. Because this is one less 2429 // than the actual work count (so 15 means 16 actual word counts), 2430 // and we can only display 0 thru 15 word counts. 2431 if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16) 2432 return 0; 2433 2434 unsigned count = 2435 (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0); 2436 2437 if (size == count) { 2438 if (strong_word_count) 2439 Result = strong_word_count; 2440 Result <<= 4; 2441 if (byref_word_count) 2442 Result += byref_word_count; 2443 Result <<= 4; 2444 if (weak_word_count) 2445 Result += weak_word_count; 2446 } 2447 } 2448 return Result; 2449 } 2450 2451 llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { 2452 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); 2453 if (RunSkipBlockVars.empty()) 2454 return nullPtr; 2455 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); 2456 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); 2457 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; 2458 2459 // Sort on byte position; captures might not be allocated in order, 2460 // and unions can do funny things. 2461 llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end()); 2462 SmallVector<unsigned char, 16> Layout; 2463 2464 unsigned size = RunSkipBlockVars.size(); 2465 for (unsigned i = 0; i < size; i++) { 2466 enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode; 2467 CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos; 2468 CharUnits end_byte_pos = start_byte_pos; 2469 unsigned j = i+1; 2470 while (j < size) { 2471 if (opcode == RunSkipBlockVars[j].opcode) { 2472 end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos; 2473 i++; 2474 } 2475 else 2476 break; 2477 } 2478 CharUnits size_in_bytes = 2479 end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size; 2480 if (j < size) { 2481 CharUnits gap = 2482 RunSkipBlockVars[j].block_var_bytepos - 2483 RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size; 2484 size_in_bytes += gap; 2485 } 2486 CharUnits residue_in_bytes = CharUnits::Zero(); 2487 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) { 2488 residue_in_bytes = size_in_bytes % WordSizeInBytes; 2489 size_in_bytes -= residue_in_bytes; 2490 opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS; 2491 } 2492 2493 unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes; 2494 while (size_in_words >= 16) { 2495 // Note that value in imm. is one less that the actual 2496 // value. So, 0xf means 16 words follow! 2497 unsigned char inst = (opcode << 4) | 0xf; 2498 Layout.push_back(inst); 2499 size_in_words -= 16; 2500 } 2501 if (size_in_words > 0) { 2502 // Note that value in imm. is one less that the actual 2503 // value. So, we subtract 1 away! 2504 unsigned char inst = (opcode << 4) | (size_in_words-1); 2505 Layout.push_back(inst); 2506 } 2507 if (residue_in_bytes > CharUnits::Zero()) { 2508 unsigned char inst = 2509 (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1); 2510 Layout.push_back(inst); 2511 } 2512 } 2513 2514 while (!Layout.empty()) { 2515 unsigned char inst = Layout.back(); 2516 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2517 if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS) 2518 Layout.pop_back(); 2519 else 2520 break; 2521 } 2522 2523 uint64_t Result = InlineLayoutInstruction(Layout); 2524 if (Result != 0) { 2525 // Block variable layout instruction has been inlined. 2526 if (CGM.getLangOpts().ObjCGCBitmapPrint) { 2527 if (ComputeByrefLayout) 2528 printf("\n Inline BYREF variable layout: "); 2529 else 2530 printf("\n Inline block variable layout: "); 2531 printf("0x0%" PRIx64 "", Result); 2532 if (auto numStrong = (Result & 0xF00) >> 8) 2533 printf(", BL_STRONG:%d", (int) numStrong); 2534 if (auto numByref = (Result & 0x0F0) >> 4) 2535 printf(", BL_BYREF:%d", (int) numByref); 2536 if (auto numWeak = (Result & 0x00F) >> 0) 2537 printf(", BL_WEAK:%d", (int) numWeak); 2538 printf(", BL_OPERATOR:0\n"); 2539 } 2540 return llvm::ConstantInt::get(CGM.IntPtrTy, Result); 2541 } 2542 2543 unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0; 2544 Layout.push_back(inst); 2545 std::string BitMap; 2546 for (unsigned i = 0, e = Layout.size(); i != e; i++) 2547 BitMap += Layout[i]; 2548 2549 if (CGM.getLangOpts().ObjCGCBitmapPrint) { 2550 if (ComputeByrefLayout) 2551 printf("\n Byref variable layout: "); 2552 else 2553 printf("\n Block variable layout: "); 2554 for (unsigned i = 0, e = BitMap.size(); i != e; i++) { 2555 unsigned char inst = BitMap[i]; 2556 enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); 2557 unsigned delta = 1; 2558 switch (opcode) { 2559 case BLOCK_LAYOUT_OPERATOR: 2560 printf("BL_OPERATOR:"); 2561 delta = 0; 2562 break; 2563 case BLOCK_LAYOUT_NON_OBJECT_BYTES: 2564 printf("BL_NON_OBJECT_BYTES:"); 2565 break; 2566 case BLOCK_LAYOUT_NON_OBJECT_WORDS: 2567 printf("BL_NON_OBJECT_WORD:"); 2568 break; 2569 case BLOCK_LAYOUT_STRONG: 2570 printf("BL_STRONG:"); 2571 break; 2572 case BLOCK_LAYOUT_BYREF: 2573 printf("BL_BYREF:"); 2574 break; 2575 case BLOCK_LAYOUT_WEAK: 2576 printf("BL_WEAK:"); 2577 break; 2578 case BLOCK_LAYOUT_UNRETAINED: 2579 printf("BL_UNRETAINED:"); 2580 break; 2581 } 2582 // Actual value of word count is one more that what is in the imm. 2583 // field of the instruction 2584 printf("%d", (inst & 0xf) + delta); 2585 if (i < e-1) 2586 printf(", "); 2587 else 2588 printf("\n"); 2589 } 2590 } 2591 2592 auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName, 2593 /*ForceNonFragileABI=*/true, 2594 /*NullTerminate=*/false); 2595 return getConstantGEP(VMContext, Entry, 0, 0); 2596 } 2597 2598 llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM, 2599 const CGBlockInfo &blockInfo) { 2600 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); 2601 2602 RunSkipBlockVars.clear(); 2603 bool hasUnion = false; 2604 2605 unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); 2606 unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); 2607 unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; 2608 2609 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 2610 2611 // Calculate the basic layout of the block structure. 2612 const llvm::StructLayout *layout = 2613 CGM.getDataLayout().getStructLayout(blockInfo.StructureType); 2614 2615 // Ignore the optional 'this' capture: C++ objects are not assumed 2616 // to be GC'ed. 2617 if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero()) 2618 UpdateRunSkipBlockVars(false, Qualifiers::OCL_None, 2619 blockInfo.BlockHeaderForcedGapOffset, 2620 blockInfo.BlockHeaderForcedGapSize); 2621 // Walk the captured variables. 2622 for (const auto &CI : blockDecl->captures()) { 2623 const VarDecl *variable = CI.getVariable(); 2624 QualType type = variable->getType(); 2625 2626 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 2627 2628 // Ignore constant captures. 2629 if (capture.isConstant()) continue; 2630 2631 CharUnits fieldOffset = 2632 CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex())); 2633 2634 assert(!type->isArrayType() && "array variable should not be caught"); 2635 if (!CI.isByRef()) 2636 if (const RecordType *record = type->getAs<RecordType>()) { 2637 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion); 2638 continue; 2639 } 2640 CharUnits fieldSize; 2641 if (CI.isByRef()) 2642 fieldSize = CharUnits::fromQuantity(WordSizeInBytes); 2643 else 2644 fieldSize = CGM.getContext().getTypeSizeInChars(type); 2645 UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false), 2646 fieldOffset, fieldSize); 2647 } 2648 return getBitmapBlockLayout(false); 2649 } 2650 2651 llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM, 2652 QualType T) { 2653 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); 2654 assert(!T->isArrayType() && "__block array variable should not be caught"); 2655 CharUnits fieldOffset; 2656 RunSkipBlockVars.clear(); 2657 bool hasUnion = false; 2658 if (const RecordType *record = T->getAs<RecordType>()) { 2659 BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */); 2660 llvm::Constant *Result = getBitmapBlockLayout(true); 2661 if (isa<llvm::ConstantInt>(Result)) 2662 Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy); 2663 return Result; 2664 } 2665 llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); 2666 return nullPtr; 2667 } 2668 2669 llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF, 2670 const ObjCProtocolDecl *PD) { 2671 // FIXME: I don't understand why gcc generates this, or where it is 2672 // resolved. Investigate. Its also wasteful to look this up over and over. 2673 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 2674 2675 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 2676 ObjCTypes.getExternalProtocolPtrTy()); 2677 } 2678 2679 void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { 2680 // FIXME: We shouldn't need this, the protocol decl should contain enough 2681 // information to tell us whether this was a declaration or a definition. 2682 DefinedProtocols.insert(PD->getIdentifier()); 2683 2684 // If we have generated a forward reference to this protocol, emit 2685 // it now. Otherwise do nothing, the protocol objects are lazily 2686 // emitted. 2687 if (Protocols.count(PD->getIdentifier())) 2688 GetOrEmitProtocol(PD); 2689 } 2690 2691 llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { 2692 if (DefinedProtocols.count(PD->getIdentifier())) 2693 return GetOrEmitProtocol(PD); 2694 2695 return GetOrEmitProtocolRef(PD); 2696 } 2697 2698 llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime( 2699 CodeGenFunction &CGF, 2700 const ObjCInterfaceDecl *ID, 2701 ObjCCommonTypesHelper &ObjCTypes) { 2702 llvm::Constant *lookUpClassFn = ObjCTypes.getLookUpClassFn(); 2703 2704 llvm::Value *className = 2705 CGF.CGM.GetAddrOfConstantCString(ID->getObjCRuntimeNameAsString()) 2706 .getPointer(); 2707 ASTContext &ctx = CGF.CGM.getContext(); 2708 className = 2709 CGF.Builder.CreateBitCast(className, 2710 CGF.ConvertType( 2711 ctx.getPointerType(ctx.CharTy.withConst()))); 2712 llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className); 2713 call->setDoesNotThrow(); 2714 return call; 2715 } 2716 2717 /* 2718 // Objective-C 1.0 extensions 2719 struct _objc_protocol { 2720 struct _objc_protocol_extension *isa; 2721 char *protocol_name; 2722 struct _objc_protocol_list *protocol_list; 2723 struct _objc__method_prototype_list *instance_methods; 2724 struct _objc__method_prototype_list *class_methods 2725 }; 2726 2727 See EmitProtocolExtension(). 2728 */ 2729 llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { 2730 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()]; 2731 2732 // Early exit if a defining object has already been generated. 2733 if (Entry && Entry->hasInitializer()) 2734 return Entry; 2735 2736 // Use the protocol definition, if there is one. 2737 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 2738 PD = Def; 2739 2740 // FIXME: I don't understand why gcc generates this, or where it is 2741 // resolved. Investigate. Its also wasteful to look this up over and over. 2742 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 2743 2744 // Construct method lists. 2745 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 2746 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 2747 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt; 2748 for (const auto *MD : PD->instance_methods()) { 2749 llvm::Constant *C = GetMethodDescriptionConstant(MD); 2750 if (!C) 2751 return GetOrEmitProtocolRef(PD); 2752 2753 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 2754 OptInstanceMethods.push_back(C); 2755 OptMethodTypesExt.push_back(GetMethodVarType(MD, true)); 2756 } else { 2757 InstanceMethods.push_back(C); 2758 MethodTypesExt.push_back(GetMethodVarType(MD, true)); 2759 } 2760 } 2761 2762 for (const auto *MD : PD->class_methods()) { 2763 llvm::Constant *C = GetMethodDescriptionConstant(MD); 2764 if (!C) 2765 return GetOrEmitProtocolRef(PD); 2766 2767 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 2768 OptClassMethods.push_back(C); 2769 OptMethodTypesExt.push_back(GetMethodVarType(MD, true)); 2770 } else { 2771 ClassMethods.push_back(C); 2772 MethodTypesExt.push_back(GetMethodVarType(MD, true)); 2773 } 2774 } 2775 2776 MethodTypesExt.insert(MethodTypesExt.end(), 2777 OptMethodTypesExt.begin(), OptMethodTypesExt.end()); 2778 2779 llvm::Constant *Values[] = { 2780 EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods, 2781 MethodTypesExt), 2782 GetClassName(PD->getObjCRuntimeNameAsString()), 2783 EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(), 2784 PD->protocol_begin(), PD->protocol_end()), 2785 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(), 2786 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 2787 InstanceMethods), 2788 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(), 2789 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 2790 ClassMethods)}; 2791 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 2792 Values); 2793 2794 if (Entry) { 2795 // Already created, update the initializer. 2796 assert(Entry->hasPrivateLinkage()); 2797 Entry->setInitializer(Init); 2798 } else { 2799 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, 2800 false, llvm::GlobalValue::PrivateLinkage, 2801 Init, "OBJC_PROTOCOL_" + PD->getName()); 2802 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 2803 // FIXME: Is this necessary? Why only for protocol? 2804 Entry->setAlignment(4); 2805 2806 Protocols[PD->getIdentifier()] = Entry; 2807 } 2808 CGM.addCompilerUsedGlobal(Entry); 2809 2810 return Entry; 2811 } 2812 2813 llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { 2814 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 2815 2816 if (!Entry) { 2817 // We use the initializer as a marker of whether this is a forward 2818 // reference or not. At module finalization we add the empty 2819 // contents for protocols which were referenced but never defined. 2820 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, 2821 false, llvm::GlobalValue::PrivateLinkage, 2822 nullptr, "OBJC_PROTOCOL_" + PD->getName()); 2823 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 2824 // FIXME: Is this necessary? Why only for protocol? 2825 Entry->setAlignment(4); 2826 } 2827 2828 return Entry; 2829 } 2830 2831 /* 2832 struct _objc_protocol_extension { 2833 uint32_t size; 2834 struct objc_method_description_list *optional_instance_methods; 2835 struct objc_method_description_list *optional_class_methods; 2836 struct objc_property_list *instance_properties; 2837 const char ** extendedMethodTypes; 2838 struct objc_property_list *class_properties; 2839 }; 2840 */ 2841 llvm::Constant * 2842 CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, 2843 ArrayRef<llvm::Constant*> OptInstanceMethods, 2844 ArrayRef<llvm::Constant*> OptClassMethods, 2845 ArrayRef<llvm::Constant*> MethodTypesExt) { 2846 uint64_t Size = 2847 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy); 2848 llvm::Constant *Values[] = { 2849 llvm::ConstantInt::get(ObjCTypes.IntTy, Size), 2850 EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getName(), 2851 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 2852 OptInstanceMethods), 2853 EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(), 2854 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 2855 OptClassMethods), 2856 EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD, 2857 ObjCTypes, false), 2858 EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(), 2859 MethodTypesExt, ObjCTypes), 2860 EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr, 2861 PD, ObjCTypes, true)}; 2862 2863 // Return null if no extension bits are used. 2864 if (Values[1]->isNullValue() && Values[2]->isNullValue() && 2865 Values[3]->isNullValue() && Values[4]->isNullValue() && 2866 Values[5]->isNullValue()) 2867 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 2868 2869 llvm::Constant *Init = 2870 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); 2871 2872 // No special section, but goes in llvm.used 2873 return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init, 2874 StringRef(), CGM.getPointerAlign(), true); 2875 } 2876 2877 /* 2878 struct objc_protocol_list { 2879 struct objc_protocol_list *next; 2880 long count; 2881 Protocol *list[]; 2882 }; 2883 */ 2884 llvm::Constant * 2885 CGObjCMac::EmitProtocolList(Twine Name, 2886 ObjCProtocolDecl::protocol_iterator begin, 2887 ObjCProtocolDecl::protocol_iterator end) { 2888 SmallVector<llvm::Constant *, 16> ProtocolRefs; 2889 2890 for (; begin != end; ++begin) 2891 ProtocolRefs.push_back(GetProtocolRef(*begin)); 2892 2893 // Just return null for empty protocol lists 2894 if (ProtocolRefs.empty()) 2895 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 2896 2897 // This list is null terminated. 2898 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); 2899 2900 llvm::Constant *Values[3]; 2901 // This field is only used by the runtime. 2902 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 2903 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, 2904 ProtocolRefs.size() - 1); 2905 Values[2] = 2906 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, 2907 ProtocolRefs.size()), 2908 ProtocolRefs); 2909 2910 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 2911 llvm::GlobalVariable *GV = 2912 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip", 2913 CGM.getPointerAlign(), false); 2914 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); 2915 } 2916 2917 void CGObjCCommonMac:: 2918 PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet, 2919 SmallVectorImpl<llvm::Constant *> &Properties, 2920 const Decl *Container, 2921 const ObjCProtocolDecl *Proto, 2922 const ObjCCommonTypesHelper &ObjCTypes, 2923 bool IsClassProperty) { 2924 for (const auto *P : Proto->protocols()) 2925 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes, 2926 IsClassProperty); 2927 2928 for (const auto *PD : Proto->properties()) { 2929 if (IsClassProperty != PD->isClassProperty()) 2930 continue; 2931 if (!PropertySet.insert(PD->getIdentifier()).second) 2932 continue; 2933 llvm::Constant *Prop[] = { 2934 GetPropertyName(PD->getIdentifier()), 2935 GetPropertyTypeString(PD, Container) 2936 }; 2937 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop)); 2938 } 2939 } 2940 2941 /* 2942 struct _objc_property { 2943 const char * const name; 2944 const char * const attributes; 2945 }; 2946 2947 struct _objc_property_list { 2948 uint32_t entsize; // sizeof (struct _objc_property) 2949 uint32_t prop_count; 2950 struct _objc_property[prop_count]; 2951 }; 2952 */ 2953 llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name, 2954 const Decl *Container, 2955 const ObjCContainerDecl *OCD, 2956 const ObjCCommonTypesHelper &ObjCTypes, 2957 bool IsClassProperty) { 2958 if (IsClassProperty) { 2959 // Make this entry NULL for OS X with deployment target < 10.11, for iOS 2960 // with deployment target < 9.0. 2961 const llvm::Triple &Triple = CGM.getTarget().getTriple(); 2962 if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) || 2963 (Triple.isiOS() && Triple.isOSVersionLT(9))) 2964 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 2965 } 2966 2967 SmallVector<llvm::Constant *, 16> Properties; 2968 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet; 2969 2970 auto AddProperty = [&](const ObjCPropertyDecl *PD) { 2971 llvm::Constant *Prop[] = {GetPropertyName(PD->getIdentifier()), 2972 GetPropertyTypeString(PD, Container)}; 2973 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop)); 2974 }; 2975 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) 2976 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions()) 2977 for (auto *PD : ClassExt->properties()) { 2978 if (IsClassProperty != PD->isClassProperty()) 2979 continue; 2980 PropertySet.insert(PD->getIdentifier()); 2981 AddProperty(PD); 2982 } 2983 2984 for (const auto *PD : OCD->properties()) { 2985 if (IsClassProperty != PD->isClassProperty()) 2986 continue; 2987 // Don't emit duplicate metadata for properties that were already in a 2988 // class extension. 2989 if (!PropertySet.insert(PD->getIdentifier()).second) 2990 continue; 2991 AddProperty(PD); 2992 } 2993 2994 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) { 2995 for (const auto *P : OID->all_referenced_protocols()) 2996 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes, 2997 IsClassProperty); 2998 } 2999 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) { 3000 for (const auto *P : CD->protocols()) 3001 PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes, 3002 IsClassProperty); 3003 } 3004 3005 // Return null for empty list. 3006 if (Properties.empty()) 3007 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 3008 3009 unsigned PropertySize = 3010 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy); 3011 llvm::Constant *Values[3]; 3012 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); 3013 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); 3014 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, 3015 Properties.size()); 3016 Values[2] = llvm::ConstantArray::get(AT, Properties); 3017 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 3018 3019 llvm::GlobalVariable *GV = 3020 CreateMetadataVar(Name, Init, 3021 (ObjCABI == 2) ? "__DATA, __objc_const" : 3022 "__OBJC,__property,regular,no_dead_strip", 3023 CGM.getPointerAlign(), 3024 true); 3025 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy); 3026 } 3027 3028 llvm::Constant * 3029 CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name, 3030 ArrayRef<llvm::Constant*> MethodTypes, 3031 const ObjCCommonTypesHelper &ObjCTypes) { 3032 // Return null for empty list. 3033 if (MethodTypes.empty()) 3034 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy); 3035 3036 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 3037 MethodTypes.size()); 3038 llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes); 3039 3040 llvm::GlobalVariable *GV = CreateMetadataVar( 3041 Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(), 3042 CGM.getPointerAlign(), true); 3043 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy); 3044 } 3045 3046 /* 3047 struct objc_method_description_list { 3048 int count; 3049 struct objc_method_description list[]; 3050 }; 3051 */ 3052 llvm::Constant * 3053 CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 3054 llvm::Constant *Desc[] = { 3055 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 3056 ObjCTypes.SelectorPtrTy), 3057 GetMethodVarType(MD) 3058 }; 3059 if (!Desc[1]) 3060 return nullptr; 3061 3062 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, 3063 Desc); 3064 } 3065 3066 llvm::Constant * 3067 CGObjCMac::EmitMethodDescList(Twine Name, StringRef Section, 3068 ArrayRef<llvm::Constant *> Methods) { 3069 // Return null for empty list. 3070 if (Methods.empty()) 3071 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 3072 3073 llvm::Constant *Values[2]; 3074 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 3075 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, 3076 Methods.size()); 3077 Values[1] = llvm::ConstantArray::get(AT, Methods); 3078 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 3079 3080 llvm::GlobalVariable *GV = 3081 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true); 3082 return llvm::ConstantExpr::getBitCast(GV, 3083 ObjCTypes.MethodDescriptionListPtrTy); 3084 } 3085 3086 /* 3087 struct _objc_category { 3088 char *category_name; 3089 char *class_name; 3090 struct _objc_method_list *instance_methods; 3091 struct _objc_method_list *class_methods; 3092 struct _objc_protocol_list *protocols; 3093 uint32_t size; // <rdar://4585769> 3094 struct _objc_property_list *instance_properties; 3095 struct _objc_property_list *class_properties; 3096 }; 3097 */ 3098 void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 3099 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy); 3100 3101 // FIXME: This is poor design, the OCD should have a pointer to the category 3102 // decl. Additionally, note that Category can be null for the @implementation 3103 // w/o an @interface case. Sema should just create one for us as it does for 3104 // @implementation so everyone else can live life under a clear blue sky. 3105 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 3106 const ObjCCategoryDecl *Category = 3107 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 3108 3109 SmallString<256> ExtName; 3110 llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_' 3111 << OCD->getName(); 3112 3113 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods; 3114 for (const auto *I : OCD->instance_methods()) 3115 // Instance methods should always be defined. 3116 InstanceMethods.push_back(GetMethodConstant(I)); 3117 3118 for (const auto *I : OCD->class_methods()) 3119 // Class methods should always be defined. 3120 ClassMethods.push_back(GetMethodConstant(I)); 3121 3122 llvm::Constant *Values[8]; 3123 Values[0] = GetClassName(OCD->getName()); 3124 Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString()); 3125 LazySymbols.insert(Interface->getIdentifier()); 3126 Values[2] = EmitMethodList("OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(), 3127 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 3128 InstanceMethods); 3129 Values[3] = EmitMethodList("OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(), 3130 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 3131 ClassMethods); 3132 if (Category) { 3133 Values[4] = 3134 EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(), 3135 Category->protocol_begin(), Category->protocol_end()); 3136 } else { 3137 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 3138 } 3139 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 3140 3141 // If there is no category @interface then there can be no properties. 3142 if (Category) { 3143 Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(), 3144 OCD, Category, ObjCTypes, false); 3145 Values[7] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(), 3146 OCD, Category, ObjCTypes, true); 3147 } else { 3148 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 3149 Values[7] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 3150 } 3151 3152 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, 3153 Values); 3154 3155 llvm::GlobalVariable *GV = 3156 CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Init, 3157 "__OBJC,__category,regular,no_dead_strip", 3158 CGM.getPointerAlign(), true); 3159 DefinedCategories.push_back(GV); 3160 DefinedCategoryNames.insert(llvm::CachedHashString(ExtName)); 3161 // method definition entries must be clear for next implementation. 3162 MethodDefinitions.clear(); 3163 } 3164 3165 enum FragileClassFlags { 3166 /// Apparently: is not a meta-class. 3167 FragileABI_Class_Factory = 0x00001, 3168 3169 /// Is a meta-class. 3170 FragileABI_Class_Meta = 0x00002, 3171 3172 /// Has a non-trivial constructor or destructor. 3173 FragileABI_Class_HasCXXStructors = 0x02000, 3174 3175 /// Has hidden visibility. 3176 FragileABI_Class_Hidden = 0x20000, 3177 3178 /// Class implementation was compiled under ARC. 3179 FragileABI_Class_CompiledByARC = 0x04000000, 3180 3181 /// Class implementation was compiled under MRC and has MRC weak ivars. 3182 /// Exclusive with CompiledByARC. 3183 FragileABI_Class_HasMRCWeakIvars = 0x08000000, 3184 }; 3185 3186 enum NonFragileClassFlags { 3187 /// Is a meta-class. 3188 NonFragileABI_Class_Meta = 0x00001, 3189 3190 /// Is a root class. 3191 NonFragileABI_Class_Root = 0x00002, 3192 3193 /// Has a non-trivial constructor or destructor. 3194 NonFragileABI_Class_HasCXXStructors = 0x00004, 3195 3196 /// Has hidden visibility. 3197 NonFragileABI_Class_Hidden = 0x00010, 3198 3199 /// Has the exception attribute. 3200 NonFragileABI_Class_Exception = 0x00020, 3201 3202 /// (Obsolete) ARC-specific: this class has a .release_ivars method 3203 NonFragileABI_Class_HasIvarReleaser = 0x00040, 3204 3205 /// Class implementation was compiled under ARC. 3206 NonFragileABI_Class_CompiledByARC = 0x00080, 3207 3208 /// Class has non-trivial destructors, but zero-initialization is okay. 3209 NonFragileABI_Class_HasCXXDestructorOnly = 0x00100, 3210 3211 /// Class implementation was compiled under MRC and has MRC weak ivars. 3212 /// Exclusive with CompiledByARC. 3213 NonFragileABI_Class_HasMRCWeakIvars = 0x00200, 3214 }; 3215 3216 static bool hasWeakMember(QualType type) { 3217 if (type.getObjCLifetime() == Qualifiers::OCL_Weak) { 3218 return true; 3219 } 3220 3221 if (auto recType = type->getAs<RecordType>()) { 3222 for (auto field : recType->getDecl()->fields()) { 3223 if (hasWeakMember(field->getType())) 3224 return true; 3225 } 3226 } 3227 3228 return false; 3229 } 3230 3231 /// For compatibility, we only want to set the "HasMRCWeakIvars" flag 3232 /// (and actually fill in a layout string) if we really do have any 3233 /// __weak ivars. 3234 static bool hasMRCWeakIvars(CodeGenModule &CGM, 3235 const ObjCImplementationDecl *ID) { 3236 if (!CGM.getLangOpts().ObjCWeak) return false; 3237 assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); 3238 3239 for (const ObjCIvarDecl *ivar = 3240 ID->getClassInterface()->all_declared_ivar_begin(); 3241 ivar; ivar = ivar->getNextIvar()) { 3242 if (hasWeakMember(ivar->getType())) 3243 return true; 3244 } 3245 3246 return false; 3247 } 3248 3249 /* 3250 struct _objc_class { 3251 Class isa; 3252 Class super_class; 3253 const char *name; 3254 long version; 3255 long info; 3256 long instance_size; 3257 struct _objc_ivar_list *ivars; 3258 struct _objc_method_list *methods; 3259 struct _objc_cache *cache; 3260 struct _objc_protocol_list *protocols; 3261 // Objective-C 1.0 extensions (<rdr://4585769>) 3262 const char *ivar_layout; 3263 struct _objc_class_ext *ext; 3264 }; 3265 3266 See EmitClassExtension(); 3267 */ 3268 void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { 3269 DefinedSymbols.insert(ID->getIdentifier()); 3270 3271 std::string ClassName = ID->getNameAsString(); 3272 // FIXME: Gross 3273 ObjCInterfaceDecl *Interface = 3274 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 3275 llvm::Constant *Protocols = 3276 EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(), 3277 Interface->all_referenced_protocol_begin(), 3278 Interface->all_referenced_protocol_end()); 3279 unsigned Flags = FragileABI_Class_Factory; 3280 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) 3281 Flags |= FragileABI_Class_HasCXXStructors; 3282 3283 bool hasMRCWeak = false; 3284 3285 if (CGM.getLangOpts().ObjCAutoRefCount) 3286 Flags |= FragileABI_Class_CompiledByARC; 3287 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID))) 3288 Flags |= FragileABI_Class_HasMRCWeakIvars; 3289 3290 CharUnits Size = 3291 CGM.getContext().getASTObjCImplementationLayout(ID).getSize(); 3292 3293 // FIXME: Set CXX-structors flag. 3294 if (ID->getClassInterface()->getVisibility() == HiddenVisibility) 3295 Flags |= FragileABI_Class_Hidden; 3296 3297 SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods; 3298 for (const auto *I : ID->instance_methods()) 3299 // Instance methods should always be defined. 3300 InstanceMethods.push_back(GetMethodConstant(I)); 3301 3302 for (const auto *I : ID->class_methods()) 3303 // Class methods should always be defined. 3304 ClassMethods.push_back(GetMethodConstant(I)); 3305 3306 for (const auto *PID : ID->property_impls()) { 3307 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3308 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3309 3310 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 3311 if (llvm::Constant *C = GetMethodConstant(MD)) 3312 InstanceMethods.push_back(C); 3313 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 3314 if (llvm::Constant *C = GetMethodConstant(MD)) 3315 InstanceMethods.push_back(C); 3316 } 3317 } 3318 3319 llvm::Constant *Values[12]; 3320 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods); 3321 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { 3322 // Record a reference to the super class. 3323 LazySymbols.insert(Super->getIdentifier()); 3324 3325 Values[ 1] = 3326 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()), 3327 ObjCTypes.ClassPtrTy); 3328 } else { 3329 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 3330 } 3331 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString()); 3332 // Version is always 0. 3333 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 3334 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 3335 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size.getQuantity()); 3336 Values[ 6] = EmitIvarList(ID, false); 3337 Values[7] = EmitMethodList("OBJC_INSTANCE_METHODS_" + ID->getName(), 3338 "__OBJC,__inst_meth,regular,no_dead_strip", 3339 InstanceMethods); 3340 // cache is always NULL. 3341 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 3342 Values[ 9] = Protocols; 3343 Values[10] = BuildStrongIvarLayout(ID, CharUnits::Zero(), Size); 3344 Values[11] = EmitClassExtension(ID, Size, hasMRCWeak, 3345 false/*isClassProperty*/); 3346 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 3347 Values); 3348 std::string Name("OBJC_CLASS_"); 3349 Name += ClassName; 3350 const char *Section = "__OBJC,__class,regular,no_dead_strip"; 3351 // Check for a forward reference. 3352 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 3353 if (GV) { 3354 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 3355 "Forward metaclass reference has incorrect type."); 3356 GV->setInitializer(Init); 3357 GV->setSection(Section); 3358 GV->setAlignment(CGM.getPointerAlign().getQuantity()); 3359 CGM.addCompilerUsedGlobal(GV); 3360 } else 3361 GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true); 3362 DefinedClasses.push_back(GV); 3363 ImplementedClasses.push_back(Interface); 3364 // method definition entries must be clear for next implementation. 3365 MethodDefinitions.clear(); 3366 } 3367 3368 llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, 3369 llvm::Constant *Protocols, 3370 ArrayRef<llvm::Constant*> Methods) { 3371 unsigned Flags = FragileABI_Class_Meta; 3372 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy); 3373 3374 if (ID->getClassInterface()->getVisibility() == HiddenVisibility) 3375 Flags |= FragileABI_Class_Hidden; 3376 3377 llvm::Constant *Values[12]; 3378 // The isa for the metaclass is the root of the hierarchy. 3379 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 3380 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 3381 Root = Super; 3382 Values[ 0] = 3383 llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()), 3384 ObjCTypes.ClassPtrTy); 3385 // The super class for the metaclass is emitted as the name of the 3386 // super class. The runtime fixes this up to point to the 3387 // *metaclass* for the super class. 3388 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { 3389 Values[ 1] = 3390 llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()), 3391 ObjCTypes.ClassPtrTy); 3392 } else { 3393 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 3394 } 3395 Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString()); 3396 // Version is always 0. 3397 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 3398 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 3399 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 3400 Values[ 6] = EmitIvarList(ID, true); 3401 Values[7] = 3402 EmitMethodList("OBJC_CLASS_METHODS_" + ID->getNameAsString(), 3403 "__OBJC,__cls_meth,regular,no_dead_strip", Methods); 3404 // cache is always NULL. 3405 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 3406 Values[ 9] = Protocols; 3407 // ivar_layout for metaclass is always NULL. 3408 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 3409 // The class extension is used to store class properties for metaclasses. 3410 Values[11] = EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/, 3411 true/*isClassProperty*/); 3412 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 3413 Values); 3414 3415 std::string Name("OBJC_METACLASS_"); 3416 Name += ID->getName(); 3417 3418 // Check for a forward reference. 3419 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 3420 if (GV) { 3421 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 3422 "Forward metaclass reference has incorrect type."); 3423 GV->setInitializer(Init); 3424 } else { 3425 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false, 3426 llvm::GlobalValue::PrivateLinkage, 3427 Init, Name); 3428 } 3429 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); 3430 GV->setAlignment(4); 3431 CGM.addCompilerUsedGlobal(GV); 3432 3433 return GV; 3434 } 3435 3436 llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { 3437 std::string Name = "OBJC_METACLASS_" + ID->getNameAsString(); 3438 3439 // FIXME: Should we look these up somewhere other than the module. Its a bit 3440 // silly since we only generate these while processing an implementation, so 3441 // exactly one pointer would work if know when we entered/exitted an 3442 // implementation block. 3443 3444 // Check for an existing forward reference. 3445 // Previously, metaclass with internal linkage may have been defined. 3446 // pass 'true' as 2nd argument so it is returned. 3447 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 3448 if (!GV) 3449 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false, 3450 llvm::GlobalValue::PrivateLinkage, nullptr, 3451 Name); 3452 3453 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 3454 "Forward metaclass reference has incorrect type."); 3455 return GV; 3456 } 3457 3458 llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) { 3459 std::string Name = "OBJC_CLASS_" + ID->getNameAsString(); 3460 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 3461 3462 if (!GV) 3463 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false, 3464 llvm::GlobalValue::PrivateLinkage, nullptr, 3465 Name); 3466 3467 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 3468 "Forward class metadata reference has incorrect type."); 3469 return GV; 3470 } 3471 3472 /* 3473 Emit a "class extension", which in this specific context means extra 3474 data that doesn't fit in the normal fragile-ABI class structure, and 3475 has nothing to do with the language concept of a class extension. 3476 3477 struct objc_class_ext { 3478 uint32_t size; 3479 const char *weak_ivar_layout; 3480 struct _objc_property_list *properties; 3481 }; 3482 */ 3483 llvm::Constant * 3484 CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID, 3485 CharUnits InstanceSize, bool hasMRCWeakIvars, 3486 bool isClassProperty) { 3487 uint64_t Size = 3488 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy); 3489 3490 llvm::Constant *Values[3]; 3491 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 3492 if (isClassProperty) { 3493 llvm::Type *PtrTy = CGM.Int8PtrTy; 3494 Values[1] = llvm::Constant::getNullValue(PtrTy); 3495 } else 3496 Values[1] = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize, 3497 hasMRCWeakIvars); 3498 if (isClassProperty) 3499 Values[2] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getName(), 3500 ID, ID->getClassInterface(), ObjCTypes, true); 3501 else 3502 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(), 3503 ID, ID->getClassInterface(), ObjCTypes, false); 3504 3505 // Return null if no extension bits are used. 3506 if ((!Values[1] || Values[1]->isNullValue()) && Values[2]->isNullValue()) 3507 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 3508 3509 llvm::Constant *Init = 3510 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); 3511 return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), Init, 3512 "__OBJC,__class_ext,regular,no_dead_strip", 3513 CGM.getPointerAlign(), true); 3514 } 3515 3516 /* 3517 struct objc_ivar { 3518 char *ivar_name; 3519 char *ivar_type; 3520 int ivar_offset; 3521 }; 3522 3523 struct objc_ivar_list { 3524 int ivar_count; 3525 struct objc_ivar list[count]; 3526 }; 3527 */ 3528 llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, 3529 bool ForClass) { 3530 std::vector<llvm::Constant*> Ivars; 3531 3532 // When emitting the root class GCC emits ivar entries for the 3533 // actual class structure. It is not clear if we need to follow this 3534 // behavior; for now lets try and get away with not doing it. If so, 3535 // the cleanest solution would be to make up an ObjCInterfaceDecl 3536 // for the class. 3537 if (ForClass) 3538 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 3539 3540 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 3541 3542 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 3543 IVD; IVD = IVD->getNextIvar()) { 3544 // Ignore unnamed bit-fields. 3545 if (!IVD->getDeclName()) 3546 continue; 3547 llvm::Constant *Ivar[] = { 3548 GetMethodVarName(IVD->getIdentifier()), 3549 GetMethodVarType(IVD), 3550 llvm::ConstantInt::get(ObjCTypes.IntTy, 3551 ComputeIvarBaseOffset(CGM, OID, IVD)) 3552 }; 3553 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar)); 3554 } 3555 3556 // Return null for empty list. 3557 if (Ivars.empty()) 3558 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 3559 3560 llvm::Constant *Values[2]; 3561 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 3562 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, 3563 Ivars.size()); 3564 Values[1] = llvm::ConstantArray::get(AT, Ivars); 3565 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 3566 3567 llvm::GlobalVariable *GV; 3568 if (ForClass) 3569 GV = 3570 CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), Init, 3571 "__OBJC,__class_vars,regular,no_dead_strip", 3572 CGM.getPointerAlign(), true); 3573 else 3574 GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), Init, 3575 "__OBJC,__instance_vars,regular,no_dead_strip", 3576 CGM.getPointerAlign(), true); 3577 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy); 3578 } 3579 3580 /* 3581 struct objc_method { 3582 SEL method_name; 3583 char *method_types; 3584 void *method; 3585 }; 3586 3587 struct objc_method_list { 3588 struct objc_method_list *obsolete; 3589 int count; 3590 struct objc_method methods_list[count]; 3591 }; 3592 */ 3593 3594 /// GetMethodConstant - Return a struct objc_method constant for the 3595 /// given method if it has been defined. The result is null if the 3596 /// method has not been defined. The return value has type MethodPtrTy. 3597 llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { 3598 llvm::Function *Fn = GetMethodDefinition(MD); 3599 if (!Fn) 3600 return nullptr; 3601 3602 llvm::Constant *Method[] = { 3603 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 3604 ObjCTypes.SelectorPtrTy), 3605 GetMethodVarType(MD), 3606 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy) 3607 }; 3608 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 3609 } 3610 3611 llvm::Constant *CGObjCMac::EmitMethodList(Twine Name, StringRef Section, 3612 ArrayRef<llvm::Constant *> Methods) { 3613 // Return null for empty list. 3614 if (Methods.empty()) 3615 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); 3616 3617 llvm::Constant *Values[3]; 3618 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 3619 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 3620 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 3621 Methods.size()); 3622 Values[2] = llvm::ConstantArray::get(AT, Methods); 3623 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 3624 3625 llvm::GlobalVariable *GV = 3626 CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true); 3627 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy); 3628 } 3629 3630 llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD, 3631 const ObjCContainerDecl *CD) { 3632 SmallString<256> Name; 3633 GetNameForMethod(OMD, CD, Name); 3634 3635 CodeGenTypes &Types = CGM.getTypes(); 3636 llvm::FunctionType *MethodTy = 3637 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD)); 3638 llvm::Function *Method = 3639 llvm::Function::Create(MethodTy, 3640 llvm::GlobalValue::InternalLinkage, 3641 Name.str(), 3642 &CGM.getModule()); 3643 MethodDefinitions.insert(std::make_pair(OMD, Method)); 3644 3645 return Method; 3646 } 3647 3648 llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name, 3649 llvm::Constant *Init, 3650 StringRef Section, 3651 CharUnits Align, 3652 bool AddToUsed) { 3653 llvm::Type *Ty = Init->getType(); 3654 llvm::GlobalVariable *GV = 3655 new llvm::GlobalVariable(CGM.getModule(), Ty, false, 3656 llvm::GlobalValue::PrivateLinkage, Init, Name); 3657 if (!Section.empty()) 3658 GV->setSection(Section); 3659 GV->setAlignment(Align.getQuantity()); 3660 if (AddToUsed) 3661 CGM.addCompilerUsedGlobal(GV); 3662 return GV; 3663 } 3664 3665 llvm::GlobalVariable * 3666 CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type, 3667 bool ForceNonFragileABI, 3668 bool NullTerminate) { 3669 StringRef Label; 3670 switch (Type) { 3671 case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break; 3672 case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break; 3673 case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break; 3674 case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break; 3675 } 3676 3677 bool NonFragile = ForceNonFragileABI || isNonFragileABI(); 3678 3679 StringRef Section; 3680 switch (Type) { 3681 case ObjCLabelType::ClassName: 3682 Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals" 3683 : "__TEXT,__cstring,cstring_literals"; 3684 break; 3685 case ObjCLabelType::MethodVarName: 3686 Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals" 3687 : "__TEXT,__cstring,cstring_literals"; 3688 break; 3689 case ObjCLabelType::MethodVarType: 3690 Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals" 3691 : "__TEXT,__cstring,cstring_literals"; 3692 break; 3693 case ObjCLabelType::PropertyName: 3694 Section = "__TEXT,__cstring,cstring_literals"; 3695 break; 3696 } 3697 3698 llvm::Constant *Value = 3699 llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate); 3700 llvm::GlobalVariable *GV = 3701 new llvm::GlobalVariable(CGM.getModule(), Value->getType(), 3702 /*isConstant=*/true, 3703 llvm::GlobalValue::PrivateLinkage, Value, Label); 3704 if (CGM.getTriple().isOSBinFormatMachO()) 3705 GV->setSection(Section); 3706 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3707 GV->setAlignment(CharUnits::One().getQuantity()); 3708 CGM.addCompilerUsedGlobal(GV); 3709 3710 return GV; 3711 } 3712 3713 llvm::Function *CGObjCMac::ModuleInitFunction() { 3714 // Abuse this interface function as a place to finalize. 3715 FinishModule(); 3716 return nullptr; 3717 } 3718 3719 llvm::Constant *CGObjCMac::GetPropertyGetFunction() { 3720 return ObjCTypes.getGetPropertyFn(); 3721 } 3722 3723 llvm::Constant *CGObjCMac::GetPropertySetFunction() { 3724 return ObjCTypes.getSetPropertyFn(); 3725 } 3726 3727 llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, 3728 bool copy) { 3729 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy); 3730 } 3731 3732 llvm::Constant *CGObjCMac::GetGetStructFunction() { 3733 return ObjCTypes.getCopyStructFn(); 3734 } 3735 3736 llvm::Constant *CGObjCMac::GetSetStructFunction() { 3737 return ObjCTypes.getCopyStructFn(); 3738 } 3739 3740 llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() { 3741 return ObjCTypes.getCppAtomicObjectFunction(); 3742 } 3743 3744 llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() { 3745 return ObjCTypes.getCppAtomicObjectFunction(); 3746 } 3747 3748 llvm::Constant *CGObjCMac::EnumerationMutationFunction() { 3749 return ObjCTypes.getEnumerationMutationFn(); 3750 } 3751 3752 void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) { 3753 return EmitTryOrSynchronizedStmt(CGF, S); 3754 } 3755 3756 void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF, 3757 const ObjCAtSynchronizedStmt &S) { 3758 return EmitTryOrSynchronizedStmt(CGF, S); 3759 } 3760 3761 namespace { 3762 struct PerformFragileFinally final : EHScopeStack::Cleanup { 3763 const Stmt &S; 3764 Address SyncArgSlot; 3765 Address CallTryExitVar; 3766 Address ExceptionData; 3767 ObjCTypesHelper &ObjCTypes; 3768 PerformFragileFinally(const Stmt *S, 3769 Address SyncArgSlot, 3770 Address CallTryExitVar, 3771 Address ExceptionData, 3772 ObjCTypesHelper *ObjCTypes) 3773 : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar), 3774 ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {} 3775 3776 void Emit(CodeGenFunction &CGF, Flags flags) override { 3777 // Check whether we need to call objc_exception_try_exit. 3778 // In optimized code, this branch will always be folded. 3779 llvm::BasicBlock *FinallyCallExit = 3780 CGF.createBasicBlock("finally.call_exit"); 3781 llvm::BasicBlock *FinallyNoCallExit = 3782 CGF.createBasicBlock("finally.no_call_exit"); 3783 CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar), 3784 FinallyCallExit, FinallyNoCallExit); 3785 3786 CGF.EmitBlock(FinallyCallExit); 3787 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(), 3788 ExceptionData.getPointer()); 3789 3790 CGF.EmitBlock(FinallyNoCallExit); 3791 3792 if (isa<ObjCAtTryStmt>(S)) { 3793 if (const ObjCAtFinallyStmt* FinallyStmt = 3794 cast<ObjCAtTryStmt>(S).getFinallyStmt()) { 3795 // Don't try to do the @finally if this is an EH cleanup. 3796 if (flags.isForEHCleanup()) return; 3797 3798 // Save the current cleanup destination in case there's 3799 // control flow inside the finally statement. 3800 llvm::Value *CurCleanupDest = 3801 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot()); 3802 3803 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 3804 3805 if (CGF.HaveInsertPoint()) { 3806 CGF.Builder.CreateStore(CurCleanupDest, 3807 CGF.getNormalCleanupDestSlot()); 3808 } else { 3809 // Currently, the end of the cleanup must always exist. 3810 CGF.EnsureInsertPoint(); 3811 } 3812 } 3813 } else { 3814 // Emit objc_sync_exit(expr); as finally's sole statement for 3815 // @synchronized. 3816 llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot); 3817 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg); 3818 } 3819 } 3820 }; 3821 3822 class FragileHazards { 3823 CodeGenFunction &CGF; 3824 SmallVector<llvm::Value*, 20> Locals; 3825 llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry; 3826 3827 llvm::InlineAsm *ReadHazard; 3828 llvm::InlineAsm *WriteHazard; 3829 3830 llvm::FunctionType *GetAsmFnType(); 3831 3832 void collectLocals(); 3833 void emitReadHazard(CGBuilderTy &Builder); 3834 3835 public: 3836 FragileHazards(CodeGenFunction &CGF); 3837 3838 void emitWriteHazard(); 3839 void emitHazardsInNewBlocks(); 3840 }; 3841 } // end anonymous namespace 3842 3843 /// Create the fragile-ABI read and write hazards based on the current 3844 /// state of the function, which is presumed to be immediately prior 3845 /// to a @try block. These hazards are used to maintain correct 3846 /// semantics in the face of optimization and the fragile ABI's 3847 /// cavalier use of setjmp/longjmp. 3848 FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) { 3849 collectLocals(); 3850 3851 if (Locals.empty()) return; 3852 3853 // Collect all the blocks in the function. 3854 for (llvm::Function::iterator 3855 I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I) 3856 BlocksBeforeTry.insert(&*I); 3857 3858 llvm::FunctionType *AsmFnTy = GetAsmFnType(); 3859 3860 // Create a read hazard for the allocas. This inhibits dead-store 3861 // optimizations and forces the values to memory. This hazard is 3862 // inserted before any 'throwing' calls in the protected scope to 3863 // reflect the possibility that the variables might be read from the 3864 // catch block if the call throws. 3865 { 3866 std::string Constraint; 3867 for (unsigned I = 0, E = Locals.size(); I != E; ++I) { 3868 if (I) Constraint += ','; 3869 Constraint += "*m"; 3870 } 3871 3872 ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false); 3873 } 3874 3875 // Create a write hazard for the allocas. This inhibits folding 3876 // loads across the hazard. This hazard is inserted at the 3877 // beginning of the catch path to reflect the possibility that the 3878 // variables might have been written within the protected scope. 3879 { 3880 std::string Constraint; 3881 for (unsigned I = 0, E = Locals.size(); I != E; ++I) { 3882 if (I) Constraint += ','; 3883 Constraint += "=*m"; 3884 } 3885 3886 WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false); 3887 } 3888 } 3889 3890 /// Emit a write hazard at the current location. 3891 void FragileHazards::emitWriteHazard() { 3892 if (Locals.empty()) return; 3893 3894 CGF.EmitNounwindRuntimeCall(WriteHazard, Locals); 3895 } 3896 3897 void FragileHazards::emitReadHazard(CGBuilderTy &Builder) { 3898 assert(!Locals.empty()); 3899 llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals); 3900 call->setDoesNotThrow(); 3901 call->setCallingConv(CGF.getRuntimeCC()); 3902 } 3903 3904 /// Emit read hazards in all the protected blocks, i.e. all the blocks 3905 /// which have been inserted since the beginning of the try. 3906 void FragileHazards::emitHazardsInNewBlocks() { 3907 if (Locals.empty()) return; 3908 3909 CGBuilderTy Builder(CGF, CGF.getLLVMContext()); 3910 3911 // Iterate through all blocks, skipping those prior to the try. 3912 for (llvm::Function::iterator 3913 FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) { 3914 llvm::BasicBlock &BB = *FI; 3915 if (BlocksBeforeTry.count(&BB)) continue; 3916 3917 // Walk through all the calls in the block. 3918 for (llvm::BasicBlock::iterator 3919 BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) { 3920 llvm::Instruction &I = *BI; 3921 3922 // Ignore instructions that aren't non-intrinsic calls. 3923 // These are the only calls that can possibly call longjmp. 3924 if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue; 3925 if (isa<llvm::IntrinsicInst>(I)) 3926 continue; 3927 3928 // Ignore call sites marked nounwind. This may be questionable, 3929 // since 'nounwind' doesn't necessarily mean 'does not call longjmp'. 3930 llvm::CallSite CS(&I); 3931 if (CS.doesNotThrow()) continue; 3932 3933 // Insert a read hazard before the call. This will ensure that 3934 // any writes to the locals are performed before making the 3935 // call. If the call throws, then this is sufficient to 3936 // guarantee correctness as long as it doesn't also write to any 3937 // locals. 3938 Builder.SetInsertPoint(&BB, BI); 3939 emitReadHazard(Builder); 3940 } 3941 } 3942 } 3943 3944 static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) { 3945 if (V) S.insert(V); 3946 } 3947 3948 static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) { 3949 if (V.isValid()) S.insert(V.getPointer()); 3950 } 3951 3952 void FragileHazards::collectLocals() { 3953 // Compute a set of allocas to ignore. 3954 llvm::DenseSet<llvm::Value*> AllocasToIgnore; 3955 addIfPresent(AllocasToIgnore, CGF.ReturnValue); 3956 addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest); 3957 3958 // Collect all the allocas currently in the function. This is 3959 // probably way too aggressive. 3960 llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock(); 3961 for (llvm::BasicBlock::iterator 3962 I = Entry.begin(), E = Entry.end(); I != E; ++I) 3963 if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I)) 3964 Locals.push_back(&*I); 3965 } 3966 3967 llvm::FunctionType *FragileHazards::GetAsmFnType() { 3968 SmallVector<llvm::Type *, 16> tys(Locals.size()); 3969 for (unsigned i = 0, e = Locals.size(); i != e; ++i) 3970 tys[i] = Locals[i]->getType(); 3971 return llvm::FunctionType::get(CGF.VoidTy, tys, false); 3972 } 3973 3974 /* 3975 3976 Objective-C setjmp-longjmp (sjlj) Exception Handling 3977 -- 3978 3979 A catch buffer is a setjmp buffer plus: 3980 - a pointer to the exception that was caught 3981 - a pointer to the previous exception data buffer 3982 - two pointers of reserved storage 3983 Therefore catch buffers form a stack, with a pointer to the top 3984 of the stack kept in thread-local storage. 3985 3986 objc_exception_try_enter pushes a catch buffer onto the EH stack. 3987 objc_exception_try_exit pops the given catch buffer, which is 3988 required to be the top of the EH stack. 3989 objc_exception_throw pops the top of the EH stack, writes the 3990 thrown exception into the appropriate field, and longjmps 3991 to the setjmp buffer. It crashes the process (with a printf 3992 and an abort()) if there are no catch buffers on the stack. 3993 objc_exception_extract just reads the exception pointer out of the 3994 catch buffer. 3995 3996 There's no reason an implementation couldn't use a light-weight 3997 setjmp here --- something like __builtin_setjmp, but API-compatible 3998 with the heavyweight setjmp. This will be more important if we ever 3999 want to implement correct ObjC/C++ exception interactions for the 4000 fragile ABI. 4001 4002 Note that for this use of setjmp/longjmp to be correct, we may need 4003 to mark some local variables volatile: if a non-volatile local 4004 variable is modified between the setjmp and the longjmp, it has 4005 indeterminate value. For the purposes of LLVM IR, it may be 4006 sufficient to make loads and stores within the @try (to variables 4007 declared outside the @try) volatile. This is necessary for 4008 optimized correctness, but is not currently being done; this is 4009 being tracked as rdar://problem/8160285 4010 4011 The basic framework for a @try-catch-finally is as follows: 4012 { 4013 objc_exception_data d; 4014 id _rethrow = null; 4015 bool _call_try_exit = true; 4016 4017 objc_exception_try_enter(&d); 4018 if (!setjmp(d.jmp_buf)) { 4019 ... try body ... 4020 } else { 4021 // exception path 4022 id _caught = objc_exception_extract(&d); 4023 4024 // enter new try scope for handlers 4025 if (!setjmp(d.jmp_buf)) { 4026 ... match exception and execute catch blocks ... 4027 4028 // fell off end, rethrow. 4029 _rethrow = _caught; 4030 ... jump-through-finally to finally_rethrow ... 4031 } else { 4032 // exception in catch block 4033 _rethrow = objc_exception_extract(&d); 4034 _call_try_exit = false; 4035 ... jump-through-finally to finally_rethrow ... 4036 } 4037 } 4038 ... jump-through-finally to finally_end ... 4039 4040 finally: 4041 if (_call_try_exit) 4042 objc_exception_try_exit(&d); 4043 4044 ... finally block .... 4045 ... dispatch to finally destination ... 4046 4047 finally_rethrow: 4048 objc_exception_throw(_rethrow); 4049 4050 finally_end: 4051 } 4052 4053 This framework differs slightly from the one gcc uses, in that gcc 4054 uses _rethrow to determine if objc_exception_try_exit should be called 4055 and if the object should be rethrown. This breaks in the face of 4056 throwing nil and introduces unnecessary branches. 4057 4058 We specialize this framework for a few particular circumstances: 4059 4060 - If there are no catch blocks, then we avoid emitting the second 4061 exception handling context. 4062 4063 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id 4064 e)) we avoid emitting the code to rethrow an uncaught exception. 4065 4066 - FIXME: If there is no @finally block we can do a few more 4067 simplifications. 4068 4069 Rethrows and Jumps-Through-Finally 4070 -- 4071 4072 '@throw;' is supported by pushing the currently-caught exception 4073 onto ObjCEHStack while the @catch blocks are emitted. 4074 4075 Branches through the @finally block are handled with an ordinary 4076 normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC 4077 exceptions are not compatible with C++ exceptions, and this is 4078 hardly the only place where this will go wrong. 4079 4080 @synchronized(expr) { stmt; } is emitted as if it were: 4081 id synch_value = expr; 4082 objc_sync_enter(synch_value); 4083 @try { stmt; } @finally { objc_sync_exit(synch_value); } 4084 */ 4085 4086 void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 4087 const Stmt &S) { 4088 bool isTry = isa<ObjCAtTryStmt>(S); 4089 4090 // A destination for the fall-through edges of the catch handlers to 4091 // jump to. 4092 CodeGenFunction::JumpDest FinallyEnd = 4093 CGF.getJumpDestInCurrentScope("finally.end"); 4094 4095 // A destination for the rethrow edge of the catch handlers to jump 4096 // to. 4097 CodeGenFunction::JumpDest FinallyRethrow = 4098 CGF.getJumpDestInCurrentScope("finally.rethrow"); 4099 4100 // For @synchronized, call objc_sync_enter(sync.expr). The 4101 // evaluation of the expression must occur before we enter the 4102 // @synchronized. We can't avoid a temp here because we need the 4103 // value to be preserved. If the backend ever does liveness 4104 // correctly after setjmp, this will be unnecessary. 4105 Address SyncArgSlot = Address::invalid(); 4106 if (!isTry) { 4107 llvm::Value *SyncArg = 4108 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 4109 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); 4110 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg); 4111 4112 SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), 4113 CGF.getPointerAlign(), "sync.arg"); 4114 CGF.Builder.CreateStore(SyncArg, SyncArgSlot); 4115 } 4116 4117 // Allocate memory for the setjmp buffer. This needs to be kept 4118 // live throughout the try and catch blocks. 4119 Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, 4120 CGF.getPointerAlign(), 4121 "exceptiondata.ptr"); 4122 4123 // Create the fragile hazards. Note that this will not capture any 4124 // of the allocas required for exception processing, but will 4125 // capture the current basic block (which extends all the way to the 4126 // setjmp call) as "before the @try". 4127 FragileHazards Hazards(CGF); 4128 4129 // Create a flag indicating whether the cleanup needs to call 4130 // objc_exception_try_exit. This is true except when 4131 // - no catches match and we're branching through the cleanup 4132 // just to rethrow the exception, or 4133 // - a catch matched and we're falling out of the catch handler. 4134 // The setjmp-safety rule here is that we should always store to this 4135 // variable in a place that dominates the branch through the cleanup 4136 // without passing through any setjmps. 4137 Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), 4138 CharUnits::One(), 4139 "_call_try_exit"); 4140 4141 // A slot containing the exception to rethrow. Only needed when we 4142 // have both a @catch and a @finally. 4143 Address PropagatingExnVar = Address::invalid(); 4144 4145 // Push a normal cleanup to leave the try scope. 4146 CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S, 4147 SyncArgSlot, 4148 CallTryExitVar, 4149 ExceptionData, 4150 &ObjCTypes); 4151 4152 // Enter a try block: 4153 // - Call objc_exception_try_enter to push ExceptionData on top of 4154 // the EH stack. 4155 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), 4156 ExceptionData.getPointer()); 4157 4158 // - Call setjmp on the exception data buffer. 4159 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0); 4160 llvm::Value *GEPIndexes[] = { Zero, Zero, Zero }; 4161 llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP( 4162 ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes, 4163 "setjmp_buffer"); 4164 llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall( 4165 ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result"); 4166 SetJmpResult->setCanReturnTwice(); 4167 4168 // If setjmp returned 0, enter the protected block; otherwise, 4169 // branch to the handler. 4170 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 4171 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 4172 llvm::Value *DidCatch = 4173 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception"); 4174 CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock); 4175 4176 // Emit the protected block. 4177 CGF.EmitBlock(TryBlock); 4178 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar); 4179 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 4180 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 4181 4182 CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP(); 4183 4184 // Emit the exception handler block. 4185 CGF.EmitBlock(TryHandler); 4186 4187 // Don't optimize loads of the in-scope locals across this point. 4188 Hazards.emitWriteHazard(); 4189 4190 // For a @synchronized (or a @try with no catches), just branch 4191 // through the cleanup to the rethrow block. 4192 if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) { 4193 // Tell the cleanup not to re-pop the exit. 4194 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar); 4195 CGF.EmitBranchThroughCleanup(FinallyRethrow); 4196 4197 // Otherwise, we have to match against the caught exceptions. 4198 } else { 4199 // Retrieve the exception object. We may emit multiple blocks but 4200 // nothing can cross this so the value is already in SSA form. 4201 llvm::CallInst *Caught = 4202 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(), 4203 ExceptionData.getPointer(), "caught"); 4204 4205 // Push the exception to rethrow onto the EH value stack for the 4206 // benefit of any @throws in the handlers. 4207 CGF.ObjCEHValueStack.push_back(Caught); 4208 4209 const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S); 4210 4211 bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr); 4212 4213 llvm::BasicBlock *CatchBlock = nullptr; 4214 llvm::BasicBlock *CatchHandler = nullptr; 4215 if (HasFinally) { 4216 // Save the currently-propagating exception before 4217 // objc_exception_try_enter clears the exception slot. 4218 PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(), 4219 CGF.getPointerAlign(), 4220 "propagating_exception"); 4221 CGF.Builder.CreateStore(Caught, PropagatingExnVar); 4222 4223 // Enter a new exception try block (in case a @catch block 4224 // throws an exception). 4225 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), 4226 ExceptionData.getPointer()); 4227 4228 llvm::CallInst *SetJmpResult = 4229 CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), 4230 SetJmpBuffer, "setjmp.result"); 4231 SetJmpResult->setCanReturnTwice(); 4232 4233 llvm::Value *Threw = 4234 CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception"); 4235 4236 CatchBlock = CGF.createBasicBlock("catch"); 4237 CatchHandler = CGF.createBasicBlock("catch_for_catch"); 4238 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); 4239 4240 CGF.EmitBlock(CatchBlock); 4241 } 4242 4243 CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar); 4244 4245 // Handle catch list. As a special case we check if everything is 4246 // matched and avoid generating code for falling off the end if 4247 // so. 4248 bool AllMatched = false; 4249 for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) { 4250 const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I); 4251 4252 const VarDecl *CatchParam = CatchStmt->getCatchParamDecl(); 4253 const ObjCObjectPointerType *OPT = nullptr; 4254 4255 // catch(...) always matches. 4256 if (!CatchParam) { 4257 AllMatched = true; 4258 } else { 4259 OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>(); 4260 4261 // catch(id e) always matches under this ABI, since only 4262 // ObjC exceptions end up here in the first place. 4263 // FIXME: For the time being we also match id<X>; this should 4264 // be rejected by Sema instead. 4265 if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType())) 4266 AllMatched = true; 4267 } 4268 4269 // If this is a catch-all, we don't need to test anything. 4270 if (AllMatched) { 4271 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF); 4272 4273 if (CatchParam) { 4274 CGF.EmitAutoVarDecl(*CatchParam); 4275 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 4276 4277 // These types work out because ConvertType(id) == i8*. 4278 EmitInitOfCatchParam(CGF, Caught, CatchParam); 4279 } 4280 4281 CGF.EmitStmt(CatchStmt->getCatchBody()); 4282 4283 // The scope of the catch variable ends right here. 4284 CatchVarCleanups.ForceCleanup(); 4285 4286 CGF.EmitBranchThroughCleanup(FinallyEnd); 4287 break; 4288 } 4289 4290 assert(OPT && "Unexpected non-object pointer type in @catch"); 4291 const ObjCObjectType *ObjTy = OPT->getObjectType(); 4292 4293 // FIXME: @catch (Class c) ? 4294 ObjCInterfaceDecl *IDecl = ObjTy->getInterface(); 4295 assert(IDecl && "Catch parameter must have Objective-C type!"); 4296 4297 // Check if the @catch block matches the exception object. 4298 llvm::Value *Class = EmitClassRef(CGF, IDecl); 4299 4300 llvm::Value *matchArgs[] = { Class, Caught }; 4301 llvm::CallInst *Match = 4302 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(), 4303 matchArgs, "match"); 4304 4305 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match"); 4306 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next"); 4307 4308 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), 4309 MatchedBlock, NextCatchBlock); 4310 4311 // Emit the @catch block. 4312 CGF.EmitBlock(MatchedBlock); 4313 4314 // Collect any cleanups for the catch variable. The scope lasts until 4315 // the end of the catch body. 4316 CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF); 4317 4318 CGF.EmitAutoVarDecl(*CatchParam); 4319 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 4320 4321 // Initialize the catch variable. 4322 llvm::Value *Tmp = 4323 CGF.Builder.CreateBitCast(Caught, 4324 CGF.ConvertType(CatchParam->getType())); 4325 EmitInitOfCatchParam(CGF, Tmp, CatchParam); 4326 4327 CGF.EmitStmt(CatchStmt->getCatchBody()); 4328 4329 // We're done with the catch variable. 4330 CatchVarCleanups.ForceCleanup(); 4331 4332 CGF.EmitBranchThroughCleanup(FinallyEnd); 4333 4334 CGF.EmitBlock(NextCatchBlock); 4335 } 4336 4337 CGF.ObjCEHValueStack.pop_back(); 4338 4339 // If nothing wanted anything to do with the caught exception, 4340 // kill the extract call. 4341 if (Caught->use_empty()) 4342 Caught->eraseFromParent(); 4343 4344 if (!AllMatched) 4345 CGF.EmitBranchThroughCleanup(FinallyRethrow); 4346 4347 if (HasFinally) { 4348 // Emit the exception handler for the @catch blocks. 4349 CGF.EmitBlock(CatchHandler); 4350 4351 // In theory we might now need a write hazard, but actually it's 4352 // unnecessary because there's no local-accessing code between 4353 // the try's write hazard and here. 4354 //Hazards.emitWriteHazard(); 4355 4356 // Extract the new exception and save it to the 4357 // propagating-exception slot. 4358 assert(PropagatingExnVar.isValid()); 4359 llvm::CallInst *NewCaught = 4360 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(), 4361 ExceptionData.getPointer(), "caught"); 4362 CGF.Builder.CreateStore(NewCaught, PropagatingExnVar); 4363 4364 // Don't pop the catch handler; the throw already did. 4365 CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar); 4366 CGF.EmitBranchThroughCleanup(FinallyRethrow); 4367 } 4368 } 4369 4370 // Insert read hazards as required in the new blocks. 4371 Hazards.emitHazardsInNewBlocks(); 4372 4373 // Pop the cleanup. 4374 CGF.Builder.restoreIP(TryFallthroughIP); 4375 if (CGF.HaveInsertPoint()) 4376 CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar); 4377 CGF.PopCleanupBlock(); 4378 CGF.EmitBlock(FinallyEnd.getBlock(), true); 4379 4380 // Emit the rethrow block. 4381 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 4382 CGF.EmitBlock(FinallyRethrow.getBlock(), true); 4383 if (CGF.HaveInsertPoint()) { 4384 // If we have a propagating-exception variable, check it. 4385 llvm::Value *PropagatingExn; 4386 if (PropagatingExnVar.isValid()) { 4387 PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar); 4388 4389 // Otherwise, just look in the buffer for the exception to throw. 4390 } else { 4391 llvm::CallInst *Caught = 4392 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(), 4393 ExceptionData.getPointer()); 4394 PropagatingExn = Caught; 4395 } 4396 4397 CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(), 4398 PropagatingExn); 4399 CGF.Builder.CreateUnreachable(); 4400 } 4401 4402 CGF.Builder.restoreIP(SavedIP); 4403 } 4404 4405 void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 4406 const ObjCAtThrowStmt &S, 4407 bool ClearInsertionPoint) { 4408 llvm::Value *ExceptionAsObject; 4409 4410 if (const Expr *ThrowExpr = S.getThrowExpr()) { 4411 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); 4412 ExceptionAsObject = 4413 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy); 4414 } else { 4415 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 4416 "Unexpected rethrow outside @catch block."); 4417 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 4418 } 4419 4420 CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject) 4421 ->setDoesNotReturn(); 4422 CGF.Builder.CreateUnreachable(); 4423 4424 // Clear the insertion point to indicate we are in unreachable code. 4425 if (ClearInsertionPoint) 4426 CGF.Builder.ClearInsertionPoint(); 4427 } 4428 4429 /// EmitObjCWeakRead - Code gen for loading value of a __weak 4430 /// object: objc_read_weak (id *src) 4431 /// 4432 llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 4433 Address AddrWeakObj) { 4434 llvm::Type* DestTy = AddrWeakObj.getElementType(); 4435 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, 4436 ObjCTypes.PtrObjectPtrTy); 4437 llvm::Value *read_weak = 4438 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(), 4439 AddrWeakObj.getPointer(), "weakread"); 4440 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); 4441 return read_weak; 4442 } 4443 4444 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 4445 /// objc_assign_weak (id src, id *dst) 4446 /// 4447 void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 4448 llvm::Value *src, Address dst) { 4449 llvm::Type * SrcTy = src->getType(); 4450 if (!isa<llvm::PointerType>(SrcTy)) { 4451 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4452 assert(Size <= 8 && "does not support size > 8"); 4453 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 4454 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 4455 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 4456 } 4457 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 4458 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 4459 llvm::Value *args[] = { src, dst.getPointer() }; 4460 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(), 4461 args, "weakassign"); 4462 } 4463 4464 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 4465 /// objc_assign_global (id src, id *dst) 4466 /// 4467 void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 4468 llvm::Value *src, Address dst, 4469 bool threadlocal) { 4470 llvm::Type * SrcTy = src->getType(); 4471 if (!isa<llvm::PointerType>(SrcTy)) { 4472 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4473 assert(Size <= 8 && "does not support size > 8"); 4474 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 4475 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 4476 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 4477 } 4478 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 4479 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 4480 llvm::Value *args[] = { src, dst.getPointer() }; 4481 if (!threadlocal) 4482 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(), 4483 args, "globalassign"); 4484 else 4485 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(), 4486 args, "threadlocalassign"); 4487 } 4488 4489 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 4490 /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset) 4491 /// 4492 void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 4493 llvm::Value *src, Address dst, 4494 llvm::Value *ivarOffset) { 4495 assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL"); 4496 llvm::Type * SrcTy = src->getType(); 4497 if (!isa<llvm::PointerType>(SrcTy)) { 4498 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4499 assert(Size <= 8 && "does not support size > 8"); 4500 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 4501 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 4502 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 4503 } 4504 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 4505 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 4506 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset }; 4507 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args); 4508 } 4509 4510 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 4511 /// objc_assign_strongCast (id src, id *dst) 4512 /// 4513 void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 4514 llvm::Value *src, Address dst) { 4515 llvm::Type * SrcTy = src->getType(); 4516 if (!isa<llvm::PointerType>(SrcTy)) { 4517 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4518 assert(Size <= 8 && "does not support size > 8"); 4519 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 4520 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 4521 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 4522 } 4523 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 4524 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 4525 llvm::Value *args[] = { src, dst.getPointer() }; 4526 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(), 4527 args, "strongassign"); 4528 } 4529 4530 void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 4531 Address DestPtr, 4532 Address SrcPtr, 4533 llvm::Value *size) { 4534 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy); 4535 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy); 4536 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size }; 4537 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args); 4538 } 4539 4540 /// EmitObjCValueForIvar - Code Gen for ivar reference. 4541 /// 4542 LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 4543 QualType ObjectTy, 4544 llvm::Value *BaseValue, 4545 const ObjCIvarDecl *Ivar, 4546 unsigned CVRQualifiers) { 4547 const ObjCInterfaceDecl *ID = 4548 ObjectTy->getAs<ObjCObjectType>()->getInterface(); 4549 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 4550 EmitIvarOffset(CGF, ID, Ivar)); 4551 } 4552 4553 llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 4554 const ObjCInterfaceDecl *Interface, 4555 const ObjCIvarDecl *Ivar) { 4556 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar); 4557 return llvm::ConstantInt::get( 4558 CGM.getTypes().ConvertType(CGM.getContext().LongTy), 4559 Offset); 4560 } 4561 4562 /* *** Private Interface *** */ 4563 4564 /// EmitImageInfo - Emit the image info marker used to encode some module 4565 /// level information. 4566 /// 4567 /// See: <rdr://4810609&4810587&4810587> 4568 /// struct IMAGE_INFO { 4569 /// unsigned version; 4570 /// unsigned flags; 4571 /// }; 4572 enum ImageInfoFlags { 4573 eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang. 4574 eImageInfo_GarbageCollected = (1 << 1), 4575 eImageInfo_GCOnly = (1 << 2), 4576 eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache. 4577 4578 // A flag indicating that the module has no instances of a @synthesize of a 4579 // superclass variable. <rdar://problem/6803242> 4580 eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang. 4581 eImageInfo_ImageIsSimulated = (1 << 5), 4582 eImageInfo_ClassProperties = (1 << 6) 4583 }; 4584 4585 void CGObjCCommonMac::EmitImageInfo() { 4586 unsigned version = 0; // Version is unused? 4587 const char *Section = (ObjCABI == 1) ? 4588 "__OBJC, __image_info,regular" : 4589 "__DATA, __objc_imageinfo, regular, no_dead_strip"; 4590 4591 // Generate module-level named metadata to convey this information to the 4592 // linker and code-gen. 4593 llvm::Module &Mod = CGM.getModule(); 4594 4595 // Add the ObjC ABI version to the module flags. 4596 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI); 4597 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version", 4598 version); 4599 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section", 4600 llvm::MDString::get(VMContext,Section)); 4601 4602 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { 4603 // Non-GC overrides those files which specify GC. 4604 Mod.addModuleFlag(llvm::Module::Override, 4605 "Objective-C Garbage Collection", (uint32_t)0); 4606 } else { 4607 // Add the ObjC garbage collection value. 4608 Mod.addModuleFlag(llvm::Module::Error, 4609 "Objective-C Garbage Collection", 4610 eImageInfo_GarbageCollected); 4611 4612 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 4613 // Add the ObjC GC Only value. 4614 Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only", 4615 eImageInfo_GCOnly); 4616 4617 // Require that GC be specified and set to eImageInfo_GarbageCollected. 4618 llvm::Metadata *Ops[2] = { 4619 llvm::MDString::get(VMContext, "Objective-C Garbage Collection"), 4620 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4621 llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))}; 4622 Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only", 4623 llvm::MDNode::get(VMContext, Ops)); 4624 } 4625 } 4626 4627 // Indicate whether we're compiling this to run on a simulator. 4628 const llvm::Triple &Triple = CGM.getTarget().getTriple(); 4629 if ((Triple.isiOS() || Triple.isWatchOS()) && 4630 (Triple.getArch() == llvm::Triple::x86 || 4631 Triple.getArch() == llvm::Triple::x86_64)) 4632 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated", 4633 eImageInfo_ImageIsSimulated); 4634 4635 // Indicate whether we are generating class properties. 4636 Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties", 4637 eImageInfo_ClassProperties); 4638 } 4639 4640 // struct objc_module { 4641 // unsigned long version; 4642 // unsigned long size; 4643 // const char *name; 4644 // Symtab symtab; 4645 // }; 4646 4647 // FIXME: Get from somewhere 4648 static const int ModuleVersion = 7; 4649 4650 void CGObjCMac::EmitModuleInfo() { 4651 uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy); 4652 4653 llvm::Constant *Values[] = { 4654 llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion), 4655 llvm::ConstantInt::get(ObjCTypes.LongTy, Size), 4656 // This used to be the filename, now it is unused. <rdr://4327263> 4657 GetClassName(StringRef("")), 4658 EmitModuleSymbols() 4659 }; 4660 CreateMetadataVar("OBJC_MODULES", 4661 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values), 4662 "__OBJC,__module_info,regular,no_dead_strip", 4663 CGM.getPointerAlign(), true); 4664 } 4665 4666 llvm::Constant *CGObjCMac::EmitModuleSymbols() { 4667 unsigned NumClasses = DefinedClasses.size(); 4668 unsigned NumCategories = DefinedCategories.size(); 4669 4670 // Return null if no symbols were defined. 4671 if (!NumClasses && !NumCategories) 4672 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); 4673 4674 llvm::Constant *Values[5]; 4675 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 4676 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); 4677 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); 4678 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); 4679 4680 // The runtime expects exactly the list of defined classes followed 4681 // by the list of defined categories, in a single array. 4682 SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories); 4683 for (unsigned i=0; i<NumClasses; i++) { 4684 const ObjCInterfaceDecl *ID = ImplementedClasses[i]; 4685 assert(ID); 4686 if (ObjCImplementationDecl *IMP = ID->getImplementation()) 4687 // We are implementing a weak imported interface. Give it external linkage 4688 if (ID->isWeakImported() && !IMP->isWeakImported()) 4689 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage); 4690 4691 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 4692 ObjCTypes.Int8PtrTy); 4693 } 4694 for (unsigned i=0; i<NumCategories; i++) 4695 Symbols[NumClasses + i] = 4696 llvm::ConstantExpr::getBitCast(DefinedCategories[i], 4697 ObjCTypes.Int8PtrTy); 4698 4699 Values[4] = 4700 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 4701 Symbols.size()), 4702 Symbols); 4703 4704 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 4705 4706 llvm::GlobalVariable *GV = CreateMetadataVar( 4707 "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip", 4708 CGM.getPointerAlign(), true); 4709 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); 4710 } 4711 4712 llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF, 4713 IdentifierInfo *II) { 4714 LazySymbols.insert(II); 4715 4716 llvm::GlobalVariable *&Entry = ClassReferences[II]; 4717 4718 if (!Entry) { 4719 llvm::Constant *Casted = 4720 llvm::ConstantExpr::getBitCast(GetClassName(II->getName()), 4721 ObjCTypes.ClassPtrTy); 4722 Entry = CreateMetadataVar( 4723 "OBJC_CLASS_REFERENCES_", Casted, 4724 "__OBJC,__cls_refs,literal_pointers,no_dead_strip", 4725 CGM.getPointerAlign(), true); 4726 } 4727 4728 return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign()); 4729 } 4730 4731 llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF, 4732 const ObjCInterfaceDecl *ID) { 4733 // If the class has the objc_runtime_visible attribute, we need to 4734 // use the Objective-C runtime to get the class. 4735 if (ID->hasAttr<ObjCRuntimeVisibleAttr>()) 4736 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes); 4737 4738 return EmitClassRefFromId(CGF, ID->getIdentifier()); 4739 } 4740 4741 llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { 4742 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool"); 4743 return EmitClassRefFromId(CGF, II); 4744 } 4745 4746 llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) { 4747 return CGF.Builder.CreateLoad(EmitSelectorAddr(CGF, Sel)); 4748 } 4749 4750 Address CGObjCMac::EmitSelectorAddr(CodeGenFunction &CGF, Selector Sel) { 4751 CharUnits Align = CGF.getPointerAlign(); 4752 4753 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 4754 if (!Entry) { 4755 llvm::Constant *Casted = 4756 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 4757 ObjCTypes.SelectorPtrTy); 4758 Entry = CreateMetadataVar( 4759 "OBJC_SELECTOR_REFERENCES_", Casted, 4760 "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true); 4761 Entry->setExternallyInitialized(true); 4762 } 4763 4764 return Address(Entry, Align); 4765 } 4766 4767 llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) { 4768 llvm::GlobalVariable *&Entry = ClassNames[RuntimeName]; 4769 if (!Entry) 4770 Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName); 4771 return getConstantGEP(VMContext, Entry, 0, 0); 4772 } 4773 4774 llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) { 4775 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator 4776 I = MethodDefinitions.find(MD); 4777 if (I != MethodDefinitions.end()) 4778 return I->second; 4779 4780 return nullptr; 4781 } 4782 4783 /// GetIvarLayoutName - Returns a unique constant for the given 4784 /// ivar layout bitmap. 4785 llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident, 4786 const ObjCCommonTypesHelper &ObjCTypes) { 4787 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 4788 } 4789 4790 void IvarLayoutBuilder::visitRecord(const RecordType *RT, 4791 CharUnits offset) { 4792 const RecordDecl *RD = RT->getDecl(); 4793 4794 // If this is a union, remember that we had one, because it might mess 4795 // up the ordering of layout entries. 4796 if (RD->isUnion()) 4797 IsDisordered = true; 4798 4799 const ASTRecordLayout *recLayout = nullptr; 4800 visitAggregate(RD->field_begin(), RD->field_end(), offset, 4801 [&](const FieldDecl *field) -> CharUnits { 4802 if (!recLayout) 4803 recLayout = &CGM.getContext().getASTRecordLayout(RD); 4804 auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex()); 4805 return CGM.getContext().toCharUnitsFromBits(offsetInBits); 4806 }); 4807 } 4808 4809 template <class Iterator, class GetOffsetFn> 4810 void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end, 4811 CharUnits aggregateOffset, 4812 const GetOffsetFn &getOffset) { 4813 for (; begin != end; ++begin) { 4814 auto field = *begin; 4815 4816 // Skip over bitfields. 4817 if (field->isBitField()) { 4818 continue; 4819 } 4820 4821 // Compute the offset of the field within the aggregate. 4822 CharUnits fieldOffset = aggregateOffset + getOffset(field); 4823 4824 visitField(field, fieldOffset); 4825 } 4826 } 4827 4828 /// Collect layout information for the given fields into IvarsInfo. 4829 void IvarLayoutBuilder::visitField(const FieldDecl *field, 4830 CharUnits fieldOffset) { 4831 QualType fieldType = field->getType(); 4832 4833 // Drill down into arrays. 4834 uint64_t numElts = 1; 4835 while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) { 4836 numElts *= arrayType->getSize().getZExtValue(); 4837 fieldType = arrayType->getElementType(); 4838 } 4839 4840 assert(!fieldType->isArrayType() && "ivar of non-constant array type?"); 4841 4842 // If we ended up with a zero-sized array, we've done what we can do within 4843 // the limits of this layout encoding. 4844 if (numElts == 0) return; 4845 4846 // Recurse if the base element type is a record type. 4847 if (auto recType = fieldType->getAs<RecordType>()) { 4848 size_t oldEnd = IvarsInfo.size(); 4849 4850 visitRecord(recType, fieldOffset); 4851 4852 // If we have an array, replicate the first entry's layout information. 4853 auto numEltEntries = IvarsInfo.size() - oldEnd; 4854 if (numElts != 1 && numEltEntries != 0) { 4855 CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType); 4856 for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) { 4857 // Copy the last numEltEntries onto the end of the array, adjusting 4858 // each for the element size. 4859 for (size_t i = 0; i != numEltEntries; ++i) { 4860 auto firstEntry = IvarsInfo[oldEnd + i]; 4861 IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize, 4862 firstEntry.SizeInWords)); 4863 } 4864 } 4865 } 4866 4867 return; 4868 } 4869 4870 // Classify the element type. 4871 Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType); 4872 4873 // If it matches what we're looking for, add an entry. 4874 if ((ForStrongLayout && GCAttr == Qualifiers::Strong) 4875 || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) { 4876 assert(CGM.getContext().getTypeSizeInChars(fieldType) 4877 == CGM.getPointerSize()); 4878 IvarsInfo.push_back(IvarInfo(fieldOffset, numElts)); 4879 } 4880 } 4881 4882 /// buildBitmap - This routine does the horsework of taking the offsets of 4883 /// strong/weak references and creating a bitmap. The bitmap is also 4884 /// returned in the given buffer, suitable for being passed to \c dump(). 4885 llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC, 4886 llvm::SmallVectorImpl<unsigned char> &buffer) { 4887 // The bitmap is a series of skip/scan instructions, aligned to word 4888 // boundaries. The skip is performed first. 4889 const unsigned char MaxNibble = 0xF; 4890 const unsigned char SkipMask = 0xF0, SkipShift = 4; 4891 const unsigned char ScanMask = 0x0F, ScanShift = 0; 4892 4893 assert(!IvarsInfo.empty() && "generating bitmap for no data"); 4894 4895 // Sort the ivar info on byte position in case we encounterred a 4896 // union nested in the ivar list. 4897 if (IsDisordered) { 4898 // This isn't a stable sort, but our algorithm should handle it fine. 4899 llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end()); 4900 } else { 4901 assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end())); 4902 } 4903 assert(IvarsInfo.back().Offset < InstanceEnd); 4904 4905 assert(buffer.empty()); 4906 4907 // Skip the next N words. 4908 auto skip = [&](unsigned numWords) { 4909 assert(numWords > 0); 4910 4911 // Try to merge into the previous byte. Since scans happen second, we 4912 // can't do this if it includes a scan. 4913 if (!buffer.empty() && !(buffer.back() & ScanMask)) { 4914 unsigned lastSkip = buffer.back() >> SkipShift; 4915 if (lastSkip < MaxNibble) { 4916 unsigned claimed = std::min(MaxNibble - lastSkip, numWords); 4917 numWords -= claimed; 4918 lastSkip += claimed; 4919 buffer.back() = (lastSkip << SkipShift); 4920 } 4921 } 4922 4923 while (numWords >= MaxNibble) { 4924 buffer.push_back(MaxNibble << SkipShift); 4925 numWords -= MaxNibble; 4926 } 4927 if (numWords) { 4928 buffer.push_back(numWords << SkipShift); 4929 } 4930 }; 4931 4932 // Scan the next N words. 4933 auto scan = [&](unsigned numWords) { 4934 assert(numWords > 0); 4935 4936 // Try to merge into the previous byte. Since scans happen second, we can 4937 // do this even if it includes a skip. 4938 if (!buffer.empty()) { 4939 unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift; 4940 if (lastScan < MaxNibble) { 4941 unsigned claimed = std::min(MaxNibble - lastScan, numWords); 4942 numWords -= claimed; 4943 lastScan += claimed; 4944 buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift); 4945 } 4946 } 4947 4948 while (numWords >= MaxNibble) { 4949 buffer.push_back(MaxNibble << ScanShift); 4950 numWords -= MaxNibble; 4951 } 4952 if (numWords) { 4953 buffer.push_back(numWords << ScanShift); 4954 } 4955 }; 4956 4957 // One past the end of the last scan. 4958 unsigned endOfLastScanInWords = 0; 4959 const CharUnits WordSize = CGM.getPointerSize(); 4960 4961 // Consider all the scan requests. 4962 for (auto &request : IvarsInfo) { 4963 CharUnits beginOfScan = request.Offset - InstanceBegin; 4964 4965 // Ignore scan requests that don't start at an even multiple of the 4966 // word size. We can't encode them. 4967 if ((beginOfScan % WordSize) != 0) continue; 4968 4969 // Ignore scan requests that start before the instance start. 4970 // This assumes that scans never span that boundary. The boundary 4971 // isn't the true start of the ivars, because in the fragile-ARC case 4972 // it's rounded up to word alignment, but the test above should leave 4973 // us ignoring that possibility. 4974 if (beginOfScan.isNegative()) { 4975 assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin); 4976 continue; 4977 } 4978 4979 unsigned beginOfScanInWords = beginOfScan / WordSize; 4980 unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords; 4981 4982 // If the scan starts some number of words after the last one ended, 4983 // skip forward. 4984 if (beginOfScanInWords > endOfLastScanInWords) { 4985 skip(beginOfScanInWords - endOfLastScanInWords); 4986 4987 // Otherwise, start scanning where the last left off. 4988 } else { 4989 beginOfScanInWords = endOfLastScanInWords; 4990 4991 // If that leaves us with nothing to scan, ignore this request. 4992 if (beginOfScanInWords >= endOfScanInWords) continue; 4993 } 4994 4995 // Scan to the end of the request. 4996 assert(beginOfScanInWords < endOfScanInWords); 4997 scan(endOfScanInWords - beginOfScanInWords); 4998 endOfLastScanInWords = endOfScanInWords; 4999 } 5000 5001 if (buffer.empty()) 5002 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy); 5003 5004 // For GC layouts, emit a skip to the end of the allocation so that we 5005 // have precise information about the entire thing. This isn't useful 5006 // or necessary for the ARC-style layout strings. 5007 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) { 5008 unsigned lastOffsetInWords = 5009 (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize; 5010 if (lastOffsetInWords > endOfLastScanInWords) { 5011 skip(lastOffsetInWords - endOfLastScanInWords); 5012 } 5013 } 5014 5015 // Null terminate the string. 5016 buffer.push_back(0); 5017 5018 auto *Entry = CGObjC.CreateCStringLiteral( 5019 reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName); 5020 return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0); 5021 } 5022 5023 /// BuildIvarLayout - Builds ivar layout bitmap for the class 5024 /// implementation for the __strong or __weak case. 5025 /// The layout map displays which words in ivar list must be skipped 5026 /// and which must be scanned by GC (see below). String is built of bytes. 5027 /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count 5028 /// of words to skip and right nibble is count of words to scan. So, each 5029 /// nibble represents up to 15 workds to skip or scan. Skipping the rest is 5030 /// represented by a 0x00 byte which also ends the string. 5031 /// 1. when ForStrongLayout is true, following ivars are scanned: 5032 /// - id, Class 5033 /// - object * 5034 /// - __strong anything 5035 /// 5036 /// 2. When ForStrongLayout is false, following ivars are scanned: 5037 /// - __weak anything 5038 /// 5039 llvm::Constant * 5040 CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD, 5041 CharUnits beginOffset, CharUnits endOffset, 5042 bool ForStrongLayout, bool HasMRCWeakIvars) { 5043 // If this is MRC, and we're either building a strong layout or there 5044 // are no weak ivars, bail out early. 5045 llvm::Type *PtrTy = CGM.Int8PtrTy; 5046 if (CGM.getLangOpts().getGC() == LangOptions::NonGC && 5047 !CGM.getLangOpts().ObjCAutoRefCount && 5048 (ForStrongLayout || !HasMRCWeakIvars)) 5049 return llvm::Constant::getNullValue(PtrTy); 5050 5051 const ObjCInterfaceDecl *OI = OMD->getClassInterface(); 5052 SmallVector<const ObjCIvarDecl*, 32> ivars; 5053 5054 // GC layout strings include the complete object layout, possibly 5055 // inaccurately in the non-fragile ABI; the runtime knows how to fix this 5056 // up. 5057 // 5058 // ARC layout strings only include the class's ivars. In non-fragile 5059 // runtimes, that means starting at InstanceStart, rounded up to word 5060 // alignment. In fragile runtimes, there's no InstanceStart, so it means 5061 // starting at the offset of the first ivar, rounded up to word alignment. 5062 // 5063 // MRC weak layout strings follow the ARC style. 5064 CharUnits baseOffset; 5065 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { 5066 for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); 5067 IVD; IVD = IVD->getNextIvar()) 5068 ivars.push_back(IVD); 5069 5070 if (isNonFragileABI()) { 5071 baseOffset = beginOffset; // InstanceStart 5072 } else if (!ivars.empty()) { 5073 baseOffset = 5074 CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0])); 5075 } else { 5076 baseOffset = CharUnits::Zero(); 5077 } 5078 5079 baseOffset = baseOffset.alignTo(CGM.getPointerAlign()); 5080 } 5081 else { 5082 CGM.getContext().DeepCollectObjCIvars(OI, true, ivars); 5083 5084 baseOffset = CharUnits::Zero(); 5085 } 5086 5087 if (ivars.empty()) 5088 return llvm::Constant::getNullValue(PtrTy); 5089 5090 IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout); 5091 5092 builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(), 5093 [&](const ObjCIvarDecl *ivar) -> CharUnits { 5094 return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar)); 5095 }); 5096 5097 if (!builder.hasBitmapData()) 5098 return llvm::Constant::getNullValue(PtrTy); 5099 5100 llvm::SmallVector<unsigned char, 4> buffer; 5101 llvm::Constant *C = builder.buildBitmap(*this, buffer); 5102 5103 if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) { 5104 printf("\n%s ivar layout for class '%s': ", 5105 ForStrongLayout ? "strong" : "weak", 5106 OMD->getClassInterface()->getName().str().c_str()); 5107 builder.dump(buffer); 5108 } 5109 return C; 5110 } 5111 5112 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { 5113 llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; 5114 // FIXME: Avoid std::string in "Sel.getAsString()" 5115 if (!Entry) 5116 Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName); 5117 return getConstantGEP(VMContext, Entry, 0, 0); 5118 } 5119 5120 // FIXME: Merge into a single cstring creation function. 5121 llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { 5122 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); 5123 } 5124 5125 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) { 5126 std::string TypeStr; 5127 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); 5128 5129 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; 5130 if (!Entry) 5131 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType); 5132 return getConstantGEP(VMContext, Entry, 0, 0); 5133 } 5134 5135 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D, 5136 bool Extended) { 5137 std::string TypeStr; 5138 if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended)) 5139 return nullptr; 5140 5141 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; 5142 if (!Entry) 5143 Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType); 5144 return getConstantGEP(VMContext, Entry, 0, 0); 5145 } 5146 5147 // FIXME: Merge into a single cstring creation function. 5148 llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { 5149 llvm::GlobalVariable *&Entry = PropertyNames[Ident]; 5150 if (!Entry) 5151 Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName); 5152 return getConstantGEP(VMContext, Entry, 0, 0); 5153 } 5154 5155 // FIXME: Merge into a single cstring creation function. 5156 // FIXME: This Decl should be more precise. 5157 llvm::Constant * 5158 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, 5159 const Decl *Container) { 5160 std::string TypeStr; 5161 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 5162 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); 5163 } 5164 5165 void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, 5166 const ObjCContainerDecl *CD, 5167 SmallVectorImpl<char> &Name) { 5168 llvm::raw_svector_ostream OS(Name); 5169 assert (CD && "Missing container decl in GetNameForMethod"); 5170 OS << '\01' << (D->isInstanceMethod() ? '-' : '+') 5171 << '[' << CD->getName(); 5172 if (const ObjCCategoryImplDecl *CID = 5173 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) 5174 OS << '(' << *CID << ')'; 5175 OS << ' ' << D->getSelector().getAsString() << ']'; 5176 } 5177 5178 void CGObjCMac::FinishModule() { 5179 EmitModuleInfo(); 5180 5181 // Emit the dummy bodies for any protocols which were referenced but 5182 // never defined. 5183 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator 5184 I = Protocols.begin(), e = Protocols.end(); I != e; ++I) { 5185 if (I->second->hasInitializer()) 5186 continue; 5187 5188 llvm::Constant *Values[5]; 5189 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 5190 Values[1] = GetClassName(I->first->getName()); 5191 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 5192 Values[3] = Values[4] = 5193 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 5194 I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 5195 Values)); 5196 CGM.addCompilerUsedGlobal(I->second); 5197 } 5198 5199 // Add assembler directives to add lazy undefined symbol references 5200 // for classes which are referenced but not defined. This is 5201 // important for correct linker interaction. 5202 // 5203 // FIXME: It would be nice if we had an LLVM construct for this. 5204 if ((!LazySymbols.empty() || !DefinedSymbols.empty()) && 5205 CGM.getTriple().isOSBinFormatMachO()) { 5206 SmallString<256> Asm; 5207 Asm += CGM.getModule().getModuleInlineAsm(); 5208 if (!Asm.empty() && Asm.back() != '\n') 5209 Asm += '\n'; 5210 5211 llvm::raw_svector_ostream OS(Asm); 5212 for (const auto *Sym : DefinedSymbols) 5213 OS << "\t.objc_class_name_" << Sym->getName() << "=0\n" 5214 << "\t.globl .objc_class_name_" << Sym->getName() << "\n"; 5215 for (const auto *Sym : LazySymbols) 5216 OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n"; 5217 for (const auto &Category : DefinedCategoryNames) 5218 OS << "\t.objc_category_name_" << Category << "=0\n" 5219 << "\t.globl .objc_category_name_" << Category << "\n"; 5220 5221 CGM.getModule().setModuleInlineAsm(OS.str()); 5222 } 5223 } 5224 5225 CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) 5226 : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr), 5227 ObjCEmptyVtableVar(nullptr) { 5228 ObjCABI = 2; 5229 } 5230 5231 /* *** */ 5232 5233 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) 5234 : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr) 5235 { 5236 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 5237 ASTContext &Ctx = CGM.getContext(); 5238 5239 ShortTy = Types.ConvertType(Ctx.ShortTy); 5240 IntTy = Types.ConvertType(Ctx.IntTy); 5241 LongTy = Types.ConvertType(Ctx.LongTy); 5242 LongLongTy = Types.ConvertType(Ctx.LongLongTy); 5243 Int8PtrTy = CGM.Int8PtrTy; 5244 Int8PtrPtrTy = CGM.Int8PtrPtrTy; 5245 5246 // arm64 targets use "int" ivar offset variables. All others, 5247 // including OS X x86_64 and Windows x86_64, use "long" ivar offsets. 5248 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64) 5249 IvarOffsetVarTy = IntTy; 5250 else 5251 IvarOffsetVarTy = LongTy; 5252 5253 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); 5254 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); 5255 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); 5256 5257 // I'm not sure I like this. The implicit coordination is a bit 5258 // gross. We should solve this in a reasonable fashion because this 5259 // is a pretty common task (match some runtime data structure with 5260 // an LLVM data structure). 5261 5262 // FIXME: This is leaked. 5263 // FIXME: Merge with rewriter code? 5264 5265 // struct _objc_super { 5266 // id self; 5267 // Class cls; 5268 // } 5269 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct, 5270 Ctx.getTranslationUnitDecl(), 5271 SourceLocation(), SourceLocation(), 5272 &Ctx.Idents.get("_objc_super")); 5273 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 5274 nullptr, Ctx.getObjCIdType(), nullptr, nullptr, 5275 false, ICIS_NoInit)); 5276 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 5277 nullptr, Ctx.getObjCClassType(), nullptr, 5278 nullptr, false, ICIS_NoInit)); 5279 RD->completeDefinition(); 5280 5281 SuperCTy = Ctx.getTagDeclType(RD); 5282 SuperPtrCTy = Ctx.getPointerType(SuperCTy); 5283 5284 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); 5285 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); 5286 5287 // struct _prop_t { 5288 // char *name; 5289 // char *attributes; 5290 // } 5291 PropertyTy = llvm::StructType::create("struct._prop_t", 5292 Int8PtrTy, Int8PtrTy, nullptr); 5293 5294 // struct _prop_list_t { 5295 // uint32_t entsize; // sizeof(struct _prop_t) 5296 // uint32_t count_of_properties; 5297 // struct _prop_t prop_list[count_of_properties]; 5298 // } 5299 PropertyListTy = 5300 llvm::StructType::create("struct._prop_list_t", IntTy, IntTy, 5301 llvm::ArrayType::get(PropertyTy, 0), nullptr); 5302 // struct _prop_list_t * 5303 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); 5304 5305 // struct _objc_method { 5306 // SEL _cmd; 5307 // char *method_type; 5308 // char *_imp; 5309 // } 5310 MethodTy = llvm::StructType::create("struct._objc_method", 5311 SelectorPtrTy, Int8PtrTy, Int8PtrTy, 5312 nullptr); 5313 5314 // struct _objc_cache * 5315 CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache"); 5316 CachePtrTy = llvm::PointerType::getUnqual(CacheTy); 5317 } 5318 5319 ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) 5320 : ObjCCommonTypesHelper(cgm) { 5321 // struct _objc_method_description { 5322 // SEL name; 5323 // char *types; 5324 // } 5325 MethodDescriptionTy = 5326 llvm::StructType::create("struct._objc_method_description", 5327 SelectorPtrTy, Int8PtrTy, nullptr); 5328 5329 // struct _objc_method_description_list { 5330 // int count; 5331 // struct _objc_method_description[1]; 5332 // } 5333 MethodDescriptionListTy = llvm::StructType::create( 5334 "struct._objc_method_description_list", IntTy, 5335 llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr); 5336 5337 // struct _objc_method_description_list * 5338 MethodDescriptionListPtrTy = 5339 llvm::PointerType::getUnqual(MethodDescriptionListTy); 5340 5341 // Protocol description structures 5342 5343 // struct _objc_protocol_extension { 5344 // uint32_t size; // sizeof(struct _objc_protocol_extension) 5345 // struct _objc_method_description_list *optional_instance_methods; 5346 // struct _objc_method_description_list *optional_class_methods; 5347 // struct _objc_property_list *instance_properties; 5348 // const char ** extendedMethodTypes; 5349 // struct _objc_property_list *class_properties; 5350 // } 5351 ProtocolExtensionTy = 5352 llvm::StructType::create("struct._objc_protocol_extension", 5353 IntTy, MethodDescriptionListPtrTy, 5354 MethodDescriptionListPtrTy, PropertyListPtrTy, 5355 Int8PtrPtrTy, PropertyListPtrTy, nullptr); 5356 5357 // struct _objc_protocol_extension * 5358 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); 5359 5360 // Handle recursive construction of Protocol and ProtocolList types 5361 5362 ProtocolTy = 5363 llvm::StructType::create(VMContext, "struct._objc_protocol"); 5364 5365 ProtocolListTy = 5366 llvm::StructType::create(VMContext, "struct._objc_protocol_list"); 5367 ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), 5368 LongTy, 5369 llvm::ArrayType::get(ProtocolTy, 0), 5370 nullptr); 5371 5372 // struct _objc_protocol { 5373 // struct _objc_protocol_extension *isa; 5374 // char *protocol_name; 5375 // struct _objc_protocol **_objc_protocol_list; 5376 // struct _objc_method_description_list *instance_methods; 5377 // struct _objc_method_description_list *class_methods; 5378 // } 5379 ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy, 5380 llvm::PointerType::getUnqual(ProtocolListTy), 5381 MethodDescriptionListPtrTy, 5382 MethodDescriptionListPtrTy, 5383 nullptr); 5384 5385 // struct _objc_protocol_list * 5386 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); 5387 5388 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); 5389 5390 // Class description structures 5391 5392 // struct _objc_ivar { 5393 // char *ivar_name; 5394 // char *ivar_type; 5395 // int ivar_offset; 5396 // } 5397 IvarTy = llvm::StructType::create("struct._objc_ivar", 5398 Int8PtrTy, Int8PtrTy, IntTy, nullptr); 5399 5400 // struct _objc_ivar_list * 5401 IvarListTy = 5402 llvm::StructType::create(VMContext, "struct._objc_ivar_list"); 5403 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); 5404 5405 // struct _objc_method_list * 5406 MethodListTy = 5407 llvm::StructType::create(VMContext, "struct._objc_method_list"); 5408 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); 5409 5410 // struct _objc_class_extension * 5411 ClassExtensionTy = 5412 llvm::StructType::create("struct._objc_class_extension", 5413 IntTy, Int8PtrTy, PropertyListPtrTy, nullptr); 5414 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); 5415 5416 ClassTy = llvm::StructType::create(VMContext, "struct._objc_class"); 5417 5418 // struct _objc_class { 5419 // Class isa; 5420 // Class super_class; 5421 // char *name; 5422 // long version; 5423 // long info; 5424 // long instance_size; 5425 // struct _objc_ivar_list *ivars; 5426 // struct _objc_method_list *methods; 5427 // struct _objc_cache *cache; 5428 // struct _objc_protocol_list *protocols; 5429 // char *ivar_layout; 5430 // struct _objc_class_ext *ext; 5431 // }; 5432 ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy), 5433 llvm::PointerType::getUnqual(ClassTy), 5434 Int8PtrTy, 5435 LongTy, 5436 LongTy, 5437 LongTy, 5438 IvarListPtrTy, 5439 MethodListPtrTy, 5440 CachePtrTy, 5441 ProtocolListPtrTy, 5442 Int8PtrTy, 5443 ClassExtensionPtrTy, 5444 nullptr); 5445 5446 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); 5447 5448 // struct _objc_category { 5449 // char *category_name; 5450 // char *class_name; 5451 // struct _objc_method_list *instance_method; 5452 // struct _objc_method_list *class_method; 5453 // struct _objc_protocol_list *protocols; 5454 // uint32_t size; // sizeof(struct _objc_category) 5455 // struct _objc_property_list *instance_properties;// category's @property 5456 // struct _objc_property_list *class_properties; 5457 // } 5458 CategoryTy = 5459 llvm::StructType::create("struct._objc_category", 5460 Int8PtrTy, Int8PtrTy, MethodListPtrTy, 5461 MethodListPtrTy, ProtocolListPtrTy, 5462 IntTy, PropertyListPtrTy, PropertyListPtrTy, 5463 nullptr); 5464 5465 // Global metadata structures 5466 5467 // struct _objc_symtab { 5468 // long sel_ref_cnt; 5469 // SEL *refs; 5470 // short cls_def_cnt; 5471 // short cat_def_cnt; 5472 // char *defs[cls_def_cnt + cat_def_cnt]; 5473 // } 5474 SymtabTy = 5475 llvm::StructType::create("struct._objc_symtab", 5476 LongTy, SelectorPtrTy, ShortTy, ShortTy, 5477 llvm::ArrayType::get(Int8PtrTy, 0), nullptr); 5478 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); 5479 5480 // struct _objc_module { 5481 // long version; 5482 // long size; // sizeof(struct _objc_module) 5483 // char *name; 5484 // struct _objc_symtab* symtab; 5485 // } 5486 ModuleTy = 5487 llvm::StructType::create("struct._objc_module", 5488 LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr); 5489 5490 5491 // FIXME: This is the size of the setjmp buffer and should be target 5492 // specific. 18 is what's used on 32-bit X86. 5493 uint64_t SetJmpBufferSize = 18; 5494 5495 // Exceptions 5496 llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4); 5497 5498 ExceptionDataTy = 5499 llvm::StructType::create("struct._objc_exception_data", 5500 llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize), 5501 StackPtrTy, nullptr); 5502 } 5503 5504 ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) 5505 : ObjCCommonTypesHelper(cgm) { 5506 // struct _method_list_t { 5507 // uint32_t entsize; // sizeof(struct _objc_method) 5508 // uint32_t method_count; 5509 // struct _objc_method method_list[method_count]; 5510 // } 5511 MethodListnfABITy = 5512 llvm::StructType::create("struct.__method_list_t", IntTy, IntTy, 5513 llvm::ArrayType::get(MethodTy, 0), nullptr); 5514 // struct method_list_t * 5515 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); 5516 5517 // struct _protocol_t { 5518 // id isa; // NULL 5519 // const char * const protocol_name; 5520 // const struct _protocol_list_t * protocol_list; // super protocols 5521 // const struct method_list_t * const instance_methods; 5522 // const struct method_list_t * const class_methods; 5523 // const struct method_list_t *optionalInstanceMethods; 5524 // const struct method_list_t *optionalClassMethods; 5525 // const struct _prop_list_t * properties; 5526 // const uint32_t size; // sizeof(struct _protocol_t) 5527 // const uint32_t flags; // = 0 5528 // const char ** extendedMethodTypes; 5529 // const char *demangledName; 5530 // const struct _prop_list_t * class_properties; 5531 // } 5532 5533 // Holder for struct _protocol_list_t * 5534 ProtocolListnfABITy = 5535 llvm::StructType::create(VMContext, "struct._objc_protocol_list"); 5536 5537 ProtocolnfABITy = 5538 llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy, 5539 llvm::PointerType::getUnqual(ProtocolListnfABITy), 5540 MethodListnfABIPtrTy, MethodListnfABIPtrTy, 5541 MethodListnfABIPtrTy, MethodListnfABIPtrTy, 5542 PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, 5543 Int8PtrTy, PropertyListPtrTy, 5544 nullptr); 5545 5546 // struct _protocol_t* 5547 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy); 5548 5549 // struct _protocol_list_t { 5550 // long protocol_count; // Note, this is 32/64 bit 5551 // struct _protocol_t *[protocol_count]; 5552 // } 5553 ProtocolListnfABITy->setBody(LongTy, 5554 llvm::ArrayType::get(ProtocolnfABIPtrTy, 0), 5555 nullptr); 5556 5557 // struct _objc_protocol_list* 5558 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); 5559 5560 // struct _ivar_t { 5561 // unsigned [long] int *offset; // pointer to ivar offset location 5562 // char *name; 5563 // char *type; 5564 // uint32_t alignment; 5565 // uint32_t size; 5566 // } 5567 IvarnfABITy = llvm::StructType::create( 5568 "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy), 5569 Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr); 5570 5571 // struct _ivar_list_t { 5572 // uint32 entsize; // sizeof(struct _ivar_t) 5573 // uint32 count; 5574 // struct _iver_t list[count]; 5575 // } 5576 IvarListnfABITy = 5577 llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy, 5578 llvm::ArrayType::get(IvarnfABITy, 0), nullptr); 5579 5580 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); 5581 5582 // struct _class_ro_t { 5583 // uint32_t const flags; 5584 // uint32_t const instanceStart; 5585 // uint32_t const instanceSize; 5586 // uint32_t const reserved; // only when building for 64bit targets 5587 // const uint8_t * const ivarLayout; 5588 // const char *const name; 5589 // const struct _method_list_t * const baseMethods; 5590 // const struct _objc_protocol_list *const baseProtocols; 5591 // const struct _ivar_list_t *const ivars; 5592 // const uint8_t * const weakIvarLayout; 5593 // const struct _prop_list_t * const properties; 5594 // } 5595 5596 // FIXME. Add 'reserved' field in 64bit abi mode! 5597 ClassRonfABITy = llvm::StructType::create("struct._class_ro_t", 5598 IntTy, IntTy, IntTy, Int8PtrTy, 5599 Int8PtrTy, MethodListnfABIPtrTy, 5600 ProtocolListnfABIPtrTy, 5601 IvarListnfABIPtrTy, 5602 Int8PtrTy, PropertyListPtrTy, 5603 nullptr); 5604 5605 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 5606 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; 5607 ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false) 5608 ->getPointerTo(); 5609 5610 // struct _class_t { 5611 // struct _class_t *isa; 5612 // struct _class_t * const superclass; 5613 // void *cache; 5614 // IMP *vtable; 5615 // struct class_ro_t *ro; 5616 // } 5617 5618 ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t"); 5619 ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy), 5620 llvm::PointerType::getUnqual(ClassnfABITy), 5621 CachePtrTy, 5622 llvm::PointerType::getUnqual(ImpnfABITy), 5623 llvm::PointerType::getUnqual(ClassRonfABITy), 5624 nullptr); 5625 5626 // LLVM for struct _class_t * 5627 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); 5628 5629 // struct _category_t { 5630 // const char * const name; 5631 // struct _class_t *const cls; 5632 // const struct _method_list_t * const instance_methods; 5633 // const struct _method_list_t * const class_methods; 5634 // const struct _protocol_list_t * const protocols; 5635 // const struct _prop_list_t * const properties; 5636 // const struct _prop_list_t * const class_properties; 5637 // const uint32_t size; 5638 // } 5639 CategorynfABITy = llvm::StructType::create("struct._category_t", 5640 Int8PtrTy, ClassnfABIPtrTy, 5641 MethodListnfABIPtrTy, 5642 MethodListnfABIPtrTy, 5643 ProtocolListnfABIPtrTy, 5644 PropertyListPtrTy, 5645 PropertyListPtrTy, 5646 IntTy, 5647 nullptr); 5648 5649 // New types for nonfragile abi messaging. 5650 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 5651 ASTContext &Ctx = CGM.getContext(); 5652 5653 // MessageRefTy - LLVM for: 5654 // struct _message_ref_t { 5655 // IMP messenger; 5656 // SEL name; 5657 // }; 5658 5659 // First the clang type for struct _message_ref_t 5660 RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct, 5661 Ctx.getTranslationUnitDecl(), 5662 SourceLocation(), SourceLocation(), 5663 &Ctx.Idents.get("_message_ref_t")); 5664 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 5665 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false, 5666 ICIS_NoInit)); 5667 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 5668 nullptr, Ctx.getObjCSelType(), nullptr, nullptr, 5669 false, ICIS_NoInit)); 5670 RD->completeDefinition(); 5671 5672 MessageRefCTy = Ctx.getTagDeclType(RD); 5673 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy); 5674 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy)); 5675 5676 // MessageRefPtrTy - LLVM for struct _message_ref_t* 5677 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy); 5678 5679 // SuperMessageRefTy - LLVM for: 5680 // struct _super_message_ref_t { 5681 // SUPER_IMP messenger; 5682 // SEL name; 5683 // }; 5684 SuperMessageRefTy = 5685 llvm::StructType::create("struct._super_message_ref_t", 5686 ImpnfABITy, SelectorPtrTy, nullptr); 5687 5688 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* 5689 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); 5690 5691 5692 // struct objc_typeinfo { 5693 // const void** vtable; // objc_ehtype_vtable + 2 5694 // const char* name; // c++ typeinfo string 5695 // Class cls; 5696 // }; 5697 EHTypeTy = 5698 llvm::StructType::create("struct._objc_typeinfo", 5699 llvm::PointerType::getUnqual(Int8PtrTy), 5700 Int8PtrTy, ClassnfABIPtrTy, nullptr); 5701 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy); 5702 } 5703 5704 llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() { 5705 FinishNonFragileABIModule(); 5706 5707 return nullptr; 5708 } 5709 5710 void CGObjCNonFragileABIMac::AddModuleClassList( 5711 ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName, 5712 StringRef SectionName) { 5713 unsigned NumClasses = Container.size(); 5714 5715 if (!NumClasses) 5716 return; 5717 5718 SmallVector<llvm::Constant*, 8> Symbols(NumClasses); 5719 for (unsigned i=0; i<NumClasses; i++) 5720 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i], 5721 ObjCTypes.Int8PtrTy); 5722 llvm::Constant *Init = 5723 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 5724 Symbols.size()), 5725 Symbols); 5726 5727 llvm::GlobalVariable *GV = 5728 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, 5729 llvm::GlobalValue::PrivateLinkage, 5730 Init, 5731 SymbolName); 5732 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType())); 5733 GV->setSection(SectionName); 5734 CGM.addCompilerUsedGlobal(GV); 5735 } 5736 5737 void CGObjCNonFragileABIMac::FinishNonFragileABIModule() { 5738 // nonfragile abi has no module definition. 5739 5740 // Build list of all implemented class addresses in array 5741 // L_OBJC_LABEL_CLASS_$. 5742 5743 for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) { 5744 const ObjCInterfaceDecl *ID = ImplementedClasses[i]; 5745 assert(ID); 5746 if (ObjCImplementationDecl *IMP = ID->getImplementation()) 5747 // We are implementing a weak imported interface. Give it external linkage 5748 if (ID->isWeakImported() && !IMP->isWeakImported()) { 5749 DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage); 5750 DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage); 5751 } 5752 } 5753 5754 AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$", 5755 "__DATA, __objc_classlist, regular, no_dead_strip"); 5756 5757 AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$", 5758 "__DATA, __objc_nlclslist, regular, no_dead_strip"); 5759 5760 // Build list of all implemented category addresses in array 5761 // L_OBJC_LABEL_CATEGORY_$. 5762 AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$", 5763 "__DATA, __objc_catlist, regular, no_dead_strip"); 5764 AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$", 5765 "__DATA, __objc_nlcatlist, regular, no_dead_strip"); 5766 5767 EmitImageInfo(); 5768 } 5769 5770 /// isVTableDispatchedSelector - Returns true if SEL is not in the list of 5771 /// VTableDispatchMethods; false otherwise. What this means is that 5772 /// except for the 19 selectors in the list, we generate 32bit-style 5773 /// message dispatch call for all the rest. 5774 bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) { 5775 // At various points we've experimented with using vtable-based 5776 // dispatch for all methods. 5777 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { 5778 case CodeGenOptions::Legacy: 5779 return false; 5780 case CodeGenOptions::NonLegacy: 5781 return true; 5782 case CodeGenOptions::Mixed: 5783 break; 5784 } 5785 5786 // If so, see whether this selector is in the white-list of things which must 5787 // use the new dispatch convention. We lazily build a dense set for this. 5788 if (VTableDispatchMethods.empty()) { 5789 VTableDispatchMethods.insert(GetNullarySelector("alloc")); 5790 VTableDispatchMethods.insert(GetNullarySelector("class")); 5791 VTableDispatchMethods.insert(GetNullarySelector("self")); 5792 VTableDispatchMethods.insert(GetNullarySelector("isFlipped")); 5793 VTableDispatchMethods.insert(GetNullarySelector("length")); 5794 VTableDispatchMethods.insert(GetNullarySelector("count")); 5795 5796 // These are vtable-based if GC is disabled. 5797 // Optimistically use vtable dispatch for hybrid compiles. 5798 if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) { 5799 VTableDispatchMethods.insert(GetNullarySelector("retain")); 5800 VTableDispatchMethods.insert(GetNullarySelector("release")); 5801 VTableDispatchMethods.insert(GetNullarySelector("autorelease")); 5802 } 5803 5804 VTableDispatchMethods.insert(GetUnarySelector("allocWithZone")); 5805 VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass")); 5806 VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector")); 5807 VTableDispatchMethods.insert(GetUnarySelector("objectForKey")); 5808 VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex")); 5809 VTableDispatchMethods.insert(GetUnarySelector("isEqualToString")); 5810 VTableDispatchMethods.insert(GetUnarySelector("isEqual")); 5811 5812 // These are vtable-based if GC is enabled. 5813 // Optimistically use vtable dispatch for hybrid compiles. 5814 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) { 5815 VTableDispatchMethods.insert(GetNullarySelector("hash")); 5816 VTableDispatchMethods.insert(GetUnarySelector("addObject")); 5817 5818 // "countByEnumeratingWithState:objects:count" 5819 IdentifierInfo *KeyIdents[] = { 5820 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 5821 &CGM.getContext().Idents.get("objects"), 5822 &CGM.getContext().Idents.get("count") 5823 }; 5824 VTableDispatchMethods.insert( 5825 CGM.getContext().Selectors.getSelector(3, KeyIdents)); 5826 } 5827 } 5828 5829 return VTableDispatchMethods.count(Sel); 5830 } 5831 5832 /// BuildClassRoTInitializer - generate meta-data for: 5833 /// struct _class_ro_t { 5834 /// uint32_t const flags; 5835 /// uint32_t const instanceStart; 5836 /// uint32_t const instanceSize; 5837 /// uint32_t const reserved; // only when building for 64bit targets 5838 /// const uint8_t * const ivarLayout; 5839 /// const char *const name; 5840 /// const struct _method_list_t * const baseMethods; 5841 /// const struct _protocol_list_t *const baseProtocols; 5842 /// const struct _ivar_list_t *const ivars; 5843 /// const uint8_t * const weakIvarLayout; 5844 /// const struct _prop_list_t * const properties; 5845 /// } 5846 /// 5847 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer( 5848 unsigned flags, 5849 unsigned InstanceStart, 5850 unsigned InstanceSize, 5851 const ObjCImplementationDecl *ID) { 5852 std::string ClassName = ID->getObjCRuntimeNameAsString(); 5853 llvm::Constant *Values[10]; // 11 for 64bit targets! 5854 5855 CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart); 5856 CharUnits endInstance = CharUnits::fromQuantity(InstanceSize); 5857 5858 bool hasMRCWeak = false; 5859 if (CGM.getLangOpts().ObjCAutoRefCount) 5860 flags |= NonFragileABI_Class_CompiledByARC; 5861 else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID))) 5862 flags |= NonFragileABI_Class_HasMRCWeakIvars; 5863 5864 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); 5865 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart); 5866 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize); 5867 // FIXME. For 64bit targets add 0 here. 5868 Values[ 3] = (flags & NonFragileABI_Class_Meta) 5869 ? GetIvarLayoutName(nullptr, ObjCTypes) 5870 : BuildStrongIvarLayout(ID, beginInstance, endInstance); 5871 Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString()); 5872 // const struct _method_list_t * const baseMethods; 5873 std::vector<llvm::Constant*> Methods; 5874 std::string MethodListName("\01l_OBJC_$_"); 5875 if (flags & NonFragileABI_Class_Meta) { 5876 MethodListName += "CLASS_METHODS_"; 5877 MethodListName += ID->getObjCRuntimeNameAsString(); 5878 for (const auto *I : ID->class_methods()) 5879 // Class methods should always be defined. 5880 Methods.push_back(GetMethodConstant(I)); 5881 } else { 5882 MethodListName += "INSTANCE_METHODS_"; 5883 MethodListName += ID->getObjCRuntimeNameAsString(); 5884 for (const auto *I : ID->instance_methods()) 5885 // Instance methods should always be defined. 5886 Methods.push_back(GetMethodConstant(I)); 5887 5888 for (const auto *PID : ID->property_impls()) { 5889 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){ 5890 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5891 5892 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 5893 if (llvm::Constant *C = GetMethodConstant(MD)) 5894 Methods.push_back(C); 5895 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 5896 if (llvm::Constant *C = GetMethodConstant(MD)) 5897 Methods.push_back(C); 5898 } 5899 } 5900 } 5901 Values[ 5] = EmitMethodList(MethodListName, 5902 "__DATA, __objc_const", Methods); 5903 5904 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 5905 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer"); 5906 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_" 5907 + OID->getObjCRuntimeNameAsString(), 5908 OID->all_referenced_protocol_begin(), 5909 OID->all_referenced_protocol_end()); 5910 5911 if (flags & NonFragileABI_Class_Meta) { 5912 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 5913 Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes); 5914 Values[ 9] = EmitPropertyList( 5915 "\01l_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(), 5916 ID, ID->getClassInterface(), ObjCTypes, true); 5917 } else { 5918 Values[ 7] = EmitIvarList(ID); 5919 Values[ 8] = BuildWeakIvarLayout(ID, beginInstance, endInstance, 5920 hasMRCWeak); 5921 Values[ 9] = EmitPropertyList( 5922 "\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(), 5923 ID, ID->getClassInterface(), ObjCTypes, false); 5924 } 5925 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy, 5926 Values); 5927 llvm::GlobalVariable *CLASS_RO_GV = 5928 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false, 5929 llvm::GlobalValue::PrivateLinkage, 5930 Init, 5931 (flags & NonFragileABI_Class_Meta) ? 5932 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName : 5933 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName); 5934 CLASS_RO_GV->setAlignment( 5935 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy)); 5936 CLASS_RO_GV->setSection("__DATA, __objc_const"); 5937 return CLASS_RO_GV; 5938 5939 } 5940 5941 /// BuildClassMetaData - This routine defines that to-level meta-data 5942 /// for the given ClassName for: 5943 /// struct _class_t { 5944 /// struct _class_t *isa; 5945 /// struct _class_t * const superclass; 5946 /// void *cache; 5947 /// IMP *vtable; 5948 /// struct class_ro_t *ro; 5949 /// } 5950 /// 5951 llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData( 5952 const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV, 5953 llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) { 5954 llvm::Constant *Values[] = { 5955 IsAGV, 5956 SuperClassGV, 5957 ObjCEmptyCacheVar, // &ObjCEmptyCacheVar 5958 ObjCEmptyVtableVar, // &ObjCEmptyVtableVar 5959 ClassRoGV // &CLASS_RO_GV 5960 }; 5961 if (!Values[1]) 5962 Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy); 5963 if (!Values[3]) 5964 Values[3] = llvm::Constant::getNullValue( 5965 llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy)); 5966 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy, 5967 Values); 5968 llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak); 5969 GV->setInitializer(Init); 5970 GV->setSection("__DATA, __objc_data"); 5971 GV->setAlignment( 5972 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy)); 5973 if (!CGM.getTriple().isOSBinFormatCOFF()) 5974 if (HiddenVisibility) 5975 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 5976 return GV; 5977 } 5978 5979 bool 5980 CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const { 5981 return OD->getClassMethod(GetNullarySelector("load")) != nullptr; 5982 } 5983 5984 void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID, 5985 uint32_t &InstanceStart, 5986 uint32_t &InstanceSize) { 5987 const ASTRecordLayout &RL = 5988 CGM.getContext().getASTObjCImplementationLayout(OID); 5989 5990 // InstanceSize is really instance end. 5991 InstanceSize = RL.getDataSize().getQuantity(); 5992 5993 // If there are no fields, the start is the same as the end. 5994 if (!RL.getFieldCount()) 5995 InstanceStart = InstanceSize; 5996 else 5997 InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth(); 5998 } 5999 6000 static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM, 6001 StringRef Name) { 6002 IdentifierInfo &II = CGM.getContext().Idents.get(Name); 6003 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); 6004 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 6005 6006 const VarDecl *VD = nullptr; 6007 for (const auto &Result : DC->lookup(&II)) 6008 if ((VD = dyn_cast<VarDecl>(Result))) 6009 break; 6010 6011 if (!VD) 6012 return llvm::GlobalValue::DLLImportStorageClass; 6013 if (VD->hasAttr<DLLExportAttr>()) 6014 return llvm::GlobalValue::DLLExportStorageClass; 6015 if (VD->hasAttr<DLLImportAttr>()) 6016 return llvm::GlobalValue::DLLImportStorageClass; 6017 return llvm::GlobalValue::DefaultStorageClass; 6018 } 6019 6020 void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) { 6021 if (!ObjCEmptyCacheVar) { 6022 ObjCEmptyCacheVar = 6023 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false, 6024 llvm::GlobalValue::ExternalLinkage, nullptr, 6025 "_objc_empty_cache"); 6026 if (CGM.getTriple().isOSBinFormatCOFF()) 6027 ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache")); 6028 6029 // Only OS X with deployment version <10.9 use the empty vtable symbol 6030 const llvm::Triple &Triple = CGM.getTarget().getTriple(); 6031 if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9)) 6032 ObjCEmptyVtableVar = 6033 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false, 6034 llvm::GlobalValue::ExternalLinkage, nullptr, 6035 "_objc_empty_vtable"); 6036 } 6037 6038 // FIXME: Is this correct (that meta class size is never computed)? 6039 uint32_t InstanceStart = 6040 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy); 6041 uint32_t InstanceSize = InstanceStart; 6042 uint32_t flags = NonFragileABI_Class_Meta; 6043 6044 llvm::GlobalVariable *SuperClassGV, *IsAGV; 6045 6046 StringRef ClassName = ID->getObjCRuntimeNameAsString(); 6047 const auto *CI = ID->getClassInterface(); 6048 assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0"); 6049 6050 // Build the flags for the metaclass. 6051 bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF()) 6052 ? !CI->hasAttr<DLLExportAttr>() 6053 : CI->getVisibility() == HiddenVisibility; 6054 if (classIsHidden) 6055 flags |= NonFragileABI_Class_Hidden; 6056 6057 // FIXME: why is this flag set on the metaclass? 6058 // ObjC metaclasses have no fields and don't really get constructed. 6059 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) { 6060 flags |= NonFragileABI_Class_HasCXXStructors; 6061 if (!ID->hasNonZeroConstructors()) 6062 flags |= NonFragileABI_Class_HasCXXDestructorOnly; 6063 } 6064 6065 if (!CI->getSuperClass()) { 6066 // class is root 6067 flags |= NonFragileABI_Class_Root; 6068 6069 SuperClassGV = GetClassGlobal((getClassSymbolPrefix() + ClassName).str(), 6070 CI->isWeakImported()); 6071 if (CGM.getTriple().isOSBinFormatCOFF()) 6072 if (CI->hasAttr<DLLImportAttr>()) 6073 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6074 6075 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + ClassName).str(), 6076 CI->isWeakImported()); 6077 if (CGM.getTriple().isOSBinFormatCOFF()) 6078 if (CI->hasAttr<DLLImportAttr>()) 6079 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6080 } else { 6081 // Has a root. Current class is not a root. 6082 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 6083 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 6084 Root = Super; 6085 6086 const auto *Super = CI->getSuperClass(); 6087 StringRef RootClassName = Root->getObjCRuntimeNameAsString(); 6088 StringRef SuperClassName = Super->getObjCRuntimeNameAsString(); 6089 6090 IsAGV = GetClassGlobal((getMetaclassSymbolPrefix() + RootClassName).str(), 6091 Root->isWeakImported()); 6092 if (CGM.getTriple().isOSBinFormatCOFF()) 6093 if (Root->hasAttr<DLLImportAttr>()) 6094 IsAGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6095 6096 // work on super class metadata symbol. 6097 SuperClassGV = 6098 GetClassGlobal((getMetaclassSymbolPrefix() + SuperClassName).str(), 6099 Super->isWeakImported()); 6100 if (CGM.getTriple().isOSBinFormatCOFF()) 6101 if (Super->hasAttr<DLLImportAttr>()) 6102 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6103 } 6104 6105 llvm::GlobalVariable *CLASS_RO_GV = 6106 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID); 6107 6108 llvm::GlobalVariable *MetaTClass = 6109 BuildClassMetaData((getMetaclassSymbolPrefix() + ClassName).str(), IsAGV, 6110 SuperClassGV, CLASS_RO_GV, classIsHidden, 6111 CI->isWeakImported()); 6112 if (CGM.getTriple().isOSBinFormatCOFF()) 6113 if (CI->hasAttr<DLLExportAttr>()) 6114 MetaTClass->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 6115 DefinedMetaClasses.push_back(MetaTClass); 6116 6117 // Metadata for the class 6118 flags = 0; 6119 if (classIsHidden) 6120 flags |= NonFragileABI_Class_Hidden; 6121 6122 if (ID->hasNonZeroConstructors() || ID->hasDestructors()) { 6123 flags |= NonFragileABI_Class_HasCXXStructors; 6124 6125 // Set a flag to enable a runtime optimization when a class has 6126 // fields that require destruction but which don't require 6127 // anything except zero-initialization during construction. This 6128 // is most notably true of __strong and __weak types, but you can 6129 // also imagine there being C++ types with non-trivial default 6130 // constructors that merely set all fields to null. 6131 if (!ID->hasNonZeroConstructors()) 6132 flags |= NonFragileABI_Class_HasCXXDestructorOnly; 6133 } 6134 6135 if (hasObjCExceptionAttribute(CGM.getContext(), CI)) 6136 flags |= NonFragileABI_Class_Exception; 6137 6138 if (!CI->getSuperClass()) { 6139 flags |= NonFragileABI_Class_Root; 6140 SuperClassGV = nullptr; 6141 } else { 6142 // Has a root. Current class is not a root. 6143 const auto *Super = CI->getSuperClass(); 6144 StringRef SuperClassName = Super->getObjCRuntimeNameAsString(); 6145 6146 SuperClassGV = 6147 GetClassGlobal((getClassSymbolPrefix() + SuperClassName).str(), 6148 Super->isWeakImported()); 6149 if (CGM.getTriple().isOSBinFormatCOFF()) 6150 if (Super->hasAttr<DLLImportAttr>()) 6151 SuperClassGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6152 } 6153 6154 GetClassSizeInfo(ID, InstanceStart, InstanceSize); 6155 CLASS_RO_GV = 6156 BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID); 6157 6158 llvm::GlobalVariable *ClassMD = 6159 BuildClassMetaData((getClassSymbolPrefix() + ClassName).str(), MetaTClass, 6160 SuperClassGV, CLASS_RO_GV, classIsHidden, 6161 CI->isWeakImported()); 6162 if (CGM.getTriple().isOSBinFormatCOFF()) 6163 if (CI->hasAttr<DLLExportAttr>()) 6164 ClassMD->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 6165 DefinedClasses.push_back(ClassMD); 6166 ImplementedClasses.push_back(CI); 6167 6168 // Determine if this class is also "non-lazy". 6169 if (ImplementationIsNonLazy(ID)) 6170 DefinedNonLazyClasses.push_back(ClassMD); 6171 6172 // Force the definition of the EHType if necessary. 6173 if (flags & NonFragileABI_Class_Exception) 6174 GetInterfaceEHType(CI, true); 6175 // Make sure method definition entries are all clear for next implementation. 6176 MethodDefinitions.clear(); 6177 } 6178 6179 /// GenerateProtocolRef - This routine is called to generate code for 6180 /// a protocol reference expression; as in: 6181 /// @code 6182 /// @protocol(Proto1); 6183 /// @endcode 6184 /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1 6185 /// which will hold address of the protocol meta-data. 6186 /// 6187 llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF, 6188 const ObjCProtocolDecl *PD) { 6189 6190 // This routine is called for @protocol only. So, we must build definition 6191 // of protocol's meta-data (not a reference to it!) 6192 // 6193 llvm::Constant *Init = 6194 llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD), 6195 ObjCTypes.getExternalProtocolPtrTy()); 6196 6197 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_"); 6198 ProtocolName += PD->getObjCRuntimeNameAsString(); 6199 6200 CharUnits Align = CGF.getPointerAlign(); 6201 6202 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); 6203 if (PTGV) 6204 return CGF.Builder.CreateAlignedLoad(PTGV, Align); 6205 PTGV = new llvm::GlobalVariable( 6206 CGM.getModule(), 6207 Init->getType(), false, 6208 llvm::GlobalValue::WeakAnyLinkage, 6209 Init, 6210 ProtocolName); 6211 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip"); 6212 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 6213 PTGV->setAlignment(Align.getQuantity()); 6214 CGM.addCompilerUsedGlobal(PTGV); 6215 return CGF.Builder.CreateAlignedLoad(PTGV, Align); 6216 } 6217 6218 /// GenerateCategory - Build metadata for a category implementation. 6219 /// struct _category_t { 6220 /// const char * const name; 6221 /// struct _class_t *const cls; 6222 /// const struct _method_list_t * const instance_methods; 6223 /// const struct _method_list_t * const class_methods; 6224 /// const struct _protocol_list_t * const protocols; 6225 /// const struct _prop_list_t * const properties; 6226 /// const struct _prop_list_t * const class_properties; 6227 /// const uint32_t size; 6228 /// } 6229 /// 6230 void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 6231 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 6232 const char *Prefix = "\01l_OBJC_$_CATEGORY_"; 6233 6234 llvm::SmallString<64> ExtCatName(Prefix); 6235 ExtCatName += Interface->getObjCRuntimeNameAsString(); 6236 ExtCatName += "_$_"; 6237 ExtCatName += OCD->getNameAsString(); 6238 6239 llvm::SmallString<64> ExtClassName(getClassSymbolPrefix()); 6240 ExtClassName += Interface->getObjCRuntimeNameAsString(); 6241 6242 llvm::Constant *Values[8]; 6243 Values[0] = GetClassName(OCD->getIdentifier()->getName()); 6244 // meta-class entry symbol 6245 llvm::GlobalVariable *ClassGV = 6246 GetClassGlobal(ExtClassName.str(), Interface->isWeakImported()); 6247 6248 Values[1] = ClassGV; 6249 std::vector<llvm::Constant*> Methods; 6250 llvm::SmallString<64> MethodListName(Prefix); 6251 6252 MethodListName += "INSTANCE_METHODS_"; 6253 MethodListName += Interface->getObjCRuntimeNameAsString(); 6254 MethodListName += "_$_"; 6255 MethodListName += OCD->getName(); 6256 6257 for (const auto *I : OCD->instance_methods()) 6258 // Instance methods should always be defined. 6259 Methods.push_back(GetMethodConstant(I)); 6260 6261 Values[2] = EmitMethodList(MethodListName.str(), 6262 "__DATA, __objc_const", 6263 Methods); 6264 6265 MethodListName = Prefix; 6266 MethodListName += "CLASS_METHODS_"; 6267 MethodListName += Interface->getObjCRuntimeNameAsString(); 6268 MethodListName += "_$_"; 6269 MethodListName += OCD->getNameAsString(); 6270 6271 Methods.clear(); 6272 for (const auto *I : OCD->class_methods()) 6273 // Class methods should always be defined. 6274 Methods.push_back(GetMethodConstant(I)); 6275 6276 Values[3] = EmitMethodList(MethodListName.str(), 6277 "__DATA, __objc_const", 6278 Methods); 6279 const ObjCCategoryDecl *Category = 6280 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 6281 if (Category) { 6282 SmallString<256> ExtName; 6283 llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_" 6284 << OCD->getName(); 6285 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_" 6286 + Interface->getObjCRuntimeNameAsString() + "_$_" 6287 + Category->getName(), 6288 Category->protocol_begin(), 6289 Category->protocol_end()); 6290 Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(), 6291 OCD, Category, ObjCTypes, false); 6292 Values[6] = EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(), 6293 OCD, Category, ObjCTypes, true); 6294 } else { 6295 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 6296 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 6297 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 6298 } 6299 6300 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy); 6301 Values[7] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 6302 6303 llvm::Constant *Init = 6304 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy, 6305 Values); 6306 llvm::GlobalVariable *GCATV 6307 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy, 6308 false, 6309 llvm::GlobalValue::PrivateLinkage, 6310 Init, 6311 ExtCatName.str()); 6312 GCATV->setAlignment( 6313 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy)); 6314 GCATV->setSection("__DATA, __objc_const"); 6315 CGM.addCompilerUsedGlobal(GCATV); 6316 DefinedCategories.push_back(GCATV); 6317 6318 // Determine if this category is also "non-lazy". 6319 if (ImplementationIsNonLazy(OCD)) 6320 DefinedNonLazyCategories.push_back(GCATV); 6321 // method definition entries must be clear for next implementation. 6322 MethodDefinitions.clear(); 6323 } 6324 6325 /// GetMethodConstant - Return a struct objc_method constant for the 6326 /// given method if it has been defined. The result is null if the 6327 /// method has not been defined. The return value has type MethodPtrTy. 6328 llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant( 6329 const ObjCMethodDecl *MD) { 6330 llvm::Function *Fn = GetMethodDefinition(MD); 6331 if (!Fn) 6332 return nullptr; 6333 6334 llvm::Constant *Method[] = { 6335 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 6336 ObjCTypes.SelectorPtrTy), 6337 GetMethodVarType(MD), 6338 llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy) 6339 }; 6340 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 6341 } 6342 6343 /// EmitMethodList - Build meta-data for method declarations 6344 /// struct _method_list_t { 6345 /// uint32_t entsize; // sizeof(struct _objc_method) 6346 /// uint32_t method_count; 6347 /// struct _objc_method method_list[method_count]; 6348 /// } 6349 /// 6350 llvm::Constant * 6351 CGObjCNonFragileABIMac::EmitMethodList(Twine Name, StringRef Section, 6352 ArrayRef<llvm::Constant *> Methods) { 6353 // Return null for empty list. 6354 if (Methods.empty()) 6355 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy); 6356 6357 llvm::Constant *Values[3]; 6358 // sizeof(struct _objc_method) 6359 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy); 6360 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 6361 // method_count 6362 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 6363 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 6364 Methods.size()); 6365 Values[2] = llvm::ConstantArray::get(AT, Methods); 6366 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 6367 6368 llvm::GlobalVariable *GV = 6369 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, 6370 llvm::GlobalValue::PrivateLinkage, Init, Name); 6371 GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType())); 6372 GV->setSection(Section); 6373 CGM.addCompilerUsedGlobal(GV); 6374 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy); 6375 } 6376 6377 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for 6378 /// the given ivar. 6379 llvm::GlobalVariable * 6380 CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 6381 const ObjCIvarDecl *Ivar) { 6382 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); 6383 llvm::SmallString<64> Name("OBJC_IVAR_$_"); 6384 Name += Container->getObjCRuntimeNameAsString(); 6385 Name += "."; 6386 Name += Ivar->getName(); 6387 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name); 6388 if (!IvarOffsetGV) { 6389 IvarOffsetGV = 6390 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy, 6391 false, llvm::GlobalValue::ExternalLinkage, 6392 nullptr, Name.str()); 6393 if (CGM.getTriple().isOSBinFormatCOFF()) { 6394 bool IsPrivateOrPackage = 6395 Ivar->getAccessControl() == ObjCIvarDecl::Private || 6396 Ivar->getAccessControl() == ObjCIvarDecl::Package; 6397 6398 if (ID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage) 6399 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 6400 else if (ID->hasAttr<DLLImportAttr>()) 6401 IvarOffsetGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6402 } 6403 } 6404 return IvarOffsetGV; 6405 } 6406 6407 llvm::Constant * 6408 CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, 6409 const ObjCIvarDecl *Ivar, 6410 unsigned long int Offset) { 6411 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar); 6412 IvarOffsetGV->setInitializer( 6413 llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset)); 6414 IvarOffsetGV->setAlignment( 6415 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy)); 6416 6417 if (!CGM.getTriple().isOSBinFormatCOFF()) { 6418 // FIXME: This matches gcc, but shouldn't the visibility be set on the use 6419 // as well (i.e., in ObjCIvarOffsetVariable). 6420 if (Ivar->getAccessControl() == ObjCIvarDecl::Private || 6421 Ivar->getAccessControl() == ObjCIvarDecl::Package || 6422 ID->getVisibility() == HiddenVisibility) 6423 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 6424 else 6425 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility); 6426 } 6427 6428 IvarOffsetGV->setSection("__DATA, __objc_ivar"); 6429 return IvarOffsetGV; 6430 } 6431 6432 /// EmitIvarList - Emit the ivar list for the given 6433 /// implementation. The return value has type 6434 /// IvarListnfABIPtrTy. 6435 /// struct _ivar_t { 6436 /// unsigned [long] int *offset; // pointer to ivar offset location 6437 /// char *name; 6438 /// char *type; 6439 /// uint32_t alignment; 6440 /// uint32_t size; 6441 /// } 6442 /// struct _ivar_list_t { 6443 /// uint32 entsize; // sizeof(struct _ivar_t) 6444 /// uint32 count; 6445 /// struct _iver_t list[count]; 6446 /// } 6447 /// 6448 6449 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( 6450 const ObjCImplementationDecl *ID) { 6451 6452 std::vector<llvm::Constant*> Ivars; 6453 6454 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 6455 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface"); 6456 6457 // FIXME. Consolidate this with similar code in GenerateClass. 6458 6459 for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 6460 IVD; IVD = IVD->getNextIvar()) { 6461 // Ignore unnamed bit-fields. 6462 if (!IVD->getDeclName()) 6463 continue; 6464 llvm::Constant *Ivar[5]; 6465 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD, 6466 ComputeIvarBaseOffset(CGM, ID, IVD)); 6467 Ivar[1] = GetMethodVarName(IVD->getIdentifier()); 6468 Ivar[2] = GetMethodVarType(IVD); 6469 llvm::Type *FieldTy = 6470 CGM.getTypes().ConvertTypeForMem(IVD->getType()); 6471 unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy); 6472 unsigned Align = CGM.getContext().getPreferredTypeAlign( 6473 IVD->getType().getTypePtr()) >> 3; 6474 Align = llvm::Log2_32(Align); 6475 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align); 6476 // NOTE. Size of a bitfield does not match gcc's, because of the 6477 // way bitfields are treated special in each. But I am told that 6478 // 'size' for bitfield ivars is ignored by the runtime so it does 6479 // not matter. If it matters, there is enough info to get the 6480 // bitfield right! 6481 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 6482 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar)); 6483 } 6484 // Return null for empty list. 6485 if (Ivars.empty()) 6486 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 6487 6488 llvm::Constant *Values[3]; 6489 unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy); 6490 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 6491 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 6492 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy, 6493 Ivars.size()); 6494 Values[2] = llvm::ConstantArray::get(AT, Ivars); 6495 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 6496 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_"; 6497 llvm::GlobalVariable *GV = 6498 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, 6499 llvm::GlobalValue::PrivateLinkage, 6500 Init, 6501 Prefix + OID->getObjCRuntimeNameAsString()); 6502 GV->setAlignment( 6503 CGM.getDataLayout().getABITypeAlignment(Init->getType())); 6504 GV->setSection("__DATA, __objc_const"); 6505 6506 CGM.addCompilerUsedGlobal(GV); 6507 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy); 6508 } 6509 6510 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef( 6511 const ObjCProtocolDecl *PD) { 6512 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 6513 6514 if (!Entry) 6515 // We use the initializer as a marker of whether this is a forward 6516 // reference or not. At module finalization we add the empty 6517 // contents for protocols which were referenced but never defined. 6518 Entry = 6519 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, 6520 false, llvm::GlobalValue::ExternalLinkage, 6521 nullptr, 6522 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString()); 6523 6524 return Entry; 6525 } 6526 6527 /// GetOrEmitProtocol - Generate the protocol meta-data: 6528 /// @code 6529 /// struct _protocol_t { 6530 /// id isa; // NULL 6531 /// const char * const protocol_name; 6532 /// const struct _protocol_list_t * protocol_list; // super protocols 6533 /// const struct method_list_t * const instance_methods; 6534 /// const struct method_list_t * const class_methods; 6535 /// const struct method_list_t *optionalInstanceMethods; 6536 /// const struct method_list_t *optionalClassMethods; 6537 /// const struct _prop_list_t * properties; 6538 /// const uint32_t size; // sizeof(struct _protocol_t) 6539 /// const uint32_t flags; // = 0 6540 /// const char ** extendedMethodTypes; 6541 /// const char *demangledName; 6542 /// const struct _prop_list_t * class_properties; 6543 /// } 6544 /// @endcode 6545 /// 6546 6547 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( 6548 const ObjCProtocolDecl *PD) { 6549 llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()]; 6550 6551 // Early exit if a defining object has already been generated. 6552 if (Entry && Entry->hasInitializer()) 6553 return Entry; 6554 6555 // Use the protocol definition, if there is one. 6556 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 6557 PD = Def; 6558 6559 // Construct method lists. 6560 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 6561 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 6562 std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt; 6563 for (const auto *MD : PD->instance_methods()) { 6564 llvm::Constant *C = GetMethodDescriptionConstant(MD); 6565 if (!C) 6566 return GetOrEmitProtocolRef(PD); 6567 6568 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 6569 OptInstanceMethods.push_back(C); 6570 OptMethodTypesExt.push_back(GetMethodVarType(MD, true)); 6571 } else { 6572 InstanceMethods.push_back(C); 6573 MethodTypesExt.push_back(GetMethodVarType(MD, true)); 6574 } 6575 } 6576 6577 for (const auto *MD : PD->class_methods()) { 6578 llvm::Constant *C = GetMethodDescriptionConstant(MD); 6579 if (!C) 6580 return GetOrEmitProtocolRef(PD); 6581 6582 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 6583 OptClassMethods.push_back(C); 6584 OptMethodTypesExt.push_back(GetMethodVarType(MD, true)); 6585 } else { 6586 ClassMethods.push_back(C); 6587 MethodTypesExt.push_back(GetMethodVarType(MD, true)); 6588 } 6589 } 6590 6591 MethodTypesExt.insert(MethodTypesExt.end(), 6592 OptMethodTypesExt.begin(), OptMethodTypesExt.end()); 6593 6594 llvm::Constant *Values[13]; 6595 // isa is NULL 6596 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy); 6597 Values[1] = GetClassName(PD->getObjCRuntimeNameAsString()); 6598 Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(), 6599 PD->protocol_begin(), 6600 PD->protocol_end()); 6601 6602 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_" 6603 + PD->getObjCRuntimeNameAsString(), 6604 "__DATA, __objc_const", 6605 InstanceMethods); 6606 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_" 6607 + PD->getObjCRuntimeNameAsString(), 6608 "__DATA, __objc_const", 6609 ClassMethods); 6610 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_" 6611 + PD->getObjCRuntimeNameAsString(), 6612 "__DATA, __objc_const", 6613 OptInstanceMethods); 6614 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_" 6615 + PD->getObjCRuntimeNameAsString(), 6616 "__DATA, __objc_const", 6617 OptClassMethods); 6618 Values[7] = EmitPropertyList( 6619 "\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(), 6620 nullptr, PD, ObjCTypes, false); 6621 uint32_t Size = 6622 CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy); 6623 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 6624 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy); 6625 Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_" 6626 + PD->getObjCRuntimeNameAsString(), 6627 MethodTypesExt, ObjCTypes); 6628 // const char *demangledName; 6629 Values[11] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 6630 6631 Values[12] = EmitPropertyList( 6632 "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(), 6633 nullptr, PD, ObjCTypes, true); 6634 6635 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy, 6636 Values); 6637 6638 if (Entry) { 6639 // Already created, fix the linkage and update the initializer. 6640 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); 6641 Entry->setInitializer(Init); 6642 } else { 6643 Entry = 6644 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, 6645 false, llvm::GlobalValue::WeakAnyLinkage, Init, 6646 "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString()); 6647 Entry->setAlignment( 6648 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy)); 6649 6650 Protocols[PD->getIdentifier()] = Entry; 6651 } 6652 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 6653 CGM.addCompilerUsedGlobal(Entry); 6654 6655 // Use this protocol meta-data to build protocol list table in section 6656 // __DATA, __objc_protolist 6657 llvm::GlobalVariable *PTGV = 6658 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy, 6659 false, llvm::GlobalValue::WeakAnyLinkage, Entry, 6660 "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString()); 6661 PTGV->setAlignment( 6662 CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy)); 6663 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip"); 6664 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 6665 CGM.addCompilerUsedGlobal(PTGV); 6666 return Entry; 6667 } 6668 6669 /// EmitProtocolList - Generate protocol list meta-data: 6670 /// @code 6671 /// struct _protocol_list_t { 6672 /// long protocol_count; // Note, this is 32/64 bit 6673 /// struct _protocol_t[protocol_count]; 6674 /// } 6675 /// @endcode 6676 /// 6677 llvm::Constant * 6678 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name, 6679 ObjCProtocolDecl::protocol_iterator begin, 6680 ObjCProtocolDecl::protocol_iterator end) { 6681 SmallVector<llvm::Constant *, 16> ProtocolRefs; 6682 6683 // Just return null for empty protocol lists 6684 if (begin == end) 6685 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 6686 6687 // FIXME: We shouldn't need to do this lookup here, should we? 6688 SmallString<256> TmpName; 6689 Name.toVector(TmpName); 6690 llvm::GlobalVariable *GV = 6691 CGM.getModule().getGlobalVariable(TmpName.str(), true); 6692 if (GV) 6693 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy); 6694 6695 for (; begin != end; ++begin) 6696 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented??? 6697 6698 // This list is null terminated. 6699 ProtocolRefs.push_back(llvm::Constant::getNullValue( 6700 ObjCTypes.ProtocolnfABIPtrTy)); 6701 6702 llvm::Constant *Values[2]; 6703 Values[0] = 6704 llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 6705 Values[1] = 6706 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy, 6707 ProtocolRefs.size()), 6708 ProtocolRefs); 6709 6710 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); 6711 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, 6712 llvm::GlobalValue::PrivateLinkage, 6713 Init, Name); 6714 GV->setSection("__DATA, __objc_const"); 6715 GV->setAlignment( 6716 CGM.getDataLayout().getABITypeAlignment(Init->getType())); 6717 CGM.addCompilerUsedGlobal(GV); 6718 return llvm::ConstantExpr::getBitCast(GV, 6719 ObjCTypes.ProtocolListnfABIPtrTy); 6720 } 6721 6722 /// GetMethodDescriptionConstant - This routine build following meta-data: 6723 /// struct _objc_method { 6724 /// SEL _cmd; 6725 /// char *method_type; 6726 /// char *_imp; 6727 /// } 6728 6729 llvm::Constant * 6730 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 6731 llvm::Constant *Desc[3]; 6732 Desc[0] = 6733 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 6734 ObjCTypes.SelectorPtrTy); 6735 Desc[1] = GetMethodVarType(MD); 6736 if (!Desc[1]) 6737 return nullptr; 6738 6739 // Protocol methods have no implementation. So, this entry is always NULL. 6740 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 6741 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc); 6742 } 6743 6744 /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference. 6745 /// This code gen. amounts to generating code for: 6746 /// @code 6747 /// (type *)((char *)base + _OBJC_IVAR_$_.ivar; 6748 /// @encode 6749 /// 6750 LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar( 6751 CodeGen::CodeGenFunction &CGF, 6752 QualType ObjectTy, 6753 llvm::Value *BaseValue, 6754 const ObjCIvarDecl *Ivar, 6755 unsigned CVRQualifiers) { 6756 ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface(); 6757 llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar); 6758 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 6759 Offset); 6760 } 6761 6762 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset( 6763 CodeGen::CodeGenFunction &CGF, 6764 const ObjCInterfaceDecl *Interface, 6765 const ObjCIvarDecl *Ivar) { 6766 llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar); 6767 IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue, 6768 CGF.getSizeAlign(), "ivar"); 6769 if (IsIvarOffsetKnownIdempotent(CGF, Ivar)) 6770 cast<llvm::LoadInst>(IvarOffsetValue) 6771 ->setMetadata(CGM.getModule().getMDKindID("invariant.load"), 6772 llvm::MDNode::get(VMContext, None)); 6773 6774 // This could be 32bit int or 64bit integer depending on the architecture. 6775 // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value 6776 // as this is what caller always expectes. 6777 if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy) 6778 IvarOffsetValue = CGF.Builder.CreateIntCast( 6779 IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv"); 6780 return IvarOffsetValue; 6781 } 6782 6783 static void appendSelectorForMessageRefTable(std::string &buffer, 6784 Selector selector) { 6785 if (selector.isUnarySelector()) { 6786 buffer += selector.getNameForSlot(0); 6787 return; 6788 } 6789 6790 for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) { 6791 buffer += selector.getNameForSlot(i); 6792 buffer += '_'; 6793 } 6794 } 6795 6796 /// Emit a "vtable" message send. We emit a weak hidden-visibility 6797 /// struct, initially containing the selector pointer and a pointer to 6798 /// a "fixup" variant of the appropriate objc_msgSend. To call, we 6799 /// load and call the function pointer, passing the address of the 6800 /// struct as the second parameter. The runtime determines whether 6801 /// the selector is currently emitted using vtable dispatch; if so, it 6802 /// substitutes a stub function which simply tail-calls through the 6803 /// appropriate vtable slot, and if not, it substitues a stub function 6804 /// which tail-calls objc_msgSend. Both stubs adjust the selector 6805 /// argument to correctly point to the selector. 6806 RValue 6807 CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, 6808 ReturnValueSlot returnSlot, 6809 QualType resultType, 6810 Selector selector, 6811 llvm::Value *arg0, 6812 QualType arg0Type, 6813 bool isSuper, 6814 const CallArgList &formalArgs, 6815 const ObjCMethodDecl *method) { 6816 // Compute the actual arguments. 6817 CallArgList args; 6818 6819 // First argument: the receiver / super-call structure. 6820 if (!isSuper) 6821 arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy); 6822 args.add(RValue::get(arg0), arg0Type); 6823 6824 // Second argument: a pointer to the message ref structure. Leave 6825 // the actual argument value blank for now. 6826 args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy); 6827 6828 args.insert(args.end(), formalArgs.begin(), formalArgs.end()); 6829 6830 MessageSendInfo MSI = getMessageSendInfo(method, resultType, args); 6831 6832 NullReturnState nullReturn; 6833 6834 // Find the function to call and the mangled name for the message 6835 // ref structure. Using a different mangled name wouldn't actually 6836 // be a problem; it would just be a waste. 6837 // 6838 // The runtime currently never uses vtable dispatch for anything 6839 // except normal, non-super message-sends. 6840 // FIXME: don't use this for that. 6841 llvm::Constant *fn = nullptr; 6842 std::string messageRefName("\01l_"); 6843 if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) { 6844 if (isSuper) { 6845 fn = ObjCTypes.getMessageSendSuper2StretFixupFn(); 6846 messageRefName += "objc_msgSendSuper2_stret_fixup"; 6847 } else { 6848 nullReturn.init(CGF, arg0); 6849 fn = ObjCTypes.getMessageSendStretFixupFn(); 6850 messageRefName += "objc_msgSend_stret_fixup"; 6851 } 6852 } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) { 6853 fn = ObjCTypes.getMessageSendFpretFixupFn(); 6854 messageRefName += "objc_msgSend_fpret_fixup"; 6855 } else { 6856 if (isSuper) { 6857 fn = ObjCTypes.getMessageSendSuper2FixupFn(); 6858 messageRefName += "objc_msgSendSuper2_fixup"; 6859 } else { 6860 fn = ObjCTypes.getMessageSendFixupFn(); 6861 messageRefName += "objc_msgSend_fixup"; 6862 } 6863 } 6864 assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend"); 6865 messageRefName += '_'; 6866 6867 // Append the selector name, except use underscores anywhere we 6868 // would have used colons. 6869 appendSelectorForMessageRefTable(messageRefName, selector); 6870 6871 llvm::GlobalVariable *messageRef 6872 = CGM.getModule().getGlobalVariable(messageRefName); 6873 if (!messageRef) { 6874 // Build the message ref structure. 6875 llvm::Constant *values[] = { fn, GetMethodVarName(selector) }; 6876 llvm::Constant *init = llvm::ConstantStruct::getAnon(values); 6877 messageRef = new llvm::GlobalVariable(CGM.getModule(), 6878 init->getType(), 6879 /*constant*/ false, 6880 llvm::GlobalValue::WeakAnyLinkage, 6881 init, 6882 messageRefName); 6883 messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility); 6884 messageRef->setAlignment(16); 6885 messageRef->setSection("__DATA, __objc_msgrefs, coalesced"); 6886 } 6887 6888 bool requiresnullCheck = false; 6889 if (CGM.getLangOpts().ObjCAutoRefCount && method) 6890 for (const auto *ParamDecl : method->parameters()) { 6891 if (ParamDecl->hasAttr<NSConsumedAttr>()) { 6892 if (!nullReturn.NullBB) 6893 nullReturn.init(CGF, arg0); 6894 requiresnullCheck = true; 6895 break; 6896 } 6897 } 6898 6899 Address mref = 6900 Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy), 6901 CGF.getPointerAlign()); 6902 6903 // Update the message ref argument. 6904 args[1].RV = RValue::get(mref.getPointer()); 6905 6906 // Load the function to call from the message ref table. 6907 Address calleeAddr = 6908 CGF.Builder.CreateStructGEP(mref, 0, CharUnits::Zero()); 6909 llvm::Value *callee = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn"); 6910 6911 callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType); 6912 6913 RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args); 6914 return nullReturn.complete(CGF, result, resultType, formalArgs, 6915 requiresnullCheck ? method : nullptr); 6916 } 6917 6918 /// Generate code for a message send expression in the nonfragile abi. 6919 CodeGen::RValue 6920 CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 6921 ReturnValueSlot Return, 6922 QualType ResultType, 6923 Selector Sel, 6924 llvm::Value *Receiver, 6925 const CallArgList &CallArgs, 6926 const ObjCInterfaceDecl *Class, 6927 const ObjCMethodDecl *Method) { 6928 return isVTableDispatchedSelector(Sel) 6929 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel, 6930 Receiver, CGF.getContext().getObjCIdType(), 6931 false, CallArgs, Method) 6932 : EmitMessageSend(CGF, Return, ResultType, 6933 EmitSelector(CGF, Sel), 6934 Receiver, CGF.getContext().getObjCIdType(), 6935 false, CallArgs, Method, Class, ObjCTypes); 6936 } 6937 6938 llvm::GlobalVariable * 6939 CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name, bool Weak) { 6940 llvm::GlobalValue::LinkageTypes L = 6941 Weak ? llvm::GlobalValue::ExternalWeakLinkage 6942 : llvm::GlobalValue::ExternalLinkage; 6943 6944 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 6945 6946 if (!GV) 6947 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy, 6948 false, L, nullptr, Name); 6949 6950 assert(GV->getLinkage() == L); 6951 return GV; 6952 } 6953 6954 llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF, 6955 IdentifierInfo *II, 6956 bool Weak, 6957 const ObjCInterfaceDecl *ID) { 6958 CharUnits Align = CGF.getPointerAlign(); 6959 llvm::GlobalVariable *&Entry = ClassReferences[II]; 6960 6961 if (!Entry) { 6962 StringRef Name = ID ? ID->getObjCRuntimeNameAsString() : II->getName(); 6963 std::string ClassName = (getClassSymbolPrefix() + Name).str(); 6964 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak); 6965 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, 6966 false, llvm::GlobalValue::PrivateLinkage, 6967 ClassGV, "OBJC_CLASSLIST_REFERENCES_$_"); 6968 Entry->setAlignment(Align.getQuantity()); 6969 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip"); 6970 CGM.addCompilerUsedGlobal(Entry); 6971 } 6972 return CGF.Builder.CreateAlignedLoad(Entry, Align); 6973 } 6974 6975 llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF, 6976 const ObjCInterfaceDecl *ID) { 6977 // If the class has the objc_runtime_visible attribute, we need to 6978 // use the Objective-C runtime to get the class. 6979 if (ID->hasAttr<ObjCRuntimeVisibleAttr>()) 6980 return EmitClassRefViaRuntime(CGF, ID, ObjCTypes); 6981 6982 return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID); 6983 } 6984 6985 llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef( 6986 CodeGenFunction &CGF) { 6987 IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool"); 6988 return EmitClassRefFromId(CGF, II, false, nullptr); 6989 } 6990 6991 llvm::Value * 6992 CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF, 6993 const ObjCInterfaceDecl *ID) { 6994 CharUnits Align = CGF.getPointerAlign(); 6995 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()]; 6996 6997 if (!Entry) { 6998 llvm::SmallString<64> ClassName(getClassSymbolPrefix()); 6999 ClassName += ID->getObjCRuntimeNameAsString(); 7000 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), 7001 ID->isWeakImported()); 7002 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, 7003 false, llvm::GlobalValue::PrivateLinkage, 7004 ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_"); 7005 Entry->setAlignment(Align.getQuantity()); 7006 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); 7007 CGM.addCompilerUsedGlobal(Entry); 7008 } 7009 return CGF.Builder.CreateAlignedLoad(Entry, Align); 7010 } 7011 7012 /// EmitMetaClassRef - Return a Value * of the address of _class_t 7013 /// meta-data 7014 /// 7015 llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF, 7016 const ObjCInterfaceDecl *ID, 7017 bool Weak) { 7018 CharUnits Align = CGF.getPointerAlign(); 7019 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()]; 7020 if (!Entry) { 7021 llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix()); 7022 MetaClassName += ID->getObjCRuntimeNameAsString(); 7023 llvm::GlobalVariable *MetaClassGV = 7024 GetClassGlobal(MetaClassName.str(), Weak); 7025 7026 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, 7027 false, llvm::GlobalValue::PrivateLinkage, 7028 MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_"); 7029 Entry->setAlignment(Align.getQuantity()); 7030 7031 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); 7032 CGM.addCompilerUsedGlobal(Entry); 7033 } 7034 7035 return CGF.Builder.CreateAlignedLoad(Entry, Align); 7036 } 7037 7038 /// GetClass - Return a reference to the class for the given interface 7039 /// decl. 7040 llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF, 7041 const ObjCInterfaceDecl *ID) { 7042 if (ID->isWeakImported()) { 7043 llvm::SmallString<64> ClassName(getClassSymbolPrefix()); 7044 ClassName += ID->getObjCRuntimeNameAsString(); 7045 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true); 7046 (void)ClassGV; 7047 assert(ClassGV->hasExternalWeakLinkage()); 7048 } 7049 7050 return EmitClassRef(CGF, ID); 7051 } 7052 7053 /// Generates a message send where the super is the receiver. This is 7054 /// a message send to self with special delivery semantics indicating 7055 /// which class's method should be called. 7056 CodeGen::RValue 7057 CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 7058 ReturnValueSlot Return, 7059 QualType ResultType, 7060 Selector Sel, 7061 const ObjCInterfaceDecl *Class, 7062 bool isCategoryImpl, 7063 llvm::Value *Receiver, 7064 bool IsClassMessage, 7065 const CodeGen::CallArgList &CallArgs, 7066 const ObjCMethodDecl *Method) { 7067 // ... 7068 // Create and init a super structure; this is a (receiver, class) 7069 // pair we will pass to objc_msgSendSuper. 7070 Address ObjCSuper = 7071 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(), 7072 "objc_super"); 7073 7074 llvm::Value *ReceiverAsObject = 7075 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 7076 CGF.Builder.CreateStore( 7077 ReceiverAsObject, 7078 CGF.Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero())); 7079 7080 // If this is a class message the metaclass is passed as the target. 7081 llvm::Value *Target; 7082 if (IsClassMessage) 7083 Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported()); 7084 else 7085 Target = EmitSuperClassRef(CGF, Class); 7086 7087 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and 7088 // ObjCTypes types. 7089 llvm::Type *ClassTy = 7090 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 7091 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 7092 CGF.Builder.CreateStore( 7093 Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize())); 7094 7095 return (isVTableDispatchedSelector(Sel)) 7096 ? EmitVTableMessageSend(CGF, Return, ResultType, Sel, 7097 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy, 7098 true, CallArgs, Method) 7099 : EmitMessageSend(CGF, Return, ResultType, 7100 EmitSelector(CGF, Sel), 7101 ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy, 7102 true, CallArgs, Method, Class, ObjCTypes); 7103 } 7104 7105 llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF, 7106 Selector Sel) { 7107 Address Addr = EmitSelectorAddr(CGF, Sel); 7108 7109 llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr); 7110 LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), 7111 llvm::MDNode::get(VMContext, None)); 7112 return LI; 7113 } 7114 7115 Address CGObjCNonFragileABIMac::EmitSelectorAddr(CodeGenFunction &CGF, 7116 Selector Sel) { 7117 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 7118 7119 CharUnits Align = CGF.getPointerAlign(); 7120 if (!Entry) { 7121 llvm::Constant *Casted = 7122 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 7123 ObjCTypes.SelectorPtrTy); 7124 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, 7125 false, llvm::GlobalValue::PrivateLinkage, 7126 Casted, "OBJC_SELECTOR_REFERENCES_"); 7127 Entry->setExternallyInitialized(true); 7128 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip"); 7129 Entry->setAlignment(Align.getQuantity()); 7130 CGM.addCompilerUsedGlobal(Entry); 7131 } 7132 7133 return Address(Entry, Align); 7134 } 7135 7136 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 7137 /// objc_assign_ivar (id src, id *dst, ptrdiff_t) 7138 /// 7139 void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 7140 llvm::Value *src, 7141 Address dst, 7142 llvm::Value *ivarOffset) { 7143 llvm::Type * SrcTy = src->getType(); 7144 if (!isa<llvm::PointerType>(SrcTy)) { 7145 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 7146 assert(Size <= 8 && "does not support size > 8"); 7147 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 7148 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 7149 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 7150 } 7151 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 7152 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 7153 llvm::Value *args[] = { src, dst.getPointer(), ivarOffset }; 7154 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args); 7155 } 7156 7157 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 7158 /// objc_assign_strongCast (id src, id *dst) 7159 /// 7160 void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign( 7161 CodeGen::CodeGenFunction &CGF, 7162 llvm::Value *src, Address dst) { 7163 llvm::Type * SrcTy = src->getType(); 7164 if (!isa<llvm::PointerType>(SrcTy)) { 7165 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 7166 assert(Size <= 8 && "does not support size > 8"); 7167 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 7168 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 7169 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 7170 } 7171 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 7172 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 7173 llvm::Value *args[] = { src, dst.getPointer() }; 7174 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(), 7175 args, "weakassign"); 7176 } 7177 7178 void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable( 7179 CodeGen::CodeGenFunction &CGF, 7180 Address DestPtr, 7181 Address SrcPtr, 7182 llvm::Value *Size) { 7183 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy); 7184 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy); 7185 llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size }; 7186 CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args); 7187 } 7188 7189 /// EmitObjCWeakRead - Code gen for loading value of a __weak 7190 /// object: objc_read_weak (id *src) 7191 /// 7192 llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( 7193 CodeGen::CodeGenFunction &CGF, 7194 Address AddrWeakObj) { 7195 llvm::Type *DestTy = AddrWeakObj.getElementType(); 7196 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 7197 llvm::Value *read_weak = 7198 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(), 7199 AddrWeakObj.getPointer(), "weakread"); 7200 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); 7201 return read_weak; 7202 } 7203 7204 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 7205 /// objc_assign_weak (id src, id *dst) 7206 /// 7207 void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 7208 llvm::Value *src, Address dst) { 7209 llvm::Type * SrcTy = src->getType(); 7210 if (!isa<llvm::PointerType>(SrcTy)) { 7211 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 7212 assert(Size <= 8 && "does not support size > 8"); 7213 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 7214 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 7215 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 7216 } 7217 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 7218 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 7219 llvm::Value *args[] = { src, dst.getPointer() }; 7220 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(), 7221 args, "weakassign"); 7222 } 7223 7224 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 7225 /// objc_assign_global (id src, id *dst) 7226 /// 7227 void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 7228 llvm::Value *src, Address dst, 7229 bool threadlocal) { 7230 llvm::Type * SrcTy = src->getType(); 7231 if (!isa<llvm::PointerType>(SrcTy)) { 7232 unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); 7233 assert(Size <= 8 && "does not support size > 8"); 7234 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 7235 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 7236 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 7237 } 7238 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 7239 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 7240 llvm::Value *args[] = { src, dst.getPointer() }; 7241 if (!threadlocal) 7242 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(), 7243 args, "globalassign"); 7244 else 7245 CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(), 7246 args, "threadlocalassign"); 7247 } 7248 7249 void 7250 CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 7251 const ObjCAtSynchronizedStmt &S) { 7252 EmitAtSynchronizedStmt(CGF, S, 7253 cast<llvm::Function>(ObjCTypes.getSyncEnterFn()), 7254 cast<llvm::Function>(ObjCTypes.getSyncExitFn())); 7255 } 7256 7257 llvm::Constant * 7258 CGObjCNonFragileABIMac::GetEHType(QualType T) { 7259 // There's a particular fixed type info for 'id'. 7260 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) { 7261 auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id"); 7262 if (!IDEHType) { 7263 IDEHType = 7264 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, 7265 llvm::GlobalValue::ExternalLinkage, nullptr, 7266 "OBJC_EHTYPE_id"); 7267 if (CGM.getTriple().isOSBinFormatCOFF()) 7268 IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id")); 7269 } 7270 return IDEHType; 7271 } 7272 7273 // All other types should be Objective-C interface pointer types. 7274 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); 7275 assert(PT && "Invalid @catch type."); 7276 7277 const ObjCInterfaceType *IT = PT->getInterfaceType(); 7278 assert(IT && "Invalid @catch type."); 7279 7280 return GetInterfaceEHType(IT->getDecl(), false); 7281 } 7282 7283 void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF, 7284 const ObjCAtTryStmt &S) { 7285 EmitTryCatchStmt(CGF, S, 7286 cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()), 7287 cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()), 7288 cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn())); 7289 } 7290 7291 /// EmitThrowStmt - Generate code for a throw statement. 7292 void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 7293 const ObjCAtThrowStmt &S, 7294 bool ClearInsertionPoint) { 7295 if (const Expr *ThrowExpr = S.getThrowExpr()) { 7296 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); 7297 Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy); 7298 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception) 7299 .setDoesNotReturn(); 7300 } else { 7301 CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn()) 7302 .setDoesNotReturn(); 7303 } 7304 7305 CGF.Builder.CreateUnreachable(); 7306 if (ClearInsertionPoint) 7307 CGF.Builder.ClearInsertionPoint(); 7308 } 7309 7310 llvm::Constant * 7311 CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID, 7312 bool ForDefinition) { 7313 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()]; 7314 StringRef ClassName = ID->getObjCRuntimeNameAsString(); 7315 7316 // If we don't need a definition, return the entry if found or check 7317 // if we use an external reference. 7318 if (!ForDefinition) { 7319 if (Entry) 7320 return Entry; 7321 7322 // If this type (or a super class) has the __objc_exception__ 7323 // attribute, emit an external reference. 7324 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) { 7325 std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str(); 7326 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, 7327 false, llvm::GlobalValue::ExternalLinkage, 7328 nullptr, EHTypeName); 7329 if (CGM.getTriple().isOSBinFormatCOFF()) { 7330 if (ID->hasAttr<DLLExportAttr>()) 7331 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 7332 else if (ID->hasAttr<DLLImportAttr>()) 7333 Entry->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 7334 } 7335 return Entry; 7336 } 7337 } 7338 7339 // Otherwise we need to either make a new entry or fill in the initializer. 7340 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition"); 7341 7342 std::string VTableName = "objc_ehtype_vtable"; 7343 auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName); 7344 if (!VTableGV) { 7345 VTableGV = 7346 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false, 7347 llvm::GlobalValue::ExternalLinkage, nullptr, 7348 VTableName); 7349 if (CGM.getTriple().isOSBinFormatCOFF()) 7350 VTableGV->setDLLStorageClass(getStorage(CGM, VTableName)); 7351 } 7352 7353 llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2); 7354 llvm::Constant *Values[] = { 7355 llvm::ConstantExpr::getGetElementPtr(VTableGV->getValueType(), VTableGV, 7356 VTableIdx), 7357 GetClassName(ID->getObjCRuntimeNameAsString()), 7358 GetClassGlobal((getClassSymbolPrefix() + ClassName).str()), 7359 }; 7360 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values); 7361 7362 llvm::GlobalValue::LinkageTypes L = ForDefinition 7363 ? llvm::GlobalValue::ExternalLinkage 7364 : llvm::GlobalValue::WeakAnyLinkage; 7365 if (Entry) { 7366 Entry->setInitializer(Init); 7367 } else { 7368 Entry = 7369 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, L, 7370 Init, ("OBJC_EHTYPE_$_" + ClassName).str()); 7371 if (CGM.getTriple().isOSBinFormatCOFF()) 7372 if (hasObjCExceptionAttribute(CGM.getContext(), ID)) 7373 if (ID->hasAttr<DLLExportAttr>()) 7374 Entry->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 7375 } 7376 assert(Entry->getLinkage() == L); 7377 7378 if (!CGM.getTriple().isOSBinFormatCOFF()) 7379 if (ID->getVisibility() == HiddenVisibility) 7380 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 7381 7382 const auto &DL = CGM.getDataLayout(); 7383 Entry->setAlignment(DL.getABITypeAlignment(ObjCTypes.EHTypeTy)); 7384 7385 if (ForDefinition) 7386 Entry->setSection("__DATA,__objc_const"); 7387 7388 return Entry; 7389 } 7390 7391 /* *** */ 7392 7393 CodeGen::CGObjCRuntime * 7394 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { 7395 switch (CGM.getLangOpts().ObjCRuntime.getKind()) { 7396 case ObjCRuntime::FragileMacOSX: 7397 return new CGObjCMac(CGM); 7398 7399 case ObjCRuntime::MacOSX: 7400 case ObjCRuntime::iOS: 7401 case ObjCRuntime::WatchOS: 7402 return new CGObjCNonFragileABIMac(CGM); 7403 7404 case ObjCRuntime::GNUstep: 7405 case ObjCRuntime::GCC: 7406 case ObjCRuntime::ObjFW: 7407 llvm_unreachable("these runtimes are not Mac runtimes"); 7408 } 7409 llvm_unreachable("bad runtime"); 7410 } 7411