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