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