CGObjCGNU.cpp revision 34e65770ad6142b033d6cec4f476ed20fb248bf3
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/ADT/SmallVector.h" 30#include "llvm/ADT/StringMap.h" 31#include "llvm/Support/Compiler.h" 32#include "llvm/Target/TargetData.h" 33 34#include <map> 35 36 37using namespace clang; 38using namespace CodeGen; 39using llvm::dyn_cast; 40 41// The version of the runtime that this class targets. Must match the version 42// in the runtime. 43static const int RuntimeVersion = 8; 44static const int NonFragileRuntimeVersion = 9; 45static const int ProtocolVersion = 2; 46 47namespace { 48class CGObjCGNU : public CodeGen::CGObjCRuntime { 49private: 50 CodeGen::CodeGenModule &CGM; 51 llvm::Module &TheModule; 52 const llvm::PointerType *SelectorTy; 53 const llvm::PointerType *PtrToInt8Ty; 54 const llvm::FunctionType *IMPTy; 55 const llvm::PointerType *IdTy; 56 const llvm::IntegerType *IntTy; 57 const llvm::PointerType *PtrTy; 58 const llvm::IntegerType *LongTy; 59 const llvm::PointerType *PtrToIntTy; 60 llvm::GlobalAlias *ClassPtrAlias; 61 llvm::GlobalAlias *MetaClassPtrAlias; 62 std::vector<llvm::Constant*> Classes; 63 std::vector<llvm::Constant*> Categories; 64 std::vector<llvm::Constant*> ConstantStrings; 65 llvm::Function *LoadFunction; 66 llvm::StringMap<llvm::Constant*> ExistingProtocols; 67 typedef std::pair<std::string, std::string> TypedSelector; 68 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors; 69 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors; 70 // Some zeros used for GEPs in lots of places. 71 llvm::Constant *Zeros[2]; 72 llvm::Constant *NULLPtr; 73private: 74 llvm::Constant *GenerateIvarList( 75 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames, 76 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes, 77 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets); 78 llvm::Constant *GenerateMethodList(const std::string &ClassName, 79 const std::string &CategoryName, 80 const llvm::SmallVectorImpl<Selector> &MethodSels, 81 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes, 82 bool isClassMethodList); 83 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName); 84 llvm::Constant *GenerateProtocolList( 85 const llvm::SmallVectorImpl<std::string> &Protocols); 86 llvm::Constant *GenerateClassStructure( 87 llvm::Constant *MetaClass, 88 llvm::Constant *SuperClass, 89 unsigned info, 90 const char *Name, 91 llvm::Constant *Version, 92 llvm::Constant *InstanceSize, 93 llvm::Constant *IVars, 94 llvm::Constant *Methods, 95 llvm::Constant *Protocols); 96 llvm::Constant *GenerateProtocolMethodList( 97 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames, 98 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes); 99 llvm::Constant *MakeConstantString(const std::string &Str, const std::string 100 &Name=""); 101 llvm::Constant *MakeGlobal(const llvm::StructType *Ty, 102 std::vector<llvm::Constant*> &V, const std::string &Name=""); 103 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty, 104 std::vector<llvm::Constant*> &V, const std::string &Name=""); 105 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 106 const ObjCIvarDecl *Ivar); 107public: 108 CGObjCGNU(CodeGen::CodeGenModule &cgm); 109 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *); 110 virtual CodeGen::RValue 111 GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 112 QualType ResultType, 113 Selector Sel, 114 llvm::Value *Receiver, 115 bool IsClassMessage, 116 const CallArgList &CallArgs, 117 const ObjCMethodDecl *Method); 118 virtual CodeGen::RValue 119 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 120 QualType ResultType, 121 Selector Sel, 122 const ObjCInterfaceDecl *Class, 123 bool isCategoryImpl, 124 llvm::Value *Receiver, 125 bool IsClassMessage, 126 const CallArgList &CallArgs); 127 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 128 const ObjCInterfaceDecl *OID); 129 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); 130 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl 131 *Method); 132 133 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 134 const ObjCContainerDecl *CD); 135 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 136 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 137 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 138 const ObjCProtocolDecl *PD); 139 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 140 virtual llvm::Function *ModuleInitFunction(); 141 virtual llvm::Function *GetPropertyGetFunction(); 142 virtual llvm::Function *GetPropertySetFunction(); 143 virtual llvm::Function *EnumerationMutationFunction(); 144 145 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 146 const Stmt &S); 147 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 148 const ObjCAtThrowStmt &S); 149 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 150 llvm::Value *AddrWeakObj); 151 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 152 llvm::Value *src, llvm::Value *dst); 153 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 154 llvm::Value *src, llvm::Value *dest); 155 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 156 llvm::Value *src, llvm::Value *dest); 157 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 158 llvm::Value *src, llvm::Value *dest); 159 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 160 QualType ObjectTy, 161 llvm::Value *BaseValue, 162 const ObjCIvarDecl *Ivar, 163 unsigned CVRQualifiers); 164 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 165 const ObjCInterfaceDecl *Interface, 166 const ObjCIvarDecl *Ivar); 167}; 168} // end anonymous namespace 169 170 171 172static std::string SymbolNameForClass(const std::string &ClassName) { 173 return "___objc_class_name_" + ClassName; 174} 175 176static std::string SymbolNameForMethod(const std::string &ClassName, const 177 std::string &CategoryName, const std::string &MethodName, bool isClassMethod) 178{ 179 return "._objc_method_" + ClassName +"("+CategoryName+")"+ 180 (isClassMethod ? "+" : "-") + MethodName; 181} 182 183CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm) 184 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0), 185 MetaClassPtrAlias(0) { 186 IntTy = cast<llvm::IntegerType>( 187 CGM.getTypes().ConvertType(CGM.getContext().IntTy)); 188 LongTy = cast<llvm::IntegerType>( 189 CGM.getTypes().ConvertType(CGM.getContext().LongTy)); 190 191 Zeros[0] = llvm::ConstantInt::get(LongTy, 0); 192 Zeros[1] = Zeros[0]; 193 NULLPtr = llvm::ConstantPointerNull::get( 194 llvm::PointerType::getUnqual(llvm::Type::Int8Ty)); 195 // C string type. Used in lots of places. 196 PtrToInt8Ty = 197 llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 198 // Get the selector Type. 199 SelectorTy = cast<llvm::PointerType>( 200 CGM.getTypes().ConvertType(CGM.getContext().getObjCSelType())); 201 202 PtrToIntTy = llvm::PointerType::getUnqual(IntTy); 203 PtrTy = PtrToInt8Ty; 204 205 // Object type 206 IdTy = cast<llvm::PointerType>( 207 CGM.getTypes().ConvertType(CGM.getContext().getObjCIdType())); 208 209 // IMP type 210 std::vector<const llvm::Type*> IMPArgs; 211 IMPArgs.push_back(IdTy); 212 IMPArgs.push_back(SelectorTy); 213 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true); 214} 215// This has to perform the lookup every time, since posing and related 216// techniques can modify the name -> class mapping. 217llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder, 218 const ObjCInterfaceDecl *OID) { 219 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString()); 220 ClassName = Builder.CreateStructGEP(ClassName, 0); 221 222 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty); 223 llvm::Constant *ClassLookupFn = 224 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, 225 Params, 226 true), 227 "objc_lookup_class"); 228 return Builder.CreateCall(ClassLookupFn, ClassName); 229} 230 231llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) { 232 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()]; 233 if (US == 0) 234 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy), 235 llvm::GlobalValue::InternalLinkage, 236 ".objc_untyped_selector_alias", 237 NULL, &TheModule); 238 239 return Builder.CreateLoad(US); 240} 241 242llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl 243 *Method) { 244 245 std::string SelName = Method->getSelector().getAsString(); 246 std::string SelTypes; 247 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes); 248 // Typed selectors 249 TypedSelector Selector = TypedSelector(SelName, 250 SelTypes); 251 252 // If it's already cached, return it. 253 if (TypedSelectors[Selector]) 254 { 255 return Builder.CreateLoad(TypedSelectors[Selector]); 256 } 257 258 // If it isn't, cache it. 259 llvm::GlobalAlias *Sel = new llvm::GlobalAlias( 260 llvm::PointerType::getUnqual(SelectorTy), 261 llvm::GlobalValue::InternalLinkage, SelName, 262 NULL, &TheModule); 263 TypedSelectors[Selector] = Sel; 264 265 return Builder.CreateLoad(Sel); 266} 267 268llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str, 269 const std::string &Name) { 270 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str); 271 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true, 272 llvm::GlobalValue::InternalLinkage, 273 ConstStr, Name, &TheModule); 274 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2); 275} 276llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty, 277 std::vector<llvm::Constant*> &V, const std::string &Name) { 278 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V); 279 return new llvm::GlobalVariable(Ty, false, 280 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule); 281} 282llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty, 283 std::vector<llvm::Constant*> &V, const std::string &Name) { 284 llvm::Constant *C = llvm::ConstantArray::get(Ty, V); 285 return new llvm::GlobalVariable(Ty, false, 286 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule); 287} 288 289/// Generate an NSConstantString object. 290//TODO: In case there are any crazy people still using the GNU runtime without 291//an OpenStep implementation, this should let them select their own class for 292//constant strings. 293llvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) { 294 std::string Str(SL->getString()->getStrData(), 295 SL->getString()->getByteLength()); 296 std::vector<llvm::Constant*> Ivars; 297 Ivars.push_back(NULLPtr); 298 Ivars.push_back(MakeConstantString(Str)); 299 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size())); 300 llvm::Constant *ObjCStr = MakeGlobal( 301 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL), 302 Ivars, ".objc_str"); 303 ConstantStrings.push_back( 304 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty)); 305 return ObjCStr; 306} 307 308///Generates a message send where the super is the receiver. This is a message 309///send to self with special delivery semantics indicating which class's method 310///should be called. 311CodeGen::RValue 312CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 313 QualType ResultType, 314 Selector Sel, 315 const ObjCInterfaceDecl *Class, 316 bool isCategoryImpl, 317 llvm::Value *Receiver, 318 bool IsClassMessage, 319 const CallArgList &CallArgs) { 320 llvm::Value *cmd = GetSelector(CGF.Builder, Sel); 321 322 CallArgList ActualArgs; 323 324 ActualArgs.push_back( 325 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)), 326 CGF.getContext().getObjCIdType())); 327 ActualArgs.push_back(std::make_pair(RValue::get(cmd), 328 CGF.getContext().getObjCSelType())); 329 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 330 331 CodeGenTypes &Types = CGM.getTypes(); 332 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); 333 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false); 334 335 llvm::Value *ReceiverClass = 0; 336 if (isCategoryImpl) { 337 llvm::Constant *classLookupFunction = 0; 338 std::vector<const llvm::Type*> Params; 339 Params.push_back(PtrTy); 340 if (IsClassMessage) { 341 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 342 IdTy, Params, true), "objc_get_meta_class"); 343 } else { 344 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 345 IdTy, Params, true), "objc_get_class"); 346 } 347 ReceiverClass = CGF.Builder.CreateCall(classLookupFunction, 348 MakeConstantString(Class->getNameAsString())); 349 } else { 350 // Set up global aliases for the metaclass or class pointer if they do not 351 // already exist. These will are forward-references which will be set to 352 // pointers to the class and metaclass structure created for the runtime load 353 // function. To send a message to super, we look up the value of the 354 // super_class pointer from either the class or metaclass structure. 355 if (IsClassMessage) { 356 if (!MetaClassPtrAlias) { 357 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy, 358 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" + 359 Class->getNameAsString(), NULL, &TheModule); 360 } 361 ReceiverClass = MetaClassPtrAlias; 362 } else { 363 if (!ClassPtrAlias) { 364 ClassPtrAlias = new llvm::GlobalAlias(IdTy, 365 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" + 366 Class->getNameAsString(), NULL, &TheModule); 367 } 368 ReceiverClass = ClassPtrAlias; 369 } 370 } 371 // Cast the pointer to a simplified version of the class structure 372 ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass, 373 llvm::PointerType::getUnqual(llvm::StructType::get(IdTy, IdTy, NULL))); 374 // Get the superclass pointer 375 ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1); 376 // Load the superclass pointer 377 ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass); 378 // Construct the structure used to look up the IMP 379 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(), 380 IdTy, NULL); 381 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy); 382 383 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 384 CGF.Builder.CreateStore(ReceiverClass, 385 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 386 387 // Get the IMP 388 std::vector<const llvm::Type*> Params; 389 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy)); 390 Params.push_back(SelectorTy); 391 llvm::Constant *lookupFunction = 392 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 393 llvm::PointerType::getUnqual(impType), Params, true), 394 "objc_msg_lookup_super"); 395 396 llvm::Value *lookupArgs[] = {ObjCSuper, cmd}; 397 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs, 398 lookupArgs+2); 399 400 return CGF.EmitCall(FnInfo, imp, ActualArgs); 401} 402 403/// Generate code for a message send expression. 404CodeGen::RValue 405CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 406 QualType ResultType, 407 Selector Sel, 408 llvm::Value *Receiver, 409 bool IsClassMessage, 410 const CallArgList &CallArgs, 411 const ObjCMethodDecl *Method) { 412 llvm::Value *cmd; 413 if (Method) 414 cmd = GetSelector(CGF.Builder, Method); 415 else 416 cmd = GetSelector(CGF.Builder, Sel); 417 CallArgList ActualArgs; 418 419 ActualArgs.push_back( 420 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)), 421 CGF.getContext().getObjCIdType())); 422 ActualArgs.push_back(std::make_pair(RValue::get(cmd), 423 CGF.getContext().getObjCSelType())); 424 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 425 426 CodeGenTypes &Types = CGM.getTypes(); 427 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); 428 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false); 429 430 llvm::Value *imp; 431 std::vector<const llvm::Type*> Params; 432 Params.push_back(Receiver->getType()); 433 Params.push_back(SelectorTy); 434 // For sender-aware dispatch, we pass the sender as the third argument to a 435 // lookup function. When sending messages from C code, the sender is nil. 436 // objc_msg_lookup_sender(id receiver, SEL selector, id sender); 437 if (CGM.getContext().getLangOptions().ObjCSenderDispatch) { 438 llvm::Value *self; 439 440 if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) { 441 self = CGF.LoadObjCSelf(); 442 } else { 443 self = llvm::ConstantPointerNull::get(IdTy); 444 } 445 Params.push_back(self->getType()); 446 llvm::Constant *lookupFunction = 447 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 448 llvm::PointerType::getUnqual(impType), Params, true), 449 "objc_msg_lookup_sender"); 450 451 imp = CGF.Builder.CreateCall3(lookupFunction, Receiver, cmd, self); 452 } else { 453 llvm::Constant *lookupFunction = 454 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 455 llvm::PointerType::getUnqual(impType), Params, true), 456 "objc_msg_lookup"); 457 458 imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd); 459 } 460 461 return CGF.EmitCall(FnInfo, imp, ActualArgs); 462} 463 464/// Generates a MethodList. Used in construction of a objc_class and 465/// objc_category structures. 466llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName, 467 const std::string &CategoryName, 468 const llvm::SmallVectorImpl<Selector> &MethodSels, 469 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes, 470 bool isClassMethodList) { 471 // Get the method structure type. 472 llvm::StructType *ObjCMethodTy = llvm::StructType::get( 473 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 474 PtrToInt8Ty, // Method types 475 llvm::PointerType::getUnqual(IMPTy), //Method pointer 476 NULL); 477 std::vector<llvm::Constant*> Methods; 478 std::vector<llvm::Constant*> Elements; 479 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) { 480 Elements.clear(); 481 if (llvm::Constant *Method = 482 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName, 483 MethodSels[i].getAsString(), 484 isClassMethodList))) { 485 llvm::Constant *C = 486 CGM.GetAddrOfConstantCString(MethodSels[i].getAsString()); 487 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2)); 488 Elements.push_back( 489 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2)); 490 Method = llvm::ConstantExpr::getBitCast(Method, 491 llvm::PointerType::getUnqual(IMPTy)); 492 Elements.push_back(Method); 493 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements)); 494 } 495 } 496 497 // Array of method structures 498 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy, 499 Methods.size()); 500 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy, 501 Methods); 502 503 // Structure containing list pointer, array and array count 504 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields; 505 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(); 506 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy); 507 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy, 508 IntTy, 509 ObjCMethodArrayTy, 510 NULL); 511 // Refine next pointer type to concrete type 512 llvm::cast<llvm::OpaqueType>( 513 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy); 514 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get()); 515 516 Methods.clear(); 517 Methods.push_back(llvm::ConstantPointerNull::get( 518 llvm::PointerType::getUnqual(ObjCMethodListTy))); 519 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 520 MethodTypes.size())); 521 Methods.push_back(MethodArray); 522 523 // Create an instance of the structure 524 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list"); 525} 526 527/// Generates an IvarList. Used in construction of a objc_class. 528llvm::Constant *CGObjCGNU::GenerateIvarList( 529 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames, 530 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes, 531 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) { 532 // Get the method structure type. 533 llvm::StructType *ObjCIvarTy = llvm::StructType::get( 534 PtrToInt8Ty, 535 PtrToInt8Ty, 536 IntTy, 537 NULL); 538 std::vector<llvm::Constant*> Ivars; 539 std::vector<llvm::Constant*> Elements; 540 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) { 541 Elements.clear(); 542 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i], 543 Zeros, 2)); 544 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i], 545 Zeros, 2)); 546 Elements.push_back(IvarOffsets[i]); 547 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements)); 548 } 549 550 // Array of method structures 551 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy, 552 IvarNames.size()); 553 554 555 Elements.clear(); 556 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size())); 557 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)); 558 // Structure containing array and array count 559 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy, 560 ObjCIvarArrayTy, 561 NULL); 562 563 // Create an instance of the structure 564 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list"); 565} 566 567/// Generate a class structure 568llvm::Constant *CGObjCGNU::GenerateClassStructure( 569 llvm::Constant *MetaClass, 570 llvm::Constant *SuperClass, 571 unsigned info, 572 const char *Name, 573 llvm::Constant *Version, 574 llvm::Constant *InstanceSize, 575 llvm::Constant *IVars, 576 llvm::Constant *Methods, 577 llvm::Constant *Protocols) { 578 // Set up the class structure 579 // Note: Several of these are char*s when they should be ids. This is 580 // because the runtime performs this translation on load. 581 llvm::StructType *ClassTy = llvm::StructType::get( 582 PtrToInt8Ty, // class_pointer 583 PtrToInt8Ty, // super_class 584 PtrToInt8Ty, // name 585 LongTy, // version 586 LongTy, // info 587 LongTy, // instance_size 588 IVars->getType(), // ivars 589 Methods->getType(), // methods 590 // These are all filled in by the runtime, so we pretend 591 PtrTy, // dtable 592 PtrTy, // subclass_list 593 PtrTy, // sibling_class 594 PtrTy, // protocols 595 PtrTy, // gc_object_type 596 NULL); 597 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0); 598 llvm::Constant *NullP = 599 llvm::ConstantPointerNull::get(PtrTy); 600 // Fill in the structure 601 std::vector<llvm::Constant*> Elements; 602 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty)); 603 Elements.push_back(SuperClass); 604 Elements.push_back(MakeConstantString(Name, ".class_name")); 605 Elements.push_back(Zero); 606 Elements.push_back(llvm::ConstantInt::get(LongTy, info)); 607 Elements.push_back(InstanceSize); 608 Elements.push_back(IVars); 609 Elements.push_back(Methods); 610 Elements.push_back(NullP); 611 Elements.push_back(NullP); 612 Elements.push_back(NullP); 613 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy)); 614 Elements.push_back(NullP); 615 // Create an instance of the structure 616 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name)); 617} 618 619llvm::Constant *CGObjCGNU::GenerateProtocolMethodList( 620 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames, 621 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) { 622 // Get the method structure type. 623 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get( 624 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us. 625 PtrToInt8Ty, 626 NULL); 627 std::vector<llvm::Constant*> Methods; 628 std::vector<llvm::Constant*> Elements; 629 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) { 630 Elements.clear(); 631 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i], 632 Zeros, 2)); 633 Elements.push_back( 634 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2)); 635 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements)); 636 } 637 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy, 638 MethodNames.size()); 639 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods); 640 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get( 641 IntTy, ObjCMethodArrayTy, NULL); 642 Methods.clear(); 643 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size())); 644 Methods.push_back(Array); 645 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list"); 646} 647// Create the protocol list structure used in classes, categories and so on 648llvm::Constant *CGObjCGNU::GenerateProtocolList( 649 const llvm::SmallVectorImpl<std::string> &Protocols) { 650 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 651 Protocols.size()); 652 llvm::StructType *ProtocolListTy = llvm::StructType::get( 653 PtrTy, //Should be a recurisve pointer, but it's always NULL here. 654 LongTy,//FIXME: Should be size_t 655 ProtocolArrayTy, 656 NULL); 657 std::vector<llvm::Constant*> Elements; 658 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); 659 iter != endIter ; iter++) { 660 llvm::Constant *protocol = ExistingProtocols[*iter]; 661 if (!protocol) 662 protocol = GenerateEmptyProtocol(*iter); 663 llvm::Constant *Ptr = 664 llvm::ConstantExpr::getBitCast(protocol, PtrToInt8Ty); 665 Elements.push_back(Ptr); 666 } 667 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 668 Elements); 669 Elements.clear(); 670 Elements.push_back(NULLPtr); 671 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size())); 672 Elements.push_back(ProtocolArray); 673 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list"); 674} 675 676llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder, 677 const ObjCProtocolDecl *PD) { 678 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()]; 679 const llvm::Type *T = 680 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); 681 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); 682} 683 684llvm::Constant *CGObjCGNU::GenerateEmptyProtocol( 685 const std::string &ProtocolName) { 686 llvm::SmallVector<std::string, 0> EmptyStringVector; 687 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector; 688 689 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector); 690 llvm::Constant *InstanceMethodList = 691 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector); 692 llvm::Constant *ClassMethodList = 693 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector); 694 // Protocols are objects containing lists of the methods implemented and 695 // protocols adopted. 696 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy, 697 PtrToInt8Ty, 698 ProtocolList->getType(), 699 InstanceMethodList->getType(), 700 ClassMethodList->getType(), 701 NULL); 702 std::vector<llvm::Constant*> Elements; 703 // The isa pointer must be set to a magic number so the runtime knows it's 704 // the correct layout. 705 Elements.push_back(llvm::ConstantExpr::getIntToPtr( 706 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy)); 707 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name")); 708 Elements.push_back(ProtocolList); 709 Elements.push_back(InstanceMethodList); 710 Elements.push_back(ClassMethodList); 711 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol"); 712} 713 714void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { 715 ASTContext &Context = CGM.getContext(); 716 std::string ProtocolName = PD->getNameAsString(); 717 llvm::SmallVector<std::string, 16> Protocols; 718 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(), 719 E = PD->protocol_end(); PI != E; ++PI) 720 Protocols.push_back((*PI)->getNameAsString()); 721 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames; 722 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 723 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(Context), 724 E = PD->instmeth_end(Context); iter != E; iter++) { 725 std::string TypeStr; 726 Context.getObjCEncodingForMethodDecl(*iter, TypeStr); 727 InstanceMethodNames.push_back( 728 CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString())); 729 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 730 } 731 // Collect information about class methods: 732 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames; 733 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 734 for (ObjCProtocolDecl::classmeth_iterator 735 iter = PD->classmeth_begin(Context), 736 endIter = PD->classmeth_end(Context) ; iter != endIter ; iter++) { 737 std::string TypeStr; 738 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 739 ClassMethodNames.push_back( 740 CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString())); 741 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 742 } 743 744 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 745 llvm::Constant *InstanceMethodList = 746 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes); 747 llvm::Constant *ClassMethodList = 748 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes); 749 // Protocols are objects containing lists of the methods implemented and 750 // protocols adopted. 751 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy, 752 PtrToInt8Ty, 753 ProtocolList->getType(), 754 InstanceMethodList->getType(), 755 ClassMethodList->getType(), 756 NULL); 757 std::vector<llvm::Constant*> Elements; 758 // The isa pointer must be set to a magic number so the runtime knows it's 759 // the correct layout. 760 Elements.push_back(llvm::ConstantExpr::getIntToPtr( 761 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy)); 762 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name")); 763 Elements.push_back(ProtocolList); 764 Elements.push_back(InstanceMethodList); 765 Elements.push_back(ClassMethodList); 766 ExistingProtocols[ProtocolName] = 767 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements, 768 ".objc_protocol"), IdTy); 769} 770 771void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 772 std::string ClassName = OCD->getClassInterface()->getNameAsString(); 773 std::string CategoryName = OCD->getNameAsString(); 774 // Collect information about instance methods 775 llvm::SmallVector<Selector, 16> InstanceMethodSels; 776 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 777 for (ObjCCategoryImplDecl::instmeth_iterator 778 iter = OCD->instmeth_begin(CGM.getContext()), 779 endIter = OCD->instmeth_end(CGM.getContext()); 780 iter != endIter ; iter++) { 781 InstanceMethodSels.push_back((*iter)->getSelector()); 782 std::string TypeStr; 783 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr); 784 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 785 } 786 787 // Collect information about class methods 788 llvm::SmallVector<Selector, 16> ClassMethodSels; 789 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 790 for (ObjCCategoryImplDecl::classmeth_iterator 791 iter = OCD->classmeth_begin(CGM.getContext()), 792 endIter = OCD->classmeth_end(CGM.getContext()); 793 iter != endIter ; iter++) { 794 ClassMethodSels.push_back((*iter)->getSelector()); 795 std::string TypeStr; 796 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr); 797 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 798 } 799 800 // Collect the names of referenced protocols 801 llvm::SmallVector<std::string, 16> Protocols; 802 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface(); 803 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols(); 804 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 805 E = Protos.end(); I != E; ++I) 806 Protocols.push_back((*I)->getNameAsString()); 807 808 std::vector<llvm::Constant*> Elements; 809 Elements.push_back(MakeConstantString(CategoryName)); 810 Elements.push_back(MakeConstantString(ClassName)); 811 // Instance method list 812 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 813 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes, 814 false), PtrTy)); 815 // Class method list 816 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 817 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true), 818 PtrTy)); 819 // Protocol list 820 Elements.push_back(llvm::ConstantExpr::getBitCast( 821 GenerateProtocolList(Protocols), PtrTy)); 822 Categories.push_back(llvm::ConstantExpr::getBitCast( 823 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy, 824 PtrTy, PtrTy, NULL), Elements), PtrTy)); 825} 826 827void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { 828 ASTContext &Context = CGM.getContext(); 829 830 // Get the superclass name. 831 const ObjCInterfaceDecl * SuperClassDecl = 832 OID->getClassInterface()->getSuperClass(); 833 std::string SuperClassName; 834 if (SuperClassDecl) 835 SuperClassName = SuperClassDecl->getNameAsString(); 836 837 // Get the class name 838 ObjCInterfaceDecl *ClassDecl = 839 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 840 std::string ClassName = ClassDecl->getNameAsString(); 841 842 // Get the size of instances. 843 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8; 844 845 // Collect information about instance variables. 846 llvm::SmallVector<llvm::Constant*, 16> IvarNames; 847 llvm::SmallVector<llvm::Constant*, 16> IvarTypes; 848 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets; 849 850 int superInstanceSize = !SuperClassDecl ? 0 : 851 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8; 852 // For non-fragile ivars, set the instance size to 0 - {the size of just this 853 // class}. The runtime will then set this to the correct value on load. 854 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 855 instanceSize = 0 - (instanceSize - superInstanceSize); 856 } 857 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(), 858 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) { 859 // Store the name 860 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter) 861 ->getNameAsString())); 862 // Get the type encoding for this ivar 863 std::string TypeStr; 864 Context.getObjCEncodingForType((*iter)->getType(), TypeStr); 865 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 866 // Get the offset 867 uint64_t Offset; 868 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 869 Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter) - 870 superInstanceSize; 871 ObjCIvarOffsetVariable(ClassDecl, *iter); 872 } else { 873 Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter); 874 } 875 IvarOffsets.push_back( 876 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset)); 877 } 878 879 // Collect information about instance methods 880 llvm::SmallVector<Selector, 16> InstanceMethodSels; 881 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 882 for (ObjCImplementationDecl::instmeth_iterator 883 iter = OID->instmeth_begin(CGM.getContext()), 884 endIter = OID->instmeth_end(CGM.getContext()); 885 iter != endIter ; iter++) { 886 InstanceMethodSels.push_back((*iter)->getSelector()); 887 std::string TypeStr; 888 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 889 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 890 } 891 for (ObjCImplDecl::propimpl_iterator 892 iter = OID->propimpl_begin(CGM.getContext()), 893 endIter = OID->propimpl_end(CGM.getContext()); 894 iter != endIter ; iter++) { 895 ObjCPropertyDecl *property = (*iter)->getPropertyDecl(); 896 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) { 897 InstanceMethodSels.push_back(getter->getSelector()); 898 std::string TypeStr; 899 Context.getObjCEncodingForMethodDecl(getter,TypeStr); 900 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 901 } 902 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) { 903 InstanceMethodSels.push_back(setter->getSelector()); 904 std::string TypeStr; 905 Context.getObjCEncodingForMethodDecl(setter,TypeStr); 906 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 907 } 908 } 909 910 // Collect information about class methods 911 llvm::SmallVector<Selector, 16> ClassMethodSels; 912 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 913 for (ObjCImplementationDecl::classmeth_iterator 914 iter = OID->classmeth_begin(CGM.getContext()), 915 endIter = OID->classmeth_end(CGM.getContext()); 916 iter != endIter ; iter++) { 917 ClassMethodSels.push_back((*iter)->getSelector()); 918 std::string TypeStr; 919 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 920 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr)); 921 } 922 // Collect the names of referenced protocols 923 llvm::SmallVector<std::string, 16> Protocols; 924 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols(); 925 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 926 E = Protos.end(); I != E; ++I) 927 Protocols.push_back((*I)->getNameAsString()); 928 929 930 931 // Get the superclass pointer. 932 llvm::Constant *SuperClass; 933 if (!SuperClassName.empty()) { 934 SuperClass = MakeConstantString(SuperClassName, ".super_class_name"); 935 } else { 936 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty); 937 } 938 // Empty vector used to construct empty method lists 939 llvm::SmallVector<llvm::Constant*, 1> empty; 940 // Generate the method and instance variable lists 941 llvm::Constant *MethodList = GenerateMethodList(ClassName, "", 942 InstanceMethodSels, InstanceMethodTypes, false); 943 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "", 944 ClassMethodSels, ClassMethodTypes, true); 945 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, 946 IvarOffsets); 947 //Generate metaclass for class methods 948 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr, 949 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList( 950 empty, empty, empty), ClassMethodList, NULLPtr); 951 952 // Generate the class structure 953 llvm::Constant *ClassStruct = 954 GenerateClassStructure(MetaClassStruct, SuperClass, 0x1L, 955 ClassName.c_str(), 0, 956 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, 957 MethodList, GenerateProtocolList(Protocols)); 958 959 // Resolve the class aliases, if they exist. 960 if (ClassPtrAlias) { 961 ClassPtrAlias->setAliasee( 962 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy)); 963 ClassPtrAlias = 0; 964 } 965 if (MetaClassPtrAlias) { 966 MetaClassPtrAlias->setAliasee( 967 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy)); 968 MetaClassPtrAlias = 0; 969 } 970 971 // Add class structure to list to be added to the symtab later 972 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty); 973 Classes.push_back(ClassStruct); 974} 975 976llvm::Function *CGObjCGNU::ModuleInitFunction() { 977 // Only emit an ObjC load function if no Objective-C stuff has been called 978 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && 979 ExistingProtocols.empty() && TypedSelectors.empty() && 980 UntypedSelectors.empty()) 981 return NULL; 982 983 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>( 984 SelectorTy->getElementType()); 985 const llvm::Type *SelStructPtrTy = SelectorTy; 986 bool isSelOpaque = false; 987 if (SelStructTy == 0) { 988 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL); 989 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy); 990 isSelOpaque = true; 991 } 992 993 // Name the ObjC types to make the IR a bit easier to read 994 TheModule.addTypeName(".objc_selector", SelStructPtrTy); 995 TheModule.addTypeName(".objc_id", IdTy); 996 TheModule.addTypeName(".objc_imp", IMPTy); 997 998 std::vector<llvm::Constant*> Elements; 999 llvm::Constant *Statics = NULLPtr; 1000 // Generate statics list: 1001 if (ConstantStrings.size()) { 1002 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 1003 ConstantStrings.size() + 1); 1004 ConstantStrings.push_back(NULLPtr); 1005 Elements.push_back(MakeConstantString("NSConstantString", 1006 ".objc_static_class_name")); 1007 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, 1008 ConstantStrings)); 1009 llvm::StructType *StaticsListTy = 1010 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL); 1011 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy); 1012 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics"); 1013 llvm::ArrayType *StaticsListArrayTy = 1014 llvm::ArrayType::get(StaticsListPtrTy, 2); 1015 Elements.clear(); 1016 Elements.push_back(Statics); 1017 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy)); 1018 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr"); 1019 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy); 1020 } 1021 // Array of classes, categories, and constant objects 1022 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty, 1023 Classes.size() + Categories.size() + 2); 1024 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy, 1025 llvm::Type::Int16Ty, 1026 llvm::Type::Int16Ty, 1027 ClassListTy, NULL); 1028 1029 Elements.clear(); 1030 // Pointer to an array of selectors used in this module. 1031 std::vector<llvm::Constant*> Selectors; 1032 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator 1033 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end(); 1034 iter != iterEnd ; ++iter) { 1035 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name")); 1036 Elements.push_back(MakeConstantString(iter->first.second, 1037 ".objc_sel_types")); 1038 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1039 Elements.clear(); 1040 } 1041 for (llvm::StringMap<llvm::GlobalAlias*>::iterator 1042 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end(); 1043 iter != iterEnd; ++iter) { 1044 Elements.push_back( 1045 MakeConstantString(iter->getKeyData(), ".objc_sel_name")); 1046 Elements.push_back(NULLPtr); 1047 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1048 Elements.clear(); 1049 } 1050 Elements.push_back(NULLPtr); 1051 Elements.push_back(NULLPtr); 1052 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1053 Elements.clear(); 1054 // Number of static selectors 1055 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() )); 1056 llvm::Constant *SelectorList = MakeGlobal( 1057 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors, 1058 ".objc_selector_list"); 1059 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, 1060 SelStructPtrTy)); 1061 1062 // Now that all of the static selectors exist, create pointers to them. 1063 int index = 0; 1064 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator 1065 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end(); 1066 iter != iterEnd; ++iter) { 1067 llvm::Constant *Idxs[] = {Zeros[0], 1068 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]}; 1069 llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy, 1070 true, llvm::GlobalValue::InternalLinkage, 1071 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), 1072 ".objc_sel_ptr", &TheModule); 1073 // If selectors are defined as an opaque type, cast the pointer to this 1074 // type. 1075 if (isSelOpaque) { 1076 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, 1077 llvm::PointerType::getUnqual(SelectorTy)); 1078 } 1079 (*iter).second->setAliasee(SelPtr); 1080 } 1081 for (llvm::StringMap<llvm::GlobalAlias*>::iterator 1082 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end(); 1083 iter != iterEnd; iter++) { 1084 llvm::Constant *Idxs[] = {Zeros[0], 1085 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]}; 1086 llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy, true, 1087 llvm::GlobalValue::InternalLinkage, 1088 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), 1089 ".objc_sel_ptr", &TheModule); 1090 // If selectors are defined as an opaque type, cast the pointer to this 1091 // type. 1092 if (isSelOpaque) { 1093 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, 1094 llvm::PointerType::getUnqual(SelectorTy)); 1095 } 1096 (*iter).second->setAliasee(SelPtr); 1097 } 1098 // Number of classes defined. 1099 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty, 1100 Classes.size())); 1101 // Number of categories defined 1102 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty, 1103 Categories.size())); 1104 // Create an array of classes, then categories, then static object instances 1105 Classes.insert(Classes.end(), Categories.begin(), Categories.end()); 1106 // NULL-terminated list of static object instances (mainly constant strings) 1107 Classes.push_back(Statics); 1108 Classes.push_back(NULLPtr); 1109 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes); 1110 Elements.push_back(ClassList); 1111 // Construct the symbol table 1112 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements); 1113 1114 // The symbol table is contained in a module which has some version-checking 1115 // constants 1116 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy, 1117 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL); 1118 Elements.clear(); 1119 // Runtime version used for compatibility checking. 1120 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 1121 Elements.push_back(llvm::ConstantInt::get(LongTy, 1122 NonFragileRuntimeVersion)); 1123 } else { 1124 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion)); 1125 } 1126 // sizeof(ModuleTy) 1127 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule); 1128 Elements.push_back(llvm::ConstantInt::get(LongTy, td.getTypeSizeInBits(ModuleTy)/8)); 1129 //FIXME: Should be the path to the file where this module was declared 1130 Elements.push_back(NULLPtr); 1131 Elements.push_back(SymTab); 1132 llvm::Value *Module = MakeGlobal(ModuleTy, Elements); 1133 1134 // Create the load function calling the runtime entry point with the module 1135 // structure 1136 std::vector<const llvm::Type*> VoidArgs; 1137 llvm::Function * LoadFunction = llvm::Function::Create( 1138 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false), 1139 llvm::GlobalValue::InternalLinkage, ".objc_load_function", 1140 &TheModule); 1141 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction); 1142 CGBuilderTy Builder; 1143 Builder.SetInsertPoint(EntryBB); 1144 1145 std::vector<const llvm::Type*> Params(1, 1146 llvm::PointerType::getUnqual(ModuleTy)); 1147 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 1148 llvm::Type::VoidTy, Params, true), "__objc_exec_class"); 1149 Builder.CreateCall(Register, Module); 1150 Builder.CreateRetVoid(); 1151 1152 return LoadFunction; 1153} 1154 1155llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, 1156 const ObjCContainerDecl *CD) { 1157 const ObjCCategoryImplDecl *OCD = 1158 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext()); 1159 std::string CategoryName = OCD ? OCD->getNameAsString() : ""; 1160 std::string ClassName = OMD->getClassInterface()->getNameAsString(); 1161 std::string MethodName = OMD->getSelector().getAsString(); 1162 bool isClassMethod = !OMD->isInstanceMethod(); 1163 1164 CodeGenTypes &Types = CGM.getTypes(); 1165 const llvm::FunctionType *MethodTy = 1166 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); 1167 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName, 1168 MethodName, isClassMethod); 1169 1170 llvm::Function *Method = llvm::Function::Create(MethodTy, 1171 llvm::GlobalValue::InternalLinkage, 1172 FunctionName, 1173 &TheModule); 1174 return Method; 1175} 1176 1177llvm::Function *CGObjCGNU::GetPropertyGetFunction() { 1178 std::vector<const llvm::Type*> Params; 1179 const llvm::Type *BoolTy = 1180 CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 1181 Params.push_back(IdTy); 1182 Params.push_back(SelectorTy); 1183 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 1184 Params.push_back(LongTy); 1185 Params.push_back(BoolTy); 1186 // void objc_getProperty (id, SEL, ptrdiff_t, bool) 1187 const llvm::FunctionType *FTy = 1188 llvm::FunctionType::get(IdTy, Params, false); 1189 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1190 "objc_getProperty")); 1191} 1192 1193llvm::Function *CGObjCGNU::GetPropertySetFunction() { 1194 std::vector<const llvm::Type*> Params; 1195 const llvm::Type *BoolTy = 1196 CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 1197 Params.push_back(IdTy); 1198 Params.push_back(SelectorTy); 1199 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 1200 Params.push_back(LongTy); 1201 Params.push_back(IdTy); 1202 Params.push_back(BoolTy); 1203 Params.push_back(BoolTy); 1204 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 1205 const llvm::FunctionType *FTy = 1206 llvm::FunctionType::get(llvm::Type::VoidTy, Params, false); 1207 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1208 "objc_setProperty")); 1209} 1210 1211llvm::Function *CGObjCGNU::EnumerationMutationFunction() { 1212 std::vector<const llvm::Type*> Params(1, IdTy); 1213 return cast<llvm::Function>(CGM.CreateRuntimeFunction( 1214 llvm::FunctionType::get(llvm::Type::VoidTy, Params, true), 1215 "objc_enumerationMutation")); 1216} 1217 1218void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1219 const Stmt &S) { 1220 // Pointer to the personality function 1221 llvm::Constant *Personality = 1222 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 1223 std::vector<const llvm::Type*>(), true), 1224 "__gnu_objc_personality_v0"); 1225 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy); 1226 std::vector<const llvm::Type*> Params; 1227 Params.push_back(PtrTy); 1228 llvm::Value *RethrowFn = 1229 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 1230 Params, false), "_Unwind_Resume_or_Rethrow"); 1231 1232 bool isTry = isa<ObjCAtTryStmt>(S); 1233 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 1234 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest(); 1235 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 1236 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow"); 1237 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 1238 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 1239 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 1240 1241 // GNU runtime does not currently support @synchronized() 1242 if (!isTry) { 1243 std::vector<const llvm::Type*> Args(1, IdTy); 1244 llvm::FunctionType *FTy = 1245 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 1246 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); 1247 llvm::Value *SyncArg = 1248 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1249 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); 1250 CGF.Builder.CreateCall(SyncEnter, SyncArg); 1251 } 1252 1253 1254 // Push an EH context entry, used for handling rethrows and jumps 1255 // through finally. 1256 CGF.PushCleanupBlock(FinallyBlock); 1257 1258 // Emit the statements in the @try {} block 1259 CGF.setInvokeDest(TryHandler); 1260 1261 CGF.EmitBlock(TryBlock); 1262 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 1263 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 1264 1265 // Jump to @finally if there is no exception 1266 CGF.EmitBranchThroughCleanup(FinallyEnd); 1267 1268 // Emit the handlers 1269 CGF.EmitBlock(TryHandler); 1270 1271 // Get the correct versions of the exception handling intrinsics 1272 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule); 1273 int PointerWidth = td.getTypeSizeInBits(PtrTy); 1274 assert((PointerWidth == 32 || PointerWidth == 64) && 1275 "Can't yet handle exceptions if pointers are not 32 or 64 bits"); 1276 llvm::Value *llvm_eh_exception = 1277 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception); 1278 llvm::Value *llvm_eh_selector = PointerWidth == 32 ? 1279 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32) : 1280 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64); 1281 llvm::Value *llvm_eh_typeid_for = PointerWidth == 32 ? 1282 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i32) : 1283 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64); 1284 1285 // Exception object 1286 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 1287 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow"); 1288 1289 llvm::SmallVector<llvm::Value*, 8> ESelArgs; 1290 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers; 1291 1292 ESelArgs.push_back(Exc); 1293 ESelArgs.push_back(Personality); 1294 1295 bool HasCatchAll = false; 1296 // Only @try blocks are allowed @catch blocks, but both can have @finally 1297 if (isTry) { 1298 if (const ObjCAtCatchStmt* CatchStmt = 1299 cast<ObjCAtTryStmt>(S).getCatchStmts()) { 1300 CGF.setInvokeDest(CatchInCatch); 1301 1302 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 1303 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 1304 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody())); 1305 1306 // @catch() and @catch(id) both catch any ObjC exception 1307 if (!CatchDecl || CGF.getContext().isObjCIdType(CatchDecl->getType()) 1308 || CatchDecl->getType()->isObjCQualifiedIdType()) { 1309 // Use i8* null here to signal this is a catch all, not a cleanup. 1310 ESelArgs.push_back(NULLPtr); 1311 HasCatchAll = true; 1312 // No further catches after this one will ever by reached 1313 break; 1314 } 1315 1316 // All other types should be Objective-C interface pointer types. 1317 const PointerType *PT = CatchDecl->getType()->getAsPointerType(); 1318 assert(PT && "Invalid @catch type."); 1319 const ObjCInterfaceType *IT = 1320 PT->getPointeeType()->getAsObjCInterfaceType(); 1321 assert(IT && "Invalid @catch type."); 1322 llvm::Value *EHType = 1323 MakeConstantString(IT->getDecl()->getNameAsString()); 1324 ESelArgs.push_back(EHType); 1325 } 1326 } 1327 } 1328 1329 // We use a cleanup unless there was already a catch all. 1330 if (!HasCatchAll) { 1331 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 1332 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0)); 1333 } 1334 1335 // Find which handler was matched. 1336 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector, 1337 ESelArgs.begin(), ESelArgs.end(), "selector"); 1338 1339 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { 1340 const ParmVarDecl *CatchParam = Handlers[i].first; 1341 const Stmt *CatchBody = Handlers[i].second; 1342 1343 llvm::BasicBlock *Next = 0; 1344 1345 // The last handler always matches. 1346 if (i + 1 != e) { 1347 assert(CatchParam && "Only last handler can be a catch all."); 1348 1349 // Test whether this block matches the type for the selector and branch 1350 // to Match if it does, or to the next BB if it doesn't. 1351 llvm::BasicBlock *Match = CGF.createBasicBlock("match"); 1352 Next = CGF.createBasicBlock("catch.next"); 1353 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for, 1354 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy)); 1355 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match, 1356 Next); 1357 1358 CGF.EmitBlock(Match); 1359 } 1360 1361 if (CatchBody) { 1362 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc, 1363 CGF.ConvertType(CatchParam->getType())); 1364 1365 // Bind the catch parameter if it exists. 1366 if (CatchParam) { 1367 // CatchParam is a ParmVarDecl because of the grammar 1368 // construction used to handle this, but for codegen purposes 1369 // we treat this as a local decl. 1370 CGF.EmitLocalBlockVarDecl(*CatchParam); 1371 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam)); 1372 } 1373 1374 CGF.ObjCEHValueStack.push_back(ExcObject); 1375 CGF.EmitStmt(CatchBody); 1376 CGF.ObjCEHValueStack.pop_back(); 1377 1378 CGF.EmitBranchThroughCleanup(FinallyEnd); 1379 1380 if (Next) 1381 CGF.EmitBlock(Next); 1382 } else { 1383 assert(!Next && "catchup should be last handler."); 1384 1385 CGF.Builder.CreateStore(Exc, RethrowPtr); 1386 CGF.EmitBranchThroughCleanup(FinallyRethrow); 1387 } 1388 } 1389 // The @finally block is a secondary landing pad for any exceptions thrown in 1390 // @catch() blocks 1391 CGF.EmitBlock(CatchInCatch); 1392 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 1393 ESelArgs.clear(); 1394 ESelArgs.push_back(Exc); 1395 ESelArgs.push_back(Personality); 1396 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 1397 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(), 1398 "selector"); 1399 CGF.Builder.CreateCall(llvm_eh_typeid_for, 1400 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy)); 1401 CGF.Builder.CreateStore(Exc, RethrowPtr); 1402 CGF.EmitBranchThroughCleanup(FinallyRethrow); 1403 1404 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 1405 1406 CGF.setInvokeDest(PrevLandingPad); 1407 1408 CGF.EmitBlock(FinallyBlock); 1409 1410 1411 if (isTry) { 1412 if (const ObjCAtFinallyStmt* FinallyStmt = 1413 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 1414 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 1415 } else { 1416 // Emit 'objc_sync_exit(expr)' as finally's sole statement for 1417 // @synchronized. 1418 std::vector<const llvm::Type*> Args(1, IdTy); 1419 llvm::FunctionType *FTy = 1420 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 1421 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); 1422 llvm::Value *SyncArg = 1423 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1424 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); 1425 CGF.Builder.CreateCall(SyncExit, SyncArg); 1426 } 1427 1428 if (Info.SwitchBlock) 1429 CGF.EmitBlock(Info.SwitchBlock); 1430 if (Info.EndBlock) 1431 CGF.EmitBlock(Info.EndBlock); 1432 1433 // Branch around the rethrow code. 1434 CGF.EmitBranch(FinallyEnd); 1435 1436 CGF.EmitBlock(FinallyRethrow); 1437 CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr)); 1438 CGF.Builder.CreateUnreachable(); 1439 1440 CGF.EmitBlock(FinallyEnd); 1441 1442} 1443 1444void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 1445 const ObjCAtThrowStmt &S) { 1446 llvm::Value *ExceptionAsObject; 1447 1448 std::vector<const llvm::Type*> Args(1, IdTy); 1449 llvm::FunctionType *FTy = 1450 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 1451 llvm::Value *ThrowFn = 1452 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 1453 1454 if (const Expr *ThrowExpr = S.getThrowExpr()) { 1455 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 1456 ExceptionAsObject = Exception; 1457 } else { 1458 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 1459 "Unexpected rethrow outside @catch block."); 1460 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 1461 } 1462 ExceptionAsObject = 1463 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp"); 1464 1465 // Note: This may have to be an invoke, if we want to support constructs like: 1466 // @try { 1467 // @throw(obj); 1468 // } 1469 // @catch(id) ... 1470 // 1471 // This is effectively turning @throw into an incredibly-expensive goto, but 1472 // it may happen as a result of inlining followed by missed optimizations, or 1473 // as a result of stupidity. 1474 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest(); 1475 if (!UnwindBB) { 1476 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject); 1477 CGF.Builder.CreateUnreachable(); 1478 } else { 1479 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject, 1480 &ExceptionAsObject+1); 1481 } 1482 // Clear the insertion point to indicate we are in unreachable code. 1483 CGF.Builder.ClearInsertionPoint(); 1484} 1485 1486llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1487 llvm::Value *AddrWeakObj) 1488{ 1489 return 0; 1490} 1491 1492void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1493 llvm::Value *src, llvm::Value *dst) 1494{ 1495 return; 1496} 1497 1498void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1499 llvm::Value *src, llvm::Value *dst) 1500{ 1501 return; 1502} 1503 1504void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1505 llvm::Value *src, llvm::Value *dst) 1506{ 1507 return; 1508} 1509 1510void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1511 llvm::Value *src, llvm::Value *dst) 1512{ 1513 return; 1514} 1515 1516llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( 1517 const ObjCInterfaceDecl *ID, 1518 const ObjCIvarDecl *Ivar) { 1519 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 1520 + '.' + Ivar->getNameAsString(); 1521 // Emit the variable and initialize it with what we think the correct value 1522 // is. This allows code compiled with non-fragile ivars to work correctly 1523 // when linked against code which isn't (most of the time). 1524 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name); 1525 if (!IvarOffsetGV) { 1526 uint64_t Offset = ComputeIvarBaseOffset(CGM, ID, Ivar); 1527 llvm::ConstantInt *OffsetGuess = 1528 llvm::ConstantInt::get(LongTy, Offset, "ivar"); 1529 IvarOffsetGV = new llvm::GlobalVariable(LongTy, false, 1530 llvm::GlobalValue::CommonLinkage, OffsetGuess, Name, &TheModule); 1531 } 1532 return IvarOffsetGV; 1533} 1534 1535LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 1536 QualType ObjectTy, 1537 llvm::Value *BaseValue, 1538 const ObjCIvarDecl *Ivar, 1539 unsigned CVRQualifiers) { 1540 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl(); 1541 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 1542 EmitIvarOffset(CGF, ID, Ivar)); 1543} 1544static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, 1545 const ObjCInterfaceDecl *OID, 1546 const ObjCIvarDecl *OIVD) { 1547 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(), 1548 IVE = OID->ivar_end(); IVI != IVE; ++IVI) 1549 if (OIVD == *IVI) 1550 return OID; 1551 1552 // Also look in synthesized ivars. 1553 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 1554 Context.CollectSynthesizedIvars(OID, Ivars); 1555 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) { 1556 if (OIVD == Ivars[k]) 1557 return OID; 1558 } 1559 1560 // Otherwise check in the super class. 1561 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 1562 return FindIvarInterface(Context, Super, OIVD); 1563 1564 return 0; 1565} 1566 1567llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 1568 const ObjCInterfaceDecl *Interface, 1569 const ObjCIvarDecl *Ivar) { 1570 if (CGF.getContext().getLangOptions().ObjCNonFragileABI) 1571 { 1572 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar); 1573 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar), 1574 false, "ivar"); 1575 } 1576 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar); 1577 return llvm::ConstantInt::get(LongTy, Offset, "ivar"); 1578} 1579 1580CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){ 1581 return new CGObjCGNU(CGM); 1582} 1583