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 "ConstantBuilder.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Support/Compiler.h"
39 using namespace clang;
40 using namespace CodeGen;
43 /// Class that lazily initialises the runtime function. Avoids inserting the
44 /// types and the function declaration into a module if they're not used, and
45 /// avoids constructing the type more than once if it's used more than once.
46 class LazyRuntimeFunction {
48 llvm::FunctionType *FTy;
49 const char *FunctionName;
50 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.
57 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
59 /// Initialises the lazy function with the name, return type, and the types
62 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
66 std::vector<llvm::Type *> ArgTys;
68 va_start(Args, RetTy);
69 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
70 ArgTys.push_back(ArgTy);
72 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
75 llvm::FunctionType *getType() { return FTy; }
77 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 operator llvm::Constant *() {
84 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
88 operator llvm::Function *() {
89 return cast<llvm::Function>((llvm::Constant *)*this);
94 /// GNU Objective-C runtime code generation. This class implements the parts of
95 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
96 /// GNUstep and ObjFW).
97 class CGObjCGNU : public CGObjCRuntime {
99 /// The LLVM module into which output is inserted
100 llvm::Module &TheModule;
101 /// strut objc_super. Used for sending messages to super. This structure
102 /// contains the receiver (object) and the expected class.
103 llvm::StructType *ObjCSuperTy;
104 /// struct objc_super*. The type of the argument to the superclass message
105 /// lookup functions.
106 llvm::PointerType *PtrToObjCSuperTy;
107 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
108 /// SEL is included in a header somewhere, in which case it will be whatever
109 /// type is declared in that header, most likely {i8*, i8*}.
110 llvm::PointerType *SelectorTy;
111 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
112 /// places where it's used
113 llvm::IntegerType *Int8Ty;
114 /// Pointer to i8 - LLVM type of char*, for all of the places where the
115 /// runtime needs to deal with C strings.
116 llvm::PointerType *PtrToInt8Ty;
117 /// Instance Method Pointer type. This is a pointer to a function that takes,
118 /// at a minimum, an object and a selector, and is the generic type for
119 /// Objective-C methods. Due to differences between variadic / non-variadic
120 /// calling conventions, it must always be cast to the correct type before
121 /// actually being used.
122 llvm::PointerType *IMPTy;
123 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
124 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
125 /// but if the runtime header declaring it is included then it may be a
126 /// pointer to a structure.
127 llvm::PointerType *IdTy;
128 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
129 /// message lookup function and some GC-related functions.
130 llvm::PointerType *PtrToIdTy;
131 /// The clang type of id. Used when using the clang CGCall infrastructure to
132 /// call Objective-C methods.
134 /// LLVM type for C int type.
135 llvm::IntegerType *IntTy;
136 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
137 /// used in the code to document the difference between i8* meaning a pointer
138 /// to a C string and i8* meaning a pointer to some opaque type.
139 llvm::PointerType *PtrTy;
140 /// LLVM type for C long type. The runtime uses this in a lot of places where
141 /// it should be using intptr_t, but we can't fix this without breaking
142 /// compatibility with GCC...
143 llvm::IntegerType *LongTy;
144 /// LLVM type for C size_t. Used in various runtime data structures.
145 llvm::IntegerType *SizeTy;
146 /// LLVM type for C intptr_t.
147 llvm::IntegerType *IntPtrTy;
148 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
149 llvm::IntegerType *PtrDiffTy;
150 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
152 llvm::PointerType *PtrToIntTy;
153 /// LLVM type for Objective-C BOOL type.
155 /// 32-bit integer type, to save us needing to look it up every time it's used.
156 llvm::IntegerType *Int32Ty;
157 /// 64-bit integer type, to save us needing to look it up every time it's used.
158 llvm::IntegerType *Int64Ty;
159 /// Metadata kind used to tie method lookups to message sends. The GNUstep
160 /// runtime provides some LLVM passes that can use this to do things like
161 /// automatic IMP caching and speculative inlining.
162 unsigned msgSendMDKind;
164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
167 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
168 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
169 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
170 Array.getPointer(), Zeros);
173 /// Emits a linkonce_odr string, whose name is the prefix followed by the
174 /// string value. This allows the linker to combine the strings between
175 /// different modules. Used for EH typeinfo names, selector strings, and a
176 /// few other things.
177 llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
178 std::string Name = Prefix.str() + Str;
179 auto *ConstStr = TheModule.getGlobalVariable(Name);
181 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
182 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
183 llvm::GlobalValue::LinkOnceODRLinkage,
186 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
193 llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
196 llvm::GlobalValue::LinkageTypes linkage
197 =llvm::GlobalValue::InternalLinkage) {
198 auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
200 GV->setAlignment(Align.getQuantity());
204 /// Returns a property name and encoding string.
205 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
206 const Decl *Container) {
207 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
208 if ((R.getKind() == ObjCRuntime::GNUstep) &&
209 (R.getVersion() >= VersionTuple(1, 6))) {
210 std::string NameAndAttributes;
211 std::string TypeStr =
212 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
213 NameAndAttributes += '\0';
214 NameAndAttributes += TypeStr.length() + 3;
215 NameAndAttributes += TypeStr;
216 NameAndAttributes += '\0';
217 NameAndAttributes += PD->getNameAsString();
218 return MakeConstantString(NameAndAttributes);
220 return MakeConstantString(PD->getNameAsString());
223 /// Push the property attributes into two structure fields.
224 void PushPropertyAttributes(ConstantStructBuilder &Fields,
225 ObjCPropertyDecl *property, bool isSynthesized=true, bool
227 int attrs = property->getPropertyAttributes();
228 // For read-only properties, clear the copy and retain flags
229 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
230 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
231 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
232 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
233 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
235 // The first flags field has the same attribute values as clang uses internally
236 Fields.addInt(Int8Ty, attrs & 0xff);
239 // For protocol properties, synthesized and dynamic have no meaning, so we
240 // reuse these flags to indicate that this is a protocol property (both set
241 // has no meaning, as a property can't be both synthesized and dynamic)
242 attrs |= isSynthesized ? (1<<0) : 0;
243 attrs |= isDynamic ? (1<<1) : 0;
244 // The second field is the next four fields left shifted by two, with the
245 // low bit set to indicate whether the field is synthesized or dynamic.
246 Fields.addInt(Int8Ty, attrs & 0xff);
247 // Two padding fields
248 Fields.addInt(Int8Ty, 0);
249 Fields.addInt(Int8Ty, 0);
252 /// Ensures that the value has the required type, by inserting a bitcast if
253 /// required. This function lets us avoid inserting bitcasts that are
255 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
256 if (V->getType() == Ty) return V;
257 return B.CreateBitCast(V, Ty);
259 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
260 if (V.getType() == Ty) return V;
261 return B.CreateBitCast(V, Ty);
264 // Some zeros used for GEPs in lots of places.
265 llvm::Constant *Zeros[2];
266 /// Null pointer value. Mainly used as a terminator in various arrays.
267 llvm::Constant *NULLPtr;
269 llvm::LLVMContext &VMContext;
272 /// Placeholder for the class. Lots of things refer to the class before we've
273 /// actually emitted it. We use this alias as a placeholder, and then replace
274 /// it with a pointer to the class structure before finally emitting the
276 llvm::GlobalAlias *ClassPtrAlias;
277 /// Placeholder for the metaclass. Lots of things refer to the class before
278 /// we've / actually emitted it. We use this alias as a placeholder, and then
279 /// replace / it with a pointer to the metaclass structure before finally
280 /// emitting the / module.
281 llvm::GlobalAlias *MetaClassPtrAlias;
282 /// All of the classes that have been generated for this compilation units.
283 std::vector<llvm::Constant*> Classes;
284 /// All of the categories that have been generated for this compilation units.
285 std::vector<llvm::Constant*> Categories;
286 /// All of the Objective-C constant strings that have been generated for this
287 /// compilation units.
288 std::vector<llvm::Constant*> ConstantStrings;
289 /// Map from string values to Objective-C constant strings in the output.
290 /// Used to prevent emitting Objective-C strings more than once. This should
291 /// not be required at all - CodeGenModule should manage this list.
292 llvm::StringMap<llvm::Constant*> ObjCStrings;
293 /// All of the protocols that have been declared.
294 llvm::StringMap<llvm::Constant*> ExistingProtocols;
295 /// For each variant of a selector, we store the type encoding and a
296 /// placeholder value. For an untyped selector, the type will be the empty
297 /// string. Selector references are all done via the module's selector table,
298 /// so we create an alias as a placeholder and then replace it with the real
300 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
301 /// Type of the selector map. This is roughly equivalent to the structure
302 /// used in the GNUstep runtime, which maintains a list of all of the valid
303 /// types for a selector in a table.
304 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
306 /// A map from selectors to selector types. This allows us to emit all
307 /// selectors of the same name and type together.
308 SelectorMap SelectorTable;
310 /// Selectors related to memory management. When compiling in GC mode, we
312 Selector RetainSel, ReleaseSel, AutoreleaseSel;
313 /// Runtime functions used for memory management in GC mode. Note that clang
314 /// supports code generation for calling these functions, but neither GNU
315 /// runtime actually supports this API properly yet.
316 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
317 WeakAssignFn, GlobalAssignFn;
319 typedef std::pair<std::string, std::string> ClassAliasPair;
320 /// All classes that have aliases set for them.
321 std::vector<ClassAliasPair> ClassAliases;
324 /// Function used for throwing Objective-C exceptions.
325 LazyRuntimeFunction ExceptionThrowFn;
326 /// Function used for rethrowing exceptions, used at the end of \@finally or
327 /// \@synchronize blocks.
328 LazyRuntimeFunction ExceptionReThrowFn;
329 /// Function called when entering a catch function. This is required for
330 /// differentiating Objective-C exceptions and foreign exceptions.
331 LazyRuntimeFunction EnterCatchFn;
332 /// Function called when exiting from a catch block. Used to do exception
334 LazyRuntimeFunction ExitCatchFn;
335 /// Function called when entering an \@synchronize block. Acquires the lock.
336 LazyRuntimeFunction SyncEnterFn;
337 /// Function called when exiting an \@synchronize block. Releases the lock.
338 LazyRuntimeFunction SyncExitFn;
341 /// Function called if fast enumeration detects that the collection is
342 /// modified during the update.
343 LazyRuntimeFunction EnumerationMutationFn;
344 /// Function for implementing synthesized property getters that return an
346 LazyRuntimeFunction GetPropertyFn;
347 /// Function for implementing synthesized property setters that return an
349 LazyRuntimeFunction SetPropertyFn;
350 /// Function used for non-object declared property getters.
351 LazyRuntimeFunction GetStructPropertyFn;
352 /// Function used for non-object declared property setters.
353 LazyRuntimeFunction SetStructPropertyFn;
355 /// The version of the runtime that this class targets. Must match the
356 /// version in the runtime.
358 /// The version of the protocol class. Used to differentiate between ObjC1
359 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
360 /// components and can not contain declared properties. We always emit
361 /// Objective-C 2 property structures, but we have to pretend that they're
362 /// Objective-C 1 property structures when targeting the GCC runtime or it
364 const int ProtocolVersion;
366 /// Generates an instance variable list structure. This is a structure
367 /// containing a size and an array of structures containing instance variable
368 /// metadata. This is used purely for introspection in the fragile ABI. In
369 /// the non-fragile ABI, it's used for instance variable fixup.
370 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
371 ArrayRef<llvm::Constant *> IvarTypes,
372 ArrayRef<llvm::Constant *> IvarOffsets);
374 /// Generates a method list structure. This is a structure containing a size
375 /// and an array of structures containing method metadata.
377 /// This structure is used by both classes and categories, and contains a next
378 /// pointer allowing them to be chained together in a linked list.
379 llvm::Constant *GenerateMethodList(StringRef ClassName,
380 StringRef CategoryName,
381 ArrayRef<Selector> MethodSels,
382 ArrayRef<llvm::Constant *> MethodTypes,
383 bool isClassMethodList);
385 /// Emits an empty protocol. This is used for \@protocol() where no protocol
386 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
388 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
390 /// Generates a list of property metadata structures. This follows the same
391 /// pattern as method and instance variable metadata lists.
392 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
393 SmallVectorImpl<Selector> &InstanceMethodSels,
394 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
396 /// Generates a list of referenced protocols. Classes, categories, and
397 /// protocols all use this structure.
398 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
400 /// To ensure that all protocols are seen by the runtime, we add a category on
401 /// a class defined in the runtime, declaring no methods, but adopting the
402 /// protocols. This is a horribly ugly hack, but it allows us to collect all
403 /// of the protocols without changing the ABI.
404 void GenerateProtocolHolderCategory();
406 /// Generates a class structure.
407 llvm::Constant *GenerateClassStructure(
408 llvm::Constant *MetaClass,
409 llvm::Constant *SuperClass,
412 llvm::Constant *Version,
413 llvm::Constant *InstanceSize,
414 llvm::Constant *IVars,
415 llvm::Constant *Methods,
416 llvm::Constant *Protocols,
417 llvm::Constant *IvarOffsets,
418 llvm::Constant *Properties,
419 llvm::Constant *StrongIvarBitmap,
420 llvm::Constant *WeakIvarBitmap,
423 /// Generates a method list. This is used by protocols to define the required
424 /// and optional methods.
425 llvm::Constant *GenerateProtocolMethodList(
426 ArrayRef<llvm::Constant *> MethodNames,
427 ArrayRef<llvm::Constant *> MethodTypes);
429 /// Returns a selector with the specified type encoding. An empty string is
430 /// used to return an untyped selector (with the types field set to NULL).
431 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
432 const std::string &TypeEncoding);
434 /// Returns the variable used to store the offset of an instance variable.
435 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
436 const ObjCIvarDecl *Ivar);
437 /// Emits a reference to a class. This allows the linker to object if there
438 /// is no class of the matching name.
441 void EmitClassRef(const std::string &className);
443 /// Emits a pointer to the named class
444 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
445 const std::string &Name, bool isWeak);
447 /// Looks up the method for sending a message to the specified object. This
448 /// mechanism differs between the GCC and GNU runtimes, so this method must be
449 /// overridden in subclasses.
450 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
451 llvm::Value *&Receiver,
454 MessageSendInfo &MSI) = 0;
456 /// Looks up the method for sending a message to a superclass. This
457 /// mechanism differs between the GCC and GNU runtimes, so this method must
458 /// be overridden in subclasses.
459 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
462 MessageSendInfo &MSI) = 0;
464 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466 /// bits set to their values, LSB first, while larger ones are stored in a
467 /// structure of this / form:
469 /// struct { int32_t length; int32_t values[length]; };
471 /// The values in the array are stored in host-endian format, with the least
472 /// significant bit being assumed to come first in the bitfield. Therefore,
473 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474 /// while a bitfield / with the 63rd bit set will be 1<<64.
475 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
478 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
479 unsigned protocolClassVersion);
481 ConstantAddress GenerateConstantString(const StringLiteral *) override;
484 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
485 QualType ResultType, Selector Sel,
486 llvm::Value *Receiver, const CallArgList &CallArgs,
487 const ObjCInterfaceDecl *Class,
488 const ObjCMethodDecl *Method) override;
490 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
491 QualType ResultType, Selector Sel,
492 const ObjCInterfaceDecl *Class,
493 bool isCategoryImpl, llvm::Value *Receiver,
494 bool IsClassMessage, const CallArgList &CallArgs,
495 const ObjCMethodDecl *Method) override;
496 llvm::Value *GetClass(CodeGenFunction &CGF,
497 const ObjCInterfaceDecl *OID) override;
498 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
499 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
500 llvm::Value *GetSelector(CodeGenFunction &CGF,
501 const ObjCMethodDecl *Method) override;
502 llvm::Constant *GetEHType(QualType T) override;
504 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
505 const ObjCContainerDecl *CD) override;
506 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
507 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
508 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
509 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
510 const ObjCProtocolDecl *PD) override;
511 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
512 llvm::Function *ModuleInitFunction() override;
513 llvm::Constant *GetPropertyGetFunction() override;
514 llvm::Constant *GetPropertySetFunction() override;
515 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
517 llvm::Constant *GetSetStructFunction() override;
518 llvm::Constant *GetGetStructFunction() override;
519 llvm::Constant *GetCppAtomicObjectGetFunction() override;
520 llvm::Constant *GetCppAtomicObjectSetFunction() override;
521 llvm::Constant *EnumerationMutationFunction() override;
523 void EmitTryStmt(CodeGenFunction &CGF,
524 const ObjCAtTryStmt &S) override;
525 void EmitSynchronizedStmt(CodeGenFunction &CGF,
526 const ObjCAtSynchronizedStmt &S) override;
527 void EmitThrowStmt(CodeGenFunction &CGF,
528 const ObjCAtThrowStmt &S,
529 bool ClearInsertionPoint=true) override;
530 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
531 Address AddrWeakObj) override;
532 void EmitObjCWeakAssign(CodeGenFunction &CGF,
533 llvm::Value *src, Address dst) override;
534 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
535 llvm::Value *src, Address dest,
536 bool threadlocal=false) override;
537 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
538 Address dest, llvm::Value *ivarOffset) override;
539 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
540 llvm::Value *src, Address dest) override;
541 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
543 llvm::Value *Size) override;
544 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
545 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
546 unsigned CVRQualifiers) override;
547 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
548 const ObjCInterfaceDecl *Interface,
549 const ObjCIvarDecl *Ivar) override;
550 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
551 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
552 const CGBlockInfo &blockInfo) override {
555 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
556 const CGBlockInfo &blockInfo) override {
560 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
565 /// Class representing the legacy GCC Objective-C ABI. This is the default when
566 /// -fobjc-nonfragile-abi is not specified.
568 /// The GCC ABI target actually generates code that is approximately compatible
569 /// with the new GNUstep runtime ABI, but refrains from using any features that
570 /// would not work with the GCC runtime. For example, clang always generates
571 /// the extended form of the class structure, and the extra fields are simply
572 /// ignored by GCC libobjc.
573 class CGObjCGCC : public CGObjCGNU {
574 /// The GCC ABI message lookup function. Returns an IMP pointing to the
575 /// method implementation for this message.
576 LazyRuntimeFunction MsgLookupFn;
577 /// The GCC ABI superclass message lookup function. Takes a pointer to a
578 /// structure describing the receiver and the class, and a selector as
579 /// arguments. Returns the IMP for the corresponding method.
580 LazyRuntimeFunction MsgLookupSuperFn;
583 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
584 llvm::Value *cmd, llvm::MDNode *node,
585 MessageSendInfo &MSI) override {
586 CGBuilderTy &Builder = CGF.Builder;
587 llvm::Value *args[] = {
588 EnforceType(Builder, Receiver, IdTy),
589 EnforceType(Builder, cmd, SelectorTy) };
590 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
591 imp->setMetadata(msgSendMDKind, node);
592 return imp.getInstruction();
595 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
596 llvm::Value *cmd, MessageSendInfo &MSI) override {
597 CGBuilderTy &Builder = CGF.Builder;
598 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
599 PtrToObjCSuperTy).getPointer(), cmd};
600 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
604 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
605 // IMP objc_msg_lookup(id, SEL);
606 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
608 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
609 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
610 PtrToObjCSuperTy, SelectorTy, nullptr);
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.
643 llvm::Constant *GetEHType(QualType T) override;
646 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
647 llvm::Value *cmd, llvm::MDNode *node,
648 MessageSendInfo &MSI) override {
649 CGBuilderTy &Builder = CGF.Builder;
650 llvm::Function *LookupFn = SlotLookupFn;
652 // Store the receiver on the stack so that we can reload it later
653 Address ReceiverPtr =
654 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
655 Builder.CreateStore(Receiver, ReceiverPtr);
659 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
660 self = CGF.LoadObjCSelf();
662 self = llvm::ConstantPointerNull::get(IdTy);
665 // The lookup function is guaranteed not to capture the receiver pointer.
666 LookupFn->setDoesNotCapture(1);
668 llvm::Value *args[] = {
669 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
670 EnforceType(Builder, cmd, SelectorTy),
671 EnforceType(Builder, self, IdTy) };
672 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
673 slot.setOnlyReadsMemory();
674 slot->setMetadata(msgSendMDKind, node);
676 // Load the imp from the slot
677 llvm::Value *imp = Builder.CreateAlignedLoad(
678 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
679 CGF.getPointerAlign());
681 // The lookup function may have changed the receiver, so make sure we use
683 Receiver = Builder.CreateLoad(ReceiverPtr, true);
687 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
689 MessageSendInfo &MSI) override {
690 CGBuilderTy &Builder = CGF.Builder;
691 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
693 llvm::CallInst *slot =
694 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
695 slot->setOnlyReadsMemory();
697 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
698 CGF.getPointerAlign());
702 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
703 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
705 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
706 PtrTy, PtrTy, IntTy, IMPTy, nullptr);
707 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
708 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
709 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
710 SelectorTy, IdTy, nullptr);
711 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
712 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
713 PtrToObjCSuperTy, SelectorTy, nullptr);
714 // If we're in ObjC++ mode, then we want to make
715 if (CGM.getLangOpts().CPlusPlus) {
716 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
717 // void *__cxa_begin_catch(void *e)
718 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
719 // void __cxa_end_catch(void)
720 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
721 // void _Unwind_Resume_or_Rethrow(void*)
722 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
724 } else if (R.getVersion() >= VersionTuple(1, 7)) {
725 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
726 // id objc_begin_catch(void *e)
727 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
728 // void objc_end_catch(void)
729 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
730 // void _Unwind_Resume_or_Rethrow(void*)
731 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
734 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
735 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
736 SelectorTy, IdTy, PtrDiffTy, nullptr);
737 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
738 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
739 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
740 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
741 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
742 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
743 // void objc_setCppObjectAtomic(void *dest, const void *src, void
745 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
746 PtrTy, PtrTy, nullptr);
747 // void objc_getCppObjectAtomic(void *dest, const void *src, void
749 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
750 PtrTy, PtrTy, nullptr);
753 llvm::Constant *GetCppAtomicObjectGetFunction() override {
754 // The optimised functions were added in version 1.7 of the GNUstep
756 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
758 return CxxAtomicObjectGetFn;
761 llvm::Constant *GetCppAtomicObjectSetFunction() override {
762 // The optimised functions were added in version 1.7 of the GNUstep
764 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
766 return CxxAtomicObjectSetFn;
769 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
770 bool copy) override {
771 // The optimised property functions omit the GC check, and so are not
772 // safe to use in GC mode. The standard functions are fast in GC mode,
773 // so there is less advantage in using them.
774 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
775 // The optimised functions were added in version 1.7 of the GNUstep
777 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
781 if (copy) return SetPropertyAtomicCopy;
782 return SetPropertyAtomic;
785 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
789 /// Support for the ObjFW runtime.
790 class CGObjCObjFW: public CGObjCGNU {
792 /// The GCC ABI message lookup function. Returns an IMP pointing to the
793 /// method implementation for this message.
794 LazyRuntimeFunction MsgLookupFn;
795 /// stret lookup function. While this does not seem to make sense at the
796 /// first look, this is required to call the correct forwarding function.
797 LazyRuntimeFunction MsgLookupFnSRet;
798 /// The GCC ABI superclass message lookup function. Takes a pointer to a
799 /// structure describing the receiver and the class, and a selector as
800 /// arguments. Returns the IMP for the corresponding method.
801 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
803 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
804 llvm::Value *cmd, llvm::MDNode *node,
805 MessageSendInfo &MSI) override {
806 CGBuilderTy &Builder = CGF.Builder;
807 llvm::Value *args[] = {
808 EnforceType(Builder, Receiver, IdTy),
809 EnforceType(Builder, cmd, SelectorTy) };
812 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
813 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
815 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
817 imp->setMetadata(msgSendMDKind, node);
818 return imp.getInstruction();
821 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
822 llvm::Value *cmd, MessageSendInfo &MSI) override {
823 CGBuilderTy &Builder = CGF.Builder;
824 llvm::Value *lookupArgs[] = {
825 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
828 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
829 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
831 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
834 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
835 bool isWeak) override {
837 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
840 std::string SymbolName = "_OBJC_CLASS_" + Name;
841 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
843 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
844 llvm::GlobalValue::ExternalLinkage,
845 nullptr, SymbolName);
850 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
851 // IMP objc_msg_lookup(id, SEL);
852 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
853 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
854 SelectorTy, nullptr);
855 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
856 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
857 PtrToObjCSuperTy, SelectorTy, nullptr);
858 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
859 PtrToObjCSuperTy, SelectorTy, nullptr);
862 } // end anonymous namespace
864 /// Emits a reference to a dummy variable which is emitted with each class.
865 /// This ensures that a linker error will be generated when trying to link
866 /// together modules where a referenced class is not defined.
867 void CGObjCGNU::EmitClassRef(const std::string &className) {
868 std::string symbolRef = "__objc_class_ref_" + className;
869 // Don't emit two copies of the same symbol
870 if (TheModule.getGlobalVariable(symbolRef))
872 std::string symbolName = "__objc_class_name_" + className;
873 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
875 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
876 llvm::GlobalValue::ExternalLinkage,
877 nullptr, symbolName);
879 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
880 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
883 static std::string SymbolNameForMethod( StringRef ClassName,
884 StringRef CategoryName, const Selector MethodName,
885 bool isClassMethod) {
886 std::string MethodNameColonStripped = MethodName.getAsString();
887 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
889 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
890 CategoryName + "_" + MethodNameColonStripped).str();
893 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
894 unsigned protocolClassVersion)
895 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
896 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
897 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
898 ProtocolVersion(protocolClassVersion) {
900 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
902 CodeGenTypes &Types = CGM.getTypes();
903 IntTy = cast<llvm::IntegerType>(
904 Types.ConvertType(CGM.getContext().IntTy));
905 LongTy = cast<llvm::IntegerType>(
906 Types.ConvertType(CGM.getContext().LongTy));
907 SizeTy = cast<llvm::IntegerType>(
908 Types.ConvertType(CGM.getContext().getSizeType()));
909 PtrDiffTy = cast<llvm::IntegerType>(
910 Types.ConvertType(CGM.getContext().getPointerDiffType()));
911 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
913 Int8Ty = llvm::Type::getInt8Ty(VMContext);
914 // C string type. Used in lots of places.
915 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
917 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
919 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
920 // Get the selector Type.
921 QualType selTy = CGM.getContext().getObjCSelType();
922 if (QualType() == selTy) {
923 SelectorTy = PtrToInt8Ty;
925 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
928 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
931 Int32Ty = llvm::Type::getInt32Ty(VMContext);
932 Int64Ty = llvm::Type::getInt64Ty(VMContext);
935 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
938 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
939 ASTIdTy = CanQualType();
940 if (UnqualIdTy != QualType()) {
941 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
942 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
946 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
948 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
949 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
951 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
953 // void objc_exception_throw(id);
954 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
955 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
956 // int objc_sync_enter(id);
957 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
958 // int objc_sync_exit(id);
959 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
961 // void objc_enumerationMutation (id)
962 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
965 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
966 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
967 PtrDiffTy, BoolTy, nullptr);
968 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
969 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
970 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
971 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
972 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
973 PtrDiffTy, BoolTy, BoolTy, nullptr);
974 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
975 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
976 PtrDiffTy, BoolTy, BoolTy, nullptr);
979 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
980 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
983 const LangOptions &Opts = CGM.getLangOpts();
984 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
987 // Don't bother initialising the GC stuff unless we're compiling in GC mode
988 if (Opts.getGC() != LangOptions::NonGC) {
989 // This is a bit of an hack. We should sort this out by having a proper
990 // CGObjCGNUstep subclass for GC, but we may want to really support the old
991 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
992 // Get selectors needed in GC mode
993 RetainSel = GetNullarySelector("retain", CGM.getContext());
994 ReleaseSel = GetNullarySelector("release", CGM.getContext());
995 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
997 // Get functions needed in GC mode
999 // id objc_assign_ivar(id, id, ptrdiff_t);
1000 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
1002 // id objc_assign_strongCast (id, id*)
1003 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
1004 PtrToIdTy, nullptr);
1005 // id objc_assign_global(id, id*);
1006 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
1008 // id objc_assign_weak(id, id*);
1009 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
1010 // id objc_read_weak(id*);
1011 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
1012 // void *objc_memmove_collectable(void*, void *, size_t);
1013 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1018 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1019 const std::string &Name, bool isWeak) {
1020 llvm::Constant *ClassName = MakeConstantString(Name);
1021 // With the incompatible ABI, this will need to be replaced with a direct
1022 // reference to the class symbol. For the compatible nonfragile ABI we are
1023 // still performing this lookup at run time but emitting the symbol for the
1024 // class externally so that we can make the switch later.
1026 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1027 // with memoized versions or with static references if it's safe to do so.
1031 llvm::Constant *ClassLookupFn =
1032 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1033 "objc_lookup_class");
1034 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1037 // This has to perform the lookup every time, since posing and related
1038 // techniques can modify the name -> class mapping.
1039 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1040 const ObjCInterfaceDecl *OID) {
1042 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1043 if (CGM.getTriple().isOSBinFormatCOFF()) {
1044 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1045 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1046 if (OID->hasAttr<DLLExportAttr>())
1047 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1048 else if (OID->hasAttr<DLLImportAttr>())
1049 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1050 ClassSymbol->setDLLStorageClass(DLLStorage);
1056 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1057 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1058 if (CGM.getTriple().isOSBinFormatCOFF()) {
1059 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1060 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1061 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1062 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1064 const VarDecl *VD = nullptr;
1065 for (const auto &Result : DC->lookup(&II))
1066 if ((VD = dyn_cast<VarDecl>(Result)))
1069 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1070 if (!VD || VD->hasAttr<DLLImportAttr>())
1071 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1072 else if (VD->hasAttr<DLLExportAttr>())
1073 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1075 ClassSymbol->setDLLStorageClass(DLLStorage);
1081 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1082 const std::string &TypeEncoding) {
1083 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1084 llvm::GlobalAlias *SelValue = nullptr;
1086 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1087 e = Types.end() ; i!=e ; i++) {
1088 if (i->first == TypeEncoding) {
1089 SelValue = i->second;
1094 SelValue = llvm::GlobalAlias::create(
1095 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1096 ".objc_selector_" + Sel.getAsString(), &TheModule);
1097 Types.emplace_back(TypeEncoding, SelValue);
1103 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1104 llvm::Value *SelValue = GetSelector(CGF, Sel);
1106 // Store it to a temporary. Does this satisfy the semantics of
1107 // GetAddrOfSelector? Hopefully.
1108 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1109 CGF.getPointerAlign());
1110 CGF.Builder.CreateStore(SelValue, tmp);
1114 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1115 return GetSelector(CGF, Sel, std::string());
1118 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1119 const ObjCMethodDecl *Method) {
1120 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
1121 return GetSelector(CGF, Method->getSelector(), SelTypes);
1124 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1125 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1126 // With the old ABI, there was only one kind of catchall, which broke
1127 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1128 // a pointer indicating object catchalls, and NULL to indicate real
1130 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1131 return MakeConstantString("@id");
1137 // All other types should be Objective-C interface pointer types.
1138 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1139 assert(OPT && "Invalid @catch type.");
1140 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1141 assert(IDecl && "Invalid @catch type.");
1142 return MakeConstantString(IDecl->getIdentifier()->getName());
1145 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1146 if (!CGM.getLangOpts().CPlusPlus)
1147 return CGObjCGNU::GetEHType(T);
1149 // For Objective-C++, we want to provide the ability to catch both C++ and
1150 // Objective-C objects in the same function.
1152 // There's a particular fixed type info for 'id'.
1153 if (T->isObjCIdType() ||
1154 T->isObjCQualifiedIdType()) {
1155 llvm::Constant *IDEHType =
1156 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1159 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1161 llvm::GlobalValue::ExternalLinkage,
1162 nullptr, "__objc_id_type_info");
1163 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1166 const ObjCObjectPointerType *PT =
1167 T->getAs<ObjCObjectPointerType>();
1168 assert(PT && "Invalid @catch type.");
1169 const ObjCInterfaceType *IT = PT->getInterfaceType();
1170 assert(IT && "Invalid @catch type.");
1171 std::string className = IT->getDecl()->getIdentifier()->getName();
1173 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1175 // Return the existing typeinfo if it exists
1176 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1178 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1180 // Otherwise create it.
1182 // vtable for gnustep::libobjc::__objc_class_type_info
1183 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1184 // platform's name mangling.
1185 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1186 auto *Vtable = TheModule.getGlobalVariable(vtableName);
1188 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1189 llvm::GlobalValue::ExternalLinkage,
1190 nullptr, vtableName);
1192 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1193 auto *BVtable = llvm::ConstantExpr::getBitCast(
1194 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1197 llvm::Constant *typeName =
1198 ExportUniqueString(className, "__objc_eh_typename_");
1200 ConstantInitBuilder builder(CGM);
1201 auto fields = builder.beginStruct();
1202 fields.add(BVtable);
1203 fields.add(typeName);
1204 llvm::Constant *TI =
1205 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1206 CGM.getPointerAlign(),
1208 llvm::GlobalValue::LinkOnceODRLinkage);
1209 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1212 /// Generate an NSConstantString object.
1213 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1215 std::string Str = SL->getString().str();
1216 CharUnits Align = CGM.getPointerAlign();
1218 // Look for an existing one
1219 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1220 if (old != ObjCStrings.end())
1221 return ConstantAddress(old->getValue(), Align);
1223 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1225 if (StringClass.empty()) StringClass = "NXConstantString";
1227 std::string Sym = "_OBJC_CLASS_";
1230 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1233 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1234 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
1235 else if (isa->getType() != PtrToIdTy)
1236 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1238 ConstantInitBuilder Builder(CGM);
1239 auto Fields = Builder.beginStruct();
1241 Fields.add(MakeConstantString(Str));
1242 Fields.addInt(IntTy, Str.size());
1243 llvm::Constant *ObjCStr =
1244 Fields.finishAndCreateGlobal(".objc_str", Align);
1245 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1246 ObjCStrings[Str] = ObjCStr;
1247 ConstantStrings.push_back(ObjCStr);
1248 return ConstantAddress(ObjCStr, Align);
1251 ///Generates a message send where the super is the receiver. This is a message
1252 ///send to self with special delivery semantics indicating which class's method
1253 ///should be called.
1255 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1256 ReturnValueSlot Return,
1257 QualType ResultType,
1259 const ObjCInterfaceDecl *Class,
1260 bool isCategoryImpl,
1261 llvm::Value *Receiver,
1262 bool IsClassMessage,
1263 const CallArgList &CallArgs,
1264 const ObjCMethodDecl *Method) {
1265 CGBuilderTy &Builder = CGF.Builder;
1266 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1267 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1268 return RValue::get(EnforceType(Builder, Receiver,
1269 CGM.getTypes().ConvertType(ResultType)));
1271 if (Sel == ReleaseSel) {
1272 return RValue::get(nullptr);
1276 llvm::Value *cmd = GetSelector(CGF, Sel);
1277 CallArgList ActualArgs;
1279 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1280 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1281 ActualArgs.addFrom(CallArgs);
1283 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1285 llvm::Value *ReceiverClass = nullptr;
1286 if (isCategoryImpl) {
1287 llvm::Constant *classLookupFunction = nullptr;
1288 if (IsClassMessage) {
1289 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1290 IdTy, PtrTy, true), "objc_get_meta_class");
1292 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1293 IdTy, PtrTy, true), "objc_get_class");
1295 ReceiverClass = Builder.CreateCall(classLookupFunction,
1296 MakeConstantString(Class->getNameAsString()));
1298 // Set up global aliases for the metaclass or class pointer if they do not
1299 // already exist. These will are forward-references which will be set to
1300 // pointers to the class and metaclass structure created for the runtime
1301 // load function. To send a message to super, we look up the value of the
1302 // super_class pointer from either the class or metaclass structure.
1303 if (IsClassMessage) {
1304 if (!MetaClassPtrAlias) {
1305 MetaClassPtrAlias = llvm::GlobalAlias::create(
1306 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1307 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1309 ReceiverClass = MetaClassPtrAlias;
1311 if (!ClassPtrAlias) {
1312 ClassPtrAlias = llvm::GlobalAlias::create(
1313 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1314 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1316 ReceiverClass = ClassPtrAlias;
1319 // Cast the pointer to a simplified version of the class structure
1320 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
1321 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1322 llvm::PointerType::getUnqual(CastTy));
1323 // Get the superclass pointer
1324 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1325 // Load the superclass pointer
1327 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
1328 // Construct the structure used to look up the IMP
1329 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1330 Receiver->getType(), IdTy, nullptr);
1332 // FIXME: Is this really supposed to be a dynamic alloca?
1333 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1334 CGF.getPointerAlign());
1336 Builder.CreateStore(Receiver,
1337 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
1338 Builder.CreateStore(ReceiverClass,
1339 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
1341 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1344 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1345 imp = EnforceType(Builder, imp, MSI.MessengerType);
1347 llvm::Metadata *impMD[] = {
1348 llvm::MDString::get(VMContext, Sel.getAsString()),
1349 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1350 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1351 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
1352 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1354 CGCallee callee(CGCalleeInfo(), imp);
1356 llvm::Instruction *call;
1357 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1358 call->setMetadata(msgSendMDKind, node);
1362 /// Generate code for a message send expression.
1364 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1365 ReturnValueSlot Return,
1366 QualType ResultType,
1368 llvm::Value *Receiver,
1369 const CallArgList &CallArgs,
1370 const ObjCInterfaceDecl *Class,
1371 const ObjCMethodDecl *Method) {
1372 CGBuilderTy &Builder = CGF.Builder;
1374 // Strip out message sends to retain / release in GC mode
1375 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1376 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1377 return RValue::get(EnforceType(Builder, Receiver,
1378 CGM.getTypes().ConvertType(ResultType)));
1380 if (Sel == ReleaseSel) {
1381 return RValue::get(nullptr);
1385 // If the return type is something that goes in an integer register, the
1386 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1389 // The language spec says the result of this kind of message send is
1390 // undefined, but lots of people seem to have forgotten to read that
1391 // paragraph and insist on sending messages to nil that have structure
1392 // returns. With GCC, this generates a random return value (whatever happens
1393 // to be on the stack / in those registers at the time) on most platforms,
1394 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1396 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1397 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1399 llvm::BasicBlock *startBB = nullptr;
1400 llvm::BasicBlock *messageBB = nullptr;
1401 llvm::BasicBlock *continueBB = nullptr;
1403 if (!isPointerSizedReturn) {
1404 startBB = Builder.GetInsertBlock();
1405 messageBB = CGF.createBasicBlock("msgSend");
1406 continueBB = CGF.createBasicBlock("continue");
1408 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1409 llvm::Constant::getNullValue(Receiver->getType()));
1410 Builder.CreateCondBr(isNil, continueBB, messageBB);
1411 CGF.EmitBlock(messageBB);
1414 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1417 cmd = GetSelector(CGF, Method);
1419 cmd = GetSelector(CGF, Sel);
1420 cmd = EnforceType(Builder, cmd, SelectorTy);
1421 Receiver = EnforceType(Builder, Receiver, IdTy);
1423 llvm::Metadata *impMD[] = {
1424 llvm::MDString::get(VMContext, Sel.getAsString()),
1425 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1426 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1427 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
1428 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1430 CallArgList ActualArgs;
1431 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1432 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1433 ActualArgs.addFrom(CallArgs);
1435 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1437 // Get the IMP to call
1440 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1441 // functions. These are not supported on all platforms (or all runtimes on a
1442 // given platform), so we
1443 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1444 case CodeGenOptions::Legacy:
1445 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1447 case CodeGenOptions::Mixed:
1448 case CodeGenOptions::NonLegacy:
1449 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1450 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1451 "objc_msgSend_fpret");
1452 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1453 // The actual types here don't matter - we're going to bitcast the
1455 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1456 "objc_msgSend_stret");
1458 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1463 // Reset the receiver in case the lookup modified it
1464 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1466 imp = EnforceType(Builder, imp, MSI.MessengerType);
1468 llvm::Instruction *call;
1469 CGCallee callee(CGCalleeInfo(), imp);
1470 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1471 call->setMetadata(msgSendMDKind, node);
1474 if (!isPointerSizedReturn) {
1475 messageBB = CGF.Builder.GetInsertBlock();
1476 CGF.Builder.CreateBr(continueBB);
1477 CGF.EmitBlock(continueBB);
1478 if (msgRet.isScalar()) {
1479 llvm::Value *v = msgRet.getScalarVal();
1480 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1481 phi->addIncoming(v, messageBB);
1482 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1483 msgRet = RValue::get(phi);
1484 } else if (msgRet.isAggregate()) {
1485 Address v = msgRet.getAggregateAddress();
1486 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1487 llvm::Type *RetTy = v.getElementType();
1488 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1489 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1490 phi->addIncoming(v.getPointer(), messageBB);
1491 phi->addIncoming(NullVal.getPointer(), startBB);
1492 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
1493 } else /* isComplex() */ {
1494 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1495 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1496 phi->addIncoming(v.first, messageBB);
1497 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1499 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1500 phi2->addIncoming(v.second, messageBB);
1501 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1503 msgRet = RValue::getComplex(phi, phi2);
1509 /// Generates a MethodList. Used in construction of a objc_class and
1510 /// objc_category structures.
1511 llvm::Constant *CGObjCGNU::
1512 GenerateMethodList(StringRef ClassName,
1513 StringRef CategoryName,
1514 ArrayRef<Selector> MethodSels,
1515 ArrayRef<llvm::Constant *> MethodTypes,
1516 bool isClassMethodList) {
1517 if (MethodSels.empty())
1520 ConstantInitBuilder Builder(CGM);
1522 auto MethodList = Builder.beginStruct();
1523 MethodList.addNullPointer(CGM.Int8PtrTy);
1524 MethodList.addInt(Int32Ty, MethodTypes.size());
1526 // Get the method structure type.
1527 llvm::StructType *ObjCMethodTy =
1528 llvm::StructType::get(CGM.getLLVMContext(), {
1529 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1530 PtrToInt8Ty, // Method types
1531 IMPTy // Method pointer
1533 auto Methods = MethodList.beginArray();
1534 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1535 llvm::Constant *FnPtr =
1536 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1538 isClassMethodList));
1539 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
1540 auto Method = Methods.beginStruct(ObjCMethodTy);
1541 Method.add(MakeConstantString(MethodSels[i].getAsString()));
1542 Method.add(MethodTypes[i]);
1543 Method.addBitCast(FnPtr, IMPTy);
1544 Method.finishAndAddTo(Methods);
1546 Methods.finishAndAddTo(MethodList);
1548 // Create an instance of the structure
1549 return MethodList.finishAndCreateGlobal(".objc_method_list",
1550 CGM.getPointerAlign());
1553 /// Generates an IvarList. Used in construction of a objc_class.
1554 llvm::Constant *CGObjCGNU::
1555 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1556 ArrayRef<llvm::Constant *> IvarTypes,
1557 ArrayRef<llvm::Constant *> IvarOffsets) {
1558 if (IvarNames.empty())
1561 ConstantInitBuilder Builder(CGM);
1563 // Structure containing array count followed by array.
1564 auto IvarList = Builder.beginStruct();
1565 IvarList.addInt(IntTy, (int)IvarNames.size());
1567 // Get the ivar structure type.
1568 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1574 // Array of ivar structures.
1575 auto Ivars = IvarList.beginArray(ObjCIvarTy);
1576 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1577 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1578 Ivar.add(IvarNames[i]);
1579 Ivar.add(IvarTypes[i]);
1580 Ivar.add(IvarOffsets[i]);
1581 Ivar.finishAndAddTo(Ivars);
1583 Ivars.finishAndAddTo(IvarList);
1585 // Create an instance of the structure
1586 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1587 CGM.getPointerAlign());
1590 /// Generate a class structure
1591 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1592 llvm::Constant *MetaClass,
1593 llvm::Constant *SuperClass,
1596 llvm::Constant *Version,
1597 llvm::Constant *InstanceSize,
1598 llvm::Constant *IVars,
1599 llvm::Constant *Methods,
1600 llvm::Constant *Protocols,
1601 llvm::Constant *IvarOffsets,
1602 llvm::Constant *Properties,
1603 llvm::Constant *StrongIvarBitmap,
1604 llvm::Constant *WeakIvarBitmap,
1606 // Set up the class structure
1607 // Note: Several of these are char*s when they should be ids. This is
1608 // because the runtime performs this translation on load.
1610 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1611 // anyway; the classes will still work with the GNU runtime, they will just
1613 llvm::StructType *ClassTy = llvm::StructType::get(
1615 PtrToInt8Ty, // super_class
1616 PtrToInt8Ty, // name
1619 LongTy, // instance_size
1620 IVars->getType(), // ivars
1621 Methods->getType(), // methods
1622 // These are all filled in by the runtime, so we pretend
1624 PtrTy, // subclass_list
1625 PtrTy, // sibling_class
1627 PtrTy, // gc_object_type
1629 LongTy, // abi_version
1630 IvarOffsets->getType(), // ivar_offsets
1631 Properties->getType(), // properties
1632 IntPtrTy, // strong_pointers
1633 IntPtrTy, // weak_pointers
1636 ConstantInitBuilder Builder(CGM);
1637 auto Elements = Builder.beginStruct(ClassTy);
1639 // Fill in the structure
1642 Elements.addBitCast(MetaClass, PtrToInt8Ty);
1644 Elements.add(SuperClass);
1646 Elements.add(MakeConstantString(Name, ".class_name"));
1648 Elements.addInt(LongTy, 0);
1650 Elements.addInt(LongTy, info);
1653 llvm::DataLayout td(&TheModule);
1654 Elements.addInt(LongTy,
1655 td.getTypeSizeInBits(ClassTy) /
1656 CGM.getContext().getCharWidth());
1658 Elements.add(InstanceSize);
1660 Elements.add(IVars);
1662 Elements.add(Methods);
1663 // These are all filled in by the runtime, so we pretend
1665 Elements.add(NULLPtr);
1667 Elements.add(NULLPtr);
1669 Elements.add(NULLPtr);
1671 Elements.addBitCast(Protocols, PtrTy);
1673 Elements.add(NULLPtr);
1675 Elements.addInt(LongTy, 1);
1677 Elements.add(IvarOffsets);
1679 Elements.add(Properties);
1681 Elements.add(StrongIvarBitmap);
1683 Elements.add(WeakIvarBitmap);
1684 // Create an instance of the structure
1685 // This is now an externally visible symbol, so that we can speed up class
1686 // messages in the next ABI. We may already have some weak references to
1687 // this, so check and fix them properly.
1688 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1690 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1691 llvm::Constant *Class =
1692 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1693 llvm::GlobalValue::ExternalLinkage);
1695 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1696 ClassRef->getType()));
1697 ClassRef->removeFromParent();
1698 Class->setName(ClassSym);
1703 llvm::Constant *CGObjCGNU::
1704 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1705 ArrayRef<llvm::Constant *> MethodTypes) {
1706 // Get the method structure type.
1707 llvm::StructType *ObjCMethodDescTy =
1708 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
1709 ConstantInitBuilder Builder(CGM);
1710 auto MethodList = Builder.beginStruct();
1711 MethodList.addInt(IntTy, MethodNames.size());
1712 auto Methods = MethodList.beginArray(ObjCMethodDescTy);
1713 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1714 auto Method = Methods.beginStruct(ObjCMethodDescTy);
1715 Method.add(MethodNames[i]);
1716 Method.add(MethodTypes[i]);
1717 Method.finishAndAddTo(Methods);
1719 Methods.finishAndAddTo(MethodList);
1720 return MethodList.finishAndCreateGlobal(".objc_method_list",
1721 CGM.getPointerAlign());
1724 // Create the protocol list structure used in classes, categories and so on
1726 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1728 ConstantInitBuilder Builder(CGM);
1729 auto ProtocolList = Builder.beginStruct();
1730 ProtocolList.add(NULLPtr);
1731 ProtocolList.addInt(LongTy, Protocols.size());
1733 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
1734 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1735 iter != endIter ; iter++) {
1736 llvm::Constant *protocol = nullptr;
1737 llvm::StringMap<llvm::Constant*>::iterator value =
1738 ExistingProtocols.find(*iter);
1739 if (value == ExistingProtocols.end()) {
1740 protocol = GenerateEmptyProtocol(*iter);
1742 protocol = value->getValue();
1744 Elements.addBitCast(protocol, PtrToInt8Ty);
1746 Elements.finishAndAddTo(ProtocolList);
1747 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1748 CGM.getPointerAlign());
1751 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1752 const ObjCProtocolDecl *PD) {
1753 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1755 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1756 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1760 CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1761 llvm::Constant *ProtocolList = GenerateProtocolList({});
1762 llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
1763 // Protocols are objects containing lists of the methods implemented and
1764 // protocols adopted.
1765 ConstantInitBuilder Builder(CGM);
1766 auto Elements = Builder.beginStruct();
1768 // The isa pointer must be set to a magic number so the runtime knows it's
1769 // the correct layout.
1770 Elements.add(llvm::ConstantExpr::getIntToPtr(
1771 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1773 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1774 Elements.add(ProtocolList);
1775 Elements.add(MethodList);
1776 Elements.add(MethodList);
1777 Elements.add(MethodList);
1778 Elements.add(MethodList);
1779 return Elements.finishAndCreateGlobal(".objc_protocol",
1780 CGM.getPointerAlign());
1783 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1784 ASTContext &Context = CGM.getContext();
1785 std::string ProtocolName = PD->getNameAsString();
1787 // Use the protocol definition, if there is one.
1788 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1791 SmallVector<std::string, 16> Protocols;
1792 for (const auto *PI : PD->protocols())
1793 Protocols.push_back(PI->getNameAsString());
1794 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1795 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1796 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1797 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1798 for (const auto *I : PD->instance_methods()) {
1799 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1800 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1801 OptionalInstanceMethodNames.push_back(
1802 MakeConstantString(I->getSelector().getAsString()));
1803 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1805 InstanceMethodNames.push_back(
1806 MakeConstantString(I->getSelector().getAsString()));
1807 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1810 // Collect information about class methods:
1811 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1812 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1813 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1814 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1815 for (const auto *I : PD->class_methods()) {
1816 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1817 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1818 OptionalClassMethodNames.push_back(
1819 MakeConstantString(I->getSelector().getAsString()));
1820 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1822 ClassMethodNames.push_back(
1823 MakeConstantString(I->getSelector().getAsString()));
1824 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1828 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1829 llvm::Constant *InstanceMethodList =
1830 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1831 llvm::Constant *ClassMethodList =
1832 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1833 llvm::Constant *OptionalInstanceMethodList =
1834 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1835 OptionalInstanceMethodTypes);
1836 llvm::Constant *OptionalClassMethodList =
1837 GenerateProtocolMethodList(OptionalClassMethodNames,
1838 OptionalClassMethodTypes);
1840 // Property metadata: name, attributes, isSynthesized, setter name, setter
1841 // types, getter name, getter types.
1842 // The isSynthesized value is always set to 0 in a protocol. It exists to
1843 // simplify the runtime library by allowing it to use the same data
1844 // structures for protocol metadata everywhere.
1846 llvm::Constant *PropertyList;
1847 llvm::Constant *OptionalPropertyList;
1849 llvm::StructType *propertyMetadataTy =
1850 llvm::StructType::get(CGM.getLLVMContext(),
1851 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1852 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1854 unsigned numReqProperties = 0, numOptProperties = 0;
1855 for (auto property : PD->instance_properties()) {
1856 if (property->isOptional())
1862 ConstantInitBuilder reqPropertyListBuilder(CGM);
1863 auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1864 reqPropertiesList.addInt(IntTy, numReqProperties);
1865 reqPropertiesList.add(NULLPtr);
1866 auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1868 ConstantInitBuilder optPropertyListBuilder(CGM);
1869 auto optPropertiesList = optPropertyListBuilder.beginStruct();
1870 optPropertiesList.addInt(IntTy, numOptProperties);
1871 optPropertiesList.add(NULLPtr);
1872 auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1874 // Add all of the property methods need adding to the method list and to the
1875 // property metadata list.
1876 for (auto *property : PD->instance_properties()) {
1877 auto &propertiesArray =
1878 (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1879 auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1881 fields.add(MakePropertyEncodingString(property, nullptr));
1882 PushPropertyAttributes(fields, property);
1884 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1885 std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
1886 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1887 InstanceMethodTypes.push_back(typeEncoding);
1888 fields.add(MakeConstantString(getter->getSelector().getAsString()));
1889 fields.add(typeEncoding);
1891 fields.add(NULLPtr);
1892 fields.add(NULLPtr);
1894 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1895 std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
1896 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1897 InstanceMethodTypes.push_back(typeEncoding);
1898 fields.add(MakeConstantString(setter->getSelector().getAsString()));
1899 fields.add(typeEncoding);
1901 fields.add(NULLPtr);
1902 fields.add(NULLPtr);
1905 fields.finishAndAddTo(propertiesArray);
1908 reqPropertiesArray.finishAndAddTo(reqPropertiesList);
1910 reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1911 CGM.getPointerAlign());
1913 optPropertiesArray.finishAndAddTo(optPropertiesList);
1914 OptionalPropertyList =
1915 optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1916 CGM.getPointerAlign());
1919 // Protocols are objects containing lists of the methods implemented and
1920 // protocols adopted.
1921 // The isa pointer must be set to a magic number so the runtime knows it's
1922 // the correct layout.
1923 ConstantInitBuilder Builder(CGM);
1924 auto Elements = Builder.beginStruct();
1926 llvm::ConstantExpr::getIntToPtr(
1927 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1929 MakeConstantString(ProtocolName, ".objc_protocol_name"));
1930 Elements.add(ProtocolList);
1931 Elements.add(InstanceMethodList);
1932 Elements.add(ClassMethodList);
1933 Elements.add(OptionalInstanceMethodList);
1934 Elements.add(OptionalClassMethodList);
1935 Elements.add(PropertyList);
1936 Elements.add(OptionalPropertyList);
1937 ExistingProtocols[ProtocolName] =
1938 llvm::ConstantExpr::getBitCast(
1939 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1942 void CGObjCGNU::GenerateProtocolHolderCategory() {
1943 // Collect information about instance methods
1944 SmallVector<Selector, 1> MethodSels;
1945 SmallVector<llvm::Constant*, 1> MethodTypes;
1947 ConstantInitBuilder Builder(CGM);
1948 auto Elements = Builder.beginStruct();
1950 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1951 const std::string CategoryName = "AnotherHack";
1952 Elements.add(MakeConstantString(CategoryName));
1953 Elements.add(MakeConstantString(ClassName));
1954 // Instance method list
1955 Elements.addBitCast(GenerateMethodList(
1956 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
1957 // Class method list
1958 Elements.addBitCast(GenerateMethodList(
1959 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
1962 ConstantInitBuilder ProtocolListBuilder(CGM);
1963 auto ProtocolList = ProtocolListBuilder.beginStruct();
1964 ProtocolList.add(NULLPtr);
1965 ProtocolList.addInt(LongTy, ExistingProtocols.size());
1966 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1967 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1968 iter != endIter ; iter++) {
1969 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
1971 ProtocolElements.finishAndAddTo(ProtocolList);
1972 Elements.addBitCast(
1973 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1974 CGM.getPointerAlign()),
1976 Categories.push_back(llvm::ConstantExpr::getBitCast(
1977 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
1981 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1982 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1983 /// bits set to their values, LSB first, while larger ones are stored in a
1984 /// structure of this / form:
1986 /// struct { int32_t length; int32_t values[length]; };
1988 /// The values in the array are stored in host-endian format, with the least
1989 /// significant bit being assumed to come first in the bitfield. Therefore, a
1990 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1991 /// bitfield / with the 63rd bit set will be 1<<64.
1992 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1993 int bitCount = bits.size();
1994 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1995 if (bitCount < ptrBits) {
1997 for (int i=0 ; i<bitCount ; ++i) {
1998 if (bits[i]) val |= 1ULL<<(i+1);
2000 return llvm::ConstantInt::get(IntPtrTy, val);
2002 SmallVector<llvm::Constant *, 8> values;
2004 while (v < bitCount) {
2006 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2007 if (bits[v]) word |= 1<<i;
2010 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2013 ConstantInitBuilder builder(CGM);
2014 auto fields = builder.beginStruct();
2015 fields.addInt(Int32Ty, values.size());
2016 auto array = fields.beginArray();
2017 for (auto v : values) array.add(v);
2018 array.finishAndAddTo(fields);
2020 llvm::Constant *GS =
2021 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
2022 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2026 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2027 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2028 std::string CategoryName = OCD->getNameAsString();
2029 // Collect information about instance methods
2030 SmallVector<Selector, 16> InstanceMethodSels;
2031 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2032 for (const auto *I : OCD->instance_methods()) {
2033 InstanceMethodSels.push_back(I->getSelector());
2034 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2035 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2038 // Collect information about class methods
2039 SmallVector<Selector, 16> ClassMethodSels;
2040 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2041 for (const auto *I : OCD->class_methods()) {
2042 ClassMethodSels.push_back(I->getSelector());
2043 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2044 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2047 // Collect the names of referenced protocols
2048 SmallVector<std::string, 16> Protocols;
2049 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2050 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2051 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2052 E = Protos.end(); I != E; ++I)
2053 Protocols.push_back((*I)->getNameAsString());
2055 ConstantInitBuilder Builder(CGM);
2056 auto Elements = Builder.beginStruct();
2057 Elements.add(MakeConstantString(CategoryName));
2058 Elements.add(MakeConstantString(ClassName));
2059 // Instance method list
2060 Elements.addBitCast(
2061 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2062 InstanceMethodTypes, false),
2064 // Class method list
2065 Elements.addBitCast(
2066 GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2067 ClassMethodTypes, true),
2070 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
2071 Categories.push_back(llvm::ConstantExpr::getBitCast(
2072 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
2076 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2077 SmallVectorImpl<Selector> &InstanceMethodSels,
2078 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2079 ASTContext &Context = CGM.getContext();
2080 // Property metadata: name, attributes, attributes2, padding1, padding2,
2081 // setter name, setter types, getter name, getter types.
2082 llvm::StructType *propertyMetadataTy =
2083 llvm::StructType::get(CGM.getLLVMContext(),
2084 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2085 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2087 unsigned numProperties = 0;
2088 for (auto *propertyImpl : OID->property_impls()) {
2089 (void) propertyImpl;
2093 ConstantInitBuilder builder(CGM);
2094 auto propertyList = builder.beginStruct();
2095 propertyList.addInt(IntTy, numProperties);
2096 propertyList.add(NULLPtr);
2097 auto properties = propertyList.beginArray(propertyMetadataTy);
2099 // Add all of the property methods need adding to the method list and to the
2100 // property metadata list.
2101 for (auto *propertyImpl : OID->property_impls()) {
2102 auto fields = properties.beginStruct(propertyMetadataTy);
2103 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2104 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2105 ObjCPropertyImplDecl::Synthesize);
2106 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2107 ObjCPropertyImplDecl::Dynamic);
2109 fields.add(MakePropertyEncodingString(property, OID));
2110 PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
2111 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2112 std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
2113 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2114 if (isSynthesized) {
2115 InstanceMethodTypes.push_back(TypeEncoding);
2116 InstanceMethodSels.push_back(getter->getSelector());
2118 fields.add(MakeConstantString(getter->getSelector().getAsString()));
2119 fields.add(TypeEncoding);
2121 fields.add(NULLPtr);
2122 fields.add(NULLPtr);
2124 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2125 std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
2126 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2127 if (isSynthesized) {
2128 InstanceMethodTypes.push_back(TypeEncoding);
2129 InstanceMethodSels.push_back(setter->getSelector());
2131 fields.add(MakeConstantString(setter->getSelector().getAsString()));
2132 fields.add(TypeEncoding);
2134 fields.add(NULLPtr);
2135 fields.add(NULLPtr);
2137 fields.finishAndAddTo(properties);
2139 properties.finishAndAddTo(propertyList);
2141 return propertyList.finishAndCreateGlobal(".objc_property_list",
2142 CGM.getPointerAlign());
2145 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2146 // Get the class declaration for which the alias is specified.
2147 ObjCInterfaceDecl *ClassDecl =
2148 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2149 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2150 OAD->getNameAsString());
2153 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2154 ASTContext &Context = CGM.getContext();
2156 // Get the superclass name.
2157 const ObjCInterfaceDecl * SuperClassDecl =
2158 OID->getClassInterface()->getSuperClass();
2159 std::string SuperClassName;
2160 if (SuperClassDecl) {
2161 SuperClassName = SuperClassDecl->getNameAsString();
2162 EmitClassRef(SuperClassName);
2165 // Get the class name
2166 ObjCInterfaceDecl *ClassDecl =
2167 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2168 std::string ClassName = ClassDecl->getNameAsString();
2170 // Emit the symbol that is used to generate linker errors if this class is
2171 // referenced in other modules but not declared.
2172 std::string classSymbolName = "__objc_class_name_" + ClassName;
2173 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
2174 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2176 new llvm::GlobalVariable(TheModule, LongTy, false,
2177 llvm::GlobalValue::ExternalLinkage,
2178 llvm::ConstantInt::get(LongTy, 0),
2182 // Get the size of instances.
2184 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2186 // Collect information about instance variables.
2187 SmallVector<llvm::Constant*, 16> IvarNames;
2188 SmallVector<llvm::Constant*, 16> IvarTypes;
2189 SmallVector<llvm::Constant*, 16> IvarOffsets;
2191 ConstantInitBuilder IvarOffsetBuilder(CGM);
2192 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
2193 SmallVector<bool, 16> WeakIvars;
2194 SmallVector<bool, 16> StrongIvars;
2196 int superInstanceSize = !SuperClassDecl ? 0 :
2197 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2198 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2199 // class}. The runtime will then set this to the correct value on load.
2200 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2201 instanceSize = 0 - (instanceSize - superInstanceSize);
2204 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2205 IVD = IVD->getNextIvar()) {
2207 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2208 // Get the type encoding for this ivar
2209 std::string TypeStr;
2210 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2211 IvarTypes.push_back(MakeConstantString(TypeStr));
2213 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2214 uint64_t Offset = BaseOffset;
2215 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2216 Offset = BaseOffset - superInstanceSize;
2218 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2219 // Create the direct offset value
2220 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2221 IVD->getNameAsString();
2222 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2224 OffsetVar->setInitializer(OffsetValue);
2225 // If this is the real definition, change its linkage type so that
2226 // different modules will use this one, rather than their private
2228 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2230 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2231 false, llvm::GlobalValue::ExternalLinkage,
2233 "__objc_ivar_offset_value_" + ClassName +"." +
2234 IVD->getNameAsString());
2235 IvarOffsets.push_back(OffsetValue);
2236 IvarOffsetValues.add(OffsetVar);
2237 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2239 case Qualifiers::OCL_Strong:
2240 StrongIvars.push_back(true);
2241 WeakIvars.push_back(false);
2243 case Qualifiers::OCL_Weak:
2244 StrongIvars.push_back(false);
2245 WeakIvars.push_back(true);
2248 StrongIvars.push_back(false);
2249 WeakIvars.push_back(false);
2252 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2253 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2254 llvm::GlobalVariable *IvarOffsetArray =
2255 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2256 CGM.getPointerAlign());
2258 // Collect information about instance methods
2259 SmallVector<Selector, 16> InstanceMethodSels;
2260 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2261 for (const auto *I : OID->instance_methods()) {
2262 InstanceMethodSels.push_back(I->getSelector());
2263 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2264 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2267 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2268 InstanceMethodTypes);
2270 // Collect information about class methods
2271 SmallVector<Selector, 16> ClassMethodSels;
2272 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2273 for (const auto *I : OID->class_methods()) {
2274 ClassMethodSels.push_back(I->getSelector());
2275 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2276 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2278 // Collect the names of referenced protocols
2279 SmallVector<std::string, 16> Protocols;
2280 for (const auto *I : ClassDecl->protocols())
2281 Protocols.push_back(I->getNameAsString());
2283 // Get the superclass pointer.
2284 llvm::Constant *SuperClass;
2285 if (!SuperClassName.empty()) {
2286 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2288 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2290 // Empty vector used to construct empty method lists
2291 SmallVector<llvm::Constant*, 1> empty;
2292 // Generate the method and instance variable lists
2293 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2294 InstanceMethodSels, InstanceMethodTypes, false);
2295 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2296 ClassMethodSels, ClassMethodTypes, true);
2297 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2299 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2300 // we emit a symbol containing the offset for each ivar in the class. This
2301 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2302 // for the legacy ABI, without causing problems. The converse is also
2303 // possible, but causes all ivar accesses to be fragile.
2305 // Offset pointer for getting at the correct field in the ivar list when
2306 // setting up the alias. These are: The base address for the global, the
2307 // ivar array (second field), the ivar in this list (set for each ivar), and
2308 // the offset (third field in ivar structure)
2309 llvm::Type *IndexTy = Int32Ty;
2310 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2311 llvm::ConstantInt::get(IndexTy, 1), nullptr,
2312 llvm::ConstantInt::get(IndexTy, 2) };
2314 unsigned ivarIndex = 0;
2315 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2316 IVD = IVD->getNextIvar()) {
2317 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2318 + IVD->getNameAsString();
2319 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2320 // Get the correct ivar field
2321 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2322 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2323 offsetPointerIndexes);
2324 // Get the existing variable, if one exists.
2325 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2327 offset->setInitializer(offsetValue);
2328 // If this is the real definition, change its linkage type so that
2329 // different modules will use this one, rather than their private
2331 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2333 // Add a new alias if there isn't one already.
2334 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2335 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2336 (void) offset; // Silence dead store warning.
2340 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2342 //Generate metaclass for class methods
2343 llvm::Constant *MetaClassStruct = GenerateClassStructure(
2344 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2345 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2346 NULLPtr, ZeroPtr, ZeroPtr, true);
2347 if (CGM.getTriple().isOSBinFormatCOFF()) {
2348 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2349 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2350 Storage = llvm::GlobalValue::DLLImportStorageClass;
2351 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2352 Storage = llvm::GlobalValue::DLLExportStorageClass;
2353 cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2356 // Generate the class structure
2357 llvm::Constant *ClassStruct = GenerateClassStructure(
2358 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2359 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2360 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2361 StrongIvarBitmap, WeakIvarBitmap);
2362 if (CGM.getTriple().isOSBinFormatCOFF()) {
2363 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2364 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2365 Storage = llvm::GlobalValue::DLLImportStorageClass;
2366 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2367 Storage = llvm::GlobalValue::DLLExportStorageClass;
2368 cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2371 // Resolve the class aliases, if they exist.
2372 if (ClassPtrAlias) {
2373 ClassPtrAlias->replaceAllUsesWith(
2374 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2375 ClassPtrAlias->eraseFromParent();
2376 ClassPtrAlias = nullptr;
2378 if (MetaClassPtrAlias) {
2379 MetaClassPtrAlias->replaceAllUsesWith(
2380 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2381 MetaClassPtrAlias->eraseFromParent();
2382 MetaClassPtrAlias = nullptr;
2385 // Add class structure to list to be added to the symtab later
2386 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2387 Classes.push_back(ClassStruct);
2390 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2391 // Only emit an ObjC load function if no Objective-C stuff has been called
2392 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2393 ExistingProtocols.empty() && SelectorTable.empty())
2396 // Add all referenced protocols to a category.
2397 GenerateProtocolHolderCategory();
2399 llvm::StructType *selStructTy =
2400 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2401 llvm::Type *selStructPtrTy = SelectorTy;
2403 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2404 { PtrToInt8Ty, PtrToInt8Ty });
2405 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
2408 // Generate statics list:
2409 llvm::Constant *statics = NULLPtr;
2410 if (!ConstantStrings.empty()) {
2411 llvm::GlobalVariable *fileStatics = [&] {
2412 ConstantInitBuilder builder(CGM);
2413 auto staticsStruct = builder.beginStruct();
2415 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2416 if (stringClass.empty()) stringClass = "NXConstantString";
2417 staticsStruct.add(MakeConstantString(stringClass,
2418 ".objc_static_class_name"));
2420 auto array = staticsStruct.beginArray();
2421 array.addAll(ConstantStrings);
2423 array.finishAndAddTo(staticsStruct);
2425 return staticsStruct.finishAndCreateGlobal(".objc_statics",
2426 CGM.getPointerAlign());
2429 ConstantInitBuilder builder(CGM);
2430 auto allStaticsArray = builder.beginArray(fileStatics->getType());
2431 allStaticsArray.add(fileStatics);
2432 allStaticsArray.addNullPointer(fileStatics->getType());
2434 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2435 CGM.getPointerAlign());
2436 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
2439 // Array of classes, categories, and constant objects.
2441 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2442 unsigned selectorCount;
2444 // Pointer to an array of selectors used in this module.
2445 llvm::GlobalVariable *selectorList = [&] {
2446 ConstantInitBuilder builder(CGM);
2447 auto selectors = builder.beginArray(selStructTy);
2448 auto &table = SelectorTable; // MSVC workaround
2449 for (auto &entry : table) {
2451 std::string selNameStr = entry.first.getAsString();
2452 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
2454 for (TypedSelector &sel : entry.second) {
2455 llvm::Constant *selectorTypeEncoding = NULLPtr;
2456 if (!sel.first.empty())
2457 selectorTypeEncoding =
2458 MakeConstantString(sel.first, ".objc_sel_types");
2460 auto selStruct = selectors.beginStruct(selStructTy);
2461 selStruct.add(selName);
2462 selStruct.add(selectorTypeEncoding);
2463 selStruct.finishAndAddTo(selectors);
2465 // Store the selector alias for later replacement
2466 selectorAliases.push_back(sel.second);
2470 // Remember the number of entries in the selector table.
2471 selectorCount = selectors.size();
2473 // NULL-terminate the selector list. This should not actually be required,
2474 // because the selector list has a length field. Unfortunately, the GCC
2475 // runtime decides to ignore the length field and expects a NULL terminator,
2476 // and GCC cooperates with this by always setting the length to 0.
2477 auto selStruct = selectors.beginStruct(selStructTy);
2478 selStruct.add(NULLPtr);
2479 selStruct.add(NULLPtr);
2480 selStruct.finishAndAddTo(selectors);
2482 return selectors.finishAndCreateGlobal(".objc_selector_list",
2483 CGM.getPointerAlign());
2486 // Now that all of the static selectors exist, create pointers to them.
2487 for (unsigned i = 0; i < selectorCount; ++i) {
2488 llvm::Constant *idxs[] = {
2490 llvm::ConstantInt::get(Int32Ty, i)
2492 // FIXME: We're generating redundant loads and stores here!
2493 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2494 selectorList->getValueType(), selectorList, idxs);
2495 // If selectors are defined as an opaque type, cast the pointer to this
2497 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2498 selectorAliases[i]->replaceAllUsesWith(selPtr);
2499 selectorAliases[i]->eraseFromParent();
2502 llvm::GlobalVariable *symtab = [&] {
2503 ConstantInitBuilder builder(CGM);
2504 auto symtab = builder.beginStruct();
2506 // Number of static selectors
2507 symtab.addInt(LongTy, selectorCount);
2509 symtab.addBitCast(selectorList, selStructPtrTy);
2511 // Number of classes defined.
2512 symtab.addInt(CGM.Int16Ty, Classes.size());
2513 // Number of categories defined
2514 symtab.addInt(CGM.Int16Ty, Categories.size());
2516 // Create an array of classes, then categories, then static object instances
2517 auto classList = symtab.beginArray(PtrToInt8Ty);
2518 classList.addAll(Classes);
2519 classList.addAll(Categories);
2520 // NULL-terminated list of static object instances (mainly constant strings)
2521 classList.add(statics);
2522 classList.add(NULLPtr);
2523 classList.finishAndAddTo(symtab);
2525 // Construct the symbol table.
2526 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2529 // The symbol table is contained in a module which has some version-checking
2531 llvm::Constant *module = [&] {
2532 llvm::Type *moduleEltTys[] = {
2533 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2535 llvm::StructType *moduleTy =
2536 llvm::StructType::get(CGM.getLLVMContext(),
2537 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
2539 ConstantInitBuilder builder(CGM);
2540 auto module = builder.beginStruct(moduleTy);
2541 // Runtime version, used for ABI compatibility checking.
2542 module.addInt(LongTy, RuntimeVersion);
2544 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2546 // The path to the source file where this module was declared
2547 SourceManager &SM = CGM.getContext().getSourceManager();
2548 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2550 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
2551 module.add(MakeConstantString(path, ".objc_source_file_name"));
2554 if (RuntimeVersion >= 10) {
2555 switch (CGM.getLangOpts().getGC()) {
2556 case LangOptions::GCOnly:
2557 module.addInt(IntTy, 2);
2559 case LangOptions::NonGC:
2560 if (CGM.getLangOpts().ObjCAutoRefCount)
2561 module.addInt(IntTy, 1);
2563 module.addInt(IntTy, 0);
2565 case LangOptions::HybridGC:
2566 module.addInt(IntTy, 1);
2571 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2574 // Create the load function calling the runtime entry point with the module
2576 llvm::Function * LoadFunction = llvm::Function::Create(
2577 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2578 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2580 llvm::BasicBlock *EntryBB =
2581 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2582 CGBuilderTy Builder(CGM, VMContext);
2583 Builder.SetInsertPoint(EntryBB);
2585 llvm::FunctionType *FT =
2586 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
2587 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2588 Builder.CreateCall(Register, module);
2590 if (!ClassAliases.empty()) {
2591 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2592 llvm::FunctionType *RegisterAliasTy =
2593 llvm::FunctionType::get(Builder.getVoidTy(),
2595 llvm::Function *RegisterAlias = llvm::Function::Create(
2597 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2599 llvm::BasicBlock *AliasBB =
2600 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2601 llvm::BasicBlock *NoAliasBB =
2602 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2604 // Branch based on whether the runtime provided class_registerAlias_np()
2605 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2606 llvm::Constant::getNullValue(RegisterAlias->getType()));
2607 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2609 // The true branch (has alias registration function):
2610 Builder.SetInsertPoint(AliasBB);
2611 // Emit alias registration calls:
2612 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2613 iter != ClassAliases.end(); ++iter) {
2614 llvm::Constant *TheClass =
2615 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
2617 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2618 Builder.CreateCall(RegisterAlias,
2619 {TheClass, MakeConstantString(iter->second)});
2623 Builder.CreateBr(NoAliasBB);
2625 // Missing alias registration function, just return from the function:
2626 Builder.SetInsertPoint(NoAliasBB);
2628 Builder.CreateRetVoid();
2630 return LoadFunction;
2633 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2634 const ObjCContainerDecl *CD) {
2635 const ObjCCategoryImplDecl *OCD =
2636 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2637 StringRef CategoryName = OCD ? OCD->getName() : "";
2638 StringRef ClassName = CD->getName();
2639 Selector MethodName = OMD->getSelector();
2640 bool isClassMethod = !OMD->isInstanceMethod();
2642 CodeGenTypes &Types = CGM.getTypes();
2643 llvm::FunctionType *MethodTy =
2644 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2645 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2646 MethodName, isClassMethod);
2648 llvm::Function *Method
2649 = llvm::Function::Create(MethodTy,
2650 llvm::GlobalValue::InternalLinkage,
2656 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2657 return GetPropertyFn;
2660 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2661 return SetPropertyFn;
2664 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2669 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2670 return GetStructPropertyFn;
2673 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2674 return SetStructPropertyFn;
2677 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2681 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2685 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2686 return EnumerationMutationFn;
2689 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2690 const ObjCAtSynchronizedStmt &S) {
2691 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2695 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2696 const ObjCAtTryStmt &S) {
2697 // Unlike the Apple non-fragile runtimes, which also uses
2698 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2699 // EH support isn't a veneer over C++ EH. Instead, exception
2700 // objects are created by objc_exception_throw and destroyed by
2701 // the personality function; this avoids the need for bracketing
2702 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2703 // (or even _Unwind_DeleteException), but probably doesn't
2704 // interoperate very well with foreign exceptions.
2706 // In Objective-C++ mode, we actually emit something equivalent to the C++
2707 // exception handler.
2708 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2711 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2712 const ObjCAtThrowStmt &S,
2713 bool ClearInsertionPoint) {
2714 llvm::Value *ExceptionAsObject;
2716 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2717 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2718 ExceptionAsObject = Exception;
2720 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2721 "Unexpected rethrow outside @catch block.");
2722 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2724 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2725 llvm::CallSite Throw =
2726 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2727 Throw.setDoesNotReturn();
2728 CGF.Builder.CreateUnreachable();
2729 if (ClearInsertionPoint)
2730 CGF.Builder.ClearInsertionPoint();
2733 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2734 Address AddrWeakObj) {
2735 CGBuilderTy &B = CGF.Builder;
2736 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2737 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2738 AddrWeakObj.getPointer());
2741 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2742 llvm::Value *src, Address dst) {
2743 CGBuilderTy &B = CGF.Builder;
2744 src = EnforceType(B, src, IdTy);
2745 dst = EnforceType(B, dst, PtrToIdTy);
2746 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2747 {src, dst.getPointer()});
2750 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2751 llvm::Value *src, Address dst,
2753 CGBuilderTy &B = CGF.Builder;
2754 src = EnforceType(B, src, IdTy);
2755 dst = EnforceType(B, dst, PtrToIdTy);
2756 // FIXME. Add threadloca assign API
2757 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
2758 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2759 {src, dst.getPointer()});
2762 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2763 llvm::Value *src, Address dst,
2764 llvm::Value *ivarOffset) {
2765 CGBuilderTy &B = CGF.Builder;
2766 src = EnforceType(B, src, IdTy);
2767 dst = EnforceType(B, dst, IdTy);
2768 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2769 {src, dst.getPointer(), ivarOffset});
2772 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2773 llvm::Value *src, Address dst) {
2774 CGBuilderTy &B = CGF.Builder;
2775 src = EnforceType(B, src, IdTy);
2776 dst = EnforceType(B, dst, PtrToIdTy);
2777 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2778 {src, dst.getPointer()});
2781 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2784 llvm::Value *Size) {
2785 CGBuilderTy &B = CGF.Builder;
2786 DestPtr = EnforceType(B, DestPtr, PtrTy);
2787 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2789 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2790 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
2793 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2794 const ObjCInterfaceDecl *ID,
2795 const ObjCIvarDecl *Ivar) {
2796 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2797 + '.' + Ivar->getNameAsString();
2798 // Emit the variable and initialize it with what we think the correct value
2799 // is. This allows code compiled with non-fragile ivars to work correctly
2800 // when linked against code which isn't (most of the time).
2801 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2802 if (!IvarOffsetPointer) {
2803 // This will cause a run-time crash if we accidentally use it. A value of
2804 // 0 would seem more sensible, but will silently overwrite the isa pointer
2805 // causing a great deal of confusion.
2806 uint64_t Offset = -1;
2807 // We can't call ComputeIvarBaseOffset() here if we have the
2808 // implementation, because it will create an invalid ASTRecordLayout object
2809 // that we are then stuck with forever, so we only initialize the ivar
2810 // offset variable with a guess if we only have the interface. The
2811 // initializer will be reset later anyway, when we are generating the class
2813 if (!CGM.getContext().getObjCImplementation(
2814 const_cast<ObjCInterfaceDecl *>(ID)))
2815 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2817 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2819 // Don't emit the guess in non-PIC code because the linker will not be able
2820 // to replace it with the real version for a library. In non-PIC code you
2821 // must compile with the fragile ABI if you want to use ivars from a
2822 // GCC-compiled class.
2823 if (CGM.getLangOpts().PICLevel) {
2824 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2826 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2827 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2828 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2829 IvarOffsetGV, Name);
2831 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2832 llvm::Type::getInt32PtrTy(VMContext), false,
2833 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
2836 return IvarOffsetPointer;
2839 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2841 llvm::Value *BaseValue,
2842 const ObjCIvarDecl *Ivar,
2843 unsigned CVRQualifiers) {
2844 const ObjCInterfaceDecl *ID =
2845 ObjectTy->getAs<ObjCObjectType>()->getInterface();
2846 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2847 EmitIvarOffset(CGF, ID, Ivar));
2850 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2851 const ObjCInterfaceDecl *OID,
2852 const ObjCIvarDecl *OIVD) {
2853 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2854 next = next->getNextIvar()) {
2859 // Otherwise check in the super class.
2860 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2861 return FindIvarInterface(Context, Super, OIVD);
2866 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2867 const ObjCInterfaceDecl *Interface,
2868 const ObjCIvarDecl *Ivar) {
2869 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2870 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2872 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2873 // and ExternalLinkage, so create a reference to the ivar global and rely on
2874 // the definition being created as part of GenerateClass.
2875 if (RuntimeVersion < 10 ||
2876 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
2877 return CGF.Builder.CreateZExtOrBitCast(
2878 CGF.Builder.CreateAlignedLoad(
2879 Int32Ty, CGF.Builder.CreateAlignedLoad(
2880 ObjCIvarOffsetVariable(Interface, Ivar),
2881 CGF.getPointerAlign(), "ivar"),
2882 CharUnits::fromQuantity(4)),
2884 std::string name = "__objc_ivar_offset_value_" +
2885 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2886 CharUnits Align = CGM.getIntAlign();
2887 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2889 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
2890 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2891 llvm::Constant::getNullValue(IntTy), name);
2892 GV->setAlignment(Align.getQuantity());
2895 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
2896 if (Offset->getType() != PtrDiffTy)
2897 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2900 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2901 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2905 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2906 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2907 case ObjCRuntime::GNUstep:
2908 return new CGObjCGNUstep(CGM);
2910 case ObjCRuntime::GCC:
2911 return new CGObjCGCC(CGM);
2913 case ObjCRuntime::ObjFW:
2914 return new CGObjCObjFW(CGM);
2916 case ObjCRuntime::FragileMacOSX:
2917 case ObjCRuntime::MacOSX:
2918 case ObjCRuntime::iOS:
2919 case ObjCRuntime::WatchOS:
2920 llvm_unreachable("these runtimes are not GNU runtimes");
2922 llvm_unreachable("bad runtime");