CGObjCGNU.cpp revision 80558d2db10a96eada4d8fb79949b3263b44652b
1//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 targetting the GNU runtime. The 11// class in this file generates structures used by the GNU Objective-C runtime 12// library. These structures are defined in objc/objc.h and objc/objc-api.h in 13// the GNU runtime distribution. 14// 15//===----------------------------------------------------------------------===// 16 17#include "CGObjCRuntime.h" 18#include "CodeGenModule.h" 19#include "CodeGenFunction.h" 20#include "CGCleanup.h" 21 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/Decl.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/RecordLayout.h" 26#include "clang/AST/StmtObjC.h" 27 28#include "llvm/Intrinsics.h" 29#include "llvm/Module.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/ADT/SmallVector.h" 32#include "llvm/ADT/StringMap.h" 33#include "llvm/Support/CallSite.h" 34#include "llvm/Support/Compiler.h" 35#include "llvm/Target/TargetData.h" 36 37#include <map> 38 39 40using namespace clang; 41using namespace CodeGen; 42using llvm::dyn_cast; 43 44// The version of the runtime that this class targets. Must match the version 45// in the runtime. 46static const int RuntimeVersion = 8; 47static const int NonFragileRuntimeVersion = 9; 48static const int ProtocolVersion = 2; 49static const int NonFragileProtocolVersion = 3; 50 51namespace { 52class CGObjCGNU : public CodeGen::CGObjCRuntime { 53private: 54 CodeGen::CodeGenModule &CGM; 55 llvm::Module &TheModule; 56 const llvm::PointerType *SelectorTy; 57 const llvm::IntegerType *Int8Ty; 58 const llvm::PointerType *PtrToInt8Ty; 59 const llvm::FunctionType *IMPTy; 60 const llvm::PointerType *IdTy; 61 const llvm::PointerType *PtrToIdTy; 62 CanQualType ASTIdTy; 63 const llvm::IntegerType *IntTy; 64 const llvm::PointerType *PtrTy; 65 const llvm::IntegerType *LongTy; 66 const llvm::IntegerType *SizeTy; 67 const llvm::IntegerType *PtrDiffTy; 68 const llvm::PointerType *PtrToIntTy; 69 const llvm::Type *BoolTy; 70 llvm::GlobalAlias *ClassPtrAlias; 71 llvm::GlobalAlias *MetaClassPtrAlias; 72 std::vector<llvm::Constant*> Classes; 73 std::vector<llvm::Constant*> Categories; 74 std::vector<llvm::Constant*> ConstantStrings; 75 llvm::StringMap<llvm::Constant*> ObjCStrings; 76 llvm::Function *LoadFunction; 77 llvm::StringMap<llvm::Constant*> ExistingProtocols; 78 typedef std::pair<std::string, std::string> TypedSelector; 79 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors; 80 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors; 81 // Selectors that we don't emit in GC mode 82 Selector RetainSel, ReleaseSel, AutoreleaseSel; 83 // Functions used for GC. 84 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn, 85 *WeakAssignFn, *GlobalAssignFn; 86 // Some zeros used for GEPs in lots of places. 87 llvm::Constant *Zeros[2]; 88 llvm::Constant *NULLPtr; 89 llvm::LLVMContext &VMContext; 90 /// Metadata kind used to tie method lookups to message sends. 91 unsigned msgSendMDKind; 92private: 93 llvm::Constant *GenerateIvarList( 94 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames, 95 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes, 96 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets); 97 llvm::Constant *GenerateMethodList(const std::string &ClassName, 98 const std::string &CategoryName, 99 const llvm::SmallVectorImpl<Selector> &MethodSels, 100 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes, 101 bool isClassMethodList); 102 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName); 103 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID, 104 llvm::SmallVectorImpl<Selector> &InstanceMethodSels, 105 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes); 106 llvm::Constant *GenerateProtocolList( 107 const llvm::SmallVectorImpl<std::string> &Protocols); 108 // To ensure that all protocols are seen by the runtime, we add a category on 109 // a class defined in the runtime, declaring no methods, but adopting the 110 // protocols. 111 void GenerateProtocolHolderCategory(void); 112 llvm::Constant *GenerateClassStructure( 113 llvm::Constant *MetaClass, 114 llvm::Constant *SuperClass, 115 unsigned info, 116 const char *Name, 117 llvm::Constant *Version, 118 llvm::Constant *InstanceSize, 119 llvm::Constant *IVars, 120 llvm::Constant *Methods, 121 llvm::Constant *Protocols, 122 llvm::Constant *IvarOffsets, 123 llvm::Constant *Properties, 124 bool isMeta=false); 125 llvm::Constant *GenerateProtocolMethodList( 126 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames, 127 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes); 128 llvm::Constant *MakeConstantString(const std::string &Str, const std::string 129 &Name=""); 130 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string 131 prefix); 132 llvm::Constant *MakeGlobal(const llvm::StructType *Ty, 133 std::vector<llvm::Constant*> &V, llvm::StringRef Name="", 134 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage); 135 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty, 136 std::vector<llvm::Constant*> &V, llvm::StringRef Name="", 137 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage); 138 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 139 const ObjCIvarDecl *Ivar); 140 void EmitClassRef(const std::string &className); 141 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){ 142 if (V->getType() == Ty) return V; 143 return B.CreateBitCast(V, Ty); 144 } 145 void EmitObjCXXTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S); 146public: 147 CGObjCGNU(CodeGen::CodeGenModule &cgm); 148 virtual llvm::Constant *GenerateConstantString(const StringLiteral *); 149 virtual CodeGen::RValue 150 GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 151 ReturnValueSlot Return, 152 QualType ResultType, 153 Selector Sel, 154 llvm::Value *Receiver, 155 const CallArgList &CallArgs, 156 const ObjCInterfaceDecl *Class, 157 const ObjCMethodDecl *Method); 158 virtual CodeGen::RValue 159 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 160 ReturnValueSlot Return, 161 QualType ResultType, 162 Selector Sel, 163 const ObjCInterfaceDecl *Class, 164 bool isCategoryImpl, 165 llvm::Value *Receiver, 166 bool IsClassMessage, 167 const CallArgList &CallArgs, 168 const ObjCMethodDecl *Method); 169 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 170 const ObjCInterfaceDecl *OID); 171 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel, 172 bool lval = false); 173 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl 174 *Method); 175 virtual llvm::Constant *GetEHType(QualType T); 176 177 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 178 const ObjCContainerDecl *CD); 179 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 180 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 181 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 182 const ObjCProtocolDecl *PD); 183 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 184 virtual llvm::Function *ModuleInitFunction(); 185 virtual llvm::Function *GetPropertyGetFunction(); 186 virtual llvm::Function *GetPropertySetFunction(); 187 virtual llvm::Function *GetSetStructFunction(); 188 virtual llvm::Function *GetGetStructFunction(); 189 virtual llvm::Constant *EnumerationMutationFunction(); 190 191 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF, 192 const ObjCAtTryStmt &S); 193 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 194 const ObjCAtSynchronizedStmt &S); 195 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 196 const ObjCAtThrowStmt &S); 197 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 198 llvm::Value *AddrWeakObj); 199 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 200 llvm::Value *src, llvm::Value *dst); 201 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 202 llvm::Value *src, llvm::Value *dest, 203 bool threadlocal=false); 204 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 205 llvm::Value *src, llvm::Value *dest, 206 llvm::Value *ivarOffset); 207 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 208 llvm::Value *src, llvm::Value *dest); 209 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 210 llvm::Value *DestPtr, 211 llvm::Value *SrcPtr, 212 llvm::Value *Size); 213 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 214 QualType ObjectTy, 215 llvm::Value *BaseValue, 216 const ObjCIvarDecl *Ivar, 217 unsigned CVRQualifiers); 218 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 219 const ObjCInterfaceDecl *Interface, 220 const ObjCIvarDecl *Ivar); 221 virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM, 222 const CGBlockInfo &blockInfo) { 223 return NULLPtr; 224 } 225}; 226} // end anonymous namespace 227 228 229/// Emits a reference to a dummy variable which is emitted with each class. 230/// This ensures that a linker error will be generated when trying to link 231/// together modules where a referenced class is not defined. 232void CGObjCGNU::EmitClassRef(const std::string &className) { 233 std::string symbolRef = "__objc_class_ref_" + className; 234 // Don't emit two copies of the same symbol 235 if (TheModule.getGlobalVariable(symbolRef)) 236 return; 237 std::string symbolName = "__objc_class_name_" + className; 238 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName); 239 if (!ClassSymbol) { 240 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 241 llvm::GlobalValue::ExternalLinkage, 0, symbolName); 242 } 243 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true, 244 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef); 245} 246 247static std::string SymbolNameForMethod(const std::string &ClassName, const 248 std::string &CategoryName, const std::string &MethodName, bool isClassMethod) 249{ 250 std::string MethodNameColonStripped = MethodName; 251 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(), 252 ':', '_'); 253 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" + 254 CategoryName + "_" + MethodNameColonStripped; 255} 256static std::string MangleSelectorTypes(const std::string &TypeString) { 257 std::string Mangled = TypeString; 258 // Simple mangling to avoid breaking when we mix JIT / static code. 259 // Not part of the ABI, subject to change without notice. 260 std::replace(Mangled.begin(), Mangled.end(), '@', '_'); 261 std::replace(Mangled.begin(), Mangled.end(), ':', 'J'); 262 std::replace(Mangled.begin(), Mangled.end(), '*', 'e'); 263 std::replace(Mangled.begin(), Mangled.end(), '#', 'E'); 264 std::replace(Mangled.begin(), Mangled.end(), ':', 'j'); 265 std::replace(Mangled.begin(), Mangled.end(), '(', 'g'); 266 std::replace(Mangled.begin(), Mangled.end(), ')', 'G'); 267 std::replace(Mangled.begin(), Mangled.end(), '[', 'h'); 268 std::replace(Mangled.begin(), Mangled.end(), ']', 'H'); 269 return Mangled; 270} 271 272CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm) 273 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0), 274 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) { 275 276 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend"); 277 278 IntTy = cast<llvm::IntegerType>( 279 CGM.getTypes().ConvertType(CGM.getContext().IntTy)); 280 LongTy = cast<llvm::IntegerType>( 281 CGM.getTypes().ConvertType(CGM.getContext().LongTy)); 282 SizeTy = cast<llvm::IntegerType>( 283 CGM.getTypes().ConvertType(CGM.getContext().getSizeType())); 284 PtrDiffTy = cast<llvm::IntegerType>( 285 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType())); 286 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 287 288 Int8Ty = llvm::Type::getInt8Ty(VMContext); 289 // C string type. Used in lots of places. 290 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty); 291 292 Zeros[0] = llvm::ConstantInt::get(LongTy, 0); 293 Zeros[1] = Zeros[0]; 294 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty); 295 // Get the selector Type. 296 QualType selTy = CGM.getContext().getObjCSelType(); 297 if (QualType() == selTy) { 298 SelectorTy = PtrToInt8Ty; 299 } else { 300 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy)); 301 } 302 303 PtrToIntTy = llvm::PointerType::getUnqual(IntTy); 304 PtrTy = PtrToInt8Ty; 305 306 // Object type 307 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType()); 308 if (QualType() == ASTIdTy) { 309 IdTy = PtrToInt8Ty; 310 } else { 311 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 312 } 313 PtrToIdTy = llvm::PointerType::getUnqual(IdTy); 314 315 // IMP type 316 std::vector<const llvm::Type*> IMPArgs; 317 IMPArgs.push_back(IdTy); 318 IMPArgs.push_back(SelectorTy); 319 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true); 320 321 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) { 322 // Get selectors needed in GC mode 323 RetainSel = GetNullarySelector("retain", CGM.getContext()); 324 ReleaseSel = GetNullarySelector("release", CGM.getContext()); 325 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext()); 326 327 // Get functions needed in GC mode 328 329 // id objc_assign_ivar(id, id, ptrdiff_t); 330 std::vector<const llvm::Type*> Args(1, IdTy); 331 Args.push_back(PtrToIdTy); 332 Args.push_back(PtrDiffTy); 333 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false); 334 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar"); 335 // id objc_assign_strongCast (id, id*) 336 Args.pop_back(); 337 FTy = llvm::FunctionType::get(IdTy, Args, false); 338 StrongCastAssignFn = 339 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast"); 340 // id objc_assign_global(id, id*); 341 FTy = llvm::FunctionType::get(IdTy, Args, false); 342 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global"); 343 // id objc_assign_weak(id, id*); 344 FTy = llvm::FunctionType::get(IdTy, Args, false); 345 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak"); 346 // id objc_read_weak(id*); 347 Args.clear(); 348 Args.push_back(PtrToIdTy); 349 FTy = llvm::FunctionType::get(IdTy, Args, false); 350 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak"); 351 // void *objc_memmove_collectable(void*, void *, size_t); 352 Args.clear(); 353 Args.push_back(PtrToInt8Ty); 354 Args.push_back(PtrToInt8Ty); 355 Args.push_back(SizeTy); 356 FTy = llvm::FunctionType::get(IdTy, Args, false); 357 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable"); 358 } 359} 360 361// This has to perform the lookup every time, since posing and related 362// techniques can modify the name -> class mapping. 363llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder, 364 const ObjCInterfaceDecl *OID) { 365 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString()); 366 // With the incompatible ABI, this will need to be replaced with a direct 367 // reference to the class symbol. For the compatible nonfragile ABI we are 368 // still performing this lookup at run time but emitting the symbol for the 369 // class externally so that we can make the switch later. 370 EmitClassRef(OID->getNameAsString()); 371 ClassName = Builder.CreateStructGEP(ClassName, 0); 372 373 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty); 374 llvm::Constant *ClassLookupFn = 375 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, 376 Params, 377 true), 378 "objc_lookup_class"); 379 return Builder.CreateCall(ClassLookupFn, ClassName); 380} 381 382llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel, 383 bool lval) { 384 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()]; 385 if (US == 0) 386 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy), 387 llvm::GlobalValue::PrivateLinkage, 388 ".objc_untyped_selector_alias"+Sel.getAsString(), 389 NULL, &TheModule); 390 if (lval) 391 return US; 392 return Builder.CreateLoad(US); 393} 394 395llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl 396 *Method) { 397 398 std::string SelName = Method->getSelector().getAsString(); 399 std::string SelTypes; 400 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes); 401 // Typed selectors 402 TypedSelector Selector = TypedSelector(SelName, 403 SelTypes); 404 405 // If it's already cached, return it. 406 if (TypedSelectors[Selector]) { 407 return Builder.CreateLoad(TypedSelectors[Selector]); 408 } 409 410 // If it isn't, cache it. 411 llvm::GlobalAlias *Sel = new llvm::GlobalAlias( 412 llvm::PointerType::getUnqual(SelectorTy), 413 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName, 414 NULL, &TheModule); 415 TypedSelectors[Selector] = Sel; 416 417 return Builder.CreateLoad(Sel); 418} 419 420llvm::Constant *CGObjCGNU::GetEHType(QualType T) { 421 // For Objective-C++, we want to provide the ability to catch both C++ and 422 // Objective-C objects in the same function. 423 424 // There's a particular fixed type info for 'id'. 425 if (T->isObjCIdType() || 426 T->isObjCQualifiedIdType()) { 427 llvm::Constant *IDEHType = 428 CGM.getModule().getGlobalVariable("__objc_id_type_info"); 429 if (!IDEHType) 430 IDEHType = 431 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty, 432 false, 433 llvm::GlobalValue::ExternalLinkage, 434 0, "__objc_id_type_info"); 435 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty); 436 } 437 438 const ObjCObjectPointerType *PT = 439 T->getAs<ObjCObjectPointerType>(); 440 assert(PT && "Invalid @catch type."); 441 const ObjCInterfaceType *IT = PT->getInterfaceType(); 442 assert(IT && "Invalid @catch type."); 443 std::string className = IT->getDecl()->getIdentifier()->getName(); 444 445 std::string typeinfoName = "__objc_eh_typeinfo_" + className; 446 447 // Return the existing typeinfo if it exists 448 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName); 449 if (typeinfo) return typeinfo; 450 451 // Otherwise create it. 452 453 // vtable for gnustep::libobjc::__objc_class_type_info 454 // It's quite ugly hard-coding this. Ideally we'd generate it using the host 455 // platform's name mangling. 456 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE"; 457 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName); 458 if (!Vtable) { 459 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true, 460 llvm::GlobalValue::ExternalLinkage, 0, vtableName); 461 } 462 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2); 463 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1); 464 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty); 465 466 llvm::Constant *typeName = 467 ExportUniqueString(className, "__objc_eh_typename_"); 468 469 std::vector<llvm::Constant*> fields; 470 fields.push_back(Vtable); 471 fields.push_back(typeName); 472 llvm::Constant *TI = 473 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, 474 NULL), fields, "__objc_eh_typeinfo_" + className, 475 llvm::GlobalValue::LinkOnceODRLinkage); 476 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty); 477} 478 479llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str, 480 const std::string &Name) { 481 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str()); 482 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2); 483} 484llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str, 485 const std::string prefix) { 486 std::string name = prefix + Str; 487 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name); 488 if (!ConstStr) { 489 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true); 490 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true, 491 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str); 492 } 493 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2); 494} 495 496llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty, 497 std::vector<llvm::Constant*> &V, llvm::StringRef Name, 498 llvm::GlobalValue::LinkageTypes linkage) { 499 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V); 500 return new llvm::GlobalVariable(TheModule, Ty, false, 501 linkage, C, Name); 502} 503 504llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty, 505 std::vector<llvm::Constant*> &V, llvm::StringRef Name, 506 llvm::GlobalValue::LinkageTypes linkage) { 507 llvm::Constant *C = llvm::ConstantArray::get(Ty, V); 508 return new llvm::GlobalVariable(TheModule, Ty, false, 509 linkage, C, Name); 510} 511 512/// Generate an NSConstantString object. 513llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) { 514 515 std::string Str = SL->getString().str(); 516 517 // Look for an existing one 518 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str); 519 if (old != ObjCStrings.end()) 520 return old->getValue(); 521 522 std::vector<llvm::Constant*> Ivars; 523 Ivars.push_back(NULLPtr); 524 Ivars.push_back(MakeConstantString(Str)); 525 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size())); 526 llvm::Constant *ObjCStr = MakeGlobal( 527 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL), 528 Ivars, ".objc_str"); 529 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty); 530 ObjCStrings[Str] = ObjCStr; 531 ConstantStrings.push_back(ObjCStr); 532 return ObjCStr; 533} 534 535///Generates a message send where the super is the receiver. This is a message 536///send to self with special delivery semantics indicating which class's method 537///should be called. 538CodeGen::RValue 539CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 540 ReturnValueSlot Return, 541 QualType ResultType, 542 Selector Sel, 543 const ObjCInterfaceDecl *Class, 544 bool isCategoryImpl, 545 llvm::Value *Receiver, 546 bool IsClassMessage, 547 const CallArgList &CallArgs, 548 const ObjCMethodDecl *Method) { 549 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) { 550 if (Sel == RetainSel || Sel == AutoreleaseSel) { 551 return RValue::get(Receiver); 552 } 553 if (Sel == ReleaseSel) { 554 return RValue::get(0); 555 } 556 } 557 558 CGBuilderTy &Builder = CGF.Builder; 559 llvm::Value *cmd = GetSelector(Builder, Sel); 560 561 562 CallArgList ActualArgs; 563 564 ActualArgs.push_back( 565 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)), 566 ASTIdTy)); 567 ActualArgs.push_back(std::make_pair(RValue::get(cmd), 568 CGF.getContext().getObjCSelType())); 569 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 570 571 CodeGenTypes &Types = CGM.getTypes(); 572 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs, 573 FunctionType::ExtInfo()); 574 const llvm::FunctionType *impType = 575 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false); 576 577 llvm::Value *ReceiverClass = 0; 578 if (isCategoryImpl) { 579 llvm::Constant *classLookupFunction = 0; 580 std::vector<const llvm::Type*> Params; 581 Params.push_back(PtrTy); 582 if (IsClassMessage) { 583 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 584 IdTy, Params, true), "objc_get_meta_class"); 585 } else { 586 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 587 IdTy, Params, true), "objc_get_class"); 588 } 589 ReceiverClass = Builder.CreateCall(classLookupFunction, 590 MakeConstantString(Class->getNameAsString())); 591 } else { 592 // Set up global aliases for the metaclass or class pointer if they do not 593 // already exist. These will are forward-references which will be set to 594 // pointers to the class and metaclass structure created for the runtime 595 // load function. To send a message to super, we look up the value of the 596 // super_class pointer from either the class or metaclass structure. 597 if (IsClassMessage) { 598 if (!MetaClassPtrAlias) { 599 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy, 600 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" + 601 Class->getNameAsString(), NULL, &TheModule); 602 } 603 ReceiverClass = MetaClassPtrAlias; 604 } else { 605 if (!ClassPtrAlias) { 606 ClassPtrAlias = new llvm::GlobalAlias(IdTy, 607 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" + 608 Class->getNameAsString(), NULL, &TheModule); 609 } 610 ReceiverClass = ClassPtrAlias; 611 } 612 } 613 // Cast the pointer to a simplified version of the class structure 614 ReceiverClass = Builder.CreateBitCast(ReceiverClass, 615 llvm::PointerType::getUnqual( 616 llvm::StructType::get(VMContext, IdTy, IdTy, NULL))); 617 // Get the superclass pointer 618 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1); 619 // Load the superclass pointer 620 ReceiverClass = Builder.CreateLoad(ReceiverClass); 621 // Construct the structure used to look up the IMP 622 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext, 623 Receiver->getType(), IdTy, NULL); 624 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy); 625 626 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0)); 627 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1)); 628 629 // Get the IMP 630 std::vector<const llvm::Type*> Params; 631 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy)); 632 Params.push_back(SelectorTy); 633 634 llvm::Value *lookupArgs[] = {ObjCSuper, cmd}; 635 llvm::Value *imp; 636 637 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 638 // The lookup function returns a slot, which can be safely cached. 639 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy, 640 IntTy, llvm::PointerType::getUnqual(impType), NULL); 641 642 llvm::Constant *lookupFunction = 643 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 644 llvm::PointerType::getUnqual(SlotTy), Params, true), 645 "objc_slot_lookup_super"); 646 647 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs, 648 lookupArgs+2); 649 slot->setOnlyReadsMemory(); 650 651 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4)); 652 } else { 653 llvm::Constant *lookupFunction = 654 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 655 llvm::PointerType::getUnqual(impType), Params, true), 656 "objc_msg_lookup_super"); 657 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2); 658 } 659 660 llvm::Value *impMD[] = { 661 llvm::MDString::get(VMContext, Sel.getAsString()), 662 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()), 663 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage) 664 }; 665 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3); 666 667 llvm::Instruction *call; 668 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs, 669 0, &call); 670 call->setMetadata(msgSendMDKind, node); 671 return msgRet; 672} 673 674/// Generate code for a message send expression. 675CodeGen::RValue 676CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 677 ReturnValueSlot Return, 678 QualType ResultType, 679 Selector Sel, 680 llvm::Value *Receiver, 681 const CallArgList &CallArgs, 682 const ObjCInterfaceDecl *Class, 683 const ObjCMethodDecl *Method) { 684 // Strip out message sends to retain / release in GC mode 685 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) { 686 if (Sel == RetainSel || Sel == AutoreleaseSel) { 687 return RValue::get(Receiver); 688 } 689 if (Sel == ReleaseSel) { 690 return RValue::get(0); 691 } 692 } 693 694 CGBuilderTy &Builder = CGF.Builder; 695 696 // If the return type is something that goes in an integer register, the 697 // runtime will handle 0 returns. For other cases, we fill in the 0 value 698 // ourselves. 699 // 700 // The language spec says the result of this kind of message send is 701 // undefined, but lots of people seem to have forgotten to read that 702 // paragraph and insist on sending messages to nil that have structure 703 // returns. With GCC, this generates a random return value (whatever happens 704 // to be on the stack / in those registers at the time) on most platforms, 705 // and generates a SegV on SPARC. With LLVM it corrupts the stack. 706 bool isPointerSizedReturn = false; 707 if (ResultType->isAnyPointerType() || 708 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType()) 709 isPointerSizedReturn = true; 710 711 llvm::BasicBlock *startBB = 0; 712 llvm::BasicBlock *messageBB = 0; 713 llvm::BasicBlock *continueBB = 0; 714 715 if (!isPointerSizedReturn) { 716 startBB = Builder.GetInsertBlock(); 717 messageBB = CGF.createBasicBlock("msgSend"); 718 continueBB = CGF.createBasicBlock("continue"); 719 720 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 721 llvm::Constant::getNullValue(Receiver->getType())); 722 Builder.CreateCondBr(isNil, continueBB, messageBB); 723 CGF.EmitBlock(messageBB); 724 } 725 726 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 727 llvm::Value *cmd; 728 if (Method) 729 cmd = GetSelector(Builder, Method); 730 else 731 cmd = GetSelector(Builder, Sel); 732 CallArgList ActualArgs; 733 734 Receiver = Builder.CreateBitCast(Receiver, IdTy); 735 ActualArgs.push_back( 736 std::make_pair(RValue::get(Receiver), ASTIdTy)); 737 ActualArgs.push_back(std::make_pair(RValue::get(cmd), 738 CGF.getContext().getObjCSelType())); 739 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 740 741 CodeGenTypes &Types = CGM.getTypes(); 742 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs, 743 FunctionType::ExtInfo()); 744 const llvm::FunctionType *impType = 745 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false); 746 747 llvm::Value *impMD[] = { 748 llvm::MDString::get(VMContext, Sel.getAsString()), 749 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""), 750 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0) 751 }; 752 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3); 753 754 755 llvm::Value *imp; 756 // For sender-aware dispatch, we pass the sender as the third argument to a 757 // lookup function. When sending messages from C code, the sender is nil. 758 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender); 759 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 760 761 std::vector<const llvm::Type*> Params; 762 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType()); 763 Builder.CreateStore(Receiver, ReceiverPtr); 764 Params.push_back(ReceiverPtr->getType()); 765 Params.push_back(SelectorTy); 766 llvm::Value *self; 767 768 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) { 769 self = CGF.LoadObjCSelf(); 770 } else { 771 self = llvm::ConstantPointerNull::get(IdTy); 772 } 773 774 Params.push_back(self->getType()); 775 776 // The lookup function returns a slot, which can be safely cached. 777 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy, 778 IntTy, llvm::PointerType::getUnqual(impType), NULL); 779 llvm::Constant *lookupFunction = 780 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 781 llvm::PointerType::getUnqual(SlotTy), Params, true), 782 "objc_msg_lookup_sender"); 783 784 // The lookup function is guaranteed not to capture the receiver pointer. 785 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) { 786 LookupFn->setDoesNotCapture(1); 787 } 788 789 llvm::CallInst *slot = 790 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self); 791 slot->setOnlyReadsMemory(); 792 slot->setMetadata(msgSendMDKind, node); 793 794 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4)); 795 796 // The lookup function may have changed the receiver, so make sure we use 797 // the new one. 798 ActualArgs[0] = std::make_pair(RValue::get( 799 Builder.CreateLoad(ReceiverPtr, true)), ASTIdTy); 800 } else { 801 std::vector<const llvm::Type*> Params; 802 Params.push_back(Receiver->getType()); 803 Params.push_back(SelectorTy); 804 llvm::Constant *lookupFunction = 805 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 806 llvm::PointerType::getUnqual(impType), Params, true), 807 "objc_msg_lookup"); 808 809 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd); 810 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node); 811 } 812 llvm::Instruction *call; 813 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs, 814 0, &call); 815 call->setMetadata(msgSendMDKind, node); 816 817 818 if (!isPointerSizedReturn) { 819 messageBB = CGF.Builder.GetInsertBlock(); 820 CGF.Builder.CreateBr(continueBB); 821 CGF.EmitBlock(continueBB); 822 if (msgRet.isScalar()) { 823 llvm::Value *v = msgRet.getScalarVal(); 824 llvm::PHINode *phi = Builder.CreatePHI(v->getType()); 825 phi->addIncoming(v, messageBB); 826 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB); 827 msgRet = RValue::get(phi); 828 } else if (msgRet.isAggregate()) { 829 llvm::Value *v = msgRet.getAggregateAddr(); 830 llvm::PHINode *phi = Builder.CreatePHI(v->getType()); 831 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType()); 832 llvm::AllocaInst *NullVal = 833 CGF.CreateTempAlloca(RetTy->getElementType(), "null"); 834 CGF.InitTempAlloca(NullVal, 835 llvm::Constant::getNullValue(RetTy->getElementType())); 836 phi->addIncoming(v, messageBB); 837 phi->addIncoming(NullVal, startBB); 838 msgRet = RValue::getAggregate(phi); 839 } else /* isComplex() */ { 840 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal(); 841 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType()); 842 phi->addIncoming(v.first, messageBB); 843 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()), 844 startBB); 845 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType()); 846 phi2->addIncoming(v.second, messageBB); 847 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()), 848 startBB); 849 msgRet = RValue::getComplex(phi, phi2); 850 } 851 } 852 return msgRet; 853} 854 855/// Generates a MethodList. Used in construction of a objc_class and 856/// objc_category structures. 857llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName, 858 const std::string &CategoryName, 859 const llvm::SmallVectorImpl<Selector> &MethodSels, 860 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes, 861 bool isClassMethodList) { 862 if (MethodSels.empty()) 863 return NULLPtr; 864 // Get the method structure type. 865 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext, 866 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 867 PtrToInt8Ty, // Method types 868 llvm::PointerType::getUnqual(IMPTy), //Method pointer 869 NULL); 870 std::vector<llvm::Constant*> Methods; 871 std::vector<llvm::Constant*> Elements; 872 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) { 873 Elements.clear(); 874 if (llvm::Constant *Method = 875 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName, 876 MethodSels[i].getAsString(), 877 isClassMethodList))) { 878 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString()); 879 Elements.push_back(C); 880 Elements.push_back(MethodTypes[i]); 881 Method = llvm::ConstantExpr::getBitCast(Method, 882 llvm::PointerType::getUnqual(IMPTy)); 883 Elements.push_back(Method); 884 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements)); 885 } 886 } 887 888 // Array of method structures 889 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy, 890 Methods.size()); 891 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy, 892 Methods); 893 894 // Structure containing list pointer, array and array count 895 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields; 896 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext); 897 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy); 898 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext, 899 NextPtrTy, 900 IntTy, 901 ObjCMethodArrayTy, 902 NULL); 903 // Refine next pointer type to concrete type 904 llvm::cast<llvm::OpaqueType>( 905 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy); 906 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get()); 907 908 Methods.clear(); 909 Methods.push_back(llvm::ConstantPointerNull::get( 910 llvm::PointerType::getUnqual(ObjCMethodListTy))); 911 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 912 MethodTypes.size())); 913 Methods.push_back(MethodArray); 914 915 // Create an instance of the structure 916 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list"); 917} 918 919/// Generates an IvarList. Used in construction of a objc_class. 920llvm::Constant *CGObjCGNU::GenerateIvarList( 921 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames, 922 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes, 923 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) { 924 if (IvarNames.size() == 0) 925 return NULLPtr; 926 // Get the method structure type. 927 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext, 928 PtrToInt8Ty, 929 PtrToInt8Ty, 930 IntTy, 931 NULL); 932 std::vector<llvm::Constant*> Ivars; 933 std::vector<llvm::Constant*> Elements; 934 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) { 935 Elements.clear(); 936 Elements.push_back(IvarNames[i]); 937 Elements.push_back(IvarTypes[i]); 938 Elements.push_back(IvarOffsets[i]); 939 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements)); 940 } 941 942 // Array of method structures 943 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy, 944 IvarNames.size()); 945 946 947 Elements.clear(); 948 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size())); 949 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)); 950 // Structure containing array and array count 951 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy, 952 ObjCIvarArrayTy, 953 NULL); 954 955 // Create an instance of the structure 956 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list"); 957} 958 959/// Generate a class structure 960llvm::Constant *CGObjCGNU::GenerateClassStructure( 961 llvm::Constant *MetaClass, 962 llvm::Constant *SuperClass, 963 unsigned info, 964 const char *Name, 965 llvm::Constant *Version, 966 llvm::Constant *InstanceSize, 967 llvm::Constant *IVars, 968 llvm::Constant *Methods, 969 llvm::Constant *Protocols, 970 llvm::Constant *IvarOffsets, 971 llvm::Constant *Properties, 972 bool isMeta) { 973 // Set up the class structure 974 // Note: Several of these are char*s when they should be ids. This is 975 // because the runtime performs this translation on load. 976 // 977 // Fields marked New ABI are part of the GNUstep runtime. We emit them 978 // anyway; the classes will still work with the GNU runtime, they will just 979 // be ignored. 980 llvm::StructType *ClassTy = llvm::StructType::get(VMContext, 981 PtrToInt8Ty, // class_pointer 982 PtrToInt8Ty, // super_class 983 PtrToInt8Ty, // name 984 LongTy, // version 985 LongTy, // info 986 LongTy, // instance_size 987 IVars->getType(), // ivars 988 Methods->getType(), // methods 989 // These are all filled in by the runtime, so we pretend 990 PtrTy, // dtable 991 PtrTy, // subclass_list 992 PtrTy, // sibling_class 993 PtrTy, // protocols 994 PtrTy, // gc_object_type 995 // New ABI: 996 LongTy, // abi_version 997 IvarOffsets->getType(), // ivar_offsets 998 Properties->getType(), // properties 999 NULL); 1000 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0); 1001 // Fill in the structure 1002 std::vector<llvm::Constant*> Elements; 1003 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty)); 1004 Elements.push_back(SuperClass); 1005 Elements.push_back(MakeConstantString(Name, ".class_name")); 1006 Elements.push_back(Zero); 1007 Elements.push_back(llvm::ConstantInt::get(LongTy, info)); 1008 if (isMeta) { 1009 llvm::TargetData td(&TheModule); 1010 Elements.push_back(llvm::ConstantInt::get(LongTy, 1011 td.getTypeSizeInBits(ClassTy)/8)); 1012 } else 1013 Elements.push_back(InstanceSize); 1014 Elements.push_back(IVars); 1015 Elements.push_back(Methods); 1016 Elements.push_back(NULLPtr); 1017 Elements.push_back(NULLPtr); 1018 Elements.push_back(NULLPtr); 1019 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy)); 1020 Elements.push_back(NULLPtr); 1021 Elements.push_back(Zero); 1022 Elements.push_back(IvarOffsets); 1023 Elements.push_back(Properties); 1024 // Create an instance of the structure 1025 // This is now an externally visible symbol, so that we can speed up class 1026 // messages in the next ABI. 1027 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_": 1028 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage); 1029} 1030 1031llvm::Constant *CGObjCGNU::GenerateProtocolMethodList( 1032 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames, 1033 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) { 1034 // Get the method structure type. 1035 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext, 1036 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us. 1037 PtrToInt8Ty, 1038 NULL); 1039 std::vector<llvm::Constant*> Methods; 1040 std::vector<llvm::Constant*> Elements; 1041 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) { 1042 Elements.clear(); 1043 Elements.push_back(MethodNames[i]); 1044 Elements.push_back(MethodTypes[i]); 1045 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements)); 1046 } 1047 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy, 1048 MethodNames.size()); 1049 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, 1050 Methods); 1051 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext, 1052 IntTy, ObjCMethodArrayTy, NULL); 1053 Methods.clear(); 1054 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size())); 1055 Methods.push_back(Array); 1056 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list"); 1057} 1058 1059// Create the protocol list structure used in classes, categories and so on 1060llvm::Constant *CGObjCGNU::GenerateProtocolList( 1061 const llvm::SmallVectorImpl<std::string> &Protocols) { 1062 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 1063 Protocols.size()); 1064 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext, 1065 PtrTy, //Should be a recurisve pointer, but it's always NULL here. 1066 SizeTy, 1067 ProtocolArrayTy, 1068 NULL); 1069 std::vector<llvm::Constant*> Elements; 1070 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); 1071 iter != endIter ; iter++) { 1072 llvm::Constant *protocol = 0; 1073 llvm::StringMap<llvm::Constant*>::iterator value = 1074 ExistingProtocols.find(*iter); 1075 if (value == ExistingProtocols.end()) { 1076 protocol = GenerateEmptyProtocol(*iter); 1077 } else { 1078 protocol = value->getValue(); 1079 } 1080 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol, 1081 PtrToInt8Ty); 1082 Elements.push_back(Ptr); 1083 } 1084 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 1085 Elements); 1086 Elements.clear(); 1087 Elements.push_back(NULLPtr); 1088 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size())); 1089 Elements.push_back(ProtocolArray); 1090 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list"); 1091} 1092 1093llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder, 1094 const ObjCProtocolDecl *PD) { 1095 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()]; 1096 const llvm::Type *T = 1097 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); 1098 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); 1099} 1100 1101llvm::Constant *CGObjCGNU::GenerateEmptyProtocol( 1102 const std::string &ProtocolName) { 1103 llvm::SmallVector<std::string, 0> EmptyStringVector; 1104 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector; 1105 1106 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector); 1107 llvm::Constant *MethodList = 1108 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector); 1109 // Protocols are objects containing lists of the methods implemented and 1110 // protocols adopted. 1111 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy, 1112 PtrToInt8Ty, 1113 ProtocolList->getType(), 1114 MethodList->getType(), 1115 MethodList->getType(), 1116 MethodList->getType(), 1117 MethodList->getType(), 1118 NULL); 1119 std::vector<llvm::Constant*> Elements; 1120 // The isa pointer must be set to a magic number so the runtime knows it's 1121 // the correct layout. 1122 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ? 1123 NonFragileProtocolVersion : ProtocolVersion; 1124 Elements.push_back(llvm::ConstantExpr::getIntToPtr( 1125 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy)); 1126 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name")); 1127 Elements.push_back(ProtocolList); 1128 Elements.push_back(MethodList); 1129 Elements.push_back(MethodList); 1130 Elements.push_back(MethodList); 1131 Elements.push_back(MethodList); 1132 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol"); 1133} 1134 1135void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { 1136 ASTContext &Context = CGM.getContext(); 1137 std::string ProtocolName = PD->getNameAsString(); 1138 llvm::SmallVector<std::string, 16> Protocols; 1139 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(), 1140 E = PD->protocol_end(); PI != E; ++PI) 1141 Protocols.push_back((*PI)->getNameAsString()); 1142 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames; 1143 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 1144 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames; 1145 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes; 1146 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(), 1147 E = PD->instmeth_end(); iter != E; iter++) { 1148 std::string TypeStr; 1149 Context.getObjCEncodingForMethodDecl(*iter, TypeStr); 1150 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) { 1151 InstanceMethodNames.push_back( 1152 MakeConstantString((*iter)->getSelector().getAsString())); 1153 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 1154 } else { 1155 OptionalInstanceMethodNames.push_back( 1156 MakeConstantString((*iter)->getSelector().getAsString())); 1157 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 1158 } 1159 } 1160 // Collect information about class methods: 1161 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames; 1162 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 1163 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames; 1164 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes; 1165 for (ObjCProtocolDecl::classmeth_iterator 1166 iter = PD->classmeth_begin(), endIter = PD->classmeth_end(); 1167 iter != endIter ; iter++) { 1168 std::string TypeStr; 1169 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 1170 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) { 1171 ClassMethodNames.push_back( 1172 MakeConstantString((*iter)->getSelector().getAsString())); 1173 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 1174 } else { 1175 OptionalClassMethodNames.push_back( 1176 MakeConstantString((*iter)->getSelector().getAsString())); 1177 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr)); 1178 } 1179 } 1180 1181 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 1182 llvm::Constant *InstanceMethodList = 1183 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes); 1184 llvm::Constant *ClassMethodList = 1185 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes); 1186 llvm::Constant *OptionalInstanceMethodList = 1187 GenerateProtocolMethodList(OptionalInstanceMethodNames, 1188 OptionalInstanceMethodTypes); 1189 llvm::Constant *OptionalClassMethodList = 1190 GenerateProtocolMethodList(OptionalClassMethodNames, 1191 OptionalClassMethodTypes); 1192 1193 // Property metadata: name, attributes, isSynthesized, setter name, setter 1194 // types, getter name, getter types. 1195 // The isSynthesized value is always set to 0 in a protocol. It exists to 1196 // simplify the runtime library by allowing it to use the same data 1197 // structures for protocol metadata everywhere. 1198 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext, 1199 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, 1200 PtrToInt8Ty, NULL); 1201 std::vector<llvm::Constant*> Properties; 1202 std::vector<llvm::Constant*> OptionalProperties; 1203 1204 // Add all of the property methods need adding to the method list and to the 1205 // property metadata list. 1206 for (ObjCContainerDecl::prop_iterator 1207 iter = PD->prop_begin(), endIter = PD->prop_end(); 1208 iter != endIter ; iter++) { 1209 std::vector<llvm::Constant*> Fields; 1210 ObjCPropertyDecl *property = (*iter); 1211 1212 Fields.push_back(MakeConstantString(property->getNameAsString())); 1213 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 1214 property->getPropertyAttributes())); 1215 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0)); 1216 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) { 1217 std::string TypeStr; 1218 Context.getObjCEncodingForMethodDecl(getter,TypeStr); 1219 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 1220 InstanceMethodTypes.push_back(TypeEncoding); 1221 Fields.push_back(MakeConstantString(getter->getSelector().getAsString())); 1222 Fields.push_back(TypeEncoding); 1223 } else { 1224 Fields.push_back(NULLPtr); 1225 Fields.push_back(NULLPtr); 1226 } 1227 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) { 1228 std::string TypeStr; 1229 Context.getObjCEncodingForMethodDecl(setter,TypeStr); 1230 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 1231 InstanceMethodTypes.push_back(TypeEncoding); 1232 Fields.push_back(MakeConstantString(setter->getSelector().getAsString())); 1233 Fields.push_back(TypeEncoding); 1234 } else { 1235 Fields.push_back(NULLPtr); 1236 Fields.push_back(NULLPtr); 1237 } 1238 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) { 1239 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields)); 1240 } else { 1241 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields)); 1242 } 1243 } 1244 llvm::Constant *PropertyArray = llvm::ConstantArray::get( 1245 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties); 1246 llvm::Constant* PropertyListInitFields[] = 1247 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray}; 1248 1249 llvm::Constant *PropertyListInit = 1250 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false); 1251 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule, 1252 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage, 1253 PropertyListInit, ".objc_property_list"); 1254 1255 llvm::Constant *OptionalPropertyArray = 1256 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy, 1257 OptionalProperties.size()) , OptionalProperties); 1258 llvm::Constant* OptionalPropertyListInitFields[] = { 1259 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr, 1260 OptionalPropertyArray }; 1261 1262 llvm::Constant *OptionalPropertyListInit = 1263 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false); 1264 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule, 1265 OptionalPropertyListInit->getType(), false, 1266 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit, 1267 ".objc_property_list"); 1268 1269 // Protocols are objects containing lists of the methods implemented and 1270 // protocols adopted. 1271 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy, 1272 PtrToInt8Ty, 1273 ProtocolList->getType(), 1274 InstanceMethodList->getType(), 1275 ClassMethodList->getType(), 1276 OptionalInstanceMethodList->getType(), 1277 OptionalClassMethodList->getType(), 1278 PropertyList->getType(), 1279 OptionalPropertyList->getType(), 1280 NULL); 1281 std::vector<llvm::Constant*> Elements; 1282 // The isa pointer must be set to a magic number so the runtime knows it's 1283 // the correct layout. 1284 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ? 1285 NonFragileProtocolVersion : ProtocolVersion; 1286 Elements.push_back(llvm::ConstantExpr::getIntToPtr( 1287 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy)); 1288 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name")); 1289 Elements.push_back(ProtocolList); 1290 Elements.push_back(InstanceMethodList); 1291 Elements.push_back(ClassMethodList); 1292 Elements.push_back(OptionalInstanceMethodList); 1293 Elements.push_back(OptionalClassMethodList); 1294 Elements.push_back(PropertyList); 1295 Elements.push_back(OptionalPropertyList); 1296 ExistingProtocols[ProtocolName] = 1297 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements, 1298 ".objc_protocol"), IdTy); 1299} 1300void CGObjCGNU::GenerateProtocolHolderCategory(void) { 1301 // Collect information about instance methods 1302 llvm::SmallVector<Selector, 1> MethodSels; 1303 llvm::SmallVector<llvm::Constant*, 1> MethodTypes; 1304 1305 std::vector<llvm::Constant*> Elements; 1306 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack"; 1307 const std::string CategoryName = "AnotherHack"; 1308 Elements.push_back(MakeConstantString(CategoryName)); 1309 Elements.push_back(MakeConstantString(ClassName)); 1310 // Instance method list 1311 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 1312 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy)); 1313 // Class method list 1314 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 1315 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy)); 1316 // Protocol list 1317 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy, 1318 ExistingProtocols.size()); 1319 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext, 1320 PtrTy, //Should be a recurisve pointer, but it's always NULL here. 1321 SizeTy, 1322 ProtocolArrayTy, 1323 NULL); 1324 std::vector<llvm::Constant*> ProtocolElements; 1325 for (llvm::StringMapIterator<llvm::Constant*> iter = 1326 ExistingProtocols.begin(), endIter = ExistingProtocols.end(); 1327 iter != endIter ; iter++) { 1328 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(), 1329 PtrTy); 1330 ProtocolElements.push_back(Ptr); 1331 } 1332 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 1333 ProtocolElements); 1334 ProtocolElements.clear(); 1335 ProtocolElements.push_back(NULLPtr); 1336 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy, 1337 ExistingProtocols.size())); 1338 ProtocolElements.push_back(ProtocolArray); 1339 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy, 1340 ProtocolElements, ".objc_protocol_list"), PtrTy)); 1341 Categories.push_back(llvm::ConstantExpr::getBitCast( 1342 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, 1343 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy)); 1344} 1345 1346void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 1347 std::string ClassName = OCD->getClassInterface()->getNameAsString(); 1348 std::string CategoryName = OCD->getNameAsString(); 1349 // Collect information about instance methods 1350 llvm::SmallVector<Selector, 16> InstanceMethodSels; 1351 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 1352 for (ObjCCategoryImplDecl::instmeth_iterator 1353 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end(); 1354 iter != endIter ; iter++) { 1355 InstanceMethodSels.push_back((*iter)->getSelector()); 1356 std::string TypeStr; 1357 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr); 1358 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 1359 } 1360 1361 // Collect information about class methods 1362 llvm::SmallVector<Selector, 16> ClassMethodSels; 1363 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 1364 for (ObjCCategoryImplDecl::classmeth_iterator 1365 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end(); 1366 iter != endIter ; iter++) { 1367 ClassMethodSels.push_back((*iter)->getSelector()); 1368 std::string TypeStr; 1369 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr); 1370 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 1371 } 1372 1373 // Collect the names of referenced protocols 1374 llvm::SmallVector<std::string, 16> Protocols; 1375 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl(); 1376 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols(); 1377 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 1378 E = Protos.end(); I != E; ++I) 1379 Protocols.push_back((*I)->getNameAsString()); 1380 1381 std::vector<llvm::Constant*> Elements; 1382 Elements.push_back(MakeConstantString(CategoryName)); 1383 Elements.push_back(MakeConstantString(ClassName)); 1384 // Instance method list 1385 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 1386 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes, 1387 false), PtrTy)); 1388 // Class method list 1389 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 1390 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true), 1391 PtrTy)); 1392 // Protocol list 1393 Elements.push_back(llvm::ConstantExpr::getBitCast( 1394 GenerateProtocolList(Protocols), PtrTy)); 1395 Categories.push_back(llvm::ConstantExpr::getBitCast( 1396 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, 1397 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy)); 1398} 1399 1400llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID, 1401 llvm::SmallVectorImpl<Selector> &InstanceMethodSels, 1402 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) { 1403 ASTContext &Context = CGM.getContext(); 1404 // 1405 // Property metadata: name, attributes, isSynthesized, setter name, setter 1406 // types, getter name, getter types. 1407 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext, 1408 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, 1409 PtrToInt8Ty, NULL); 1410 std::vector<llvm::Constant*> Properties; 1411 1412 1413 // Add all of the property methods need adding to the method list and to the 1414 // property metadata list. 1415 for (ObjCImplDecl::propimpl_iterator 1416 iter = OID->propimpl_begin(), endIter = OID->propimpl_end(); 1417 iter != endIter ; iter++) { 1418 std::vector<llvm::Constant*> Fields; 1419 ObjCPropertyDecl *property = (*iter)->getPropertyDecl(); 1420 ObjCPropertyImplDecl *propertyImpl = *iter; 1421 bool isSynthesized = (propertyImpl->getPropertyImplementation() == 1422 ObjCPropertyImplDecl::Synthesize); 1423 1424 Fields.push_back(MakeConstantString(property->getNameAsString())); 1425 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 1426 property->getPropertyAttributes())); 1427 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized)); 1428 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) { 1429 std::string TypeStr; 1430 Context.getObjCEncodingForMethodDecl(getter,TypeStr); 1431 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 1432 if (isSynthesized) { 1433 InstanceMethodTypes.push_back(TypeEncoding); 1434 InstanceMethodSels.push_back(getter->getSelector()); 1435 } 1436 Fields.push_back(MakeConstantString(getter->getSelector().getAsString())); 1437 Fields.push_back(TypeEncoding); 1438 } else { 1439 Fields.push_back(NULLPtr); 1440 Fields.push_back(NULLPtr); 1441 } 1442 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) { 1443 std::string TypeStr; 1444 Context.getObjCEncodingForMethodDecl(setter,TypeStr); 1445 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 1446 if (isSynthesized) { 1447 InstanceMethodTypes.push_back(TypeEncoding); 1448 InstanceMethodSels.push_back(setter->getSelector()); 1449 } 1450 Fields.push_back(MakeConstantString(setter->getSelector().getAsString())); 1451 Fields.push_back(TypeEncoding); 1452 } else { 1453 Fields.push_back(NULLPtr); 1454 Fields.push_back(NULLPtr); 1455 } 1456 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields)); 1457 } 1458 llvm::ArrayType *PropertyArrayTy = 1459 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()); 1460 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy, 1461 Properties); 1462 llvm::Constant* PropertyListInitFields[] = 1463 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray}; 1464 1465 llvm::Constant *PropertyListInit = 1466 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false); 1467 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false, 1468 llvm::GlobalValue::InternalLinkage, PropertyListInit, 1469 ".objc_property_list"); 1470} 1471 1472void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { 1473 ASTContext &Context = CGM.getContext(); 1474 1475 // Get the superclass name. 1476 const ObjCInterfaceDecl * SuperClassDecl = 1477 OID->getClassInterface()->getSuperClass(); 1478 std::string SuperClassName; 1479 if (SuperClassDecl) { 1480 SuperClassName = SuperClassDecl->getNameAsString(); 1481 EmitClassRef(SuperClassName); 1482 } 1483 1484 // Get the class name 1485 ObjCInterfaceDecl *ClassDecl = 1486 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 1487 std::string ClassName = ClassDecl->getNameAsString(); 1488 // Emit the symbol that is used to generate linker errors if this class is 1489 // referenced in other modules but not declared. 1490 std::string classSymbolName = "__objc_class_name_" + ClassName; 1491 if (llvm::GlobalVariable *symbol = 1492 TheModule.getGlobalVariable(classSymbolName)) { 1493 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0)); 1494 } else { 1495 new llvm::GlobalVariable(TheModule, LongTy, false, 1496 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0), 1497 classSymbolName); 1498 } 1499 1500 // Get the size of instances. 1501 int instanceSize = 1502 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity(); 1503 1504 // Collect information about instance variables. 1505 llvm::SmallVector<llvm::Constant*, 16> IvarNames; 1506 llvm::SmallVector<llvm::Constant*, 16> IvarTypes; 1507 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets; 1508 1509 std::vector<llvm::Constant*> IvarOffsetValues; 1510 1511 int superInstanceSize = !SuperClassDecl ? 0 : 1512 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity(); 1513 // For non-fragile ivars, set the instance size to 0 - {the size of just this 1514 // class}. The runtime will then set this to the correct value on load. 1515 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 1516 instanceSize = 0 - (instanceSize - superInstanceSize); 1517 } 1518 1519 // Collect declared and synthesized ivars. 1520 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars; 1521 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars); 1522 1523 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) { 1524 ObjCIvarDecl *IVD = OIvars[i]; 1525 // Store the name 1526 IvarNames.push_back(MakeConstantString(IVD->getNameAsString())); 1527 // Get the type encoding for this ivar 1528 std::string TypeStr; 1529 Context.getObjCEncodingForType(IVD->getType(), TypeStr); 1530 IvarTypes.push_back(MakeConstantString(TypeStr)); 1531 // Get the offset 1532 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD); 1533 uint64_t Offset = BaseOffset; 1534 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 1535 Offset = BaseOffset - superInstanceSize; 1536 } 1537 IvarOffsets.push_back( 1538 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset)); 1539 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy, 1540 false, llvm::GlobalValue::ExternalLinkage, 1541 llvm::ConstantInt::get(IntTy, Offset), 1542 "__objc_ivar_offset_value_" + ClassName +"." + 1543 IVD->getNameAsString())); 1544 } 1545 llvm::Constant *IvarOffsetArrayInit = 1546 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy, 1547 IvarOffsetValues.size()), IvarOffsetValues); 1548 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule, 1549 IvarOffsetArrayInit->getType(), false, 1550 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit, 1551 ".ivar.offsets"); 1552 1553 // Collect information about instance methods 1554 llvm::SmallVector<Selector, 16> InstanceMethodSels; 1555 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 1556 for (ObjCImplementationDecl::instmeth_iterator 1557 iter = OID->instmeth_begin(), endIter = OID->instmeth_end(); 1558 iter != endIter ; iter++) { 1559 InstanceMethodSels.push_back((*iter)->getSelector()); 1560 std::string TypeStr; 1561 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 1562 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 1563 } 1564 1565 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels, 1566 InstanceMethodTypes); 1567 1568 1569 // Collect information about class methods 1570 llvm::SmallVector<Selector, 16> ClassMethodSels; 1571 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 1572 for (ObjCImplementationDecl::classmeth_iterator 1573 iter = OID->classmeth_begin(), endIter = OID->classmeth_end(); 1574 iter != endIter ; iter++) { 1575 ClassMethodSels.push_back((*iter)->getSelector()); 1576 std::string TypeStr; 1577 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 1578 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 1579 } 1580 // Collect the names of referenced protocols 1581 llvm::SmallVector<std::string, 16> Protocols; 1582 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols(); 1583 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 1584 E = Protos.end(); I != E; ++I) 1585 Protocols.push_back((*I)->getNameAsString()); 1586 1587 1588 1589 // Get the superclass pointer. 1590 llvm::Constant *SuperClass; 1591 if (!SuperClassName.empty()) { 1592 SuperClass = MakeConstantString(SuperClassName, ".super_class_name"); 1593 } else { 1594 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty); 1595 } 1596 // Empty vector used to construct empty method lists 1597 llvm::SmallVector<llvm::Constant*, 1> empty; 1598 // Generate the method and instance variable lists 1599 llvm::Constant *MethodList = GenerateMethodList(ClassName, "", 1600 InstanceMethodSels, InstanceMethodTypes, false); 1601 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "", 1602 ClassMethodSels, ClassMethodTypes, true); 1603 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, 1604 IvarOffsets); 1605 // Irrespective of whether we are compiling for a fragile or non-fragile ABI, 1606 // we emit a symbol containing the offset for each ivar in the class. This 1607 // allows code compiled for the non-Fragile ABI to inherit from code compiled 1608 // for the legacy ABI, without causing problems. The converse is also 1609 // possible, but causes all ivar accesses to be fragile. 1610 1611 // Offset pointer for getting at the correct field in the ivar list when 1612 // setting up the alias. These are: The base address for the global, the 1613 // ivar array (second field), the ivar in this list (set for each ivar), and 1614 // the offset (third field in ivar structure) 1615 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext); 1616 llvm::Constant *offsetPointerIndexes[] = {Zeros[0], 1617 llvm::ConstantInt::get(IndexTy, 1), 0, 1618 llvm::ConstantInt::get(IndexTy, 2) }; 1619 1620 1621 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) { 1622 ObjCIvarDecl *IVD = OIvars[i]; 1623 const std::string Name = "__objc_ivar_offset_" + ClassName + '.' 1624 + IVD->getNameAsString(); 1625 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i); 1626 // Get the correct ivar field 1627 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr( 1628 IvarList, offsetPointerIndexes, 4); 1629 // Get the existing variable, if one exists. 1630 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name); 1631 if (offset) { 1632 offset->setInitializer(offsetValue); 1633 // If this is the real definition, change its linkage type so that 1634 // different modules will use this one, rather than their private 1635 // copy. 1636 offset->setLinkage(llvm::GlobalValue::ExternalLinkage); 1637 } else { 1638 // Add a new alias if there isn't one already. 1639 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(), 1640 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name); 1641 } 1642 } 1643 //Generate metaclass for class methods 1644 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr, 1645 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList( 1646 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true); 1647 1648 // Generate the class structure 1649 llvm::Constant *ClassStruct = 1650 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L, 1651 ClassName.c_str(), 0, 1652 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, 1653 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray, 1654 Properties); 1655 1656 // Resolve the class aliases, if they exist. 1657 if (ClassPtrAlias) { 1658 ClassPtrAlias->replaceAllUsesWith( 1659 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy)); 1660 ClassPtrAlias->eraseFromParent(); 1661 ClassPtrAlias = 0; 1662 } 1663 if (MetaClassPtrAlias) { 1664 MetaClassPtrAlias->replaceAllUsesWith( 1665 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy)); 1666 MetaClassPtrAlias->eraseFromParent(); 1667 MetaClassPtrAlias = 0; 1668 } 1669 1670 // Add class structure to list to be added to the symtab later 1671 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty); 1672 Classes.push_back(ClassStruct); 1673} 1674 1675 1676llvm::Function *CGObjCGNU::ModuleInitFunction() { 1677 // Only emit an ObjC load function if no Objective-C stuff has been called 1678 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && 1679 ExistingProtocols.empty() && TypedSelectors.empty() && 1680 UntypedSelectors.empty()) 1681 return NULL; 1682 1683 // Add all referenced protocols to a category. 1684 GenerateProtocolHolderCategory(); 1685 1686 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>( 1687 SelectorTy->getElementType()); 1688 const llvm::Type *SelStructPtrTy = SelectorTy; 1689 bool isSelOpaque = false; 1690 if (SelStructTy == 0) { 1691 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty, 1692 PtrToInt8Ty, NULL); 1693 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy); 1694 isSelOpaque = true; 1695 } 1696 1697 // Name the ObjC types to make the IR a bit easier to read 1698 TheModule.addTypeName(".objc_selector", SelStructPtrTy); 1699 TheModule.addTypeName(".objc_id", IdTy); 1700 TheModule.addTypeName(".objc_imp", IMPTy); 1701 1702 std::vector<llvm::Constant*> Elements; 1703 llvm::Constant *Statics = NULLPtr; 1704 // Generate statics list: 1705 if (ConstantStrings.size()) { 1706 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 1707 ConstantStrings.size() + 1); 1708 ConstantStrings.push_back(NULLPtr); 1709 1710 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass; 1711 if (StringClass.empty()) StringClass = "NXConstantString"; 1712 Elements.push_back(MakeConstantString(StringClass, 1713 ".objc_static_class_name")); 1714 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, 1715 ConstantStrings)); 1716 llvm::StructType *StaticsListTy = 1717 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL); 1718 llvm::Type *StaticsListPtrTy = 1719 llvm::PointerType::getUnqual(StaticsListTy); 1720 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics"); 1721 llvm::ArrayType *StaticsListArrayTy = 1722 llvm::ArrayType::get(StaticsListPtrTy, 2); 1723 Elements.clear(); 1724 Elements.push_back(Statics); 1725 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy)); 1726 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr"); 1727 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy); 1728 } 1729 // Array of classes, categories, and constant objects 1730 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty, 1731 Classes.size() + Categories.size() + 2); 1732 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext, 1733 LongTy, SelStructPtrTy, 1734 llvm::Type::getInt16Ty(VMContext), 1735 llvm::Type::getInt16Ty(VMContext), 1736 ClassListTy, NULL); 1737 1738 Elements.clear(); 1739 // Pointer to an array of selectors used in this module. 1740 std::vector<llvm::Constant*> Selectors; 1741 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator 1742 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end(); 1743 iter != iterEnd ; ++iter) { 1744 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name")); 1745 Elements.push_back(MakeConstantString(iter->first.second, 1746 ".objc_sel_types")); 1747 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1748 Elements.clear(); 1749 } 1750 for (llvm::StringMap<llvm::GlobalAlias*>::iterator 1751 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end(); 1752 iter != iterEnd; ++iter) { 1753 Elements.push_back( 1754 ExportUniqueString(iter->getKeyData(), ".objc_sel_name")); 1755 Elements.push_back(NULLPtr); 1756 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1757 Elements.clear(); 1758 } 1759 Elements.push_back(NULLPtr); 1760 Elements.push_back(NULLPtr); 1761 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1762 Elements.clear(); 1763 // Number of static selectors 1764 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() )); 1765 llvm::Constant *SelectorList = MakeGlobal( 1766 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors, 1767 ".objc_selector_list"); 1768 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, 1769 SelStructPtrTy)); 1770 1771 // Now that all of the static selectors exist, create pointers to them. 1772 int index = 0; 1773 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator 1774 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end(); 1775 iter != iterEnd; ++iter) { 1776 llvm::Constant *Idxs[] = {Zeros[0], 1777 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]}; 1778 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy, 1779 true, llvm::GlobalValue::InternalLinkage, 1780 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), 1781 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+ 1782 iter->first.second)); 1783 // If selectors are defined as an opaque type, cast the pointer to this 1784 // type. 1785 if (isSelOpaque) { 1786 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, 1787 llvm::PointerType::getUnqual(SelectorTy)); 1788 } 1789 (*iter).second->replaceAllUsesWith(SelPtr); 1790 (*iter).second->eraseFromParent(); 1791 } 1792 for (llvm::StringMap<llvm::GlobalAlias*>::iterator 1793 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end(); 1794 iter != iterEnd; iter++) { 1795 llvm::Constant *Idxs[] = {Zeros[0], 1796 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]}; 1797 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy, 1798 true, llvm::GlobalValue::InternalLinkage, 1799 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), 1800 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str())); 1801 // If selectors are defined as an opaque type, cast the pointer to this 1802 // type. 1803 if (isSelOpaque) { 1804 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, 1805 llvm::PointerType::getUnqual(SelectorTy)); 1806 } 1807 (*iter).second->replaceAllUsesWith(SelPtr); 1808 (*iter).second->eraseFromParent(); 1809 } 1810 // Number of classes defined. 1811 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), 1812 Classes.size())); 1813 // Number of categories defined 1814 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), 1815 Categories.size())); 1816 // Create an array of classes, then categories, then static object instances 1817 Classes.insert(Classes.end(), Categories.begin(), Categories.end()); 1818 // NULL-terminated list of static object instances (mainly constant strings) 1819 Classes.push_back(Statics); 1820 Classes.push_back(NULLPtr); 1821 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes); 1822 Elements.push_back(ClassList); 1823 // Construct the symbol table 1824 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements); 1825 1826 // The symbol table is contained in a module which has some version-checking 1827 // constants 1828 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy, 1829 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL); 1830 Elements.clear(); 1831 // Runtime version used for compatibility checking. 1832 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 1833 Elements.push_back(llvm::ConstantInt::get(LongTy, 1834 NonFragileRuntimeVersion)); 1835 } else { 1836 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion)); 1837 } 1838 // sizeof(ModuleTy) 1839 llvm::TargetData td(&TheModule); 1840 Elements.push_back(llvm::ConstantInt::get(LongTy, 1841 td.getTypeSizeInBits(ModuleTy)/8)); 1842 //FIXME: Should be the path to the file where this module was declared 1843 Elements.push_back(NULLPtr); 1844 Elements.push_back(SymTab); 1845 llvm::Value *Module = MakeGlobal(ModuleTy, Elements); 1846 1847 // Create the load function calling the runtime entry point with the module 1848 // structure 1849 llvm::Function * LoadFunction = llvm::Function::Create( 1850 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 1851 llvm::GlobalValue::InternalLinkage, ".objc_load_function", 1852 &TheModule); 1853 llvm::BasicBlock *EntryBB = 1854 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 1855 CGBuilderTy Builder(VMContext); 1856 Builder.SetInsertPoint(EntryBB); 1857 1858 std::vector<const llvm::Type*> Params(1, 1859 llvm::PointerType::getUnqual(ModuleTy)); 1860 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 1861 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class"); 1862 Builder.CreateCall(Register, Module); 1863 Builder.CreateRetVoid(); 1864 1865 return LoadFunction; 1866} 1867 1868llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, 1869 const ObjCContainerDecl *CD) { 1870 const ObjCCategoryImplDecl *OCD = 1871 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext()); 1872 std::string CategoryName = OCD ? OCD->getNameAsString() : ""; 1873 std::string ClassName = CD->getName(); 1874 std::string MethodName = OMD->getSelector().getAsString(); 1875 bool isClassMethod = !OMD->isInstanceMethod(); 1876 1877 CodeGenTypes &Types = CGM.getTypes(); 1878 const llvm::FunctionType *MethodTy = 1879 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); 1880 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName, 1881 MethodName, isClassMethod); 1882 1883 llvm::Function *Method 1884 = llvm::Function::Create(MethodTy, 1885 llvm::GlobalValue::InternalLinkage, 1886 FunctionName, 1887 &TheModule); 1888 return Method; 1889} 1890 1891llvm::Function *CGObjCGNU::GetPropertyGetFunction() { 1892 std::vector<const llvm::Type*> Params; 1893 Params.push_back(IdTy); 1894 Params.push_back(SelectorTy); 1895 Params.push_back(SizeTy); 1896 Params.push_back(BoolTy); 1897 // void objc_getProperty (id, SEL, ptrdiff_t, bool) 1898 const llvm::FunctionType *FTy = 1899 llvm::FunctionType::get(IdTy, Params, false); 1900 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1901 "objc_getProperty")); 1902} 1903 1904llvm::Function *CGObjCGNU::GetPropertySetFunction() { 1905 std::vector<const llvm::Type*> Params; 1906 Params.push_back(IdTy); 1907 Params.push_back(SelectorTy); 1908 Params.push_back(SizeTy); 1909 Params.push_back(IdTy); 1910 Params.push_back(BoolTy); 1911 Params.push_back(BoolTy); 1912 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 1913 const llvm::FunctionType *FTy = 1914 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); 1915 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1916 "objc_setProperty")); 1917} 1918 1919llvm::Function *CGObjCGNU::GetGetStructFunction() { 1920 std::vector<const llvm::Type*> Params; 1921 Params.push_back(PtrTy); 1922 Params.push_back(PtrTy); 1923 Params.push_back(PtrDiffTy); 1924 Params.push_back(BoolTy); 1925 Params.push_back(BoolTy); 1926 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL) 1927 const llvm::FunctionType *FTy = 1928 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); 1929 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1930 "objc_getPropertyStruct")); 1931} 1932llvm::Function *CGObjCGNU::GetSetStructFunction() { 1933 std::vector<const llvm::Type*> Params; 1934 Params.push_back(PtrTy); 1935 Params.push_back(PtrTy); 1936 Params.push_back(PtrDiffTy); 1937 Params.push_back(BoolTy); 1938 Params.push_back(BoolTy); 1939 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL) 1940 const llvm::FunctionType *FTy = 1941 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); 1942 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1943 "objc_setPropertyStruct")); 1944} 1945 1946llvm::Constant *CGObjCGNU::EnumerationMutationFunction() { 1947 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 1948 ASTContext &Ctx = CGM.getContext(); 1949 // void objc_enumerationMutation (id) 1950 llvm::SmallVector<CanQualType,1> Params; 1951 Params.push_back(ASTIdTy); 1952 const llvm::FunctionType *FTy = 1953 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params, 1954 FunctionType::ExtInfo()), false); 1955 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation"); 1956} 1957 1958namespace { 1959 struct CallSyncExit : EHScopeStack::Cleanup { 1960 llvm::Value *SyncExitFn; 1961 llvm::Value *SyncArg; 1962 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg) 1963 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {} 1964 1965 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) { 1966 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow(); 1967 } 1968 }; 1969} 1970 1971void CGObjCGNU::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1972 const ObjCAtSynchronizedStmt &S) { 1973 std::vector<const llvm::Type*> Args(1, IdTy); 1974 llvm::FunctionType *FTy = 1975 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); 1976 1977 // Evaluate the lock operand. This should dominate the cleanup. 1978 llvm::Value *SyncArg = 1979 CGF.EmitScalarExpr(S.getSynchExpr()); 1980 1981 // Acquire the lock. 1982 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); 1983 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); 1984 CGF.Builder.CreateCall(SyncEnter, SyncArg); 1985 1986 // Register an all-paths cleanup to release the lock. 1987 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); 1988 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExit, SyncArg); 1989 1990 // Emit the body of the statement. 1991 CGF.EmitStmt(S.getSynchBody()); 1992 1993 // Pop the lock-release cleanup. 1994 CGF.PopCleanupBlock(); 1995} 1996 1997namespace { 1998 struct CatchHandler { 1999 const VarDecl *Variable; 2000 const Stmt *Body; 2001 llvm::BasicBlock *Block; 2002 llvm::Value *TypeInfo; 2003 }; 2004 2005 struct CallObjCEndCatch : EHScopeStack::Cleanup { 2006 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) : 2007 MightThrow(MightThrow), Fn(Fn) {} 2008 bool MightThrow; 2009 llvm::Value *Fn; 2010 2011 void Emit(CodeGenFunction &CGF, bool IsForEH) { 2012 if (!MightThrow) { 2013 CGF.Builder.CreateCall(Fn)->setDoesNotThrow(); 2014 return; 2015 } 2016 2017 CGF.EmitCallOrInvoke(Fn, 0, 0); 2018 } 2019 }; 2020} 2021 2022void CGObjCGNU::EmitObjCXXTryStmt(CodeGen::CodeGenFunction &CGF, 2023 const ObjCAtTryStmt &S) { 2024 std::vector<const llvm::Type*> Args(1, PtrToInt8Ty); 2025 llvm::FunctionType *FTy = llvm::FunctionType::get(PtrToInt8Ty, Args, false); 2026 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 2027 2028 llvm::Constant *beginCatchFn = 2029 CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); 2030 2031 FTy = llvm::FunctionType::get(VoidTy, false); 2032 llvm::Constant *endCatchFn = 2033 CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); 2034 FTy = llvm::FunctionType::get(VoidTy, Args, false); 2035 llvm::Constant *exceptionRethrowFn = 2036 CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow"); 2037 2038 // Jump destination for falling out of catch bodies. 2039 CodeGenFunction::JumpDest Cont; 2040 if (S.getNumCatchStmts()) 2041 Cont = CGF.getJumpDestInCurrentScope("eh.cont"); 2042 2043 CodeGenFunction::FinallyInfo FinallyInfo; 2044 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) 2045 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 2046 beginCatchFn, 2047 endCatchFn, 2048 exceptionRethrowFn); 2049 2050 llvm::SmallVector<CatchHandler, 8> Handlers; 2051 2052 // Enter the catch, if there is one. 2053 if (S.getNumCatchStmts()) { 2054 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) { 2055 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I); 2056 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 2057 2058 Handlers.push_back(CatchHandler()); 2059 CatchHandler &Handler = Handlers.back(); 2060 Handler.Variable = CatchDecl; 2061 Handler.Body = CatchStmt->getCatchBody(); 2062 Handler.Block = CGF.createBasicBlock("catch"); 2063 2064 // @catch(...) always matches. 2065 if (!CatchDecl) { 2066 Handler.TypeInfo = 0; // catch-all 2067 // Don't consider any other catches. 2068 break; 2069 } 2070 2071 Handler.TypeInfo = GetEHType(CatchDecl->getType()); 2072 } 2073 2074 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size()); 2075 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) 2076 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); 2077 } 2078 2079 // Emit the try body. 2080 CGF.EmitStmt(S.getTryBody()); 2081 2082 // Leave the try. 2083 if (S.getNumCatchStmts()) 2084 CGF.EHStack.popCatch(); 2085 2086 // Remember where we were. 2087 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 2088 2089 // Emit the handlers. 2090 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) { 2091 CatchHandler &Handler = Handlers[I]; 2092 2093 CGF.EmitBlock(Handler.Block); 2094 llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot()); 2095 2096 // Enter the catch. 2097 llvm::CallInst *Exn = 2098 CGF.Builder.CreateCall(beginCatchFn, RawExn, 2099 "exn.adjusted"); 2100 Exn->setDoesNotThrow(); 2101 2102 // Add a cleanup to leave the catch. 2103 bool EndCatchMightThrow = (Handler.Variable == 0); 2104 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup, 2105 EndCatchMightThrow, 2106 endCatchFn); 2107 2108 // Bind the catch parameter if it exists. 2109 if (const VarDecl *CatchParam = Handler.Variable) { 2110 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType()); 2111 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType); 2112 2113 CGF.EmitAutoVarDecl(*CatchParam); 2114 CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam)); 2115 } 2116 2117 CGF.ObjCEHValueStack.push_back(Exn); 2118 CGF.EmitStmt(Handler.Body); 2119 CGF.ObjCEHValueStack.pop_back(); 2120 2121 // Leave the earlier cleanup. 2122 CGF.PopCleanupBlock(); 2123 2124 CGF.EmitBranchThroughCleanup(Cont); 2125 } 2126 2127 // Go back to the try-statement fallthrough. 2128 CGF.Builder.restoreIP(SavedIP); 2129 2130 // Pop out of the normal cleanup on the finally. 2131 if (S.getFinallyStmt()) 2132 CGF.ExitFinallyBlock(FinallyInfo); 2133 2134 if (Cont.isValid()) 2135 CGF.EmitBlock(Cont.getBlock()); 2136} 2137 2138void CGObjCGNU::EmitTryStmt(CodeGen::CodeGenFunction &CGF, 2139 const ObjCAtTryStmt &S) { 2140 // Unlike the Apple non-fragile runtimes, which also uses 2141 // unwind-based zero cost exceptions, the GNU Objective C runtime's 2142 // EH support isn't a veneer over C++ EH. Instead, exception 2143 // objects are created by __objc_exception_throw and destroyed by 2144 // the personality function; this avoids the need for bracketing 2145 // catch handlers with calls to __blah_begin_catch/__blah_end_catch 2146 // (or even _Unwind_DeleteException), but probably doesn't 2147 // interoperate very well with foreign exceptions. 2148 2149 // In Objective-C++ mode, we actually emit something equivalent to the C++ 2150 // exception handler. 2151 if (CGM.getLangOptions().CPlusPlus) { 2152 EmitObjCXXTryStmt(CGF, S); 2153 return; 2154 } 2155 2156 // Jump destination for falling out of catch bodies. 2157 CodeGenFunction::JumpDest Cont; 2158 if (S.getNumCatchStmts()) 2159 Cont = CGF.getJumpDestInCurrentScope("eh.cont"); 2160 2161 // We handle @finally statements by pushing them as a cleanup 2162 // before entering the catch. 2163 CodeGenFunction::FinallyInfo FinallyInfo; 2164 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) { 2165 std::vector<const llvm::Type*> Args(1, IdTy); 2166 llvm::FunctionType *FTy = 2167 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); 2168 llvm::Constant *Rethrow = 2169 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 2170 2171 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0, 2172 Rethrow); 2173 } 2174 2175 llvm::SmallVector<CatchHandler, 8> Handlers; 2176 2177 // Enter the catch, if there is one. 2178 if (S.getNumCatchStmts()) { 2179 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) { 2180 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I); 2181 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 2182 2183 Handlers.push_back(CatchHandler()); 2184 CatchHandler &Handler = Handlers.back(); 2185 Handler.Variable = CatchDecl; 2186 Handler.Body = CatchStmt->getCatchBody(); 2187 Handler.Block = CGF.createBasicBlock("catch"); 2188 2189 // @catch() and @catch(id) both catch any ObjC exception. 2190 // Treat them as catch-alls. 2191 // really be catching foreign exceptions? 2192 2193 if (!CatchDecl) { 2194 Handler.TypeInfo = 0; // catch-all 2195 // Don't consider any other catches. 2196 break; 2197 } 2198 if (CatchDecl->getType()->isObjCIdType() 2199 || CatchDecl->getType()->isObjCQualifiedIdType()) { 2200 // With the old ABI, there was only one kind of catchall, which broke 2201 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as 2202 // a pointer indicating object catchalls, and NULL to indicate real 2203 // catchalls 2204 if (CGM.getLangOptions().ObjCNonFragileABI) { 2205 Handler.TypeInfo = MakeConstantString("@id"); 2206 continue; 2207 } else { 2208 Handler.TypeInfo = 0; // catch-all 2209 // Don't consider any other catches. 2210 break; 2211 } 2212 } 2213 2214 // All other types should be Objective-C interface pointer types. 2215 const ObjCObjectPointerType *OPT = 2216 CatchDecl->getType()->getAs<ObjCObjectPointerType>(); 2217 assert(OPT && "Invalid @catch type."); 2218 const ObjCInterfaceDecl *IDecl = 2219 OPT->getObjectType()->getInterface(); 2220 assert(IDecl && "Invalid @catch type."); 2221 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString()); 2222 } 2223 2224 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size()); 2225 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) 2226 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); 2227 } 2228 2229 // Emit the try body. 2230 CGF.EmitStmt(S.getTryBody()); 2231 2232 // Leave the try. 2233 if (S.getNumCatchStmts()) 2234 CGF.EHStack.popCatch(); 2235 2236 // Remember where we were. 2237 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 2238 2239 // Emit the handlers. 2240 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) { 2241 CatchHandler &Handler = Handlers[I]; 2242 CGF.EmitBlock(Handler.Block); 2243 2244 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot()); 2245 2246 // Bind the catch parameter if it exists. 2247 if (const VarDecl *CatchParam = Handler.Variable) { 2248 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType()); 2249 Exn = CGF.Builder.CreateBitCast(Exn, CatchType); 2250 2251 CGF.EmitAutoVarDecl(*CatchParam); 2252 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam)); 2253 } 2254 2255 CGF.ObjCEHValueStack.push_back(Exn); 2256 CGF.EmitStmt(Handler.Body); 2257 CGF.ObjCEHValueStack.pop_back(); 2258 2259 CGF.EmitBranchThroughCleanup(Cont); 2260 } 2261 2262 // Go back to the try-statement fallthrough. 2263 CGF.Builder.restoreIP(SavedIP); 2264 2265 // Pop out of the finally. 2266 if (S.getFinallyStmt()) 2267 CGF.ExitFinallyBlock(FinallyInfo); 2268 2269 if (Cont.isValid()) { 2270 if (Cont.getBlock()->use_empty()) 2271 delete Cont.getBlock(); 2272 else 2273 CGF.EmitBlock(Cont.getBlock()); 2274 } 2275} 2276 2277void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 2278 const ObjCAtThrowStmt &S) { 2279 llvm::Value *ExceptionAsObject; 2280 2281 std::vector<const llvm::Type*> Args(1, IdTy); 2282 llvm::FunctionType *FTy = 2283 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); 2284 llvm::Value *ThrowFn = 2285 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 2286 2287 if (const Expr *ThrowExpr = S.getThrowExpr()) { 2288 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 2289 ExceptionAsObject = Exception; 2290 } else { 2291 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 2292 "Unexpected rethrow outside @catch block."); 2293 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 2294 } 2295 ExceptionAsObject = 2296 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp"); 2297 2298 // Note: This may have to be an invoke, if we want to support constructs like: 2299 // @try { 2300 // @throw(obj); 2301 // } 2302 // @catch(id) ... 2303 // 2304 // This is effectively turning @throw into an incredibly-expensive goto, but 2305 // it may happen as a result of inlining followed by missed optimizations, or 2306 // as a result of stupidity. 2307 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest(); 2308 if (!UnwindBB) { 2309 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject); 2310 CGF.Builder.CreateUnreachable(); 2311 } else { 2312 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject, 2313 &ExceptionAsObject+1); 2314 } 2315 // Clear the insertion point to indicate we are in unreachable code. 2316 CGF.Builder.ClearInsertionPoint(); 2317} 2318 2319llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 2320 llvm::Value *AddrWeakObj) { 2321 CGBuilderTy B = CGF.Builder; 2322 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy); 2323 return B.CreateCall(WeakReadFn, AddrWeakObj); 2324} 2325 2326void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 2327 llvm::Value *src, llvm::Value *dst) { 2328 CGBuilderTy B = CGF.Builder; 2329 src = EnforceType(B, src, IdTy); 2330 dst = EnforceType(B, dst, PtrToIdTy); 2331 B.CreateCall2(WeakAssignFn, src, dst); 2332} 2333 2334void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 2335 llvm::Value *src, llvm::Value *dst, 2336 bool threadlocal) { 2337 CGBuilderTy B = CGF.Builder; 2338 src = EnforceType(B, src, IdTy); 2339 dst = EnforceType(B, dst, PtrToIdTy); 2340 if (!threadlocal) 2341 B.CreateCall2(GlobalAssignFn, src, dst); 2342 else 2343 // FIXME. Add threadloca assign API 2344 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI"); 2345} 2346 2347void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 2348 llvm::Value *src, llvm::Value *dst, 2349 llvm::Value *ivarOffset) { 2350 CGBuilderTy B = CGF.Builder; 2351 src = EnforceType(B, src, IdTy); 2352 dst = EnforceType(B, dst, PtrToIdTy); 2353 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset); 2354} 2355 2356void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 2357 llvm::Value *src, llvm::Value *dst) { 2358 CGBuilderTy B = CGF.Builder; 2359 src = EnforceType(B, src, IdTy); 2360 dst = EnforceType(B, dst, PtrToIdTy); 2361 B.CreateCall2(StrongCastAssignFn, src, dst); 2362} 2363 2364void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 2365 llvm::Value *DestPtr, 2366 llvm::Value *SrcPtr, 2367 llvm::Value *Size) { 2368 CGBuilderTy B = CGF.Builder; 2369 DestPtr = EnforceType(B, DestPtr, IdTy); 2370 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy); 2371 2372 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size); 2373} 2374 2375llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( 2376 const ObjCInterfaceDecl *ID, 2377 const ObjCIvarDecl *Ivar) { 2378 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 2379 + '.' + Ivar->getNameAsString(); 2380 // Emit the variable and initialize it with what we think the correct value 2381 // is. This allows code compiled with non-fragile ivars to work correctly 2382 // when linked against code which isn't (most of the time). 2383 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 2384 if (!IvarOffsetPointer) { 2385 // This will cause a run-time crash if we accidentally use it. A value of 2386 // 0 would seem more sensible, but will silently overwrite the isa pointer 2387 // causing a great deal of confusion. 2388 uint64_t Offset = -1; 2389 // We can't call ComputeIvarBaseOffset() here if we have the 2390 // implementation, because it will create an invalid ASTRecordLayout object 2391 // that we are then stuck with forever, so we only initialize the ivar 2392 // offset variable with a guess if we only have the interface. The 2393 // initializer will be reset later anyway, when we are generating the class 2394 // description. 2395 if (!CGM.getContext().getObjCImplementation( 2396 const_cast<ObjCInterfaceDecl *>(ID))) 2397 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar); 2398 2399 llvm::ConstantInt *OffsetGuess = 2400 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar"); 2401 // Don't emit the guess in non-PIC code because the linker will not be able 2402 // to replace it with the real version for a library. In non-PIC code you 2403 // must compile with the fragile ABI if you want to use ivars from a 2404 // GCC-compiled class. 2405 if (CGM.getLangOptions().PICLevel) { 2406 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule, 2407 llvm::Type::getInt32Ty(VMContext), false, 2408 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess"); 2409 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 2410 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage, 2411 IvarOffsetGV, Name); 2412 } else { 2413 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 2414 llvm::Type::getInt32PtrTy(VMContext), false, 2415 llvm::GlobalValue::ExternalLinkage, 0, Name); 2416 } 2417 } 2418 return IvarOffsetPointer; 2419} 2420 2421LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 2422 QualType ObjectTy, 2423 llvm::Value *BaseValue, 2424 const ObjCIvarDecl *Ivar, 2425 unsigned CVRQualifiers) { 2426 const ObjCInterfaceDecl *ID = 2427 ObjectTy->getAs<ObjCObjectType>()->getInterface(); 2428 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 2429 EmitIvarOffset(CGF, ID, Ivar)); 2430} 2431 2432static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, 2433 const ObjCInterfaceDecl *OID, 2434 const ObjCIvarDecl *OIVD) { 2435 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 2436 Context.ShallowCollectObjCIvars(OID, Ivars); 2437 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) { 2438 if (OIVD == Ivars[k]) 2439 return OID; 2440 } 2441 2442 // Otherwise check in the super class. 2443 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 2444 return FindIvarInterface(Context, Super, OIVD); 2445 2446 return 0; 2447} 2448 2449llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 2450 const ObjCInterfaceDecl *Interface, 2451 const ObjCIvarDecl *Ivar) { 2452 if (CGM.getLangOptions().ObjCNonFragileABI) { 2453 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar); 2454 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad( 2455 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")); 2456 } 2457 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar); 2458 return llvm::ConstantInt::get(LongTy, Offset, "ivar"); 2459} 2460 2461CodeGen::CGObjCRuntime * 2462CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) { 2463 return new CGObjCGNU(CGM); 2464} 2465