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