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