1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides Objective-C code generation targeting 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.
15 //===----------------------------------------------------------------------===//
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CodeGenFunction.h"
20 #include "CGCleanup.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/FileManager.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/Module.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/DataLayout.h"
41 using namespace clang;
42 using namespace CodeGen;
46 /// Class that lazily initialises the runtime function. Avoids inserting the
47 /// types and the function declaration into a module if they're not used, and
48 /// avoids constructing the type more than once if it's used more than once.
49 class LazyRuntimeFunction {
51 std::vector<llvm::Type*> ArgTys;
52 const char *FunctionName;
53 llvm::Constant *Function;
55 /// Constructor leaves this class uninitialized, because it is intended to
56 /// be used as a field in another class and not all of the types that are
57 /// used as arguments will necessarily be available at construction time.
58 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60 /// Initialises the lazy function with the name, return type, and the types
63 void init(CodeGenModule *Mod, const char *name,
64 llvm::Type *RetTy, ...) {
70 va_start(Args, RetTy);
71 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
72 ArgTys.push_back(ArgTy);
74 // Push the return type on at the end so we can pop it off easily
75 ArgTys.push_back(RetTy);
77 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 operator llvm::Constant*() {
81 if (0 == FunctionName) return 0;
82 // We put the return type on the end of the vector, so pop it back off
83 llvm::Type *RetTy = ArgTys.back();
85 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
88 // We won't need to use the types again, so we may as well clean up the
94 operator llvm::Function*() {
95 return cast<llvm::Function>((llvm::Constant*)*this);
101 /// GNU Objective-C runtime code generation. This class implements the parts of
102 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
103 /// GNUstep and ObjFW).
104 class CGObjCGNU : public CGObjCRuntime {
106 /// The LLVM module into which output is inserted
107 llvm::Module &TheModule;
108 /// strut objc_super. Used for sending messages to super. This structure
109 /// contains the receiver (object) and the expected class.
110 llvm::StructType *ObjCSuperTy;
111 /// struct objc_super*. The type of the argument to the superclass message
112 /// lookup functions.
113 llvm::PointerType *PtrToObjCSuperTy;
114 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
115 /// SEL is included in a header somewhere, in which case it will be whatever
116 /// type is declared in that header, most likely {i8*, i8*}.
117 llvm::PointerType *SelectorTy;
118 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
119 /// places where it's used
120 llvm::IntegerType *Int8Ty;
121 /// Pointer to i8 - LLVM type of char*, for all of the places where the
122 /// runtime needs to deal with C strings.
123 llvm::PointerType *PtrToInt8Ty;
124 /// Instance Method Pointer type. This is a pointer to a function that takes,
125 /// at a minimum, an object and a selector, and is the generic type for
126 /// Objective-C methods. Due to differences between variadic / non-variadic
127 /// calling conventions, it must always be cast to the correct type before
128 /// actually being used.
129 llvm::PointerType *IMPTy;
130 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
131 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
132 /// but if the runtime header declaring it is included then it may be a
133 /// pointer to a structure.
134 llvm::PointerType *IdTy;
135 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
136 /// message lookup function and some GC-related functions.
137 llvm::PointerType *PtrToIdTy;
138 /// The clang type of id. Used when using the clang CGCall infrastructure to
139 /// call Objective-C methods.
141 /// LLVM type for C int type.
142 llvm::IntegerType *IntTy;
143 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
144 /// used in the code to document the difference between i8* meaning a pointer
145 /// to a C string and i8* meaning a pointer to some opaque type.
146 llvm::PointerType *PtrTy;
147 /// LLVM type for C long type. The runtime uses this in a lot of places where
148 /// it should be using intptr_t, but we can't fix this without breaking
149 /// compatibility with GCC...
150 llvm::IntegerType *LongTy;
151 /// LLVM type for C size_t. Used in various runtime data structures.
152 llvm::IntegerType *SizeTy;
153 /// LLVM type for C intptr_t.
154 llvm::IntegerType *IntPtrTy;
155 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
156 llvm::IntegerType *PtrDiffTy;
157 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
159 llvm::PointerType *PtrToIntTy;
160 /// LLVM type for Objective-C BOOL type.
162 /// 32-bit integer type, to save us needing to look it up every time it's used.
163 llvm::IntegerType *Int32Ty;
164 /// 64-bit integer type, to save us needing to look it up every time it's used.
165 llvm::IntegerType *Int64Ty;
166 /// Metadata kind used to tie method lookups to message sends. The GNUstep
167 /// runtime provides some LLVM passes that can use this to do things like
168 /// automatic IMP caching and speculative inlining.
169 unsigned msgSendMDKind;
170 /// Helper function that generates a constant string and returns a pointer to
171 /// the start of the string. The result of this function can be used anywhere
172 /// where the C code specifies const char*.
173 llvm::Constant *MakeConstantString(const std::string &Str,
174 const std::string &Name="") {
175 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
176 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
178 /// Emits a linkonce_odr string, whose name is the prefix followed by the
179 /// string value. This allows the linker to combine the strings between
180 /// different modules. Used for EH typeinfo names, selector strings, and a
181 /// few other things.
182 llvm::Constant *ExportUniqueString(const std::string &Str,
183 const std::string prefix) {
184 std::string name = prefix + Str;
185 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
187 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
188 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
189 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
191 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
193 /// Generates a global structure, initialized by the elements in the vector.
194 /// The element types must match the types of the structure elements in the
196 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
197 llvm::ArrayRef<llvm::Constant*> V,
199 llvm::GlobalValue::LinkageTypes linkage
200 =llvm::GlobalValue::InternalLinkage) {
201 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
202 return new llvm::GlobalVariable(TheModule, Ty, false,
205 /// Generates a global array. The vector must contain the same number of
206 /// elements that the array type declares, of the type specified as the array
208 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
209 llvm::ArrayRef<llvm::Constant*> V,
211 llvm::GlobalValue::LinkageTypes linkage
212 =llvm::GlobalValue::InternalLinkage) {
213 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
214 return new llvm::GlobalVariable(TheModule, Ty, false,
217 /// Generates a global array, inferring the array type from the specified
218 /// element type and the size of the initialiser.
219 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
220 llvm::ArrayRef<llvm::Constant*> V,
222 llvm::GlobalValue::LinkageTypes linkage
223 =llvm::GlobalValue::InternalLinkage) {
224 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
225 return MakeGlobal(ArrayTy, V, Name, linkage);
227 /// Returns a property name and encoding string.
228 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
229 const Decl *Container) {
230 ObjCRuntime R = CGM.getLangOpts().ObjCRuntime;
231 if ((R.getKind() == ObjCRuntime::GNUstep) &&
232 (R.getVersion() >= VersionTuple(1, 6))) {
233 std::string NameAndAttributes;
235 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
236 NameAndAttributes += '\0';
237 NameAndAttributes += TypeStr.length() + 3;
238 NameAndAttributes += TypeStr;
239 NameAndAttributes += '\0';
240 NameAndAttributes += PD->getNameAsString();
241 return llvm::ConstantExpr::getGetElementPtr(
242 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
244 return MakeConstantString(PD->getNameAsString());
246 /// Ensures that the value has the required type, by inserting a bitcast if
247 /// required. This function lets us avoid inserting bitcasts that are
249 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
250 if (V->getType() == Ty) return V;
251 return B.CreateBitCast(V, Ty);
253 // Some zeros used for GEPs in lots of places.
254 llvm::Constant *Zeros[2];
255 /// Null pointer value. Mainly used as a terminator in various arrays.
256 llvm::Constant *NULLPtr;
258 llvm::LLVMContext &VMContext;
260 /// Placeholder for the class. Lots of things refer to the class before we've
261 /// actually emitted it. We use this alias as a placeholder, and then replace
262 /// it with a pointer to the class structure before finally emitting the
264 llvm::GlobalAlias *ClassPtrAlias;
265 /// Placeholder for the metaclass. Lots of things refer to the class before
266 /// we've / actually emitted it. We use this alias as a placeholder, and then
267 /// replace / it with a pointer to the metaclass structure before finally
268 /// emitting the / module.
269 llvm::GlobalAlias *MetaClassPtrAlias;
270 /// All of the classes that have been generated for this compilation units.
271 std::vector<llvm::Constant*> Classes;
272 /// All of the categories that have been generated for this compilation units.
273 std::vector<llvm::Constant*> Categories;
274 /// All of the Objective-C constant strings that have been generated for this
275 /// compilation units.
276 std::vector<llvm::Constant*> ConstantStrings;
277 /// Map from string values to Objective-C constant strings in the output.
278 /// Used to prevent emitting Objective-C strings more than once. This should
279 /// not be required at all - CodeGenModule should manage this list.
280 llvm::StringMap<llvm::Constant*> ObjCStrings;
281 /// All of the protocols that have been declared.
282 llvm::StringMap<llvm::Constant*> ExistingProtocols;
283 /// For each variant of a selector, we store the type encoding and a
284 /// placeholder value. For an untyped selector, the type will be the empty
285 /// string. Selector references are all done via the module's selector table,
286 /// so we create an alias as a placeholder and then replace it with the real
288 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
289 /// Type of the selector map. This is roughly equivalent to the structure
290 /// used in the GNUstep runtime, which maintains a list of all of the valid
291 /// types for a selector in a table.
292 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
294 /// A map from selectors to selector types. This allows us to emit all
295 /// selectors of the same name and type together.
296 SelectorMap SelectorTable;
298 /// Selectors related to memory management. When compiling in GC mode, we
300 Selector RetainSel, ReleaseSel, AutoreleaseSel;
301 /// Runtime functions used for memory management in GC mode. Note that clang
302 /// supports code generation for calling these functions, but neither GNU
303 /// runtime actually supports this API properly yet.
304 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
305 WeakAssignFn, GlobalAssignFn;
307 typedef std::pair<std::string, std::string> ClassAliasPair;
308 /// All classes that have aliases set for them.
309 std::vector<ClassAliasPair> ClassAliases;
312 /// Function used for throwing Objective-C exceptions.
313 LazyRuntimeFunction ExceptionThrowFn;
314 /// Function used for rethrowing exceptions, used at the end of \@finally or
315 /// \@synchronize blocks.
316 LazyRuntimeFunction ExceptionReThrowFn;
317 /// Function called when entering a catch function. This is required for
318 /// differentiating Objective-C exceptions and foreign exceptions.
319 LazyRuntimeFunction EnterCatchFn;
320 /// Function called when exiting from a catch block. Used to do exception
322 LazyRuntimeFunction ExitCatchFn;
323 /// Function called when entering an \@synchronize block. Acquires the lock.
324 LazyRuntimeFunction SyncEnterFn;
325 /// Function called when exiting an \@synchronize block. Releases the lock.
326 LazyRuntimeFunction SyncExitFn;
330 /// Function called if fast enumeration detects that the collection is
331 /// modified during the update.
332 LazyRuntimeFunction EnumerationMutationFn;
333 /// Function for implementing synthesized property getters that return an
335 LazyRuntimeFunction GetPropertyFn;
336 /// Function for implementing synthesized property setters that return an
338 LazyRuntimeFunction SetPropertyFn;
339 /// Function used for non-object declared property getters.
340 LazyRuntimeFunction GetStructPropertyFn;
341 /// Function used for non-object declared property setters.
342 LazyRuntimeFunction SetStructPropertyFn;
344 /// The version of the runtime that this class targets. Must match the
345 /// version in the runtime.
347 /// The version of the protocol class. Used to differentiate between ObjC1
348 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
349 /// components and can not contain declared properties. We always emit
350 /// Objective-C 2 property structures, but we have to pretend that they're
351 /// Objective-C 1 property structures when targeting the GCC runtime or it
353 const int ProtocolVersion;
355 /// Generates an instance variable list structure. This is a structure
356 /// containing a size and an array of structures containing instance variable
357 /// metadata. This is used purely for introspection in the fragile ABI. In
358 /// the non-fragile ABI, it's used for instance variable fixup.
359 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
360 ArrayRef<llvm::Constant *> IvarTypes,
361 ArrayRef<llvm::Constant *> IvarOffsets);
362 /// Generates a method list structure. This is a structure containing a size
363 /// and an array of structures containing method metadata.
365 /// This structure is used by both classes and categories, and contains a next
366 /// pointer allowing them to be chained together in a linked list.
367 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
368 const StringRef &CategoryName,
369 ArrayRef<Selector> MethodSels,
370 ArrayRef<llvm::Constant *> MethodTypes,
371 bool isClassMethodList);
372 /// Emits an empty protocol. This is used for \@protocol() where no protocol
373 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
375 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
376 /// Generates a list of property metadata structures. This follows the same
377 /// pattern as method and instance variable metadata lists.
378 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
379 SmallVectorImpl<Selector> &InstanceMethodSels,
380 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
381 /// Generates a list of referenced protocols. Classes, categories, and
382 /// protocols all use this structure.
383 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
384 /// To ensure that all protocols are seen by the runtime, we add a category on
385 /// a class defined in the runtime, declaring no methods, but adopting the
386 /// protocols. This is a horribly ugly hack, but it allows us to collect all
387 /// of the protocols without changing the ABI.
388 void GenerateProtocolHolderCategory(void);
389 /// Generates a class structure.
390 llvm::Constant *GenerateClassStructure(
391 llvm::Constant *MetaClass,
392 llvm::Constant *SuperClass,
395 llvm::Constant *Version,
396 llvm::Constant *InstanceSize,
397 llvm::Constant *IVars,
398 llvm::Constant *Methods,
399 llvm::Constant *Protocols,
400 llvm::Constant *IvarOffsets,
401 llvm::Constant *Properties,
402 llvm::Constant *StrongIvarBitmap,
403 llvm::Constant *WeakIvarBitmap,
405 /// Generates a method list. This is used by protocols to define the required
406 /// and optional methods.
407 llvm::Constant *GenerateProtocolMethodList(
408 ArrayRef<llvm::Constant *> MethodNames,
409 ArrayRef<llvm::Constant *> MethodTypes);
410 /// Returns a selector with the specified type encoding. An empty string is
411 /// used to return an untyped selector (with the types field set to NULL).
412 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
413 const std::string &TypeEncoding, bool lval);
414 /// Returns the variable used to store the offset of an instance variable.
415 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
416 const ObjCIvarDecl *Ivar);
417 /// Emits a reference to a class. This allows the linker to object if there
418 /// is no class of the matching name.
420 void EmitClassRef(const std::string &className);
421 /// Emits a pointer to the named class
422 virtual llvm::Value *GetClassNamed(CGBuilderTy &Builder,
423 const std::string &Name, bool isWeak);
424 /// Looks up the method for sending a message to the specified object. This
425 /// mechanism differs between the GCC and GNU runtimes, so this method must be
426 /// overridden in subclasses.
427 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
428 llvm::Value *&Receiver,
430 llvm::MDNode *node) = 0;
431 /// Looks up the method for sending a message to a superclass. This
432 /// mechanism differs between the GCC and GNU runtimes, so this method must
433 /// be overridden in subclasses.
434 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
435 llvm::Value *ObjCSuper,
436 llvm::Value *cmd) = 0;
437 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
438 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
439 /// bits set to their values, LSB first, while larger ones are stored in a
440 /// structure of this / form:
442 /// struct { int32_t length; int32_t values[length]; };
444 /// The values in the array are stored in host-endian format, with the least
445 /// significant bit being assumed to come first in the bitfield. Therefore,
446 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
447 /// while a bitfield / with the 63rd bit set will be 1<<64.
448 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
450 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
451 unsigned protocolClassVersion);
453 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
456 GenerateMessageSend(CodeGenFunction &CGF,
457 ReturnValueSlot Return,
460 llvm::Value *Receiver,
461 const CallArgList &CallArgs,
462 const ObjCInterfaceDecl *Class,
463 const ObjCMethodDecl *Method);
465 GenerateMessageSendSuper(CodeGenFunction &CGF,
466 ReturnValueSlot Return,
469 const ObjCInterfaceDecl *Class,
471 llvm::Value *Receiver,
473 const CallArgList &CallArgs,
474 const ObjCMethodDecl *Method);
475 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
476 const ObjCInterfaceDecl *OID);
477 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
479 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
481 virtual llvm::Constant *GetEHType(QualType T);
483 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
484 const ObjCContainerDecl *CD);
485 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
486 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
487 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
488 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
489 const ObjCProtocolDecl *PD);
490 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
491 virtual llvm::Function *ModuleInitFunction();
492 virtual llvm::Constant *GetPropertyGetFunction();
493 virtual llvm::Constant *GetPropertySetFunction();
494 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
496 virtual llvm::Constant *GetSetStructFunction();
497 virtual llvm::Constant *GetCppAtomicObjectFunction();
498 virtual llvm::Constant *GetGetStructFunction();
499 virtual llvm::Constant *EnumerationMutationFunction();
501 virtual void EmitTryStmt(CodeGenFunction &CGF,
502 const ObjCAtTryStmt &S);
503 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
504 const ObjCAtSynchronizedStmt &S);
505 virtual void EmitThrowStmt(CodeGenFunction &CGF,
506 const ObjCAtThrowStmt &S);
507 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
508 llvm::Value *AddrWeakObj);
509 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
510 llvm::Value *src, llvm::Value *dst);
511 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
512 llvm::Value *src, llvm::Value *dest,
513 bool threadlocal=false);
514 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
515 llvm::Value *src, llvm::Value *dest,
516 llvm::Value *ivarOffset);
517 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
518 llvm::Value *src, llvm::Value *dest);
519 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
520 llvm::Value *DestPtr,
523 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
525 llvm::Value *BaseValue,
526 const ObjCIvarDecl *Ivar,
527 unsigned CVRQualifiers);
528 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
529 const ObjCInterfaceDecl *Interface,
530 const ObjCIvarDecl *Ivar);
531 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
532 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
533 const CGBlockInfo &blockInfo) {
536 virtual llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
537 const CGBlockInfo &blockInfo) {
540 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
544 /// Class representing the legacy GCC Objective-C ABI. This is the default when
545 /// -fobjc-nonfragile-abi is not specified.
547 /// The GCC ABI target actually generates code that is approximately compatible
548 /// with the new GNUstep runtime ABI, but refrains from using any features that
549 /// would not work with the GCC runtime. For example, clang always generates
550 /// the extended form of the class structure, and the extra fields are simply
551 /// ignored by GCC libobjc.
552 class CGObjCGCC : public CGObjCGNU {
553 /// The GCC ABI message lookup function. Returns an IMP pointing to the
554 /// method implementation for this message.
555 LazyRuntimeFunction MsgLookupFn;
556 /// The GCC ABI superclass message lookup function. Takes a pointer to a
557 /// structure describing the receiver and the class, and a selector as
558 /// arguments. Returns the IMP for the corresponding method.
559 LazyRuntimeFunction MsgLookupSuperFn;
561 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
562 llvm::Value *&Receiver,
564 llvm::MDNode *node) {
565 CGBuilderTy &Builder = CGF.Builder;
566 llvm::Value *args[] = {
567 EnforceType(Builder, Receiver, IdTy),
568 EnforceType(Builder, cmd, SelectorTy) };
569 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
570 imp->setMetadata(msgSendMDKind, node);
571 return imp.getInstruction();
573 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
574 llvm::Value *ObjCSuper,
576 CGBuilderTy &Builder = CGF.Builder;
577 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
578 PtrToObjCSuperTy), cmd};
579 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
582 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
583 // IMP objc_msg_lookup(id, SEL);
584 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
585 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
586 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
587 PtrToObjCSuperTy, SelectorTy, NULL);
590 /// Class used when targeting the new GNUstep runtime ABI.
591 class CGObjCGNUstep : public CGObjCGNU {
592 /// The slot lookup function. Returns a pointer to a cacheable structure
593 /// that contains (among other things) the IMP.
594 LazyRuntimeFunction SlotLookupFn;
595 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
596 /// a structure describing the receiver and the class, and a selector as
597 /// arguments. Returns the slot for the corresponding method. Superclass
598 /// message lookup rarely changes, so this is a good caching opportunity.
599 LazyRuntimeFunction SlotLookupSuperFn;
600 /// Type of an slot structure pointer. This is returned by the various
601 /// lookup functions.
604 virtual llvm::Constant *GetEHType(QualType T);
606 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
607 llvm::Value *&Receiver,
609 llvm::MDNode *node) {
610 CGBuilderTy &Builder = CGF.Builder;
611 llvm::Function *LookupFn = SlotLookupFn;
613 // Store the receiver on the stack so that we can reload it later
614 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
615 Builder.CreateStore(Receiver, ReceiverPtr);
619 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
620 self = CGF.LoadObjCSelf();
622 self = llvm::ConstantPointerNull::get(IdTy);
625 // The lookup function is guaranteed not to capture the receiver pointer.
626 LookupFn->setDoesNotCapture(1);
628 llvm::Value *args[] = {
629 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
630 EnforceType(Builder, cmd, SelectorTy),
631 EnforceType(Builder, self, IdTy) };
632 llvm::CallSite slot = CGF.EmitCallOrInvoke(LookupFn, args);
633 slot.setOnlyReadsMemory();
634 slot->setMetadata(msgSendMDKind, node);
636 // Load the imp from the slot
638 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
640 // The lookup function may have changed the receiver, so make sure we use
642 Receiver = Builder.CreateLoad(ReceiverPtr, true);
645 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
646 llvm::Value *ObjCSuper,
648 CGBuilderTy &Builder = CGF.Builder;
649 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
651 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
652 slot->setOnlyReadsMemory();
654 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
657 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
658 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
659 PtrTy, PtrTy, IntTy, IMPTy, NULL);
660 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
661 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
662 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
663 SelectorTy, IdTy, NULL);
664 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
665 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
666 PtrToObjCSuperTy, SelectorTy, NULL);
667 // If we're in ObjC++ mode, then we want to make
668 if (CGM.getLangOpts().CPlusPlus) {
669 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
670 // void *__cxa_begin_catch(void *e)
671 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
672 // void __cxa_end_catch(void)
673 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
674 // void _Unwind_Resume_or_Rethrow(void*)
675 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
680 /// Support for the ObjFW runtime. Support here is due to
681 /// Jonathan Schleifer <js@webkeks.org>, the ObjFW maintainer.
682 class CGObjCObjFW: public CGObjCGNU {
684 /// The GCC ABI message lookup function. Returns an IMP pointing to the
685 /// method implementation for this message.
686 LazyRuntimeFunction MsgLookupFn;
687 /// The GCC ABI superclass message lookup function. Takes a pointer to a
688 /// structure describing the receiver and the class, and a selector as
689 /// arguments. Returns the IMP for the corresponding method.
690 LazyRuntimeFunction MsgLookupSuperFn;
692 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
693 llvm::Value *&Receiver,
695 llvm::MDNode *node) {
696 CGBuilderTy &Builder = CGF.Builder;
697 llvm::Value *args[] = {
698 EnforceType(Builder, Receiver, IdTy),
699 EnforceType(Builder, cmd, SelectorTy) };
700 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
701 imp->setMetadata(msgSendMDKind, node);
702 return imp.getInstruction();
705 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
706 llvm::Value *ObjCSuper,
708 CGBuilderTy &Builder = CGF.Builder;
709 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
710 PtrToObjCSuperTy), cmd};
711 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
714 virtual llvm::Value *GetClassNamed(CGBuilderTy &Builder,
715 const std::string &Name, bool isWeak) {
717 return CGObjCGNU::GetClassNamed(Builder, Name, isWeak);
721 std::string SymbolName = "_OBJC_CLASS_" + Name;
723 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
726 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
727 llvm::GlobalValue::ExternalLinkage,
734 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
735 // IMP objc_msg_lookup(id, SEL);
736 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
737 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
738 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
739 PtrToObjCSuperTy, SelectorTy, NULL);
742 } // end anonymous namespace
745 /// Emits a reference to a dummy variable which is emitted with each class.
746 /// This ensures that a linker error will be generated when trying to link
747 /// together modules where a referenced class is not defined.
748 void CGObjCGNU::EmitClassRef(const std::string &className) {
749 std::string symbolRef = "__objc_class_ref_" + className;
750 // Don't emit two copies of the same symbol
751 if (TheModule.getGlobalVariable(symbolRef))
753 std::string symbolName = "__objc_class_name_" + className;
754 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
756 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
757 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
759 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
760 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
763 static std::string SymbolNameForMethod(const StringRef &ClassName,
764 const StringRef &CategoryName, const Selector MethodName,
765 bool isClassMethod) {
766 std::string MethodNameColonStripped = MethodName.getAsString();
767 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
769 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
770 CategoryName + "_" + MethodNameColonStripped).str();
773 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
774 unsigned protocolClassVersion)
775 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
776 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
777 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
779 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
781 CodeGenTypes &Types = CGM.getTypes();
782 IntTy = cast<llvm::IntegerType>(
783 Types.ConvertType(CGM.getContext().IntTy));
784 LongTy = cast<llvm::IntegerType>(
785 Types.ConvertType(CGM.getContext().LongTy));
786 SizeTy = cast<llvm::IntegerType>(
787 Types.ConvertType(CGM.getContext().getSizeType()));
788 PtrDiffTy = cast<llvm::IntegerType>(
789 Types.ConvertType(CGM.getContext().getPointerDiffType()));
790 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
792 Int8Ty = llvm::Type::getInt8Ty(VMContext);
793 // C string type. Used in lots of places.
794 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
796 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
798 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
799 // Get the selector Type.
800 QualType selTy = CGM.getContext().getObjCSelType();
801 if (QualType() == selTy) {
802 SelectorTy = PtrToInt8Ty;
804 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
807 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
810 Int32Ty = llvm::Type::getInt32Ty(VMContext);
811 Int64Ty = llvm::Type::getInt64Ty(VMContext);
814 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
817 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
818 ASTIdTy = CanQualType();
819 if (UnqualIdTy != QualType()) {
820 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
821 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
825 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
827 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
828 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
830 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
832 // void objc_exception_throw(id);
833 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
834 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
835 // int objc_sync_enter(id);
836 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
837 // int objc_sync_exit(id);
838 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
840 // void objc_enumerationMutation (id)
841 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
844 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
845 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
846 PtrDiffTy, BoolTy, NULL);
847 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
848 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
849 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
850 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
851 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
852 PtrDiffTy, BoolTy, BoolTy, NULL);
853 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
854 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
855 PtrDiffTy, BoolTy, BoolTy, NULL);
858 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
859 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
862 const LangOptions &Opts = CGM.getLangOpts();
863 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
866 // Don't bother initialising the GC stuff unless we're compiling in GC mode
867 if (Opts.getGC() != LangOptions::NonGC) {
868 // This is a bit of an hack. We should sort this out by having a proper
869 // CGObjCGNUstep subclass for GC, but we may want to really support the old
870 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
871 // Get selectors needed in GC mode
872 RetainSel = GetNullarySelector("retain", CGM.getContext());
873 ReleaseSel = GetNullarySelector("release", CGM.getContext());
874 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
876 // Get functions needed in GC mode
878 // id objc_assign_ivar(id, id, ptrdiff_t);
879 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
881 // id objc_assign_strongCast (id, id*)
882 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
884 // id objc_assign_global(id, id*);
885 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
887 // id objc_assign_weak(id, id*);
888 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
889 // id objc_read_weak(id*);
890 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
891 // void *objc_memmove_collectable(void*, void *, size_t);
892 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
897 llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
898 const std::string &Name,
900 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
901 // With the incompatible ABI, this will need to be replaced with a direct
902 // reference to the class symbol. For the compatible nonfragile ABI we are
903 // still performing this lookup at run time but emitting the symbol for the
904 // class externally so that we can make the switch later.
906 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
907 // with memoized versions or with static references if it's safe to do so.
910 ClassName = Builder.CreateStructGEP(ClassName, 0);
912 llvm::Constant *ClassLookupFn =
913 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
914 "objc_lookup_class");
915 return Builder.CreateCall(ClassLookupFn, ClassName);
918 // This has to perform the lookup every time, since posing and related
919 // techniques can modify the name -> class mapping.
920 llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
921 const ObjCInterfaceDecl *OID) {
922 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
924 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
925 return GetClassNamed(Builder, "NSAutoreleasePool", false);
928 llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
929 const std::string &TypeEncoding, bool lval) {
931 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
932 llvm::GlobalAlias *SelValue = 0;
935 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
936 e = Types.end() ; i!=e ; i++) {
937 if (i->first == TypeEncoding) {
938 SelValue = i->second;
943 SelValue = new llvm::GlobalAlias(SelectorTy,
944 llvm::GlobalValue::PrivateLinkage,
945 ".objc_selector_"+Sel.getAsString(), NULL,
947 Types.push_back(TypedSelector(TypeEncoding, SelValue));
951 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
952 Builder.CreateStore(SelValue, tmp);
958 llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
960 return GetSelector(Builder, Sel, std::string(), lval);
963 llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
965 std::string SelTypes;
966 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
967 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
970 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
971 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
972 // With the old ABI, there was only one kind of catchall, which broke
973 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
974 // a pointer indicating object catchalls, and NULL to indicate real
976 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
977 return MakeConstantString("@id");
983 // All other types should be Objective-C interface pointer types.
984 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
985 assert(OPT && "Invalid @catch type.");
986 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
987 assert(IDecl && "Invalid @catch type.");
988 return MakeConstantString(IDecl->getIdentifier()->getName());
991 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
992 if (!CGM.getLangOpts().CPlusPlus)
993 return CGObjCGNU::GetEHType(T);
995 // For Objective-C++, we want to provide the ability to catch both C++ and
996 // Objective-C objects in the same function.
998 // There's a particular fixed type info for 'id'.
999 if (T->isObjCIdType() ||
1000 T->isObjCQualifiedIdType()) {
1001 llvm::Constant *IDEHType =
1002 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1005 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1007 llvm::GlobalValue::ExternalLinkage,
1008 0, "__objc_id_type_info");
1009 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1012 const ObjCObjectPointerType *PT =
1013 T->getAs<ObjCObjectPointerType>();
1014 assert(PT && "Invalid @catch type.");
1015 const ObjCInterfaceType *IT = PT->getInterfaceType();
1016 assert(IT && "Invalid @catch type.");
1017 std::string className = IT->getDecl()->getIdentifier()->getName();
1019 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1021 // Return the existing typeinfo if it exists
1022 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1024 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1026 // Otherwise create it.
1028 // vtable for gnustep::libobjc::__objc_class_type_info
1029 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1030 // platform's name mangling.
1031 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1032 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1034 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1035 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1037 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1038 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
1039 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1041 llvm::Constant *typeName =
1042 ExportUniqueString(className, "__objc_eh_typename_");
1044 std::vector<llvm::Constant*> fields;
1045 fields.push_back(Vtable);
1046 fields.push_back(typeName);
1047 llvm::Constant *TI =
1048 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1049 NULL), fields, "__objc_eh_typeinfo_" + className,
1050 llvm::GlobalValue::LinkOnceODRLinkage);
1051 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1054 /// Generate an NSConstantString object.
1055 llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1057 std::string Str = SL->getString().str();
1059 // Look for an existing one
1060 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1061 if (old != ObjCStrings.end())
1062 return old->getValue();
1064 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1066 if (StringClass.empty()) StringClass = "NXConstantString";
1068 std::string Sym = "_OBJC_CLASS_";
1071 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1074 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1075 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1076 else if (isa->getType() != PtrToIdTy)
1077 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1079 std::vector<llvm::Constant*> Ivars;
1080 Ivars.push_back(isa);
1081 Ivars.push_back(MakeConstantString(Str));
1082 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
1083 llvm::Constant *ObjCStr = MakeGlobal(
1084 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
1085 Ivars, ".objc_str");
1086 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1087 ObjCStrings[Str] = ObjCStr;
1088 ConstantStrings.push_back(ObjCStr);
1092 ///Generates a message send where the super is the receiver. This is a message
1093 ///send to self with special delivery semantics indicating which class's method
1094 ///should be called.
1096 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1097 ReturnValueSlot Return,
1098 QualType ResultType,
1100 const ObjCInterfaceDecl *Class,
1101 bool isCategoryImpl,
1102 llvm::Value *Receiver,
1103 bool IsClassMessage,
1104 const CallArgList &CallArgs,
1105 const ObjCMethodDecl *Method) {
1106 CGBuilderTy &Builder = CGF.Builder;
1107 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1108 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1109 return RValue::get(EnforceType(Builder, Receiver,
1110 CGM.getTypes().ConvertType(ResultType)));
1112 if (Sel == ReleaseSel) {
1113 return RValue::get(0);
1117 llvm::Value *cmd = GetSelector(Builder, Sel);
1120 CallArgList ActualArgs;
1122 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1123 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1124 ActualArgs.addFrom(CallArgs);
1126 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1128 llvm::Value *ReceiverClass = 0;
1129 if (isCategoryImpl) {
1130 llvm::Constant *classLookupFunction = 0;
1131 if (IsClassMessage) {
1132 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1133 IdTy, PtrTy, true), "objc_get_meta_class");
1135 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1136 IdTy, PtrTy, true), "objc_get_class");
1138 ReceiverClass = Builder.CreateCall(classLookupFunction,
1139 MakeConstantString(Class->getNameAsString()));
1141 // Set up global aliases for the metaclass or class pointer if they do not
1142 // already exist. These will are forward-references which will be set to
1143 // pointers to the class and metaclass structure created for the runtime
1144 // load function. To send a message to super, we look up the value of the
1145 // super_class pointer from either the class or metaclass structure.
1146 if (IsClassMessage) {
1147 if (!MetaClassPtrAlias) {
1148 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1149 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1150 Class->getNameAsString(), NULL, &TheModule);
1152 ReceiverClass = MetaClassPtrAlias;
1154 if (!ClassPtrAlias) {
1155 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1156 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1157 Class->getNameAsString(), NULL, &TheModule);
1159 ReceiverClass = ClassPtrAlias;
1162 // Cast the pointer to a simplified version of the class structure
1163 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1164 llvm::PointerType::getUnqual(
1165 llvm::StructType::get(IdTy, IdTy, NULL)));
1166 // Get the superclass pointer
1167 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
1168 // Load the superclass pointer
1169 ReceiverClass = Builder.CreateLoad(ReceiverClass);
1170 // Construct the structure used to look up the IMP
1171 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1172 Receiver->getType(), IdTy, NULL);
1173 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
1175 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1176 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
1178 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1181 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1182 imp = EnforceType(Builder, imp, MSI.MessengerType);
1184 llvm::Value *impMD[] = {
1185 llvm::MDString::get(VMContext, Sel.getAsString()),
1186 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1187 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1189 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1191 llvm::Instruction *call;
1192 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1193 call->setMetadata(msgSendMDKind, node);
1197 /// Generate code for a message send expression.
1199 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1200 ReturnValueSlot Return,
1201 QualType ResultType,
1203 llvm::Value *Receiver,
1204 const CallArgList &CallArgs,
1205 const ObjCInterfaceDecl *Class,
1206 const ObjCMethodDecl *Method) {
1207 CGBuilderTy &Builder = CGF.Builder;
1209 // Strip out message sends to retain / release in GC mode
1210 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1211 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1212 return RValue::get(EnforceType(Builder, Receiver,
1213 CGM.getTypes().ConvertType(ResultType)));
1215 if (Sel == ReleaseSel) {
1216 return RValue::get(0);
1220 // If the return type is something that goes in an integer register, the
1221 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1224 // The language spec says the result of this kind of message send is
1225 // undefined, but lots of people seem to have forgotten to read that
1226 // paragraph and insist on sending messages to nil that have structure
1227 // returns. With GCC, this generates a random return value (whatever happens
1228 // to be on the stack / in those registers at the time) on most platforms,
1229 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1231 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1232 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1234 llvm::BasicBlock *startBB = 0;
1235 llvm::BasicBlock *messageBB = 0;
1236 llvm::BasicBlock *continueBB = 0;
1238 if (!isPointerSizedReturn) {
1239 startBB = Builder.GetInsertBlock();
1240 messageBB = CGF.createBasicBlock("msgSend");
1241 continueBB = CGF.createBasicBlock("continue");
1243 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1244 llvm::Constant::getNullValue(Receiver->getType()));
1245 Builder.CreateCondBr(isNil, continueBB, messageBB);
1246 CGF.EmitBlock(messageBB);
1249 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1252 cmd = GetSelector(Builder, Method);
1254 cmd = GetSelector(Builder, Sel);
1255 cmd = EnforceType(Builder, cmd, SelectorTy);
1256 Receiver = EnforceType(Builder, Receiver, IdTy);
1258 llvm::Value *impMD[] = {
1259 llvm::MDString::get(VMContext, Sel.getAsString()),
1260 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1261 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1263 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1265 CallArgList ActualArgs;
1266 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1267 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1268 ActualArgs.addFrom(CallArgs);
1270 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1272 // Get the IMP to call
1275 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1276 // functions. These are not supported on all platforms (or all runtimes on a
1277 // given platform), so we
1278 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1279 case CodeGenOptions::Legacy:
1280 imp = LookupIMP(CGF, Receiver, cmd, node);
1282 case CodeGenOptions::Mixed:
1283 case CodeGenOptions::NonLegacy:
1284 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1285 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1286 "objc_msgSend_fpret");
1287 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1288 // The actual types here don't matter - we're going to bitcast the
1290 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1291 "objc_msgSend_stret");
1293 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1298 // Reset the receiver in case the lookup modified it
1299 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1301 imp = EnforceType(Builder, imp, MSI.MessengerType);
1303 llvm::Instruction *call;
1304 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
1306 call->setMetadata(msgSendMDKind, node);
1309 if (!isPointerSizedReturn) {
1310 messageBB = CGF.Builder.GetInsertBlock();
1311 CGF.Builder.CreateBr(continueBB);
1312 CGF.EmitBlock(continueBB);
1313 if (msgRet.isScalar()) {
1314 llvm::Value *v = msgRet.getScalarVal();
1315 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1316 phi->addIncoming(v, messageBB);
1317 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1318 msgRet = RValue::get(phi);
1319 } else if (msgRet.isAggregate()) {
1320 llvm::Value *v = msgRet.getAggregateAddr();
1321 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1322 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
1323 llvm::AllocaInst *NullVal =
1324 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
1325 CGF.InitTempAlloca(NullVal,
1326 llvm::Constant::getNullValue(RetTy->getElementType()));
1327 phi->addIncoming(v, messageBB);
1328 phi->addIncoming(NullVal, startBB);
1329 msgRet = RValue::getAggregate(phi);
1330 } else /* isComplex() */ {
1331 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1332 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1333 phi->addIncoming(v.first, messageBB);
1334 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1336 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1337 phi2->addIncoming(v.second, messageBB);
1338 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1340 msgRet = RValue::getComplex(phi, phi2);
1346 /// Generates a MethodList. Used in construction of a objc_class and
1347 /// objc_category structures.
1348 llvm::Constant *CGObjCGNU::
1349 GenerateMethodList(const StringRef &ClassName,
1350 const StringRef &CategoryName,
1351 ArrayRef<Selector> MethodSels,
1352 ArrayRef<llvm::Constant *> MethodTypes,
1353 bool isClassMethodList) {
1354 if (MethodSels.empty())
1356 // Get the method structure type.
1357 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1358 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1359 PtrToInt8Ty, // Method types
1360 IMPTy, //Method pointer
1362 std::vector<llvm::Constant*> Methods;
1363 std::vector<llvm::Constant*> Elements;
1364 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1366 llvm::Constant *Method =
1367 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1369 isClassMethodList));
1370 assert(Method && "Can't generate metadata for method that doesn't exist");
1371 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1372 Elements.push_back(C);
1373 Elements.push_back(MethodTypes[i]);
1374 Method = llvm::ConstantExpr::getBitCast(Method,
1376 Elements.push_back(Method);
1377 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
1380 // Array of method structures
1381 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1383 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1386 // Structure containing list pointer, array and array count
1387 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
1388 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1389 ObjCMethodListTy->setBody(
1396 Methods.push_back(llvm::ConstantPointerNull::get(
1397 llvm::PointerType::getUnqual(ObjCMethodListTy)));
1398 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
1399 Methods.push_back(MethodArray);
1401 // Create an instance of the structure
1402 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1405 /// Generates an IvarList. Used in construction of a objc_class.
1406 llvm::Constant *CGObjCGNU::
1407 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1408 ArrayRef<llvm::Constant *> IvarTypes,
1409 ArrayRef<llvm::Constant *> IvarOffsets) {
1410 if (IvarNames.size() == 0)
1412 // Get the method structure type.
1413 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1418 std::vector<llvm::Constant*> Ivars;
1419 std::vector<llvm::Constant*> Elements;
1420 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1422 Elements.push_back(IvarNames[i]);
1423 Elements.push_back(IvarTypes[i]);
1424 Elements.push_back(IvarOffsets[i]);
1425 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
1428 // Array of method structures
1429 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1434 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
1435 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
1436 // Structure containing array and array count
1437 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1441 // Create an instance of the structure
1442 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1445 /// Generate a class structure
1446 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1447 llvm::Constant *MetaClass,
1448 llvm::Constant *SuperClass,
1451 llvm::Constant *Version,
1452 llvm::Constant *InstanceSize,
1453 llvm::Constant *IVars,
1454 llvm::Constant *Methods,
1455 llvm::Constant *Protocols,
1456 llvm::Constant *IvarOffsets,
1457 llvm::Constant *Properties,
1458 llvm::Constant *StrongIvarBitmap,
1459 llvm::Constant *WeakIvarBitmap,
1461 // Set up the class structure
1462 // Note: Several of these are char*s when they should be ids. This is
1463 // because the runtime performs this translation on load.
1465 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1466 // anyway; the classes will still work with the GNU runtime, they will just
1468 llvm::StructType *ClassTy = llvm::StructType::get(
1470 PtrToInt8Ty, // super_class
1471 PtrToInt8Ty, // name
1474 LongTy, // instance_size
1475 IVars->getType(), // ivars
1476 Methods->getType(), // methods
1477 // These are all filled in by the runtime, so we pretend
1479 PtrTy, // subclass_list
1480 PtrTy, // sibling_class
1482 PtrTy, // gc_object_type
1484 LongTy, // abi_version
1485 IvarOffsets->getType(), // ivar_offsets
1486 Properties->getType(), // properties
1487 IntPtrTy, // strong_pointers
1488 IntPtrTy, // weak_pointers
1490 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1491 // Fill in the structure
1492 std::vector<llvm::Constant*> Elements;
1493 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1494 Elements.push_back(SuperClass);
1495 Elements.push_back(MakeConstantString(Name, ".class_name"));
1496 Elements.push_back(Zero);
1497 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1499 llvm::DataLayout td(&TheModule);
1501 llvm::ConstantInt::get(LongTy,
1502 td.getTypeSizeInBits(ClassTy) /
1503 CGM.getContext().getCharWidth()));
1505 Elements.push_back(InstanceSize);
1506 Elements.push_back(IVars);
1507 Elements.push_back(Methods);
1508 Elements.push_back(NULLPtr);
1509 Elements.push_back(NULLPtr);
1510 Elements.push_back(NULLPtr);
1511 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1512 Elements.push_back(NULLPtr);
1513 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
1514 Elements.push_back(IvarOffsets);
1515 Elements.push_back(Properties);
1516 Elements.push_back(StrongIvarBitmap);
1517 Elements.push_back(WeakIvarBitmap);
1518 // Create an instance of the structure
1519 // This is now an externally visible symbol, so that we can speed up class
1520 // messages in the next ABI. We may already have some weak references to
1521 // this, so check and fix them properly.
1522 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1524 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1525 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1526 llvm::GlobalValue::ExternalLinkage);
1528 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1529 ClassRef->getType()));
1530 ClassRef->removeFromParent();
1531 Class->setName(ClassSym);
1536 llvm::Constant *CGObjCGNU::
1537 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1538 ArrayRef<llvm::Constant *> MethodTypes) {
1539 // Get the method structure type.
1540 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1541 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1544 std::vector<llvm::Constant*> Methods;
1545 std::vector<llvm::Constant*> Elements;
1546 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1548 Elements.push_back(MethodNames[i]);
1549 Elements.push_back(MethodTypes[i]);
1550 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
1552 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1553 MethodNames.size());
1554 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1556 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1557 IntTy, ObjCMethodArrayTy, NULL);
1559 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1560 Methods.push_back(Array);
1561 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1564 // Create the protocol list structure used in classes, categories and so on
1565 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
1566 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1568 llvm::StructType *ProtocolListTy = llvm::StructType::get(
1569 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1573 std::vector<llvm::Constant*> Elements;
1574 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1575 iter != endIter ; iter++) {
1576 llvm::Constant *protocol = 0;
1577 llvm::StringMap<llvm::Constant*>::iterator value =
1578 ExistingProtocols.find(*iter);
1579 if (value == ExistingProtocols.end()) {
1580 protocol = GenerateEmptyProtocol(*iter);
1582 protocol = value->getValue();
1584 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1586 Elements.push_back(Ptr);
1588 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1591 Elements.push_back(NULLPtr);
1592 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1593 Elements.push_back(ProtocolArray);
1594 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1597 llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
1598 const ObjCProtocolDecl *PD) {
1599 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1601 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1602 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1605 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1606 const std::string &ProtocolName) {
1607 SmallVector<std::string, 0> EmptyStringVector;
1608 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1610 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1611 llvm::Constant *MethodList =
1612 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1613 // Protocols are objects containing lists of the methods implemented and
1614 // protocols adopted.
1615 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1617 ProtocolList->getType(),
1618 MethodList->getType(),
1619 MethodList->getType(),
1620 MethodList->getType(),
1621 MethodList->getType(),
1623 std::vector<llvm::Constant*> Elements;
1624 // The isa pointer must be set to a magic number so the runtime knows it's
1625 // the correct layout.
1626 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1627 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1628 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1629 Elements.push_back(ProtocolList);
1630 Elements.push_back(MethodList);
1631 Elements.push_back(MethodList);
1632 Elements.push_back(MethodList);
1633 Elements.push_back(MethodList);
1634 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1637 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1638 ASTContext &Context = CGM.getContext();
1639 std::string ProtocolName = PD->getNameAsString();
1641 // Use the protocol definition, if there is one.
1642 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1645 SmallVector<std::string, 16> Protocols;
1646 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1647 E = PD->protocol_end(); PI != E; ++PI)
1648 Protocols.push_back((*PI)->getNameAsString());
1649 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1650 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1651 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1652 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1653 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1654 E = PD->instmeth_end(); iter != E; iter++) {
1655 std::string TypeStr;
1656 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
1657 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1658 OptionalInstanceMethodNames.push_back(
1659 MakeConstantString((*iter)->getSelector().getAsString()));
1660 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1662 InstanceMethodNames.push_back(
1663 MakeConstantString((*iter)->getSelector().getAsString()));
1664 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1667 // Collect information about class methods:
1668 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1669 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1670 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1671 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1672 for (ObjCProtocolDecl::classmeth_iterator
1673 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1674 iter != endIter ; iter++) {
1675 std::string TypeStr;
1676 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1677 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1678 OptionalClassMethodNames.push_back(
1679 MakeConstantString((*iter)->getSelector().getAsString()));
1680 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1682 ClassMethodNames.push_back(
1683 MakeConstantString((*iter)->getSelector().getAsString()));
1684 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1688 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1689 llvm::Constant *InstanceMethodList =
1690 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1691 llvm::Constant *ClassMethodList =
1692 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1693 llvm::Constant *OptionalInstanceMethodList =
1694 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1695 OptionalInstanceMethodTypes);
1696 llvm::Constant *OptionalClassMethodList =
1697 GenerateProtocolMethodList(OptionalClassMethodNames,
1698 OptionalClassMethodTypes);
1700 // Property metadata: name, attributes, isSynthesized, setter name, setter
1701 // types, getter name, getter types.
1702 // The isSynthesized value is always set to 0 in a protocol. It exists to
1703 // simplify the runtime library by allowing it to use the same data
1704 // structures for protocol metadata everywhere.
1705 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1706 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1708 std::vector<llvm::Constant*> Properties;
1709 std::vector<llvm::Constant*> OptionalProperties;
1711 // Add all of the property methods need adding to the method list and to the
1712 // property metadata list.
1713 for (ObjCContainerDecl::prop_iterator
1714 iter = PD->prop_begin(), endIter = PD->prop_end();
1715 iter != endIter ; iter++) {
1716 std::vector<llvm::Constant*> Fields;
1717 ObjCPropertyDecl *property = *iter;
1720 Fields.push_back(MakePropertyEncodingString(property, PD));
1722 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1723 property->getPropertyAttributes()));
1724 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1725 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1726 std::string TypeStr;
1727 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1728 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1729 InstanceMethodTypes.push_back(TypeEncoding);
1730 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1731 Fields.push_back(TypeEncoding);
1733 Fields.push_back(NULLPtr);
1734 Fields.push_back(NULLPtr);
1736 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1737 std::string TypeStr;
1738 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1739 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1740 InstanceMethodTypes.push_back(TypeEncoding);
1741 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1742 Fields.push_back(TypeEncoding);
1744 Fields.push_back(NULLPtr);
1745 Fields.push_back(NULLPtr);
1747 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1748 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1750 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1753 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1754 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1755 llvm::Constant* PropertyListInitFields[] =
1756 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1758 llvm::Constant *PropertyListInit =
1759 llvm::ConstantStruct::getAnon(PropertyListInitFields);
1760 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1761 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1762 PropertyListInit, ".objc_property_list");
1764 llvm::Constant *OptionalPropertyArray =
1765 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1766 OptionalProperties.size()) , OptionalProperties);
1767 llvm::Constant* OptionalPropertyListInitFields[] = {
1768 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1769 OptionalPropertyArray };
1771 llvm::Constant *OptionalPropertyListInit =
1772 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1773 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1774 OptionalPropertyListInit->getType(), false,
1775 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1776 ".objc_property_list");
1778 // Protocols are objects containing lists of the methods implemented and
1779 // protocols adopted.
1780 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1782 ProtocolList->getType(),
1783 InstanceMethodList->getType(),
1784 ClassMethodList->getType(),
1785 OptionalInstanceMethodList->getType(),
1786 OptionalClassMethodList->getType(),
1787 PropertyList->getType(),
1788 OptionalPropertyList->getType(),
1790 std::vector<llvm::Constant*> Elements;
1791 // The isa pointer must be set to a magic number so the runtime knows it's
1792 // the correct layout.
1793 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1794 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1795 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1796 Elements.push_back(ProtocolList);
1797 Elements.push_back(InstanceMethodList);
1798 Elements.push_back(ClassMethodList);
1799 Elements.push_back(OptionalInstanceMethodList);
1800 Elements.push_back(OptionalClassMethodList);
1801 Elements.push_back(PropertyList);
1802 Elements.push_back(OptionalPropertyList);
1803 ExistingProtocols[ProtocolName] =
1804 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1805 ".objc_protocol"), IdTy);
1807 void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1808 // Collect information about instance methods
1809 SmallVector<Selector, 1> MethodSels;
1810 SmallVector<llvm::Constant*, 1> MethodTypes;
1812 std::vector<llvm::Constant*> Elements;
1813 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1814 const std::string CategoryName = "AnotherHack";
1815 Elements.push_back(MakeConstantString(CategoryName));
1816 Elements.push_back(MakeConstantString(ClassName));
1817 // Instance method list
1818 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1819 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1820 // Class method list
1821 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1822 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1824 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1825 ExistingProtocols.size());
1826 llvm::StructType *ProtocolListTy = llvm::StructType::get(
1827 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1831 std::vector<llvm::Constant*> ProtocolElements;
1832 for (llvm::StringMapIterator<llvm::Constant*> iter =
1833 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1834 iter != endIter ; iter++) {
1835 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1837 ProtocolElements.push_back(Ptr);
1839 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1841 ProtocolElements.clear();
1842 ProtocolElements.push_back(NULLPtr);
1843 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1844 ExistingProtocols.size()));
1845 ProtocolElements.push_back(ProtocolArray);
1846 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1847 ProtocolElements, ".objc_protocol_list"), PtrTy));
1848 Categories.push_back(llvm::ConstantExpr::getBitCast(
1849 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1850 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1853 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1854 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1855 /// bits set to their values, LSB first, while larger ones are stored in a
1856 /// structure of this / form:
1858 /// struct { int32_t length; int32_t values[length]; };
1860 /// The values in the array are stored in host-endian format, with the least
1861 /// significant bit being assumed to come first in the bitfield. Therefore, a
1862 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1863 /// bitfield / with the 63rd bit set will be 1<<64.
1864 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1865 int bitCount = bits.size();
1867 (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
1868 if (bitCount < ptrBits) {
1870 for (int i=0 ; i<bitCount ; ++i) {
1871 if (bits[i]) val |= 1ULL<<(i+1);
1873 return llvm::ConstantInt::get(IntPtrTy, val);
1875 llvm::SmallVector<llvm::Constant*, 8> values;
1877 while (v < bitCount) {
1879 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1880 if (bits[v]) word |= 1<<i;
1883 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1885 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1886 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1887 llvm::Constant *fields[2] = {
1888 llvm::ConstantInt::get(Int32Ty, values.size()),
1890 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1892 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
1896 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1897 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1898 std::string CategoryName = OCD->getNameAsString();
1899 // Collect information about instance methods
1900 SmallVector<Selector, 16> InstanceMethodSels;
1901 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1902 for (ObjCCategoryImplDecl::instmeth_iterator
1903 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
1904 iter != endIter ; iter++) {
1905 InstanceMethodSels.push_back((*iter)->getSelector());
1906 std::string TypeStr;
1907 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
1908 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1911 // Collect information about class methods
1912 SmallVector<Selector, 16> ClassMethodSels;
1913 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1914 for (ObjCCategoryImplDecl::classmeth_iterator
1915 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
1916 iter != endIter ; iter++) {
1917 ClassMethodSels.push_back((*iter)->getSelector());
1918 std::string TypeStr;
1919 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
1920 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1923 // Collect the names of referenced protocols
1924 SmallVector<std::string, 16> Protocols;
1925 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1926 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
1927 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1928 E = Protos.end(); I != E; ++I)
1929 Protocols.push_back((*I)->getNameAsString());
1931 std::vector<llvm::Constant*> Elements;
1932 Elements.push_back(MakeConstantString(CategoryName));
1933 Elements.push_back(MakeConstantString(ClassName));
1934 // Instance method list
1935 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1936 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
1938 // Class method list
1939 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1940 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
1943 Elements.push_back(llvm::ConstantExpr::getBitCast(
1944 GenerateProtocolList(Protocols), PtrTy));
1945 Categories.push_back(llvm::ConstantExpr::getBitCast(
1946 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1947 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1950 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1951 SmallVectorImpl<Selector> &InstanceMethodSels,
1952 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1953 ASTContext &Context = CGM.getContext();
1955 // Property metadata: name, attributes, isSynthesized, setter name, setter
1956 // types, getter name, getter types.
1957 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1958 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1960 std::vector<llvm::Constant*> Properties;
1963 // Add all of the property methods need adding to the method list and to the
1964 // property metadata list.
1965 for (ObjCImplDecl::propimpl_iterator
1966 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1967 iter != endIter ; iter++) {
1968 std::vector<llvm::Constant*> Fields;
1969 ObjCPropertyDecl *property = iter->getPropertyDecl();
1970 ObjCPropertyImplDecl *propertyImpl = *iter;
1971 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1972 ObjCPropertyImplDecl::Synthesize);
1974 Fields.push_back(MakePropertyEncodingString(property, OID));
1975 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1976 property->getPropertyAttributes()));
1977 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
1978 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1979 std::string TypeStr;
1980 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1981 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1982 if (isSynthesized) {
1983 InstanceMethodTypes.push_back(TypeEncoding);
1984 InstanceMethodSels.push_back(getter->getSelector());
1986 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1987 Fields.push_back(TypeEncoding);
1989 Fields.push_back(NULLPtr);
1990 Fields.push_back(NULLPtr);
1992 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1993 std::string TypeStr;
1994 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1995 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1996 if (isSynthesized) {
1997 InstanceMethodTypes.push_back(TypeEncoding);
1998 InstanceMethodSels.push_back(setter->getSelector());
2000 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2001 Fields.push_back(TypeEncoding);
2003 Fields.push_back(NULLPtr);
2004 Fields.push_back(NULLPtr);
2006 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2008 llvm::ArrayType *PropertyArrayTy =
2009 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2010 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2012 llvm::Constant* PropertyListInitFields[] =
2013 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2015 llvm::Constant *PropertyListInit =
2016 llvm::ConstantStruct::getAnon(PropertyListInitFields);
2017 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2018 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2019 ".objc_property_list");
2022 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2023 // Get the class declaration for which the alias is specified.
2024 ObjCInterfaceDecl *ClassDecl =
2025 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2026 std::string ClassName = ClassDecl->getNameAsString();
2027 std::string AliasName = OAD->getNameAsString();
2028 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2031 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2032 ASTContext &Context = CGM.getContext();
2034 // Get the superclass name.
2035 const ObjCInterfaceDecl * SuperClassDecl =
2036 OID->getClassInterface()->getSuperClass();
2037 std::string SuperClassName;
2038 if (SuperClassDecl) {
2039 SuperClassName = SuperClassDecl->getNameAsString();
2040 EmitClassRef(SuperClassName);
2043 // Get the class name
2044 ObjCInterfaceDecl *ClassDecl =
2045 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2046 std::string ClassName = ClassDecl->getNameAsString();
2047 // Emit the symbol that is used to generate linker errors if this class is
2048 // referenced in other modules but not declared.
2049 std::string classSymbolName = "__objc_class_name_" + ClassName;
2050 if (llvm::GlobalVariable *symbol =
2051 TheModule.getGlobalVariable(classSymbolName)) {
2052 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2054 new llvm::GlobalVariable(TheModule, LongTy, false,
2055 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
2059 // Get the size of instances.
2061 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2063 // Collect information about instance variables.
2064 SmallVector<llvm::Constant*, 16> IvarNames;
2065 SmallVector<llvm::Constant*, 16> IvarTypes;
2066 SmallVector<llvm::Constant*, 16> IvarOffsets;
2068 std::vector<llvm::Constant*> IvarOffsetValues;
2069 SmallVector<bool, 16> WeakIvars;
2070 SmallVector<bool, 16> StrongIvars;
2072 int superInstanceSize = !SuperClassDecl ? 0 :
2073 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2074 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2075 // class}. The runtime will then set this to the correct value on load.
2076 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2077 instanceSize = 0 - (instanceSize - superInstanceSize);
2080 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2081 IVD = IVD->getNextIvar()) {
2083 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2084 // Get the type encoding for this ivar
2085 std::string TypeStr;
2086 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2087 IvarTypes.push_back(MakeConstantString(TypeStr));
2089 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2090 uint64_t Offset = BaseOffset;
2091 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2092 Offset = BaseOffset - superInstanceSize;
2094 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2095 // Create the direct offset value
2096 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2097 IVD->getNameAsString();
2098 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2100 OffsetVar->setInitializer(OffsetValue);
2101 // If this is the real definition, change its linkage type so that
2102 // different modules will use this one, rather than their private
2104 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2106 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2107 false, llvm::GlobalValue::ExternalLinkage,
2109 "__objc_ivar_offset_value_" + ClassName +"." +
2110 IVD->getNameAsString());
2111 IvarOffsets.push_back(OffsetValue);
2112 IvarOffsetValues.push_back(OffsetVar);
2113 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2115 case Qualifiers::OCL_Strong:
2116 StrongIvars.push_back(true);
2117 WeakIvars.push_back(false);
2119 case Qualifiers::OCL_Weak:
2120 StrongIvars.push_back(false);
2121 WeakIvars.push_back(true);
2124 StrongIvars.push_back(false);
2125 WeakIvars.push_back(false);
2128 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2129 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2130 llvm::GlobalVariable *IvarOffsetArray =
2131 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2134 // Collect information about instance methods
2135 SmallVector<Selector, 16> InstanceMethodSels;
2136 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2137 for (ObjCImplementationDecl::instmeth_iterator
2138 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
2139 iter != endIter ; iter++) {
2140 InstanceMethodSels.push_back((*iter)->getSelector());
2141 std::string TypeStr;
2142 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
2143 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2146 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2147 InstanceMethodTypes);
2150 // Collect information about class methods
2151 SmallVector<Selector, 16> ClassMethodSels;
2152 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2153 for (ObjCImplementationDecl::classmeth_iterator
2154 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
2155 iter != endIter ; iter++) {
2156 ClassMethodSels.push_back((*iter)->getSelector());
2157 std::string TypeStr;
2158 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
2159 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2161 // Collect the names of referenced protocols
2162 SmallVector<std::string, 16> Protocols;
2163 for (ObjCInterfaceDecl::protocol_iterator
2164 I = ClassDecl->protocol_begin(),
2165 E = ClassDecl->protocol_end(); I != E; ++I)
2166 Protocols.push_back((*I)->getNameAsString());
2170 // Get the superclass pointer.
2171 llvm::Constant *SuperClass;
2172 if (!SuperClassName.empty()) {
2173 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2175 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2177 // Empty vector used to construct empty method lists
2178 SmallVector<llvm::Constant*, 1> empty;
2179 // Generate the method and instance variable lists
2180 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2181 InstanceMethodSels, InstanceMethodTypes, false);
2182 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2183 ClassMethodSels, ClassMethodTypes, true);
2184 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2186 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2187 // we emit a symbol containing the offset for each ivar in the class. This
2188 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2189 // for the legacy ABI, without causing problems. The converse is also
2190 // possible, but causes all ivar accesses to be fragile.
2192 // Offset pointer for getting at the correct field in the ivar list when
2193 // setting up the alias. These are: The base address for the global, the
2194 // ivar array (second field), the ivar in this list (set for each ivar), and
2195 // the offset (third field in ivar structure)
2196 llvm::Type *IndexTy = Int32Ty;
2197 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2198 llvm::ConstantInt::get(IndexTy, 1), 0,
2199 llvm::ConstantInt::get(IndexTy, 2) };
2201 unsigned ivarIndex = 0;
2202 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2203 IVD = IVD->getNextIvar()) {
2204 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2205 + IVD->getNameAsString();
2206 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2207 // Get the correct ivar field
2208 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2209 IvarList, offsetPointerIndexes);
2210 // Get the existing variable, if one exists.
2211 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2213 offset->setInitializer(offsetValue);
2214 // If this is the real definition, change its linkage type so that
2215 // different modules will use this one, rather than their private
2217 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2219 // Add a new alias if there isn't one already.
2220 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2221 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2222 (void) offset; // Silence dead store warning.
2226 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2227 //Generate metaclass for class methods
2228 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
2229 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
2230 empty, empty, empty), ClassMethodList, NULLPtr,
2231 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
2233 // Generate the class structure
2234 llvm::Constant *ClassStruct =
2235 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
2236 ClassName.c_str(), 0,
2237 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
2238 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2239 Properties, StrongIvarBitmap, WeakIvarBitmap);
2241 // Resolve the class aliases, if they exist.
2242 if (ClassPtrAlias) {
2243 ClassPtrAlias->replaceAllUsesWith(
2244 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2245 ClassPtrAlias->eraseFromParent();
2248 if (MetaClassPtrAlias) {
2249 MetaClassPtrAlias->replaceAllUsesWith(
2250 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2251 MetaClassPtrAlias->eraseFromParent();
2252 MetaClassPtrAlias = 0;
2255 // Add class structure to list to be added to the symtab later
2256 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2257 Classes.push_back(ClassStruct);
2261 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2262 // Only emit an ObjC load function if no Objective-C stuff has been called
2263 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2264 ExistingProtocols.empty() && SelectorTable.empty())
2267 // Add all referenced protocols to a category.
2268 GenerateProtocolHolderCategory();
2270 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2271 SelectorTy->getElementType());
2272 llvm::Type *SelStructPtrTy = SelectorTy;
2273 if (SelStructTy == 0) {
2274 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
2275 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2278 std::vector<llvm::Constant*> Elements;
2279 llvm::Constant *Statics = NULLPtr;
2280 // Generate statics list:
2281 if (ConstantStrings.size()) {
2282 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2283 ConstantStrings.size() + 1);
2284 ConstantStrings.push_back(NULLPtr);
2286 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2288 if (StringClass.empty()) StringClass = "NXConstantString";
2290 Elements.push_back(MakeConstantString(StringClass,
2291 ".objc_static_class_name"));
2292 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2294 llvm::StructType *StaticsListTy =
2295 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
2296 llvm::Type *StaticsListPtrTy =
2297 llvm::PointerType::getUnqual(StaticsListTy);
2298 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
2299 llvm::ArrayType *StaticsListArrayTy =
2300 llvm::ArrayType::get(StaticsListPtrTy, 2);
2302 Elements.push_back(Statics);
2303 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2304 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
2305 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2307 // Array of classes, categories, and constant objects
2308 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2309 Classes.size() + Categories.size() + 2);
2310 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2311 llvm::Type::getInt16Ty(VMContext),
2312 llvm::Type::getInt16Ty(VMContext),
2316 // Pointer to an array of selectors used in this module.
2317 std::vector<llvm::Constant*> Selectors;
2318 std::vector<llvm::GlobalAlias*> SelectorAliases;
2319 for (SelectorMap::iterator iter = SelectorTable.begin(),
2320 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2322 std::string SelNameStr = iter->first.getAsString();
2323 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2325 SmallVectorImpl<TypedSelector> &Types = iter->second;
2326 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2327 e = Types.end() ; i!=e ; i++) {
2329 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2330 if (!i->first.empty())
2331 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2333 Elements.push_back(SelName);
2334 Elements.push_back(SelectorTypeEncoding);
2335 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2338 // Store the selector alias for later replacement
2339 SelectorAliases.push_back(i->second);
2342 unsigned SelectorCount = Selectors.size();
2343 // NULL-terminate the selector list. This should not actually be required,
2344 // because the selector list has a length field. Unfortunately, the GCC
2345 // runtime decides to ignore the length field and expects a NULL terminator,
2346 // and GCC cooperates with this by always setting the length to 0.
2347 Elements.push_back(NULLPtr);
2348 Elements.push_back(NULLPtr);
2349 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2352 // Number of static selectors
2353 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2354 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
2355 ".objc_selector_list");
2356 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2359 // Now that all of the static selectors exist, create pointers to them.
2360 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2362 llvm::Constant *Idxs[] = {Zeros[0],
2363 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
2364 // FIXME: We're generating redundant loads and stores here!
2365 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2366 makeArrayRef(Idxs, 2));
2367 // If selectors are defined as an opaque type, cast the pointer to this
2369 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2370 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2371 SelectorAliases[i]->eraseFromParent();
2374 // Number of classes defined.
2375 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2377 // Number of categories defined
2378 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2379 Categories.size()));
2380 // Create an array of classes, then categories, then static object instances
2381 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2382 // NULL-terminated list of static object instances (mainly constant strings)
2383 Classes.push_back(Statics);
2384 Classes.push_back(NULLPtr);
2385 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2386 Elements.push_back(ClassList);
2387 // Construct the symbol table
2388 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2390 // The symbol table is contained in a module which has some version-checking
2392 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2393 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2394 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
2396 // Runtime version, used for ABI compatibility checking.
2397 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2399 llvm::DataLayout td(&TheModule);
2401 llvm::ConstantInt::get(LongTy,
2402 td.getTypeSizeInBits(ModuleTy) /
2403 CGM.getContext().getCharWidth()));
2405 // The path to the source file where this module was declared
2406 SourceManager &SM = CGM.getContext().getSourceManager();
2407 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2409 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2410 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2411 Elements.push_back(SymTab);
2413 if (RuntimeVersion >= 10)
2414 switch (CGM.getLangOpts().getGC()) {
2415 case LangOptions::GCOnly:
2416 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2418 case LangOptions::NonGC:
2419 if (CGM.getLangOpts().ObjCAutoRefCount)
2420 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2422 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2424 case LangOptions::HybridGC:
2425 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2429 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2431 // Create the load function calling the runtime entry point with the module
2433 llvm::Function * LoadFunction = llvm::Function::Create(
2434 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2435 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2437 llvm::BasicBlock *EntryBB =
2438 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2439 CGBuilderTy Builder(VMContext);
2440 Builder.SetInsertPoint(EntryBB);
2442 llvm::FunctionType *FT =
2443 llvm::FunctionType::get(Builder.getVoidTy(),
2444 llvm::PointerType::getUnqual(ModuleTy), true);
2445 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2446 Builder.CreateCall(Register, Module);
2448 if (!ClassAliases.empty()) {
2449 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2450 llvm::FunctionType *RegisterAliasTy =
2451 llvm::FunctionType::get(Builder.getVoidTy(),
2453 llvm::Function *RegisterAlias = llvm::Function::Create(
2455 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2457 llvm::BasicBlock *AliasBB =
2458 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2459 llvm::BasicBlock *NoAliasBB =
2460 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2462 // Branch based on whether the runtime provided class_registerAlias_np()
2463 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2464 llvm::Constant::getNullValue(RegisterAlias->getType()));
2465 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2467 // The true branch (has alias registration fucntion):
2468 Builder.SetInsertPoint(AliasBB);
2469 // Emit alias registration calls:
2470 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2471 iter != ClassAliases.end(); ++iter) {
2472 llvm::Constant *TheClass =
2473 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2475 if (0 != TheClass) {
2476 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2477 Builder.CreateCall2(RegisterAlias, TheClass,
2478 MakeConstantString(iter->second));
2482 Builder.CreateBr(NoAliasBB);
2484 // Missing alias registration function, just return from the function:
2485 Builder.SetInsertPoint(NoAliasBB);
2487 Builder.CreateRetVoid();
2489 return LoadFunction;
2492 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2493 const ObjCContainerDecl *CD) {
2494 const ObjCCategoryImplDecl *OCD =
2495 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2496 StringRef CategoryName = OCD ? OCD->getName() : "";
2497 StringRef ClassName = CD->getName();
2498 Selector MethodName = OMD->getSelector();
2499 bool isClassMethod = !OMD->isInstanceMethod();
2501 CodeGenTypes &Types = CGM.getTypes();
2502 llvm::FunctionType *MethodTy =
2503 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2504 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2505 MethodName, isClassMethod);
2507 llvm::Function *Method
2508 = llvm::Function::Create(MethodTy,
2509 llvm::GlobalValue::InternalLinkage,
2515 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2516 return GetPropertyFn;
2519 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2520 return SetPropertyFn;
2523 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2528 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2529 return GetStructPropertyFn;
2531 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2532 return SetStructPropertyFn;
2534 llvm::Constant *CGObjCGNU::GetCppAtomicObjectFunction() {
2538 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2539 return EnumerationMutationFn;
2542 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2543 const ObjCAtSynchronizedStmt &S) {
2544 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2548 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2549 const ObjCAtTryStmt &S) {
2550 // Unlike the Apple non-fragile runtimes, which also uses
2551 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2552 // EH support isn't a veneer over C++ EH. Instead, exception
2553 // objects are created by objc_exception_throw and destroyed by
2554 // the personality function; this avoids the need for bracketing
2555 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2556 // (or even _Unwind_DeleteException), but probably doesn't
2557 // interoperate very well with foreign exceptions.
2559 // In Objective-C++ mode, we actually emit something equivalent to the C++
2560 // exception handler.
2561 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2565 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2566 const ObjCAtThrowStmt &S) {
2567 llvm::Value *ExceptionAsObject;
2569 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2570 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2571 ExceptionAsObject = Exception;
2573 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2574 "Unexpected rethrow outside @catch block.");
2575 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2577 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2578 llvm::CallSite Throw =
2579 CGF.EmitCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2580 Throw.setDoesNotReturn();
2581 CGF.Builder.CreateUnreachable();
2582 CGF.Builder.ClearInsertionPoint();
2585 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2586 llvm::Value *AddrWeakObj) {
2587 CGBuilderTy B = CGF.Builder;
2588 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2589 return B.CreateCall(WeakReadFn, AddrWeakObj);
2592 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2593 llvm::Value *src, llvm::Value *dst) {
2594 CGBuilderTy B = CGF.Builder;
2595 src = EnforceType(B, src, IdTy);
2596 dst = EnforceType(B, dst, PtrToIdTy);
2597 B.CreateCall2(WeakAssignFn, src, dst);
2600 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2601 llvm::Value *src, llvm::Value *dst,
2603 CGBuilderTy B = CGF.Builder;
2604 src = EnforceType(B, src, IdTy);
2605 dst = EnforceType(B, dst, PtrToIdTy);
2607 B.CreateCall2(GlobalAssignFn, src, dst);
2609 // FIXME. Add threadloca assign API
2610 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
2613 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2614 llvm::Value *src, llvm::Value *dst,
2615 llvm::Value *ivarOffset) {
2616 CGBuilderTy B = CGF.Builder;
2617 src = EnforceType(B, src, IdTy);
2618 dst = EnforceType(B, dst, IdTy);
2619 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
2622 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2623 llvm::Value *src, llvm::Value *dst) {
2624 CGBuilderTy B = CGF.Builder;
2625 src = EnforceType(B, src, IdTy);
2626 dst = EnforceType(B, dst, PtrToIdTy);
2627 B.CreateCall2(StrongCastAssignFn, src, dst);
2630 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2631 llvm::Value *DestPtr,
2632 llvm::Value *SrcPtr,
2633 llvm::Value *Size) {
2634 CGBuilderTy B = CGF.Builder;
2635 DestPtr = EnforceType(B, DestPtr, PtrTy);
2636 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2638 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
2641 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2642 const ObjCInterfaceDecl *ID,
2643 const ObjCIvarDecl *Ivar) {
2644 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2645 + '.' + Ivar->getNameAsString();
2646 // Emit the variable and initialize it with what we think the correct value
2647 // is. This allows code compiled with non-fragile ivars to work correctly
2648 // when linked against code which isn't (most of the time).
2649 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2650 if (!IvarOffsetPointer) {
2651 // This will cause a run-time crash if we accidentally use it. A value of
2652 // 0 would seem more sensible, but will silently overwrite the isa pointer
2653 // causing a great deal of confusion.
2654 uint64_t Offset = -1;
2655 // We can't call ComputeIvarBaseOffset() here if we have the
2656 // implementation, because it will create an invalid ASTRecordLayout object
2657 // that we are then stuck with forever, so we only initialize the ivar
2658 // offset variable with a guess if we only have the interface. The
2659 // initializer will be reset later anyway, when we are generating the class
2661 if (!CGM.getContext().getObjCImplementation(
2662 const_cast<ObjCInterfaceDecl *>(ID)))
2663 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2665 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2667 // Don't emit the guess in non-PIC code because the linker will not be able
2668 // to replace it with the real version for a library. In non-PIC code you
2669 // must compile with the fragile ABI if you want to use ivars from a
2670 // GCC-compiled class.
2671 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
2672 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2674 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2675 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2676 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2677 IvarOffsetGV, Name);
2679 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2680 llvm::Type::getInt32PtrTy(VMContext), false,
2681 llvm::GlobalValue::ExternalLinkage, 0, Name);
2684 return IvarOffsetPointer;
2687 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2689 llvm::Value *BaseValue,
2690 const ObjCIvarDecl *Ivar,
2691 unsigned CVRQualifiers) {
2692 const ObjCInterfaceDecl *ID =
2693 ObjectTy->getAs<ObjCObjectType>()->getInterface();
2694 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2695 EmitIvarOffset(CGF, ID, Ivar));
2698 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2699 const ObjCInterfaceDecl *OID,
2700 const ObjCIvarDecl *OIVD) {
2701 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2702 next = next->getNextIvar()) {
2707 // Otherwise check in the super class.
2708 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2709 return FindIvarInterface(Context, Super, OIVD);
2714 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2715 const ObjCInterfaceDecl *Interface,
2716 const ObjCIvarDecl *Ivar) {
2717 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2718 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2719 if (RuntimeVersion < 10)
2720 return CGF.Builder.CreateZExtOrBitCast(
2721 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2722 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2724 std::string name = "__objc_ivar_offset_value_" +
2725 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2726 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2728 Offset = new llvm::GlobalVariable(TheModule, IntTy,
2729 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2730 llvm::Constant::getNullValue(IntTy), name);
2731 Offset = CGF.Builder.CreateLoad(Offset);
2732 if (Offset->getType() != PtrDiffTy)
2733 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2736 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2737 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2741 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2742 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2743 case ObjCRuntime::GNUstep:
2744 return new CGObjCGNUstep(CGM);
2746 case ObjCRuntime::GCC:
2747 return new CGObjCGCC(CGM);
2749 case ObjCRuntime::ObjFW:
2750 return new CGObjCObjFW(CGM);
2752 case ObjCRuntime::FragileMacOSX:
2753 case ObjCRuntime::MacOSX:
2754 case ObjCRuntime::iOS:
2755 llvm_unreachable("these runtimes are not GNU runtimes");
2757 llvm_unreachable("bad runtime");