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