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