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