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 "CGCleanup.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.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/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Compiler.h"
39 using namespace clang;
40 using namespace CodeGen;
44 /// Class that lazily initialises the runtime function. Avoids inserting the
45 /// types and the function declaration into a module if they're not used, and
46 /// avoids constructing the type more than once if it's used more than once.
47 class LazyRuntimeFunction {
49 std::vector<llvm::Type*> ArgTys;
50 const char *FunctionName;
51 llvm::Constant *Function;
53 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
56 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
58 /// Initialises the lazy function with the name, return type, and the types
61 void init(CodeGenModule *Mod, const char *name,
62 llvm::Type *RetTy, ...) {
68 va_start(Args, RetTy);
69 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
70 ArgTys.push_back(ArgTy);
72 // Push the return type on at the end so we can pop it off easily
73 ArgTys.push_back(RetTy);
75 /// Overloaded cast operator, allows the class to be implicitly cast to an
77 operator llvm::Constant*() {
79 if (0 == FunctionName) return 0;
80 // We put the return type on the end of the vector, so pop it back off
81 llvm::Type *RetTy = ArgTys.back();
83 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
85 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
86 // We won't need to use the types again, so we may as well clean up the
92 operator llvm::Function*() {
93 return cast<llvm::Function>((llvm::Constant*)*this);
99 /// GNU Objective-C runtime code generation. This class implements the parts of
100 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
101 /// GNUstep and ObjFW).
102 class CGObjCGNU : public CGObjCRuntime {
104 /// The LLVM module into which output is inserted
105 llvm::Module &TheModule;
106 /// strut objc_super. Used for sending messages to super. This structure
107 /// contains the receiver (object) and the expected class.
108 llvm::StructType *ObjCSuperTy;
109 /// struct objc_super*. The type of the argument to the superclass message
110 /// lookup functions.
111 llvm::PointerType *PtrToObjCSuperTy;
112 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
113 /// SEL is included in a header somewhere, in which case it will be whatever
114 /// type is declared in that header, most likely {i8*, i8*}.
115 llvm::PointerType *SelectorTy;
116 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
117 /// places where it's used
118 llvm::IntegerType *Int8Ty;
119 /// Pointer to i8 - LLVM type of char*, for all of the places where the
120 /// runtime needs to deal with C strings.
121 llvm::PointerType *PtrToInt8Ty;
122 /// Instance Method Pointer type. This is a pointer to a function that takes,
123 /// at a minimum, an object and a selector, and is the generic type for
124 /// Objective-C methods. Due to differences between variadic / non-variadic
125 /// calling conventions, it must always be cast to the correct type before
126 /// actually being used.
127 llvm::PointerType *IMPTy;
128 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
129 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
130 /// but if the runtime header declaring it is included then it may be a
131 /// pointer to a structure.
132 llvm::PointerType *IdTy;
133 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
134 /// message lookup function and some GC-related functions.
135 llvm::PointerType *PtrToIdTy;
136 /// The clang type of id. Used when using the clang CGCall infrastructure to
137 /// call Objective-C methods.
139 /// LLVM type for C int type.
140 llvm::IntegerType *IntTy;
141 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
142 /// used in the code to document the difference between i8* meaning a pointer
143 /// to a C string and i8* meaning a pointer to some opaque type.
144 llvm::PointerType *PtrTy;
145 /// LLVM type for C long type. The runtime uses this in a lot of places where
146 /// it should be using intptr_t, but we can't fix this without breaking
147 /// compatibility with GCC...
148 llvm::IntegerType *LongTy;
149 /// LLVM type for C size_t. Used in various runtime data structures.
150 llvm::IntegerType *SizeTy;
151 /// LLVM type for C intptr_t.
152 llvm::IntegerType *IntPtrTy;
153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
154 llvm::IntegerType *PtrDiffTy;
155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
157 llvm::PointerType *PtrToIntTy;
158 /// LLVM type for Objective-C BOOL type.
160 /// 32-bit integer type, to save us needing to look it up every time it's used.
161 llvm::IntegerType *Int32Ty;
162 /// 64-bit integer type, to save us needing to look it up every time it's used.
163 llvm::IntegerType *Int64Ty;
164 /// Metadata kind used to tie method lookups to message sends. The GNUstep
165 /// runtime provides some LLVM passes that can use this to do things like
166 /// automatic IMP caching and speculative inlining.
167 unsigned msgSendMDKind;
168 /// Helper function that generates a constant string and returns a pointer to
169 /// the start of the string. The result of this function can be used anywhere
170 /// where the C code specifies const char*.
171 llvm::Constant *MakeConstantString(const std::string &Str,
172 const std::string &Name="") {
173 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
174 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
176 /// Emits a linkonce_odr string, whose name is the prefix followed by the
177 /// string value. This allows the linker to combine the strings between
178 /// different modules. Used for EH typeinfo names, selector strings, and a
179 /// few other things.
180 llvm::Constant *ExportUniqueString(const std::string &Str,
181 const std::string prefix) {
182 std::string name = prefix + Str;
183 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
185 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
186 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
187 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
189 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
191 /// Generates a global structure, initialized by the elements in the vector.
192 /// The element types must match the types of the structure elements in the
194 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
195 ArrayRef<llvm::Constant *> V,
197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
200 return new llvm::GlobalVariable(TheModule, Ty, false,
203 /// Generates a global array. The vector must contain the same number of
204 /// elements that the array type declares, of the type specified as the array
206 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
207 ArrayRef<llvm::Constant *> V,
209 llvm::GlobalValue::LinkageTypes linkage
210 =llvm::GlobalValue::InternalLinkage) {
211 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
212 return new llvm::GlobalVariable(TheModule, Ty, false,
215 /// Generates a global array, inferring the array type from the specified
216 /// element type and the size of the initialiser.
217 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
218 ArrayRef<llvm::Constant *> V,
220 llvm::GlobalValue::LinkageTypes linkage
221 =llvm::GlobalValue::InternalLinkage) {
222 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
223 return MakeGlobal(ArrayTy, V, Name, linkage);
225 /// Returns a property name and encoding string.
226 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
227 const Decl *Container) {
228 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
229 if ((R.getKind() == ObjCRuntime::GNUstep) &&
230 (R.getVersion() >= VersionTuple(1, 6))) {
231 std::string NameAndAttributes;
233 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
234 NameAndAttributes += '\0';
235 NameAndAttributes += TypeStr.length() + 3;
236 NameAndAttributes += TypeStr;
237 NameAndAttributes += '\0';
238 NameAndAttributes += PD->getNameAsString();
239 NameAndAttributes += '\0';
240 return llvm::ConstantExpr::getGetElementPtr(
241 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
243 return MakeConstantString(PD->getNameAsString());
245 /// Push the property attributes into two structure fields.
246 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
247 ObjCPropertyDecl *property, bool isSynthesized=true, bool
249 int attrs = property->getPropertyAttributes();
250 // For read-only properties, clear the copy and retain flags
251 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
252 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
257 // The first flags field has the same attribute values as clang uses internally
258 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
261 // For protocol properties, synthesized and dynamic have no meaning, so we
262 // reuse these flags to indicate that this is a protocol property (both set
263 // has no meaning, as a property can't be both synthesized and dynamic)
264 attrs |= isSynthesized ? (1<<0) : 0;
265 attrs |= isDynamic ? (1<<1) : 0;
266 // The second field is the next four fields left shifted by two, with the
267 // low bit set to indicate whether the field is synthesized or dynamic.
268 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
269 // Two padding fields
270 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
271 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
273 /// Ensures that the value has the required type, by inserting a bitcast if
274 /// required. This function lets us avoid inserting bitcasts that are
276 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
277 if (V->getType() == Ty) return V;
278 return B.CreateBitCast(V, Ty);
280 // Some zeros used for GEPs in lots of places.
281 llvm::Constant *Zeros[2];
282 /// Null pointer value. Mainly used as a terminator in various arrays.
283 llvm::Constant *NULLPtr;
285 llvm::LLVMContext &VMContext;
287 /// Placeholder for the class. Lots of things refer to the class before we've
288 /// actually emitted it. We use this alias as a placeholder, and then replace
289 /// it with a pointer to the class structure before finally emitting the
291 llvm::GlobalAlias *ClassPtrAlias;
292 /// Placeholder for the metaclass. Lots of things refer to the class before
293 /// we've / actually emitted it. We use this alias as a placeholder, and then
294 /// replace / it with a pointer to the metaclass structure before finally
295 /// emitting the / module.
296 llvm::GlobalAlias *MetaClassPtrAlias;
297 /// All of the classes that have been generated for this compilation units.
298 std::vector<llvm::Constant*> Classes;
299 /// All of the categories that have been generated for this compilation units.
300 std::vector<llvm::Constant*> Categories;
301 /// All of the Objective-C constant strings that have been generated for this
302 /// compilation units.
303 std::vector<llvm::Constant*> ConstantStrings;
304 /// Map from string values to Objective-C constant strings in the output.
305 /// Used to prevent emitting Objective-C strings more than once. This should
306 /// not be required at all - CodeGenModule should manage this list.
307 llvm::StringMap<llvm::Constant*> ObjCStrings;
308 /// All of the protocols that have been declared.
309 llvm::StringMap<llvm::Constant*> ExistingProtocols;
310 /// For each variant of a selector, we store the type encoding and a
311 /// placeholder value. For an untyped selector, the type will be the empty
312 /// string. Selector references are all done via the module's selector table,
313 /// so we create an alias as a placeholder and then replace it with the real
315 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
316 /// Type of the selector map. This is roughly equivalent to the structure
317 /// used in the GNUstep runtime, which maintains a list of all of the valid
318 /// types for a selector in a table.
319 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
321 /// A map from selectors to selector types. This allows us to emit all
322 /// selectors of the same name and type together.
323 SelectorMap SelectorTable;
325 /// Selectors related to memory management. When compiling in GC mode, we
327 Selector RetainSel, ReleaseSel, AutoreleaseSel;
328 /// Runtime functions used for memory management in GC mode. Note that clang
329 /// supports code generation for calling these functions, but neither GNU
330 /// runtime actually supports this API properly yet.
331 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
332 WeakAssignFn, GlobalAssignFn;
334 typedef std::pair<std::string, std::string> ClassAliasPair;
335 /// All classes that have aliases set for them.
336 std::vector<ClassAliasPair> ClassAliases;
339 /// Function used for throwing Objective-C exceptions.
340 LazyRuntimeFunction ExceptionThrowFn;
341 /// Function used for rethrowing exceptions, used at the end of \@finally or
342 /// \@synchronize blocks.
343 LazyRuntimeFunction ExceptionReThrowFn;
344 /// Function called when entering a catch function. This is required for
345 /// differentiating Objective-C exceptions and foreign exceptions.
346 LazyRuntimeFunction EnterCatchFn;
347 /// Function called when exiting from a catch block. Used to do exception
349 LazyRuntimeFunction ExitCatchFn;
350 /// Function called when entering an \@synchronize block. Acquires the lock.
351 LazyRuntimeFunction SyncEnterFn;
352 /// Function called when exiting an \@synchronize block. Releases the lock.
353 LazyRuntimeFunction SyncExitFn;
357 /// Function called if fast enumeration detects that the collection is
358 /// modified during the update.
359 LazyRuntimeFunction EnumerationMutationFn;
360 /// Function for implementing synthesized property getters that return an
362 LazyRuntimeFunction GetPropertyFn;
363 /// Function for implementing synthesized property setters that return an
365 LazyRuntimeFunction SetPropertyFn;
366 /// Function used for non-object declared property getters.
367 LazyRuntimeFunction GetStructPropertyFn;
368 /// Function used for non-object declared property setters.
369 LazyRuntimeFunction SetStructPropertyFn;
371 /// The version of the runtime that this class targets. Must match the
372 /// version in the runtime.
374 /// The version of the protocol class. Used to differentiate between ObjC1
375 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
376 /// components and can not contain declared properties. We always emit
377 /// Objective-C 2 property structures, but we have to pretend that they're
378 /// Objective-C 1 property structures when targeting the GCC runtime or it
380 const int ProtocolVersion;
382 /// Generates an instance variable list structure. This is a structure
383 /// containing a size and an array of structures containing instance variable
384 /// metadata. This is used purely for introspection in the fragile ABI. In
385 /// the non-fragile ABI, it's used for instance variable fixup.
386 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
387 ArrayRef<llvm::Constant *> IvarTypes,
388 ArrayRef<llvm::Constant *> IvarOffsets);
389 /// Generates a method list structure. This is a structure containing a size
390 /// and an array of structures containing method metadata.
392 /// This structure is used by both classes and categories, and contains a next
393 /// pointer allowing them to be chained together in a linked list.
394 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
395 const StringRef &CategoryName,
396 ArrayRef<Selector> MethodSels,
397 ArrayRef<llvm::Constant *> MethodTypes,
398 bool isClassMethodList);
399 /// Emits an empty protocol. This is used for \@protocol() where no protocol
400 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
402 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
403 /// Generates a list of property metadata structures. This follows the same
404 /// pattern as method and instance variable metadata lists.
405 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
406 SmallVectorImpl<Selector> &InstanceMethodSels,
407 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
408 /// Generates a list of referenced protocols. Classes, categories, and
409 /// protocols all use this structure.
410 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
411 /// To ensure that all protocols are seen by the runtime, we add a category on
412 /// a class defined in the runtime, declaring no methods, but adopting the
413 /// protocols. This is a horribly ugly hack, but it allows us to collect all
414 /// of the protocols without changing the ABI.
415 void GenerateProtocolHolderCategory();
416 /// Generates a class structure.
417 llvm::Constant *GenerateClassStructure(
418 llvm::Constant *MetaClass,
419 llvm::Constant *SuperClass,
422 llvm::Constant *Version,
423 llvm::Constant *InstanceSize,
424 llvm::Constant *IVars,
425 llvm::Constant *Methods,
426 llvm::Constant *Protocols,
427 llvm::Constant *IvarOffsets,
428 llvm::Constant *Properties,
429 llvm::Constant *StrongIvarBitmap,
430 llvm::Constant *WeakIvarBitmap,
432 /// Generates a method list. This is used by protocols to define the required
433 /// and optional methods.
434 llvm::Constant *GenerateProtocolMethodList(
435 ArrayRef<llvm::Constant *> MethodNames,
436 ArrayRef<llvm::Constant *> MethodTypes);
437 /// Returns a selector with the specified type encoding. An empty string is
438 /// used to return an untyped selector (with the types field set to NULL).
439 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
440 const std::string &TypeEncoding, bool lval);
441 /// Returns the variable used to store the offset of an instance variable.
442 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
443 const ObjCIvarDecl *Ivar);
444 /// Emits a reference to a class. This allows the linker to object if there
445 /// is no class of the matching name.
447 void EmitClassRef(const std::string &className);
448 /// Emits a pointer to the named class
449 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
450 const std::string &Name, bool isWeak);
451 /// Looks up the method for sending a message to the specified object. This
452 /// mechanism differs between the GCC and GNU runtimes, so this method must be
453 /// overridden in subclasses.
454 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
455 llvm::Value *&Receiver,
458 MessageSendInfo &MSI) = 0;
459 /// Looks up the method for sending a message to a superclass. This
460 /// mechanism differs between the GCC and GNU runtimes, so this method must
461 /// be overridden in subclasses.
462 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
463 llvm::Value *ObjCSuper,
465 MessageSendInfo &MSI) = 0;
466 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
467 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
468 /// bits set to their values, LSB first, while larger ones are stored in a
469 /// structure of this / form:
471 /// struct { int32_t length; int32_t values[length]; };
473 /// The values in the array are stored in host-endian format, with the least
474 /// significant bit being assumed to come first in the bitfield. Therefore,
475 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
476 /// while a bitfield / with the 63rd bit set will be 1<<64.
477 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
479 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
480 unsigned protocolClassVersion);
482 llvm::Constant *GenerateConstantString(const StringLiteral *) override;
485 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
486 QualType ResultType, Selector Sel,
487 llvm::Value *Receiver, const CallArgList &CallArgs,
488 const ObjCInterfaceDecl *Class,
489 const ObjCMethodDecl *Method) override;
491 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
492 QualType ResultType, Selector Sel,
493 const ObjCInterfaceDecl *Class,
494 bool isCategoryImpl, llvm::Value *Receiver,
495 bool IsClassMessage, const CallArgList &CallArgs,
496 const ObjCMethodDecl *Method) override;
497 llvm::Value *GetClass(CodeGenFunction &CGF,
498 const ObjCInterfaceDecl *OID) override;
499 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
500 bool lval = false) override;
501 llvm::Value *GetSelector(CodeGenFunction &CGF,
502 const ObjCMethodDecl *Method) override;
503 llvm::Constant *GetEHType(QualType T) override;
505 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD) override;
507 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
508 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
509 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
510 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
511 const ObjCProtocolDecl *PD) override;
512 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
513 llvm::Function *ModuleInitFunction() override;
514 llvm::Constant *GetPropertyGetFunction() override;
515 llvm::Constant *GetPropertySetFunction() override;
516 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
518 llvm::Constant *GetSetStructFunction() override;
519 llvm::Constant *GetGetStructFunction() override;
520 llvm::Constant *GetCppAtomicObjectGetFunction() override;
521 llvm::Constant *GetCppAtomicObjectSetFunction() override;
522 llvm::Constant *EnumerationMutationFunction() override;
524 void EmitTryStmt(CodeGenFunction &CGF,
525 const ObjCAtTryStmt &S) override;
526 void EmitSynchronizedStmt(CodeGenFunction &CGF,
527 const ObjCAtSynchronizedStmt &S) override;
528 void EmitThrowStmt(CodeGenFunction &CGF,
529 const ObjCAtThrowStmt &S,
530 bool ClearInsertionPoint=true) override;
531 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
532 llvm::Value *AddrWeakObj) override;
533 void EmitObjCWeakAssign(CodeGenFunction &CGF,
534 llvm::Value *src, llvm::Value *dst) override;
535 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
536 llvm::Value *src, llvm::Value *dest,
537 bool threadlocal=false) override;
538 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
539 llvm::Value *dest, llvm::Value *ivarOffset) override;
540 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
541 llvm::Value *src, llvm::Value *dest) override;
542 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, llvm::Value *DestPtr,
544 llvm::Value *Size) override;
545 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
546 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
547 unsigned CVRQualifiers) override;
548 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
549 const ObjCInterfaceDecl *Interface,
550 const ObjCIvarDecl *Ivar) override;
551 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
552 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
553 const CGBlockInfo &blockInfo) override {
556 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
557 const CGBlockInfo &blockInfo) override {
561 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
565 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
566 bool Weak = false) override {
570 /// Class representing the legacy GCC Objective-C ABI. This is the default when
571 /// -fobjc-nonfragile-abi is not specified.
573 /// The GCC ABI target actually generates code that is approximately compatible
574 /// with the new GNUstep runtime ABI, but refrains from using any features that
575 /// would not work with the GCC runtime. For example, clang always generates
576 /// the extended form of the class structure, and the extra fields are simply
577 /// ignored by GCC libobjc.
578 class CGObjCGCC : public CGObjCGNU {
579 /// The GCC ABI message lookup function. Returns an IMP pointing to the
580 /// method implementation for this message.
581 LazyRuntimeFunction MsgLookupFn;
582 /// The GCC ABI superclass message lookup function. Takes a pointer to a
583 /// structure describing the receiver and the class, and a selector as
584 /// arguments. Returns the IMP for the corresponding method.
585 LazyRuntimeFunction MsgLookupSuperFn;
587 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
588 llvm::Value *cmd, llvm::MDNode *node,
589 MessageSendInfo &MSI) override {
590 CGBuilderTy &Builder = CGF.Builder;
591 llvm::Value *args[] = {
592 EnforceType(Builder, Receiver, IdTy),
593 EnforceType(Builder, cmd, SelectorTy) };
594 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
595 imp->setMetadata(msgSendMDKind, node);
596 return imp.getInstruction();
598 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
599 llvm::Value *cmd, MessageSendInfo &MSI) override {
600 CGBuilderTy &Builder = CGF.Builder;
601 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
602 PtrToObjCSuperTy), cmd};
603 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
606 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
607 // IMP objc_msg_lookup(id, SEL);
608 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
609 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
610 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
611 PtrToObjCSuperTy, SelectorTy, NULL);
614 /// Class used when targeting the new GNUstep runtime ABI.
615 class CGObjCGNUstep : public CGObjCGNU {
616 /// The slot lookup function. Returns a pointer to a cacheable structure
617 /// that contains (among other things) the IMP.
618 LazyRuntimeFunction SlotLookupFn;
619 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
620 /// a structure describing the receiver and the class, and a selector as
621 /// arguments. Returns the slot for the corresponding method. Superclass
622 /// message lookup rarely changes, so this is a good caching opportunity.
623 LazyRuntimeFunction SlotLookupSuperFn;
624 /// Specialised function for setting atomic retain properties
625 LazyRuntimeFunction SetPropertyAtomic;
626 /// Specialised function for setting atomic copy properties
627 LazyRuntimeFunction SetPropertyAtomicCopy;
628 /// Specialised function for setting nonatomic retain properties
629 LazyRuntimeFunction SetPropertyNonAtomic;
630 /// Specialised function for setting nonatomic copy properties
631 LazyRuntimeFunction SetPropertyNonAtomicCopy;
632 /// Function to perform atomic copies of C++ objects with nontrivial copy
633 /// constructors from Objective-C ivars.
634 LazyRuntimeFunction CxxAtomicObjectGetFn;
635 /// Function to perform atomic copies of C++ objects with nontrivial copy
636 /// constructors to Objective-C ivars.
637 LazyRuntimeFunction CxxAtomicObjectSetFn;
638 /// Type of an slot structure pointer. This is returned by the various
639 /// lookup functions.
642 llvm::Constant *GetEHType(QualType T) override;
644 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
645 llvm::Value *cmd, llvm::MDNode *node,
646 MessageSendInfo &MSI) override {
647 CGBuilderTy &Builder = CGF.Builder;
648 llvm::Function *LookupFn = SlotLookupFn;
650 // Store the receiver on the stack so that we can reload it later
651 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
652 Builder.CreateStore(Receiver, ReceiverPtr);
656 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
657 self = CGF.LoadObjCSelf();
659 self = llvm::ConstantPointerNull::get(IdTy);
662 // The lookup function is guaranteed not to capture the receiver pointer.
663 LookupFn->setDoesNotCapture(1);
665 llvm::Value *args[] = {
666 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
667 EnforceType(Builder, cmd, SelectorTy),
668 EnforceType(Builder, self, IdTy) };
669 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
670 slot.setOnlyReadsMemory();
671 slot->setMetadata(msgSendMDKind, node);
673 // Load the imp from the slot
675 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
677 // The lookup function may have changed the receiver, so make sure we use
679 Receiver = Builder.CreateLoad(ReceiverPtr, true);
682 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
684 MessageSendInfo &MSI) override {
685 CGBuilderTy &Builder = CGF.Builder;
686 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
688 llvm::CallInst *slot =
689 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
690 slot->setOnlyReadsMemory();
692 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
695 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
696 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
698 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
699 PtrTy, PtrTy, IntTy, IMPTy, NULL);
700 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
701 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
702 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
703 SelectorTy, IdTy, NULL);
704 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
705 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
706 PtrToObjCSuperTy, SelectorTy, NULL);
707 // If we're in ObjC++ mode, then we want to make
708 if (CGM.getLangOpts().CPlusPlus) {
709 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
710 // void *__cxa_begin_catch(void *e)
711 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
712 // void __cxa_end_catch(void)
713 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
714 // void _Unwind_Resume_or_Rethrow(void*)
715 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
717 } else if (R.getVersion() >= VersionTuple(1, 7)) {
718 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
719 // id objc_begin_catch(void *e)
720 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, NULL);
721 // void objc_end_catch(void)
722 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, NULL);
723 // void _Unwind_Resume_or_Rethrow(void*)
724 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
727 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
728 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
729 SelectorTy, IdTy, PtrDiffTy, NULL);
730 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
731 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
732 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
733 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
734 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
735 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
736 // void objc_setCppObjectAtomic(void *dest, const void *src, void
738 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
740 // void objc_getCppObjectAtomic(void *dest, const void *src, void
742 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
745 llvm::Constant *GetCppAtomicObjectGetFunction() override {
746 // The optimised functions were added in version 1.7 of the GNUstep
748 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
750 return CxxAtomicObjectGetFn;
752 llvm::Constant *GetCppAtomicObjectSetFunction() override {
753 // The optimised functions were added in version 1.7 of the GNUstep
755 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
757 return CxxAtomicObjectSetFn;
759 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
760 bool copy) override {
761 // The optimised property functions omit the GC check, and so are not
762 // safe to use in GC mode. The standard functions are fast in GC mode,
763 // so there is less advantage in using them.
764 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
765 // The optimised functions were added in version 1.7 of the GNUstep
767 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
771 if (copy) return SetPropertyAtomicCopy;
772 return SetPropertyAtomic;
775 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
779 /// Support for the ObjFW runtime.
780 class CGObjCObjFW: public CGObjCGNU {
782 /// The GCC ABI message lookup function. Returns an IMP pointing to the
783 /// method implementation for this message.
784 LazyRuntimeFunction MsgLookupFn;
785 /// stret lookup function. While this does not seem to make sense at the
786 /// first look, this is required to call the correct forwarding function.
787 LazyRuntimeFunction MsgLookupFnSRet;
788 /// The GCC ABI superclass message lookup function. Takes a pointer to a
789 /// structure describing the receiver and the class, and a selector as
790 /// arguments. Returns the IMP for the corresponding method.
791 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
793 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
794 llvm::Value *cmd, llvm::MDNode *node,
795 MessageSendInfo &MSI) override {
796 CGBuilderTy &Builder = CGF.Builder;
797 llvm::Value *args[] = {
798 EnforceType(Builder, Receiver, IdTy),
799 EnforceType(Builder, cmd, SelectorTy) };
802 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
803 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
805 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
807 imp->setMetadata(msgSendMDKind, node);
808 return imp.getInstruction();
811 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
812 llvm::Value *cmd, MessageSendInfo &MSI) override {
813 CGBuilderTy &Builder = CGF.Builder;
814 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
815 PtrToObjCSuperTy), cmd};
817 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
818 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
820 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
823 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
824 const std::string &Name, bool isWeak) override {
826 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
830 std::string SymbolName = "_OBJC_CLASS_" + Name;
832 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
835 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
836 llvm::GlobalValue::ExternalLinkage,
843 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
844 // IMP objc_msg_lookup(id, SEL);
845 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
846 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
848 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
849 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
850 PtrToObjCSuperTy, SelectorTy, NULL);
851 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
852 PtrToObjCSuperTy, SelectorTy, NULL);
855 } // end anonymous namespace
858 /// Emits a reference to a dummy variable which is emitted with each class.
859 /// This ensures that a linker error will be generated when trying to link
860 /// together modules where a referenced class is not defined.
861 void CGObjCGNU::EmitClassRef(const std::string &className) {
862 std::string symbolRef = "__objc_class_ref_" + className;
863 // Don't emit two copies of the same symbol
864 if (TheModule.getGlobalVariable(symbolRef))
866 std::string symbolName = "__objc_class_name_" + className;
867 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
869 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
870 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
872 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
873 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
876 static std::string SymbolNameForMethod(const StringRef &ClassName,
877 const StringRef &CategoryName, const Selector MethodName,
878 bool isClassMethod) {
879 std::string MethodNameColonStripped = MethodName.getAsString();
880 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
882 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
883 CategoryName + "_" + MethodNameColonStripped).str();
886 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
887 unsigned protocolClassVersion)
888 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
889 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
890 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
892 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
894 CodeGenTypes &Types = CGM.getTypes();
895 IntTy = cast<llvm::IntegerType>(
896 Types.ConvertType(CGM.getContext().IntTy));
897 LongTy = cast<llvm::IntegerType>(
898 Types.ConvertType(CGM.getContext().LongTy));
899 SizeTy = cast<llvm::IntegerType>(
900 Types.ConvertType(CGM.getContext().getSizeType()));
901 PtrDiffTy = cast<llvm::IntegerType>(
902 Types.ConvertType(CGM.getContext().getPointerDiffType()));
903 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
905 Int8Ty = llvm::Type::getInt8Ty(VMContext);
906 // C string type. Used in lots of places.
907 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
909 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
911 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
912 // Get the selector Type.
913 QualType selTy = CGM.getContext().getObjCSelType();
914 if (QualType() == selTy) {
915 SelectorTy = PtrToInt8Ty;
917 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
920 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
923 Int32Ty = llvm::Type::getInt32Ty(VMContext);
924 Int64Ty = llvm::Type::getInt64Ty(VMContext);
927 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
930 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
931 ASTIdTy = CanQualType();
932 if (UnqualIdTy != QualType()) {
933 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
934 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
938 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
940 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
941 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
943 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
945 // void objc_exception_throw(id);
946 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
947 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
948 // int objc_sync_enter(id);
949 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
950 // int objc_sync_exit(id);
951 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
953 // void objc_enumerationMutation (id)
954 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
957 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
958 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
959 PtrDiffTy, BoolTy, NULL);
960 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
961 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
962 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
963 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
964 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
965 PtrDiffTy, BoolTy, BoolTy, NULL);
966 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
967 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
968 PtrDiffTy, BoolTy, BoolTy, NULL);
971 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
972 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
975 const LangOptions &Opts = CGM.getLangOpts();
976 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
979 // Don't bother initialising the GC stuff unless we're compiling in GC mode
980 if (Opts.getGC() != LangOptions::NonGC) {
981 // This is a bit of an hack. We should sort this out by having a proper
982 // CGObjCGNUstep subclass for GC, but we may want to really support the old
983 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
984 // Get selectors needed in GC mode
985 RetainSel = GetNullarySelector("retain", CGM.getContext());
986 ReleaseSel = GetNullarySelector("release", CGM.getContext());
987 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
989 // Get functions needed in GC mode
991 // id objc_assign_ivar(id, id, ptrdiff_t);
992 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
994 // id objc_assign_strongCast (id, id*)
995 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
997 // id objc_assign_global(id, id*);
998 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
1000 // id objc_assign_weak(id, id*);
1001 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
1002 // id objc_read_weak(id*);
1003 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
1004 // void *objc_memmove_collectable(void*, void *, size_t);
1005 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1010 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1011 const std::string &Name,
1013 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
1014 // With the incompatible ABI, this will need to be replaced with a direct
1015 // reference to the class symbol. For the compatible nonfragile ABI we are
1016 // still performing this lookup at run time but emitting the symbol for the
1017 // class externally so that we can make the switch later.
1019 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1020 // with memoized versions or with static references if it's safe to do so.
1023 ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
1025 llvm::Constant *ClassLookupFn =
1026 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1027 "objc_lookup_class");
1028 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1031 // This has to perform the lookup every time, since posing and related
1032 // techniques can modify the name -> class mapping.
1033 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1034 const ObjCInterfaceDecl *OID) {
1035 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1037 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1038 return GetClassNamed(CGF, "NSAutoreleasePool", false);
1041 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1042 const std::string &TypeEncoding, bool lval) {
1044 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1045 llvm::GlobalAlias *SelValue = 0;
1048 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1049 e = Types.end() ; i!=e ; i++) {
1050 if (i->first == TypeEncoding) {
1051 SelValue = i->second;
1055 if (0 == SelValue) {
1056 SelValue = llvm::GlobalAlias::create(
1057 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1058 ".objc_selector_" + Sel.getAsString(), &TheModule);
1059 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1063 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1064 CGF.Builder.CreateStore(SelValue, tmp);
1070 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1072 return GetSelector(CGF, Sel, std::string(), lval);
1075 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1076 const ObjCMethodDecl *Method) {
1077 std::string SelTypes;
1078 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
1079 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
1082 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1083 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1084 // With the old ABI, there was only one kind of catchall, which broke
1085 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1086 // a pointer indicating object catchalls, and NULL to indicate real
1088 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1089 return MakeConstantString("@id");
1095 // All other types should be Objective-C interface pointer types.
1096 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1097 assert(OPT && "Invalid @catch type.");
1098 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1099 assert(IDecl && "Invalid @catch type.");
1100 return MakeConstantString(IDecl->getIdentifier()->getName());
1103 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1104 if (!CGM.getLangOpts().CPlusPlus)
1105 return CGObjCGNU::GetEHType(T);
1107 // For Objective-C++, we want to provide the ability to catch both C++ and
1108 // Objective-C objects in the same function.
1110 // There's a particular fixed type info for 'id'.
1111 if (T->isObjCIdType() ||
1112 T->isObjCQualifiedIdType()) {
1113 llvm::Constant *IDEHType =
1114 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1117 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1119 llvm::GlobalValue::ExternalLinkage,
1120 0, "__objc_id_type_info");
1121 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1124 const ObjCObjectPointerType *PT =
1125 T->getAs<ObjCObjectPointerType>();
1126 assert(PT && "Invalid @catch type.");
1127 const ObjCInterfaceType *IT = PT->getInterfaceType();
1128 assert(IT && "Invalid @catch type.");
1129 std::string className = IT->getDecl()->getIdentifier()->getName();
1131 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1133 // Return the existing typeinfo if it exists
1134 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1136 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1138 // Otherwise create it.
1140 // vtable for gnustep::libobjc::__objc_class_type_info
1141 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1142 // platform's name mangling.
1143 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1144 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1146 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1147 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1149 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1150 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
1151 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1153 llvm::Constant *typeName =
1154 ExportUniqueString(className, "__objc_eh_typename_");
1156 std::vector<llvm::Constant*> fields;
1157 fields.push_back(Vtable);
1158 fields.push_back(typeName);
1159 llvm::Constant *TI =
1160 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1161 NULL), fields, "__objc_eh_typeinfo_" + className,
1162 llvm::GlobalValue::LinkOnceODRLinkage);
1163 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1166 /// Generate an NSConstantString object.
1167 llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1169 std::string Str = SL->getString().str();
1171 // Look for an existing one
1172 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1173 if (old != ObjCStrings.end())
1174 return old->getValue();
1176 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1178 if (StringClass.empty()) StringClass = "NXConstantString";
1180 std::string Sym = "_OBJC_CLASS_";
1183 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1186 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1187 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1188 else if (isa->getType() != PtrToIdTy)
1189 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1191 std::vector<llvm::Constant*> Ivars;
1192 Ivars.push_back(isa);
1193 Ivars.push_back(MakeConstantString(Str));
1194 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
1195 llvm::Constant *ObjCStr = MakeGlobal(
1196 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
1197 Ivars, ".objc_str");
1198 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1199 ObjCStrings[Str] = ObjCStr;
1200 ConstantStrings.push_back(ObjCStr);
1204 ///Generates a message send where the super is the receiver. This is a message
1205 ///send to self with special delivery semantics indicating which class's method
1206 ///should be called.
1208 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1209 ReturnValueSlot Return,
1210 QualType ResultType,
1212 const ObjCInterfaceDecl *Class,
1213 bool isCategoryImpl,
1214 llvm::Value *Receiver,
1215 bool IsClassMessage,
1216 const CallArgList &CallArgs,
1217 const ObjCMethodDecl *Method) {
1218 CGBuilderTy &Builder = CGF.Builder;
1219 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1220 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1221 return RValue::get(EnforceType(Builder, Receiver,
1222 CGM.getTypes().ConvertType(ResultType)));
1224 if (Sel == ReleaseSel) {
1225 return RValue::get(0);
1229 llvm::Value *cmd = GetSelector(CGF, Sel);
1232 CallArgList ActualArgs;
1234 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1235 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1236 ActualArgs.addFrom(CallArgs);
1238 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1240 llvm::Value *ReceiverClass = 0;
1241 if (isCategoryImpl) {
1242 llvm::Constant *classLookupFunction = 0;
1243 if (IsClassMessage) {
1244 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1245 IdTy, PtrTy, true), "objc_get_meta_class");
1247 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1248 IdTy, PtrTy, true), "objc_get_class");
1250 ReceiverClass = Builder.CreateCall(classLookupFunction,
1251 MakeConstantString(Class->getNameAsString()));
1253 // Set up global aliases for the metaclass or class pointer if they do not
1254 // already exist. These will are forward-references which will be set to
1255 // pointers to the class and metaclass structure created for the runtime
1256 // load function. To send a message to super, we look up the value of the
1257 // super_class pointer from either the class or metaclass structure.
1258 if (IsClassMessage) {
1259 if (!MetaClassPtrAlias) {
1260 MetaClassPtrAlias = llvm::GlobalAlias::create(
1261 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1262 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1264 ReceiverClass = MetaClassPtrAlias;
1266 if (!ClassPtrAlias) {
1267 ClassPtrAlias = llvm::GlobalAlias::create(
1268 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1269 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1271 ReceiverClass = ClassPtrAlias;
1274 // Cast the pointer to a simplified version of the class structure
1275 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1276 llvm::PointerType::getUnqual(
1277 llvm::StructType::get(IdTy, IdTy, NULL)));
1278 // Get the superclass pointer
1279 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
1280 // Load the superclass pointer
1281 ReceiverClass = Builder.CreateLoad(ReceiverClass);
1282 // Construct the structure used to look up the IMP
1283 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1284 Receiver->getType(), IdTy, NULL);
1285 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
1287 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1288 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
1290 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1293 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1294 imp = EnforceType(Builder, imp, MSI.MessengerType);
1296 llvm::Value *impMD[] = {
1297 llvm::MDString::get(VMContext, Sel.getAsString()),
1298 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1299 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1301 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1303 llvm::Instruction *call;
1304 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1305 call->setMetadata(msgSendMDKind, node);
1309 /// Generate code for a message send expression.
1311 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1312 ReturnValueSlot Return,
1313 QualType ResultType,
1315 llvm::Value *Receiver,
1316 const CallArgList &CallArgs,
1317 const ObjCInterfaceDecl *Class,
1318 const ObjCMethodDecl *Method) {
1319 CGBuilderTy &Builder = CGF.Builder;
1321 // Strip out message sends to retain / release in GC mode
1322 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1323 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1324 return RValue::get(EnforceType(Builder, Receiver,
1325 CGM.getTypes().ConvertType(ResultType)));
1327 if (Sel == ReleaseSel) {
1328 return RValue::get(0);
1332 // If the return type is something that goes in an integer register, the
1333 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1336 // The language spec says the result of this kind of message send is
1337 // undefined, but lots of people seem to have forgotten to read that
1338 // paragraph and insist on sending messages to nil that have structure
1339 // returns. With GCC, this generates a random return value (whatever happens
1340 // to be on the stack / in those registers at the time) on most platforms,
1341 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1343 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1344 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1346 llvm::BasicBlock *startBB = 0;
1347 llvm::BasicBlock *messageBB = 0;
1348 llvm::BasicBlock *continueBB = 0;
1350 if (!isPointerSizedReturn) {
1351 startBB = Builder.GetInsertBlock();
1352 messageBB = CGF.createBasicBlock("msgSend");
1353 continueBB = CGF.createBasicBlock("continue");
1355 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1356 llvm::Constant::getNullValue(Receiver->getType()));
1357 Builder.CreateCondBr(isNil, continueBB, messageBB);
1358 CGF.EmitBlock(messageBB);
1361 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1364 cmd = GetSelector(CGF, Method);
1366 cmd = GetSelector(CGF, Sel);
1367 cmd = EnforceType(Builder, cmd, SelectorTy);
1368 Receiver = EnforceType(Builder, Receiver, IdTy);
1370 llvm::Value *impMD[] = {
1371 llvm::MDString::get(VMContext, Sel.getAsString()),
1372 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1373 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1375 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1377 CallArgList ActualArgs;
1378 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1379 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1380 ActualArgs.addFrom(CallArgs);
1382 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1384 // Get the IMP to call
1387 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1388 // functions. These are not supported on all platforms (or all runtimes on a
1389 // given platform), so we
1390 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1391 case CodeGenOptions::Legacy:
1392 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1394 case CodeGenOptions::Mixed:
1395 case CodeGenOptions::NonLegacy:
1396 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1397 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1398 "objc_msgSend_fpret");
1399 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1400 // The actual types here don't matter - we're going to bitcast the
1402 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1403 "objc_msgSend_stret");
1405 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1410 // Reset the receiver in case the lookup modified it
1411 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1413 imp = EnforceType(Builder, imp, MSI.MessengerType);
1415 llvm::Instruction *call;
1416 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1417 call->setMetadata(msgSendMDKind, node);
1420 if (!isPointerSizedReturn) {
1421 messageBB = CGF.Builder.GetInsertBlock();
1422 CGF.Builder.CreateBr(continueBB);
1423 CGF.EmitBlock(continueBB);
1424 if (msgRet.isScalar()) {
1425 llvm::Value *v = msgRet.getScalarVal();
1426 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1427 phi->addIncoming(v, messageBB);
1428 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1429 msgRet = RValue::get(phi);
1430 } else if (msgRet.isAggregate()) {
1431 llvm::Value *v = msgRet.getAggregateAddr();
1432 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1433 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
1434 llvm::AllocaInst *NullVal =
1435 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
1436 CGF.InitTempAlloca(NullVal,
1437 llvm::Constant::getNullValue(RetTy->getElementType()));
1438 phi->addIncoming(v, messageBB);
1439 phi->addIncoming(NullVal, startBB);
1440 msgRet = RValue::getAggregate(phi);
1441 } else /* isComplex() */ {
1442 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1443 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1444 phi->addIncoming(v.first, messageBB);
1445 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1447 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1448 phi2->addIncoming(v.second, messageBB);
1449 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1451 msgRet = RValue::getComplex(phi, phi2);
1457 /// Generates a MethodList. Used in construction of a objc_class and
1458 /// objc_category structures.
1459 llvm::Constant *CGObjCGNU::
1460 GenerateMethodList(const StringRef &ClassName,
1461 const StringRef &CategoryName,
1462 ArrayRef<Selector> MethodSels,
1463 ArrayRef<llvm::Constant *> MethodTypes,
1464 bool isClassMethodList) {
1465 if (MethodSels.empty())
1467 // Get the method structure type.
1468 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1469 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1470 PtrToInt8Ty, // Method types
1471 IMPTy, //Method pointer
1473 std::vector<llvm::Constant*> Methods;
1474 std::vector<llvm::Constant*> Elements;
1475 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1477 llvm::Constant *Method =
1478 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1480 isClassMethodList));
1481 assert(Method && "Can't generate metadata for method that doesn't exist");
1482 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1483 Elements.push_back(C);
1484 Elements.push_back(MethodTypes[i]);
1485 Method = llvm::ConstantExpr::getBitCast(Method,
1487 Elements.push_back(Method);
1488 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
1491 // Array of method structures
1492 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1494 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1497 // Structure containing list pointer, array and array count
1498 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
1499 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1500 ObjCMethodListTy->setBody(
1507 Methods.push_back(llvm::ConstantPointerNull::get(
1508 llvm::PointerType::getUnqual(ObjCMethodListTy)));
1509 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
1510 Methods.push_back(MethodArray);
1512 // Create an instance of the structure
1513 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1516 /// Generates an IvarList. Used in construction of a objc_class.
1517 llvm::Constant *CGObjCGNU::
1518 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1519 ArrayRef<llvm::Constant *> IvarTypes,
1520 ArrayRef<llvm::Constant *> IvarOffsets) {
1521 if (IvarNames.size() == 0)
1523 // Get the method structure type.
1524 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1529 std::vector<llvm::Constant*> Ivars;
1530 std::vector<llvm::Constant*> Elements;
1531 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1533 Elements.push_back(IvarNames[i]);
1534 Elements.push_back(IvarTypes[i]);
1535 Elements.push_back(IvarOffsets[i]);
1536 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
1539 // Array of method structures
1540 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1545 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
1546 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
1547 // Structure containing array and array count
1548 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1552 // Create an instance of the structure
1553 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1556 /// Generate a class structure
1557 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1558 llvm::Constant *MetaClass,
1559 llvm::Constant *SuperClass,
1562 llvm::Constant *Version,
1563 llvm::Constant *InstanceSize,
1564 llvm::Constant *IVars,
1565 llvm::Constant *Methods,
1566 llvm::Constant *Protocols,
1567 llvm::Constant *IvarOffsets,
1568 llvm::Constant *Properties,
1569 llvm::Constant *StrongIvarBitmap,
1570 llvm::Constant *WeakIvarBitmap,
1572 // Set up the class structure
1573 // Note: Several of these are char*s when they should be ids. This is
1574 // because the runtime performs this translation on load.
1576 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1577 // anyway; the classes will still work with the GNU runtime, they will just
1579 llvm::StructType *ClassTy = llvm::StructType::get(
1581 PtrToInt8Ty, // super_class
1582 PtrToInt8Ty, // name
1585 LongTy, // instance_size
1586 IVars->getType(), // ivars
1587 Methods->getType(), // methods
1588 // These are all filled in by the runtime, so we pretend
1590 PtrTy, // subclass_list
1591 PtrTy, // sibling_class
1593 PtrTy, // gc_object_type
1595 LongTy, // abi_version
1596 IvarOffsets->getType(), // ivar_offsets
1597 Properties->getType(), // properties
1598 IntPtrTy, // strong_pointers
1599 IntPtrTy, // weak_pointers
1601 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1602 // Fill in the structure
1603 std::vector<llvm::Constant*> Elements;
1604 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1605 Elements.push_back(SuperClass);
1606 Elements.push_back(MakeConstantString(Name, ".class_name"));
1607 Elements.push_back(Zero);
1608 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1610 llvm::DataLayout td(&TheModule);
1612 llvm::ConstantInt::get(LongTy,
1613 td.getTypeSizeInBits(ClassTy) /
1614 CGM.getContext().getCharWidth()));
1616 Elements.push_back(InstanceSize);
1617 Elements.push_back(IVars);
1618 Elements.push_back(Methods);
1619 Elements.push_back(NULLPtr);
1620 Elements.push_back(NULLPtr);
1621 Elements.push_back(NULLPtr);
1622 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1623 Elements.push_back(NULLPtr);
1624 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
1625 Elements.push_back(IvarOffsets);
1626 Elements.push_back(Properties);
1627 Elements.push_back(StrongIvarBitmap);
1628 Elements.push_back(WeakIvarBitmap);
1629 // Create an instance of the structure
1630 // This is now an externally visible symbol, so that we can speed up class
1631 // messages in the next ABI. We may already have some weak references to
1632 // this, so check and fix them properly.
1633 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1635 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1636 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1637 llvm::GlobalValue::ExternalLinkage);
1639 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1640 ClassRef->getType()));
1641 ClassRef->removeFromParent();
1642 Class->setName(ClassSym);
1647 llvm::Constant *CGObjCGNU::
1648 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1649 ArrayRef<llvm::Constant *> MethodTypes) {
1650 // Get the method structure type.
1651 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1652 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1655 std::vector<llvm::Constant*> Methods;
1656 std::vector<llvm::Constant*> Elements;
1657 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1659 Elements.push_back(MethodNames[i]);
1660 Elements.push_back(MethodTypes[i]);
1661 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
1663 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1664 MethodNames.size());
1665 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1667 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1668 IntTy, ObjCMethodArrayTy, NULL);
1670 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1671 Methods.push_back(Array);
1672 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1675 // Create the protocol list structure used in classes, categories and so on
1676 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
1677 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1679 llvm::StructType *ProtocolListTy = llvm::StructType::get(
1680 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1684 std::vector<llvm::Constant*> Elements;
1685 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1686 iter != endIter ; iter++) {
1687 llvm::Constant *protocol = 0;
1688 llvm::StringMap<llvm::Constant*>::iterator value =
1689 ExistingProtocols.find(*iter);
1690 if (value == ExistingProtocols.end()) {
1691 protocol = GenerateEmptyProtocol(*iter);
1693 protocol = value->getValue();
1695 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1697 Elements.push_back(Ptr);
1699 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1702 Elements.push_back(NULLPtr);
1703 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1704 Elements.push_back(ProtocolArray);
1705 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1708 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1709 const ObjCProtocolDecl *PD) {
1710 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1712 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1713 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1716 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1717 const std::string &ProtocolName) {
1718 SmallVector<std::string, 0> EmptyStringVector;
1719 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1721 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1722 llvm::Constant *MethodList =
1723 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1724 // Protocols are objects containing lists of the methods implemented and
1725 // protocols adopted.
1726 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1728 ProtocolList->getType(),
1729 MethodList->getType(),
1730 MethodList->getType(),
1731 MethodList->getType(),
1732 MethodList->getType(),
1734 std::vector<llvm::Constant*> Elements;
1735 // The isa pointer must be set to a magic number so the runtime knows it's
1736 // the correct layout.
1737 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1738 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1739 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1740 Elements.push_back(ProtocolList);
1741 Elements.push_back(MethodList);
1742 Elements.push_back(MethodList);
1743 Elements.push_back(MethodList);
1744 Elements.push_back(MethodList);
1745 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1748 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1749 ASTContext &Context = CGM.getContext();
1750 std::string ProtocolName = PD->getNameAsString();
1752 // Use the protocol definition, if there is one.
1753 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1756 SmallVector<std::string, 16> Protocols;
1757 for (const auto *PI : PD->protocols())
1758 Protocols.push_back(PI->getNameAsString());
1759 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1760 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1761 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1762 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1763 for (const auto *I : PD->instance_methods()) {
1764 std::string TypeStr;
1765 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1766 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1767 OptionalInstanceMethodNames.push_back(
1768 MakeConstantString(I->getSelector().getAsString()));
1769 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1771 InstanceMethodNames.push_back(
1772 MakeConstantString(I->getSelector().getAsString()));
1773 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1776 // Collect information about class methods:
1777 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1778 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1779 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1780 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1781 for (const auto *I : PD->class_methods()) {
1782 std::string TypeStr;
1783 Context.getObjCEncodingForMethodDecl(I,TypeStr);
1784 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1785 OptionalClassMethodNames.push_back(
1786 MakeConstantString(I->getSelector().getAsString()));
1787 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1789 ClassMethodNames.push_back(
1790 MakeConstantString(I->getSelector().getAsString()));
1791 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1795 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1796 llvm::Constant *InstanceMethodList =
1797 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1798 llvm::Constant *ClassMethodList =
1799 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1800 llvm::Constant *OptionalInstanceMethodList =
1801 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1802 OptionalInstanceMethodTypes);
1803 llvm::Constant *OptionalClassMethodList =
1804 GenerateProtocolMethodList(OptionalClassMethodNames,
1805 OptionalClassMethodTypes);
1807 // Property metadata: name, attributes, isSynthesized, setter name, setter
1808 // types, getter name, getter types.
1809 // The isSynthesized value is always set to 0 in a protocol. It exists to
1810 // simplify the runtime library by allowing it to use the same data
1811 // structures for protocol metadata everywhere.
1812 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1813 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1814 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
1815 std::vector<llvm::Constant*> Properties;
1816 std::vector<llvm::Constant*> OptionalProperties;
1818 // Add all of the property methods need adding to the method list and to the
1819 // property metadata list.
1820 for (auto *property : PD->properties()) {
1821 std::vector<llvm::Constant*> Fields;
1823 Fields.push_back(MakePropertyEncodingString(property, 0));
1824 PushPropertyAttributes(Fields, property);
1826 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1827 std::string TypeStr;
1828 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1829 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1830 InstanceMethodTypes.push_back(TypeEncoding);
1831 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1832 Fields.push_back(TypeEncoding);
1834 Fields.push_back(NULLPtr);
1835 Fields.push_back(NULLPtr);
1837 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1838 std::string TypeStr;
1839 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1840 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1841 InstanceMethodTypes.push_back(TypeEncoding);
1842 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1843 Fields.push_back(TypeEncoding);
1845 Fields.push_back(NULLPtr);
1846 Fields.push_back(NULLPtr);
1848 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1849 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1851 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1854 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1855 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1856 llvm::Constant* PropertyListInitFields[] =
1857 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1859 llvm::Constant *PropertyListInit =
1860 llvm::ConstantStruct::getAnon(PropertyListInitFields);
1861 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1862 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1863 PropertyListInit, ".objc_property_list");
1865 llvm::Constant *OptionalPropertyArray =
1866 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1867 OptionalProperties.size()) , OptionalProperties);
1868 llvm::Constant* OptionalPropertyListInitFields[] = {
1869 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1870 OptionalPropertyArray };
1872 llvm::Constant *OptionalPropertyListInit =
1873 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1874 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1875 OptionalPropertyListInit->getType(), false,
1876 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1877 ".objc_property_list");
1879 // Protocols are objects containing lists of the methods implemented and
1880 // protocols adopted.
1881 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1883 ProtocolList->getType(),
1884 InstanceMethodList->getType(),
1885 ClassMethodList->getType(),
1886 OptionalInstanceMethodList->getType(),
1887 OptionalClassMethodList->getType(),
1888 PropertyList->getType(),
1889 OptionalPropertyList->getType(),
1891 std::vector<llvm::Constant*> Elements;
1892 // The isa pointer must be set to a magic number so the runtime knows it's
1893 // the correct layout.
1894 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1895 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1896 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1897 Elements.push_back(ProtocolList);
1898 Elements.push_back(InstanceMethodList);
1899 Elements.push_back(ClassMethodList);
1900 Elements.push_back(OptionalInstanceMethodList);
1901 Elements.push_back(OptionalClassMethodList);
1902 Elements.push_back(PropertyList);
1903 Elements.push_back(OptionalPropertyList);
1904 ExistingProtocols[ProtocolName] =
1905 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1906 ".objc_protocol"), IdTy);
1908 void CGObjCGNU::GenerateProtocolHolderCategory() {
1909 // Collect information about instance methods
1910 SmallVector<Selector, 1> MethodSels;
1911 SmallVector<llvm::Constant*, 1> MethodTypes;
1913 std::vector<llvm::Constant*> Elements;
1914 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1915 const std::string CategoryName = "AnotherHack";
1916 Elements.push_back(MakeConstantString(CategoryName));
1917 Elements.push_back(MakeConstantString(ClassName));
1918 // Instance method list
1919 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1920 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1921 // Class method list
1922 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1923 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1925 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1926 ExistingProtocols.size());
1927 llvm::StructType *ProtocolListTy = llvm::StructType::get(
1928 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1932 std::vector<llvm::Constant*> ProtocolElements;
1933 for (llvm::StringMapIterator<llvm::Constant*> iter =
1934 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1935 iter != endIter ; iter++) {
1936 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1938 ProtocolElements.push_back(Ptr);
1940 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1942 ProtocolElements.clear();
1943 ProtocolElements.push_back(NULLPtr);
1944 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1945 ExistingProtocols.size()));
1946 ProtocolElements.push_back(ProtocolArray);
1947 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1948 ProtocolElements, ".objc_protocol_list"), PtrTy));
1949 Categories.push_back(llvm::ConstantExpr::getBitCast(
1950 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1951 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1954 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1955 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1956 /// bits set to their values, LSB first, while larger ones are stored in a
1957 /// structure of this / form:
1959 /// struct { int32_t length; int32_t values[length]; };
1961 /// The values in the array are stored in host-endian format, with the least
1962 /// significant bit being assumed to come first in the bitfield. Therefore, a
1963 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1964 /// bitfield / with the 63rd bit set will be 1<<64.
1965 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1966 int bitCount = bits.size();
1967 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1968 if (bitCount < ptrBits) {
1970 for (int i=0 ; i<bitCount ; ++i) {
1971 if (bits[i]) val |= 1ULL<<(i+1);
1973 return llvm::ConstantInt::get(IntPtrTy, val);
1975 SmallVector<llvm::Constant *, 8> values;
1977 while (v < bitCount) {
1979 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1980 if (bits[v]) word |= 1<<i;
1983 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1985 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1986 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1987 llvm::Constant *fields[2] = {
1988 llvm::ConstantInt::get(Int32Ty, values.size()),
1990 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1992 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
1996 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1997 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1998 std::string CategoryName = OCD->getNameAsString();
1999 // Collect information about instance methods
2000 SmallVector<Selector, 16> InstanceMethodSels;
2001 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2002 for (const auto *I : OCD->instance_methods()) {
2003 InstanceMethodSels.push_back(I->getSelector());
2004 std::string TypeStr;
2005 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2006 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2009 // Collect information about class methods
2010 SmallVector<Selector, 16> ClassMethodSels;
2011 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2012 for (const auto *I : OCD->class_methods()) {
2013 ClassMethodSels.push_back(I->getSelector());
2014 std::string TypeStr;
2015 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2016 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2019 // Collect the names of referenced protocols
2020 SmallVector<std::string, 16> Protocols;
2021 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2022 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2023 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2024 E = Protos.end(); I != E; ++I)
2025 Protocols.push_back((*I)->getNameAsString());
2027 std::vector<llvm::Constant*> Elements;
2028 Elements.push_back(MakeConstantString(CategoryName));
2029 Elements.push_back(MakeConstantString(ClassName));
2030 // Instance method list
2031 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2032 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
2034 // Class method list
2035 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2036 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
2039 Elements.push_back(llvm::ConstantExpr::getBitCast(
2040 GenerateProtocolList(Protocols), PtrTy));
2041 Categories.push_back(llvm::ConstantExpr::getBitCast(
2042 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
2043 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
2046 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2047 SmallVectorImpl<Selector> &InstanceMethodSels,
2048 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2049 ASTContext &Context = CGM.getContext();
2050 // Property metadata: name, attributes, attributes2, padding1, padding2,
2051 // setter name, setter types, getter name, getter types.
2052 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
2053 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2054 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
2055 std::vector<llvm::Constant*> Properties;
2057 // Add all of the property methods need adding to the method list and to the
2058 // property metadata list.
2059 for (auto *propertyImpl : OID->property_impls()) {
2060 std::vector<llvm::Constant*> Fields;
2061 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2062 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2063 ObjCPropertyImplDecl::Synthesize);
2064 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2065 ObjCPropertyImplDecl::Dynamic);
2067 Fields.push_back(MakePropertyEncodingString(property, OID));
2068 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
2069 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2070 std::string TypeStr;
2071 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2072 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2073 if (isSynthesized) {
2074 InstanceMethodTypes.push_back(TypeEncoding);
2075 InstanceMethodSels.push_back(getter->getSelector());
2077 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2078 Fields.push_back(TypeEncoding);
2080 Fields.push_back(NULLPtr);
2081 Fields.push_back(NULLPtr);
2083 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2084 std::string TypeStr;
2085 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2086 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2087 if (isSynthesized) {
2088 InstanceMethodTypes.push_back(TypeEncoding);
2089 InstanceMethodSels.push_back(setter->getSelector());
2091 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2092 Fields.push_back(TypeEncoding);
2094 Fields.push_back(NULLPtr);
2095 Fields.push_back(NULLPtr);
2097 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2099 llvm::ArrayType *PropertyArrayTy =
2100 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2101 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2103 llvm::Constant* PropertyListInitFields[] =
2104 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2106 llvm::Constant *PropertyListInit =
2107 llvm::ConstantStruct::getAnon(PropertyListInitFields);
2108 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2109 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2110 ".objc_property_list");
2113 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2114 // Get the class declaration for which the alias is specified.
2115 ObjCInterfaceDecl *ClassDecl =
2116 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2117 std::string ClassName = ClassDecl->getNameAsString();
2118 std::string AliasName = OAD->getNameAsString();
2119 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2122 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2123 ASTContext &Context = CGM.getContext();
2125 // Get the superclass name.
2126 const ObjCInterfaceDecl * SuperClassDecl =
2127 OID->getClassInterface()->getSuperClass();
2128 std::string SuperClassName;
2129 if (SuperClassDecl) {
2130 SuperClassName = SuperClassDecl->getNameAsString();
2131 EmitClassRef(SuperClassName);
2134 // Get the class name
2135 ObjCInterfaceDecl *ClassDecl =
2136 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2137 std::string ClassName = ClassDecl->getNameAsString();
2138 // Emit the symbol that is used to generate linker errors if this class is
2139 // referenced in other modules but not declared.
2140 std::string classSymbolName = "__objc_class_name_" + ClassName;
2141 if (llvm::GlobalVariable *symbol =
2142 TheModule.getGlobalVariable(classSymbolName)) {
2143 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2145 new llvm::GlobalVariable(TheModule, LongTy, false,
2146 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
2150 // Get the size of instances.
2152 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2154 // Collect information about instance variables.
2155 SmallVector<llvm::Constant*, 16> IvarNames;
2156 SmallVector<llvm::Constant*, 16> IvarTypes;
2157 SmallVector<llvm::Constant*, 16> IvarOffsets;
2159 std::vector<llvm::Constant*> IvarOffsetValues;
2160 SmallVector<bool, 16> WeakIvars;
2161 SmallVector<bool, 16> StrongIvars;
2163 int superInstanceSize = !SuperClassDecl ? 0 :
2164 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2165 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2166 // class}. The runtime will then set this to the correct value on load.
2167 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2168 instanceSize = 0 - (instanceSize - superInstanceSize);
2171 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2172 IVD = IVD->getNextIvar()) {
2174 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2175 // Get the type encoding for this ivar
2176 std::string TypeStr;
2177 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2178 IvarTypes.push_back(MakeConstantString(TypeStr));
2180 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2181 uint64_t Offset = BaseOffset;
2182 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2183 Offset = BaseOffset - superInstanceSize;
2185 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2186 // Create the direct offset value
2187 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2188 IVD->getNameAsString();
2189 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2191 OffsetVar->setInitializer(OffsetValue);
2192 // If this is the real definition, change its linkage type so that
2193 // different modules will use this one, rather than their private
2195 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2197 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2198 false, llvm::GlobalValue::ExternalLinkage,
2200 "__objc_ivar_offset_value_" + ClassName +"." +
2201 IVD->getNameAsString());
2202 IvarOffsets.push_back(OffsetValue);
2203 IvarOffsetValues.push_back(OffsetVar);
2204 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2206 case Qualifiers::OCL_Strong:
2207 StrongIvars.push_back(true);
2208 WeakIvars.push_back(false);
2210 case Qualifiers::OCL_Weak:
2211 StrongIvars.push_back(false);
2212 WeakIvars.push_back(true);
2215 StrongIvars.push_back(false);
2216 WeakIvars.push_back(false);
2219 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2220 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2221 llvm::GlobalVariable *IvarOffsetArray =
2222 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2225 // Collect information about instance methods
2226 SmallVector<Selector, 16> InstanceMethodSels;
2227 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2228 for (const auto *I : OID->instance_methods()) {
2229 InstanceMethodSels.push_back(I->getSelector());
2230 std::string TypeStr;
2231 Context.getObjCEncodingForMethodDecl(I,TypeStr);
2232 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2235 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2236 InstanceMethodTypes);
2239 // Collect information about class methods
2240 SmallVector<Selector, 16> ClassMethodSels;
2241 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2242 for (const auto *I : OID->class_methods()) {
2243 ClassMethodSels.push_back(I->getSelector());
2244 std::string TypeStr;
2245 Context.getObjCEncodingForMethodDecl(I,TypeStr);
2246 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2248 // Collect the names of referenced protocols
2249 SmallVector<std::string, 16> Protocols;
2250 for (const auto *I : ClassDecl->protocols())
2251 Protocols.push_back(I->getNameAsString());
2253 // Get the superclass pointer.
2254 llvm::Constant *SuperClass;
2255 if (!SuperClassName.empty()) {
2256 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2258 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2260 // Empty vector used to construct empty method lists
2261 SmallVector<llvm::Constant*, 1> empty;
2262 // Generate the method and instance variable lists
2263 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2264 InstanceMethodSels, InstanceMethodTypes, false);
2265 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2266 ClassMethodSels, ClassMethodTypes, true);
2267 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2269 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2270 // we emit a symbol containing the offset for each ivar in the class. This
2271 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2272 // for the legacy ABI, without causing problems. The converse is also
2273 // possible, but causes all ivar accesses to be fragile.
2275 // Offset pointer for getting at the correct field in the ivar list when
2276 // setting up the alias. These are: The base address for the global, the
2277 // ivar array (second field), the ivar in this list (set for each ivar), and
2278 // the offset (third field in ivar structure)
2279 llvm::Type *IndexTy = Int32Ty;
2280 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2281 llvm::ConstantInt::get(IndexTy, 1), 0,
2282 llvm::ConstantInt::get(IndexTy, 2) };
2284 unsigned ivarIndex = 0;
2285 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2286 IVD = IVD->getNextIvar()) {
2287 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2288 + IVD->getNameAsString();
2289 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2290 // Get the correct ivar field
2291 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2292 IvarList, offsetPointerIndexes);
2293 // Get the existing variable, if one exists.
2294 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2296 offset->setInitializer(offsetValue);
2297 // If this is the real definition, change its linkage type so that
2298 // different modules will use this one, rather than their private
2300 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2302 // Add a new alias if there isn't one already.
2303 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2304 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2305 (void) offset; // Silence dead store warning.
2309 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2310 //Generate metaclass for class methods
2311 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
2312 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
2313 empty, empty, empty), ClassMethodList, NULLPtr,
2314 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
2316 // Generate the class structure
2317 llvm::Constant *ClassStruct =
2318 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
2319 ClassName.c_str(), 0,
2320 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
2321 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2322 Properties, StrongIvarBitmap, WeakIvarBitmap);
2324 // Resolve the class aliases, if they exist.
2325 if (ClassPtrAlias) {
2326 ClassPtrAlias->replaceAllUsesWith(
2327 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2328 ClassPtrAlias->eraseFromParent();
2331 if (MetaClassPtrAlias) {
2332 MetaClassPtrAlias->replaceAllUsesWith(
2333 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2334 MetaClassPtrAlias->eraseFromParent();
2335 MetaClassPtrAlias = 0;
2338 // Add class structure to list to be added to the symtab later
2339 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2340 Classes.push_back(ClassStruct);
2344 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2345 // Only emit an ObjC load function if no Objective-C stuff has been called
2346 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2347 ExistingProtocols.empty() && SelectorTable.empty())
2350 // Add all referenced protocols to a category.
2351 GenerateProtocolHolderCategory();
2353 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2354 SelectorTy->getElementType());
2355 llvm::Type *SelStructPtrTy = SelectorTy;
2356 if (SelStructTy == 0) {
2357 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
2358 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2361 std::vector<llvm::Constant*> Elements;
2362 llvm::Constant *Statics = NULLPtr;
2363 // Generate statics list:
2364 if (ConstantStrings.size()) {
2365 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2366 ConstantStrings.size() + 1);
2367 ConstantStrings.push_back(NULLPtr);
2369 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2371 if (StringClass.empty()) StringClass = "NXConstantString";
2373 Elements.push_back(MakeConstantString(StringClass,
2374 ".objc_static_class_name"));
2375 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2377 llvm::StructType *StaticsListTy =
2378 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
2379 llvm::Type *StaticsListPtrTy =
2380 llvm::PointerType::getUnqual(StaticsListTy);
2381 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
2382 llvm::ArrayType *StaticsListArrayTy =
2383 llvm::ArrayType::get(StaticsListPtrTy, 2);
2385 Elements.push_back(Statics);
2386 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2387 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
2388 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2390 // Array of classes, categories, and constant objects
2391 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2392 Classes.size() + Categories.size() + 2);
2393 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2394 llvm::Type::getInt16Ty(VMContext),
2395 llvm::Type::getInt16Ty(VMContext),
2399 // Pointer to an array of selectors used in this module.
2400 std::vector<llvm::Constant*> Selectors;
2401 std::vector<llvm::GlobalAlias*> SelectorAliases;
2402 for (SelectorMap::iterator iter = SelectorTable.begin(),
2403 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2405 std::string SelNameStr = iter->first.getAsString();
2406 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2408 SmallVectorImpl<TypedSelector> &Types = iter->second;
2409 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2410 e = Types.end() ; i!=e ; i++) {
2412 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2413 if (!i->first.empty())
2414 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2416 Elements.push_back(SelName);
2417 Elements.push_back(SelectorTypeEncoding);
2418 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2421 // Store the selector alias for later replacement
2422 SelectorAliases.push_back(i->second);
2425 unsigned SelectorCount = Selectors.size();
2426 // NULL-terminate the selector list. This should not actually be required,
2427 // because the selector list has a length field. Unfortunately, the GCC
2428 // runtime decides to ignore the length field and expects a NULL terminator,
2429 // and GCC cooperates with this by always setting the length to 0.
2430 Elements.push_back(NULLPtr);
2431 Elements.push_back(NULLPtr);
2432 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2435 // Number of static selectors
2436 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2437 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
2438 ".objc_selector_list");
2439 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2442 // Now that all of the static selectors exist, create pointers to them.
2443 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2445 llvm::Constant *Idxs[] = {Zeros[0],
2446 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
2447 // FIXME: We're generating redundant loads and stores here!
2448 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2449 makeArrayRef(Idxs, 2));
2450 // If selectors are defined as an opaque type, cast the pointer to this
2452 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2453 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2454 SelectorAliases[i]->eraseFromParent();
2457 // Number of classes defined.
2458 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2460 // Number of categories defined
2461 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2462 Categories.size()));
2463 // Create an array of classes, then categories, then static object instances
2464 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2465 // NULL-terminated list of static object instances (mainly constant strings)
2466 Classes.push_back(Statics);
2467 Classes.push_back(NULLPtr);
2468 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2469 Elements.push_back(ClassList);
2470 // Construct the symbol table
2471 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2473 // The symbol table is contained in a module which has some version-checking
2475 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2476 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2477 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
2479 // Runtime version, used for ABI compatibility checking.
2480 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2482 llvm::DataLayout td(&TheModule);
2484 llvm::ConstantInt::get(LongTy,
2485 td.getTypeSizeInBits(ModuleTy) /
2486 CGM.getContext().getCharWidth()));
2488 // The path to the source file where this module was declared
2489 SourceManager &SM = CGM.getContext().getSourceManager();
2490 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2492 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2493 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2494 Elements.push_back(SymTab);
2496 if (RuntimeVersion >= 10)
2497 switch (CGM.getLangOpts().getGC()) {
2498 case LangOptions::GCOnly:
2499 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2501 case LangOptions::NonGC:
2502 if (CGM.getLangOpts().ObjCAutoRefCount)
2503 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2505 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2507 case LangOptions::HybridGC:
2508 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2512 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2514 // Create the load function calling the runtime entry point with the module
2516 llvm::Function * LoadFunction = llvm::Function::Create(
2517 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2518 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2520 llvm::BasicBlock *EntryBB =
2521 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2522 CGBuilderTy Builder(VMContext);
2523 Builder.SetInsertPoint(EntryBB);
2525 llvm::FunctionType *FT =
2526 llvm::FunctionType::get(Builder.getVoidTy(),
2527 llvm::PointerType::getUnqual(ModuleTy), true);
2528 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2529 Builder.CreateCall(Register, Module);
2531 if (!ClassAliases.empty()) {
2532 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2533 llvm::FunctionType *RegisterAliasTy =
2534 llvm::FunctionType::get(Builder.getVoidTy(),
2536 llvm::Function *RegisterAlias = llvm::Function::Create(
2538 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2540 llvm::BasicBlock *AliasBB =
2541 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2542 llvm::BasicBlock *NoAliasBB =
2543 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2545 // Branch based on whether the runtime provided class_registerAlias_np()
2546 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2547 llvm::Constant::getNullValue(RegisterAlias->getType()));
2548 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2550 // The true branch (has alias registration function):
2551 Builder.SetInsertPoint(AliasBB);
2552 // Emit alias registration calls:
2553 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2554 iter != ClassAliases.end(); ++iter) {
2555 llvm::Constant *TheClass =
2556 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2558 if (0 != TheClass) {
2559 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2560 Builder.CreateCall2(RegisterAlias, TheClass,
2561 MakeConstantString(iter->second));
2565 Builder.CreateBr(NoAliasBB);
2567 // Missing alias registration function, just return from the function:
2568 Builder.SetInsertPoint(NoAliasBB);
2570 Builder.CreateRetVoid();
2572 return LoadFunction;
2575 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2576 const ObjCContainerDecl *CD) {
2577 const ObjCCategoryImplDecl *OCD =
2578 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2579 StringRef CategoryName = OCD ? OCD->getName() : "";
2580 StringRef ClassName = CD->getName();
2581 Selector MethodName = OMD->getSelector();
2582 bool isClassMethod = !OMD->isInstanceMethod();
2584 CodeGenTypes &Types = CGM.getTypes();
2585 llvm::FunctionType *MethodTy =
2586 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2587 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2588 MethodName, isClassMethod);
2590 llvm::Function *Method
2591 = llvm::Function::Create(MethodTy,
2592 llvm::GlobalValue::InternalLinkage,
2598 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2599 return GetPropertyFn;
2602 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2603 return SetPropertyFn;
2606 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2611 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2612 return GetStructPropertyFn;
2614 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2615 return SetStructPropertyFn;
2617 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2620 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2624 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2625 return EnumerationMutationFn;
2628 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2629 const ObjCAtSynchronizedStmt &S) {
2630 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2634 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2635 const ObjCAtTryStmt &S) {
2636 // Unlike the Apple non-fragile runtimes, which also uses
2637 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2638 // EH support isn't a veneer over C++ EH. Instead, exception
2639 // objects are created by objc_exception_throw and destroyed by
2640 // the personality function; this avoids the need for bracketing
2641 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2642 // (or even _Unwind_DeleteException), but probably doesn't
2643 // interoperate very well with foreign exceptions.
2645 // In Objective-C++ mode, we actually emit something equivalent to the C++
2646 // exception handler.
2647 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2651 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2652 const ObjCAtThrowStmt &S,
2653 bool ClearInsertionPoint) {
2654 llvm::Value *ExceptionAsObject;
2656 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2657 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2658 ExceptionAsObject = Exception;
2660 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2661 "Unexpected rethrow outside @catch block.");
2662 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2664 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2665 llvm::CallSite Throw =
2666 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2667 Throw.setDoesNotReturn();
2668 CGF.Builder.CreateUnreachable();
2669 if (ClearInsertionPoint)
2670 CGF.Builder.ClearInsertionPoint();
2673 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2674 llvm::Value *AddrWeakObj) {
2675 CGBuilderTy &B = CGF.Builder;
2676 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2677 return B.CreateCall(WeakReadFn, AddrWeakObj);
2680 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2681 llvm::Value *src, llvm::Value *dst) {
2682 CGBuilderTy &B = CGF.Builder;
2683 src = EnforceType(B, src, IdTy);
2684 dst = EnforceType(B, dst, PtrToIdTy);
2685 B.CreateCall2(WeakAssignFn, src, dst);
2688 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2689 llvm::Value *src, llvm::Value *dst,
2691 CGBuilderTy &B = CGF.Builder;
2692 src = EnforceType(B, src, IdTy);
2693 dst = EnforceType(B, dst, PtrToIdTy);
2695 B.CreateCall2(GlobalAssignFn, src, dst);
2697 // FIXME. Add threadloca assign API
2698 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
2701 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2702 llvm::Value *src, llvm::Value *dst,
2703 llvm::Value *ivarOffset) {
2704 CGBuilderTy &B = CGF.Builder;
2705 src = EnforceType(B, src, IdTy);
2706 dst = EnforceType(B, dst, IdTy);
2707 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
2710 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2711 llvm::Value *src, llvm::Value *dst) {
2712 CGBuilderTy &B = CGF.Builder;
2713 src = EnforceType(B, src, IdTy);
2714 dst = EnforceType(B, dst, PtrToIdTy);
2715 B.CreateCall2(StrongCastAssignFn, src, dst);
2718 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2719 llvm::Value *DestPtr,
2720 llvm::Value *SrcPtr,
2721 llvm::Value *Size) {
2722 CGBuilderTy &B = CGF.Builder;
2723 DestPtr = EnforceType(B, DestPtr, PtrTy);
2724 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2726 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
2729 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2730 const ObjCInterfaceDecl *ID,
2731 const ObjCIvarDecl *Ivar) {
2732 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2733 + '.' + Ivar->getNameAsString();
2734 // Emit the variable and initialize it with what we think the correct value
2735 // is. This allows code compiled with non-fragile ivars to work correctly
2736 // when linked against code which isn't (most of the time).
2737 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2738 if (!IvarOffsetPointer) {
2739 // This will cause a run-time crash if we accidentally use it. A value of
2740 // 0 would seem more sensible, but will silently overwrite the isa pointer
2741 // causing a great deal of confusion.
2742 uint64_t Offset = -1;
2743 // We can't call ComputeIvarBaseOffset() here if we have the
2744 // implementation, because it will create an invalid ASTRecordLayout object
2745 // that we are then stuck with forever, so we only initialize the ivar
2746 // offset variable with a guess if we only have the interface. The
2747 // initializer will be reset later anyway, when we are generating the class
2749 if (!CGM.getContext().getObjCImplementation(
2750 const_cast<ObjCInterfaceDecl *>(ID)))
2751 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2753 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2755 // Don't emit the guess in non-PIC code because the linker will not be able
2756 // to replace it with the real version for a library. In non-PIC code you
2757 // must compile with the fragile ABI if you want to use ivars from a
2758 // GCC-compiled class.
2759 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
2760 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2762 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2763 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2764 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2765 IvarOffsetGV, Name);
2767 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2768 llvm::Type::getInt32PtrTy(VMContext), false,
2769 llvm::GlobalValue::ExternalLinkage, 0, Name);
2772 return IvarOffsetPointer;
2775 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2777 llvm::Value *BaseValue,
2778 const ObjCIvarDecl *Ivar,
2779 unsigned CVRQualifiers) {
2780 const ObjCInterfaceDecl *ID =
2781 ObjectTy->getAs<ObjCObjectType>()->getInterface();
2782 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2783 EmitIvarOffset(CGF, ID, Ivar));
2786 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2787 const ObjCInterfaceDecl *OID,
2788 const ObjCIvarDecl *OIVD) {
2789 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2790 next = next->getNextIvar()) {
2795 // Otherwise check in the super class.
2796 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2797 return FindIvarInterface(Context, Super, OIVD);
2802 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2803 const ObjCInterfaceDecl *Interface,
2804 const ObjCIvarDecl *Ivar) {
2805 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2806 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2807 if (RuntimeVersion < 10)
2808 return CGF.Builder.CreateZExtOrBitCast(
2809 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2810 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2812 std::string name = "__objc_ivar_offset_value_" +
2813 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2814 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2816 Offset = new llvm::GlobalVariable(TheModule, IntTy,
2817 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2818 llvm::Constant::getNullValue(IntTy), name);
2819 Offset = CGF.Builder.CreateLoad(Offset);
2820 if (Offset->getType() != PtrDiffTy)
2821 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2824 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2825 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2829 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2830 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2831 case ObjCRuntime::GNUstep:
2832 return new CGObjCGNUstep(CGM);
2834 case ObjCRuntime::GCC:
2835 return new CGObjCGCC(CGM);
2837 case ObjCRuntime::ObjFW:
2838 return new CGObjCObjFW(CGM);
2840 case ObjCRuntime::FragileMacOSX:
2841 case ObjCRuntime::MacOSX:
2842 case ObjCRuntime::iOS:
2843 llvm_unreachable("these runtimes are not GNU runtimes");
2845 llvm_unreachable("bad runtime");