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