1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides Objective-C code generation targeting the GNU runtime. The
11 // class in this file generates structures used by the GNU Objective-C runtime
12 // library. These structures are defined in objc/objc.h and objc/objc-api.h in
13 // the GNU runtime distribution.
15 //===----------------------------------------------------------------------===//
17 #include "CGObjCRuntime.h"
18 #include "CGCleanup.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/CodeGen/ConstantInitBuilder.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"
38 using namespace clang;
39 using namespace CodeGen;
42 /// Class that lazily initialises the runtime function. Avoids inserting the
43 /// types and the function declaration into a module if they're not used, and
44 /// avoids constructing the type more than once if it's used more than once.
45 class LazyRuntimeFunction {
47 llvm::FunctionType *FTy;
48 const char *FunctionName;
49 llvm::Constant *Function;
52 /// Constructor leaves this class uninitialized, because it is intended to
53 /// be used as a field in another class and not all of the types that are
54 /// used as arguments will necessarily be available at construction time.
56 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
58 /// Initialises the lazy function with the name, return type, and the types
60 template <typename... Tys>
61 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
67 SmallVector<llvm::Type *, 8> ArgTys({Types...});
68 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
71 FTy = llvm::FunctionType::get(RetTy, None, 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);
607 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
608 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
609 PtrToObjCSuperTy, SelectorTy);
613 /// Class used when targeting the new GNUstep runtime ABI.
614 class CGObjCGNUstep : public CGObjCGNU {
615 /// The slot lookup function. Returns a pointer to a cacheable structure
616 /// that contains (among other things) the IMP.
617 LazyRuntimeFunction SlotLookupFn;
618 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
619 /// a structure describing the receiver and the class, and a selector as
620 /// arguments. Returns the slot for the corresponding method. Superclass
621 /// message lookup rarely changes, so this is a good caching opportunity.
622 LazyRuntimeFunction SlotLookupSuperFn;
623 /// Specialised function for setting atomic retain properties
624 LazyRuntimeFunction SetPropertyAtomic;
625 /// Specialised function for setting atomic copy properties
626 LazyRuntimeFunction SetPropertyAtomicCopy;
627 /// Specialised function for setting nonatomic retain properties
628 LazyRuntimeFunction SetPropertyNonAtomic;
629 /// Specialised function for setting nonatomic copy properties
630 LazyRuntimeFunction SetPropertyNonAtomicCopy;
631 /// Function to perform atomic copies of C++ objects with nontrivial copy
632 /// constructors from Objective-C ivars.
633 LazyRuntimeFunction CxxAtomicObjectGetFn;
634 /// Function to perform atomic copies of C++ objects with nontrivial copy
635 /// constructors to Objective-C ivars.
636 LazyRuntimeFunction CxxAtomicObjectSetFn;
637 /// Type of an slot structure pointer. This is returned by the various
638 /// lookup functions.
642 llvm::Constant *GetEHType(QualType T) override;
645 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
646 llvm::Value *cmd, llvm::MDNode *node,
647 MessageSendInfo &MSI) override {
648 CGBuilderTy &Builder = CGF.Builder;
649 llvm::Function *LookupFn = SlotLookupFn;
651 // Store the receiver on the stack so that we can reload it later
652 Address ReceiverPtr =
653 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
654 Builder.CreateStore(Receiver, ReceiverPtr);
658 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
659 self = CGF.LoadObjCSelf();
661 self = llvm::ConstantPointerNull::get(IdTy);
664 // The lookup function is guaranteed not to capture the receiver pointer.
665 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
667 llvm::Value *args[] = {
668 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
669 EnforceType(Builder, cmd, SelectorTy),
670 EnforceType(Builder, self, IdTy) };
671 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
672 slot.setOnlyReadsMemory();
673 slot->setMetadata(msgSendMDKind, node);
675 // Load the imp from the slot
676 llvm::Value *imp = Builder.CreateAlignedLoad(
677 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
678 CGF.getPointerAlign());
680 // The lookup function may have changed the receiver, so make sure we use
682 Receiver = Builder.CreateLoad(ReceiverPtr, true);
686 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
688 MessageSendInfo &MSI) override {
689 CGBuilderTy &Builder = CGF.Builder;
690 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
692 llvm::CallInst *slot =
693 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
694 slot->setOnlyReadsMemory();
696 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
697 CGF.getPointerAlign());
701 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
702 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
704 llvm::StructType *SlotStructTy =
705 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
706 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
707 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
708 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
710 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
711 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
712 PtrToObjCSuperTy, SelectorTy);
713 // If we're in ObjC++ mode, then we want to make
714 if (CGM.getLangOpts().CPlusPlus) {
715 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
716 // void *__cxa_begin_catch(void *e)
717 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
718 // void __cxa_end_catch(void)
719 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
720 // void _Unwind_Resume_or_Rethrow(void*)
721 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
723 } else if (R.getVersion() >= VersionTuple(1, 7)) {
724 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
725 // id objc_begin_catch(void *e)
726 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
727 // void objc_end_catch(void)
728 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
729 // void _Unwind_Resume_or_Rethrow(void*)
730 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
732 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
733 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
734 SelectorTy, IdTy, PtrDiffTy);
735 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
736 IdTy, SelectorTy, IdTy, PtrDiffTy);
737 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
738 IdTy, SelectorTy, IdTy, PtrDiffTy);
739 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
740 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
741 // void objc_setCppObjectAtomic(void *dest, const void *src, void
743 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
745 // void objc_getCppObjectAtomic(void *dest, const void *src, void
747 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
751 llvm::Constant *GetCppAtomicObjectGetFunction() override {
752 // The optimised functions were added in version 1.7 of the GNUstep
754 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
756 return CxxAtomicObjectGetFn;
759 llvm::Constant *GetCppAtomicObjectSetFunction() override {
760 // The optimised functions were added in version 1.7 of the GNUstep
762 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
764 return CxxAtomicObjectSetFn;
767 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
768 bool copy) override {
769 // The optimised property functions omit the GC check, and so are not
770 // safe to use in GC mode. The standard functions are fast in GC mode,
771 // so there is less advantage in using them.
772 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
773 // The optimised functions were added in version 1.7 of the GNUstep
775 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
779 if (copy) return SetPropertyAtomicCopy;
780 return SetPropertyAtomic;
783 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
787 /// Support for the ObjFW runtime.
788 class CGObjCObjFW: public CGObjCGNU {
790 /// The GCC ABI message lookup function. Returns an IMP pointing to the
791 /// method implementation for this message.
792 LazyRuntimeFunction MsgLookupFn;
793 /// stret lookup function. While this does not seem to make sense at the
794 /// first look, this is required to call the correct forwarding function.
795 LazyRuntimeFunction MsgLookupFnSRet;
796 /// The GCC ABI superclass message lookup function. Takes a pointer to a
797 /// structure describing the receiver and the class, and a selector as
798 /// arguments. Returns the IMP for the corresponding method.
799 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
801 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
802 llvm::Value *cmd, llvm::MDNode *node,
803 MessageSendInfo &MSI) override {
804 CGBuilderTy &Builder = CGF.Builder;
805 llvm::Value *args[] = {
806 EnforceType(Builder, Receiver, IdTy),
807 EnforceType(Builder, cmd, SelectorTy) };
810 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
811 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
813 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
815 imp->setMetadata(msgSendMDKind, node);
816 return imp.getInstruction();
819 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
820 llvm::Value *cmd, MessageSendInfo &MSI) override {
821 CGBuilderTy &Builder = CGF.Builder;
822 llvm::Value *lookupArgs[] = {
823 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
826 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
827 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
829 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
832 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
833 bool isWeak) override {
835 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
838 std::string SymbolName = "_OBJC_CLASS_" + Name;
839 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
841 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
842 llvm::GlobalValue::ExternalLinkage,
843 nullptr, SymbolName);
848 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
849 // IMP objc_msg_lookup(id, SEL);
850 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
851 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
853 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
854 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
855 PtrToObjCSuperTy, SelectorTy);
856 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
857 PtrToObjCSuperTy, SelectorTy);
860 } // end anonymous namespace
862 /// Emits a reference to a dummy variable which is emitted with each class.
863 /// This ensures that a linker error will be generated when trying to link
864 /// together modules where a referenced class is not defined.
865 void CGObjCGNU::EmitClassRef(const std::string &className) {
866 std::string symbolRef = "__objc_class_ref_" + className;
867 // Don't emit two copies of the same symbol
868 if (TheModule.getGlobalVariable(symbolRef))
870 std::string symbolName = "__objc_class_name_" + className;
871 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
873 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
874 llvm::GlobalValue::ExternalLinkage,
875 nullptr, symbolName);
877 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
878 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
881 static std::string SymbolNameForMethod( StringRef ClassName,
882 StringRef CategoryName, const Selector MethodName,
883 bool isClassMethod) {
884 std::string MethodNameColonStripped = MethodName.getAsString();
885 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
887 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
888 CategoryName + "_" + MethodNameColonStripped).str();
891 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
892 unsigned protocolClassVersion)
893 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
894 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
895 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
896 ProtocolVersion(protocolClassVersion) {
898 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
900 CodeGenTypes &Types = CGM.getTypes();
901 IntTy = cast<llvm::IntegerType>(
902 Types.ConvertType(CGM.getContext().IntTy));
903 LongTy = cast<llvm::IntegerType>(
904 Types.ConvertType(CGM.getContext().LongTy));
905 SizeTy = cast<llvm::IntegerType>(
906 Types.ConvertType(CGM.getContext().getSizeType()));
907 PtrDiffTy = cast<llvm::IntegerType>(
908 Types.ConvertType(CGM.getContext().getPointerDiffType()));
909 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
911 Int8Ty = llvm::Type::getInt8Ty(VMContext);
912 // C string type. Used in lots of places.
913 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
915 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
917 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
918 // Get the selector Type.
919 QualType selTy = CGM.getContext().getObjCSelType();
920 if (QualType() == selTy) {
921 SelectorTy = PtrToInt8Ty;
923 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
926 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
929 Int32Ty = llvm::Type::getInt32Ty(VMContext);
930 Int64Ty = llvm::Type::getInt64Ty(VMContext);
933 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
936 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
937 ASTIdTy = CanQualType();
938 if (UnqualIdTy != QualType()) {
939 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
940 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
944 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
946 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
947 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
949 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
951 // void objc_exception_throw(id);
952 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
953 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
954 // int objc_sync_enter(id);
955 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
956 // int objc_sync_exit(id);
957 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
959 // void objc_enumerationMutation (id)
960 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
962 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
963 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
965 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
966 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
967 PtrDiffTy, IdTy, BoolTy, BoolTy);
968 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
969 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
970 PtrDiffTy, BoolTy, BoolTy);
971 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
972 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
973 PtrDiffTy, BoolTy, BoolTy);
976 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
977 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
980 const LangOptions &Opts = CGM.getLangOpts();
981 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
984 // Don't bother initialising the GC stuff unless we're compiling in GC mode
985 if (Opts.getGC() != LangOptions::NonGC) {
986 // This is a bit of an hack. We should sort this out by having a proper
987 // CGObjCGNUstep subclass for GC, but we may want to really support the old
988 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
989 // Get selectors needed in GC mode
990 RetainSel = GetNullarySelector("retain", CGM.getContext());
991 ReleaseSel = GetNullarySelector("release", CGM.getContext());
992 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
994 // Get functions needed in GC mode
996 // id objc_assign_ivar(id, id, ptrdiff_t);
997 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
998 // id objc_assign_strongCast (id, id*)
999 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
1001 // id objc_assign_global(id, id*);
1002 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
1003 // id objc_assign_weak(id, id*);
1004 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
1005 // id objc_read_weak(id*);
1006 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
1007 // void *objc_memmove_collectable(void*, void *, size_t);
1008 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1013 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1014 const std::string &Name, bool isWeak) {
1015 llvm::Constant *ClassName = MakeConstantString(Name);
1016 // With the incompatible ABI, this will need to be replaced with a direct
1017 // reference to the class symbol. For the compatible nonfragile ABI we are
1018 // still performing this lookup at run time but emitting the symbol for the
1019 // class externally so that we can make the switch later.
1021 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1022 // with memoized versions or with static references if it's safe to do so.
1026 llvm::Constant *ClassLookupFn =
1027 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1028 "objc_lookup_class");
1029 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1032 // This has to perform the lookup every time, since posing and related
1033 // techniques can modify the name -> class mapping.
1034 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1035 const ObjCInterfaceDecl *OID) {
1037 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1038 if (CGM.getTriple().isOSBinFormatCOFF()) {
1039 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1040 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1041 if (OID->hasAttr<DLLExportAttr>())
1042 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1043 else if (OID->hasAttr<DLLImportAttr>())
1044 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1045 ClassSymbol->setDLLStorageClass(DLLStorage);
1051 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1052 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1053 if (CGM.getTriple().isOSBinFormatCOFF()) {
1054 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1055 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1056 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1057 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1059 const VarDecl *VD = nullptr;
1060 for (const auto &Result : DC->lookup(&II))
1061 if ((VD = dyn_cast<VarDecl>(Result)))
1064 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1065 if (!VD || VD->hasAttr<DLLImportAttr>())
1066 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1067 else if (VD->hasAttr<DLLExportAttr>())
1068 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1070 ClassSymbol->setDLLStorageClass(DLLStorage);
1076 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1077 const std::string &TypeEncoding) {
1078 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1079 llvm::GlobalAlias *SelValue = nullptr;
1081 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1082 e = Types.end() ; i!=e ; i++) {
1083 if (i->first == TypeEncoding) {
1084 SelValue = i->second;
1089 SelValue = llvm::GlobalAlias::create(
1090 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1091 ".objc_selector_" + Sel.getAsString(), &TheModule);
1092 Types.emplace_back(TypeEncoding, SelValue);
1098 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1099 llvm::Value *SelValue = GetSelector(CGF, Sel);
1101 // Store it to a temporary. Does this satisfy the semantics of
1102 // GetAddrOfSelector? Hopefully.
1103 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1104 CGF.getPointerAlign());
1105 CGF.Builder.CreateStore(SelValue, tmp);
1109 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1110 return GetSelector(CGF, Sel, std::string());
1113 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1114 const ObjCMethodDecl *Method) {
1115 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
1116 return GetSelector(CGF, Method->getSelector(), SelTypes);
1119 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1120 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1121 // With the old ABI, there was only one kind of catchall, which broke
1122 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1123 // a pointer indicating object catchalls, and NULL to indicate real
1125 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1126 return MakeConstantString("@id");
1132 // All other types should be Objective-C interface pointer types.
1133 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1134 assert(OPT && "Invalid @catch type.");
1135 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1136 assert(IDecl && "Invalid @catch type.");
1137 return MakeConstantString(IDecl->getIdentifier()->getName());
1140 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1141 if (!CGM.getLangOpts().CPlusPlus)
1142 return CGObjCGNU::GetEHType(T);
1144 // For Objective-C++, we want to provide the ability to catch both C++ and
1145 // Objective-C objects in the same function.
1147 // There's a particular fixed type info for 'id'.
1148 if (T->isObjCIdType() ||
1149 T->isObjCQualifiedIdType()) {
1150 llvm::Constant *IDEHType =
1151 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1154 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1156 llvm::GlobalValue::ExternalLinkage,
1157 nullptr, "__objc_id_type_info");
1158 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1161 const ObjCObjectPointerType *PT =
1162 T->getAs<ObjCObjectPointerType>();
1163 assert(PT && "Invalid @catch type.");
1164 const ObjCInterfaceType *IT = PT->getInterfaceType();
1165 assert(IT && "Invalid @catch type.");
1166 std::string className = IT->getDecl()->getIdentifier()->getName();
1168 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1170 // Return the existing typeinfo if it exists
1171 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1173 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1175 // Otherwise create it.
1177 // vtable for gnustep::libobjc::__objc_class_type_info
1178 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1179 // platform's name mangling.
1180 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1181 auto *Vtable = TheModule.getGlobalVariable(vtableName);
1183 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1184 llvm::GlobalValue::ExternalLinkage,
1185 nullptr, vtableName);
1187 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1188 auto *BVtable = llvm::ConstantExpr::getBitCast(
1189 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1192 llvm::Constant *typeName =
1193 ExportUniqueString(className, "__objc_eh_typename_");
1195 ConstantInitBuilder builder(CGM);
1196 auto fields = builder.beginStruct();
1197 fields.add(BVtable);
1198 fields.add(typeName);
1199 llvm::Constant *TI =
1200 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1201 CGM.getPointerAlign(),
1203 llvm::GlobalValue::LinkOnceODRLinkage);
1204 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1207 /// Generate an NSConstantString object.
1208 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1210 std::string Str = SL->getString().str();
1211 CharUnits Align = CGM.getPointerAlign();
1213 // Look for an existing one
1214 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1215 if (old != ObjCStrings.end())
1216 return ConstantAddress(old->getValue(), Align);
1218 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1220 if (StringClass.empty()) StringClass = "NXConstantString";
1222 std::string Sym = "_OBJC_CLASS_";
1225 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1228 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1229 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
1230 else if (isa->getType() != PtrToIdTy)
1231 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1233 ConstantInitBuilder Builder(CGM);
1234 auto Fields = Builder.beginStruct();
1236 Fields.add(MakeConstantString(Str));
1237 Fields.addInt(IntTy, Str.size());
1238 llvm::Constant *ObjCStr =
1239 Fields.finishAndCreateGlobal(".objc_str", Align);
1240 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1241 ObjCStrings[Str] = ObjCStr;
1242 ConstantStrings.push_back(ObjCStr);
1243 return ConstantAddress(ObjCStr, Align);
1246 ///Generates a message send where the super is the receiver. This is a message
1247 ///send to self with special delivery semantics indicating which class's method
1248 ///should be called.
1250 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1251 ReturnValueSlot Return,
1252 QualType ResultType,
1254 const ObjCInterfaceDecl *Class,
1255 bool isCategoryImpl,
1256 llvm::Value *Receiver,
1257 bool IsClassMessage,
1258 const CallArgList &CallArgs,
1259 const ObjCMethodDecl *Method) {
1260 CGBuilderTy &Builder = CGF.Builder;
1261 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1262 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1263 return RValue::get(EnforceType(Builder, Receiver,
1264 CGM.getTypes().ConvertType(ResultType)));
1266 if (Sel == ReleaseSel) {
1267 return RValue::get(nullptr);
1271 llvm::Value *cmd = GetSelector(CGF, Sel);
1272 CallArgList ActualArgs;
1274 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1275 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1276 ActualArgs.addFrom(CallArgs);
1278 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1280 llvm::Value *ReceiverClass = nullptr;
1281 if (isCategoryImpl) {
1282 llvm::Constant *classLookupFunction = nullptr;
1283 if (IsClassMessage) {
1284 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1285 IdTy, PtrTy, true), "objc_get_meta_class");
1287 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1288 IdTy, PtrTy, true), "objc_get_class");
1290 ReceiverClass = Builder.CreateCall(classLookupFunction,
1291 MakeConstantString(Class->getNameAsString()));
1293 // Set up global aliases for the metaclass or class pointer if they do not
1294 // already exist. These will are forward-references which will be set to
1295 // pointers to the class and metaclass structure created for the runtime
1296 // load function. To send a message to super, we look up the value of the
1297 // super_class pointer from either the class or metaclass structure.
1298 if (IsClassMessage) {
1299 if (!MetaClassPtrAlias) {
1300 MetaClassPtrAlias = llvm::GlobalAlias::create(
1301 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1302 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1304 ReceiverClass = MetaClassPtrAlias;
1306 if (!ClassPtrAlias) {
1307 ClassPtrAlias = llvm::GlobalAlias::create(
1308 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1309 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1311 ReceiverClass = ClassPtrAlias;
1314 // Cast the pointer to a simplified version of the class structure
1315 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
1316 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1317 llvm::PointerType::getUnqual(CastTy));
1318 // Get the superclass pointer
1319 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1320 // Load the superclass pointer
1322 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
1323 // Construct the structure used to look up the IMP
1324 llvm::StructType *ObjCSuperTy =
1325 llvm::StructType::get(Receiver->getType(), IdTy);
1327 // FIXME: Is this really supposed to be a dynamic alloca?
1328 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1329 CGF.getPointerAlign());
1331 Builder.CreateStore(Receiver,
1332 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
1333 Builder.CreateStore(ReceiverClass,
1334 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
1336 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1339 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1340 imp = EnforceType(Builder, imp, MSI.MessengerType);
1342 llvm::Metadata *impMD[] = {
1343 llvm::MDString::get(VMContext, Sel.getAsString()),
1344 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1345 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1346 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
1347 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1349 CGCallee callee(CGCalleeInfo(), imp);
1351 llvm::Instruction *call;
1352 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1353 call->setMetadata(msgSendMDKind, node);
1357 /// Generate code for a message send expression.
1359 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1360 ReturnValueSlot Return,
1361 QualType ResultType,
1363 llvm::Value *Receiver,
1364 const CallArgList &CallArgs,
1365 const ObjCInterfaceDecl *Class,
1366 const ObjCMethodDecl *Method) {
1367 CGBuilderTy &Builder = CGF.Builder;
1369 // Strip out message sends to retain / release in GC mode
1370 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1371 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1372 return RValue::get(EnforceType(Builder, Receiver,
1373 CGM.getTypes().ConvertType(ResultType)));
1375 if (Sel == ReleaseSel) {
1376 return RValue::get(nullptr);
1380 // If the return type is something that goes in an integer register, the
1381 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1384 // The language spec says the result of this kind of message send is
1385 // undefined, but lots of people seem to have forgotten to read that
1386 // paragraph and insist on sending messages to nil that have structure
1387 // returns. With GCC, this generates a random return value (whatever happens
1388 // to be on the stack / in those registers at the time) on most platforms,
1389 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1391 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1392 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1394 llvm::BasicBlock *startBB = nullptr;
1395 llvm::BasicBlock *messageBB = nullptr;
1396 llvm::BasicBlock *continueBB = nullptr;
1398 if (!isPointerSizedReturn) {
1399 startBB = Builder.GetInsertBlock();
1400 messageBB = CGF.createBasicBlock("msgSend");
1401 continueBB = CGF.createBasicBlock("continue");
1403 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1404 llvm::Constant::getNullValue(Receiver->getType()));
1405 Builder.CreateCondBr(isNil, continueBB, messageBB);
1406 CGF.EmitBlock(messageBB);
1409 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1412 cmd = GetSelector(CGF, Method);
1414 cmd = GetSelector(CGF, Sel);
1415 cmd = EnforceType(Builder, cmd, SelectorTy);
1416 Receiver = EnforceType(Builder, Receiver, IdTy);
1418 llvm::Metadata *impMD[] = {
1419 llvm::MDString::get(VMContext, Sel.getAsString()),
1420 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1421 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1422 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
1423 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1425 CallArgList ActualArgs;
1426 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1427 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1428 ActualArgs.addFrom(CallArgs);
1430 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1432 // Get the IMP to call
1435 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1436 // functions. These are not supported on all platforms (or all runtimes on a
1437 // given platform), so we
1438 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1439 case CodeGenOptions::Legacy:
1440 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1442 case CodeGenOptions::Mixed:
1443 case CodeGenOptions::NonLegacy:
1444 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1445 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1446 "objc_msgSend_fpret");
1447 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1448 // The actual types here don't matter - we're going to bitcast the
1450 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1451 "objc_msgSend_stret");
1453 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1458 // Reset the receiver in case the lookup modified it
1459 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1461 imp = EnforceType(Builder, imp, MSI.MessengerType);
1463 llvm::Instruction *call;
1464 CGCallee callee(CGCalleeInfo(), imp);
1465 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1466 call->setMetadata(msgSendMDKind, node);
1469 if (!isPointerSizedReturn) {
1470 messageBB = CGF.Builder.GetInsertBlock();
1471 CGF.Builder.CreateBr(continueBB);
1472 CGF.EmitBlock(continueBB);
1473 if (msgRet.isScalar()) {
1474 llvm::Value *v = msgRet.getScalarVal();
1475 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1476 phi->addIncoming(v, messageBB);
1477 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1478 msgRet = RValue::get(phi);
1479 } else if (msgRet.isAggregate()) {
1480 Address v = msgRet.getAggregateAddress();
1481 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1482 llvm::Type *RetTy = v.getElementType();
1483 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1484 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1485 phi->addIncoming(v.getPointer(), messageBB);
1486 phi->addIncoming(NullVal.getPointer(), startBB);
1487 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
1488 } else /* isComplex() */ {
1489 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1490 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1491 phi->addIncoming(v.first, messageBB);
1492 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1494 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1495 phi2->addIncoming(v.second, messageBB);
1496 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1498 msgRet = RValue::getComplex(phi, phi2);
1504 /// Generates a MethodList. Used in construction of a objc_class and
1505 /// objc_category structures.
1506 llvm::Constant *CGObjCGNU::
1507 GenerateMethodList(StringRef ClassName,
1508 StringRef CategoryName,
1509 ArrayRef<Selector> MethodSels,
1510 ArrayRef<llvm::Constant *> MethodTypes,
1511 bool isClassMethodList) {
1512 if (MethodSels.empty())
1515 ConstantInitBuilder Builder(CGM);
1517 auto MethodList = Builder.beginStruct();
1518 MethodList.addNullPointer(CGM.Int8PtrTy);
1519 MethodList.addInt(Int32Ty, MethodTypes.size());
1521 // Get the method structure type.
1522 llvm::StructType *ObjCMethodTy =
1523 llvm::StructType::get(CGM.getLLVMContext(), {
1524 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1525 PtrToInt8Ty, // Method types
1526 IMPTy // Method pointer
1528 auto Methods = MethodList.beginArray();
1529 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1530 llvm::Constant *FnPtr =
1531 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1533 isClassMethodList));
1534 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
1535 auto Method = Methods.beginStruct(ObjCMethodTy);
1536 Method.add(MakeConstantString(MethodSels[i].getAsString()));
1537 Method.add(MethodTypes[i]);
1538 Method.addBitCast(FnPtr, IMPTy);
1539 Method.finishAndAddTo(Methods);
1541 Methods.finishAndAddTo(MethodList);
1543 // Create an instance of the structure
1544 return MethodList.finishAndCreateGlobal(".objc_method_list",
1545 CGM.getPointerAlign());
1548 /// Generates an IvarList. Used in construction of a objc_class.
1549 llvm::Constant *CGObjCGNU::
1550 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1551 ArrayRef<llvm::Constant *> IvarTypes,
1552 ArrayRef<llvm::Constant *> IvarOffsets) {
1553 if (IvarNames.empty())
1556 ConstantInitBuilder Builder(CGM);
1558 // Structure containing array count followed by array.
1559 auto IvarList = Builder.beginStruct();
1560 IvarList.addInt(IntTy, (int)IvarNames.size());
1562 // Get the ivar structure type.
1563 llvm::StructType *ObjCIvarTy =
1564 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
1566 // Array of ivar structures.
1567 auto Ivars = IvarList.beginArray(ObjCIvarTy);
1568 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1569 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1570 Ivar.add(IvarNames[i]);
1571 Ivar.add(IvarTypes[i]);
1572 Ivar.add(IvarOffsets[i]);
1573 Ivar.finishAndAddTo(Ivars);
1575 Ivars.finishAndAddTo(IvarList);
1577 // Create an instance of the structure
1578 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1579 CGM.getPointerAlign());
1582 /// Generate a class structure
1583 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1584 llvm::Constant *MetaClass,
1585 llvm::Constant *SuperClass,
1588 llvm::Constant *Version,
1589 llvm::Constant *InstanceSize,
1590 llvm::Constant *IVars,
1591 llvm::Constant *Methods,
1592 llvm::Constant *Protocols,
1593 llvm::Constant *IvarOffsets,
1594 llvm::Constant *Properties,
1595 llvm::Constant *StrongIvarBitmap,
1596 llvm::Constant *WeakIvarBitmap,
1598 // Set up the class structure
1599 // Note: Several of these are char*s when they should be ids. This is
1600 // because the runtime performs this translation on load.
1602 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1603 // anyway; the classes will still work with the GNU runtime, they will just
1605 llvm::StructType *ClassTy = llvm::StructType::get(
1607 PtrToInt8Ty, // super_class
1608 PtrToInt8Ty, // name
1611 LongTy, // instance_size
1612 IVars->getType(), // ivars
1613 Methods->getType(), // methods
1614 // These are all filled in by the runtime, so we pretend
1616 PtrTy, // subclass_list
1617 PtrTy, // sibling_class
1619 PtrTy, // gc_object_type
1621 LongTy, // abi_version
1622 IvarOffsets->getType(), // ivar_offsets
1623 Properties->getType(), // properties
1624 IntPtrTy, // strong_pointers
1625 IntPtrTy // weak_pointers
1628 ConstantInitBuilder Builder(CGM);
1629 auto Elements = Builder.beginStruct(ClassTy);
1631 // Fill in the structure
1634 Elements.addBitCast(MetaClass, PtrToInt8Ty);
1636 Elements.add(SuperClass);
1638 Elements.add(MakeConstantString(Name, ".class_name"));
1640 Elements.addInt(LongTy, 0);
1642 Elements.addInt(LongTy, info);
1645 llvm::DataLayout td(&TheModule);
1646 Elements.addInt(LongTy,
1647 td.getTypeSizeInBits(ClassTy) /
1648 CGM.getContext().getCharWidth());
1650 Elements.add(InstanceSize);
1652 Elements.add(IVars);
1654 Elements.add(Methods);
1655 // These are all filled in by the runtime, so we pretend
1657 Elements.add(NULLPtr);
1659 Elements.add(NULLPtr);
1661 Elements.add(NULLPtr);
1663 Elements.addBitCast(Protocols, PtrTy);
1665 Elements.add(NULLPtr);
1667 Elements.addInt(LongTy, 1);
1669 Elements.add(IvarOffsets);
1671 Elements.add(Properties);
1673 Elements.add(StrongIvarBitmap);
1675 Elements.add(WeakIvarBitmap);
1676 // Create an instance of the structure
1677 // This is now an externally visible symbol, so that we can speed up class
1678 // messages in the next ABI. We may already have some weak references to
1679 // this, so check and fix them properly.
1680 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1682 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1683 llvm::Constant *Class =
1684 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1685 llvm::GlobalValue::ExternalLinkage);
1687 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1688 ClassRef->getType()));
1689 ClassRef->removeFromParent();
1690 Class->setName(ClassSym);
1695 llvm::Constant *CGObjCGNU::
1696 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1697 ArrayRef<llvm::Constant *> MethodTypes) {
1698 // Get the method structure type.
1699 llvm::StructType *ObjCMethodDescTy =
1700 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
1701 ConstantInitBuilder Builder(CGM);
1702 auto MethodList = Builder.beginStruct();
1703 MethodList.addInt(IntTy, MethodNames.size());
1704 auto Methods = MethodList.beginArray(ObjCMethodDescTy);
1705 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1706 auto Method = Methods.beginStruct(ObjCMethodDescTy);
1707 Method.add(MethodNames[i]);
1708 Method.add(MethodTypes[i]);
1709 Method.finishAndAddTo(Methods);
1711 Methods.finishAndAddTo(MethodList);
1712 return MethodList.finishAndCreateGlobal(".objc_method_list",
1713 CGM.getPointerAlign());
1716 // Create the protocol list structure used in classes, categories and so on
1718 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1720 ConstantInitBuilder Builder(CGM);
1721 auto ProtocolList = Builder.beginStruct();
1722 ProtocolList.add(NULLPtr);
1723 ProtocolList.addInt(LongTy, Protocols.size());
1725 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
1726 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1727 iter != endIter ; iter++) {
1728 llvm::Constant *protocol = nullptr;
1729 llvm::StringMap<llvm::Constant*>::iterator value =
1730 ExistingProtocols.find(*iter);
1731 if (value == ExistingProtocols.end()) {
1732 protocol = GenerateEmptyProtocol(*iter);
1734 protocol = value->getValue();
1736 Elements.addBitCast(protocol, PtrToInt8Ty);
1738 Elements.finishAndAddTo(ProtocolList);
1739 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1740 CGM.getPointerAlign());
1743 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1744 const ObjCProtocolDecl *PD) {
1745 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1747 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1748 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1752 CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1753 llvm::Constant *ProtocolList = GenerateProtocolList({});
1754 llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
1755 // Protocols are objects containing lists of the methods implemented and
1756 // protocols adopted.
1757 ConstantInitBuilder Builder(CGM);
1758 auto Elements = Builder.beginStruct();
1760 // The isa pointer must be set to a magic number so the runtime knows it's
1761 // the correct layout.
1762 Elements.add(llvm::ConstantExpr::getIntToPtr(
1763 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1765 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1766 Elements.add(ProtocolList);
1767 Elements.add(MethodList);
1768 Elements.add(MethodList);
1769 Elements.add(MethodList);
1770 Elements.add(MethodList);
1771 return Elements.finishAndCreateGlobal(".objc_protocol",
1772 CGM.getPointerAlign());
1775 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1776 ASTContext &Context = CGM.getContext();
1777 std::string ProtocolName = PD->getNameAsString();
1779 // Use the protocol definition, if there is one.
1780 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1783 SmallVector<std::string, 16> Protocols;
1784 for (const auto *PI : PD->protocols())
1785 Protocols.push_back(PI->getNameAsString());
1786 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1787 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1788 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1789 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1790 for (const auto *I : PD->instance_methods()) {
1791 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1792 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1793 OptionalInstanceMethodNames.push_back(
1794 MakeConstantString(I->getSelector().getAsString()));
1795 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1797 InstanceMethodNames.push_back(
1798 MakeConstantString(I->getSelector().getAsString()));
1799 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1802 // Collect information about class methods:
1803 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1804 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1805 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1806 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1807 for (const auto *I : PD->class_methods()) {
1808 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1809 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1810 OptionalClassMethodNames.push_back(
1811 MakeConstantString(I->getSelector().getAsString()));
1812 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1814 ClassMethodNames.push_back(
1815 MakeConstantString(I->getSelector().getAsString()));
1816 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1820 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1821 llvm::Constant *InstanceMethodList =
1822 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1823 llvm::Constant *ClassMethodList =
1824 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1825 llvm::Constant *OptionalInstanceMethodList =
1826 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1827 OptionalInstanceMethodTypes);
1828 llvm::Constant *OptionalClassMethodList =
1829 GenerateProtocolMethodList(OptionalClassMethodNames,
1830 OptionalClassMethodTypes);
1832 // Property metadata: name, attributes, isSynthesized, setter name, setter
1833 // types, getter name, getter types.
1834 // The isSynthesized value is always set to 0 in a protocol. It exists to
1835 // simplify the runtime library by allowing it to use the same data
1836 // structures for protocol metadata everywhere.
1838 llvm::Constant *PropertyList;
1839 llvm::Constant *OptionalPropertyList;
1841 llvm::StructType *propertyMetadataTy =
1842 llvm::StructType::get(CGM.getLLVMContext(),
1843 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1844 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1846 unsigned numReqProperties = 0, numOptProperties = 0;
1847 for (auto property : PD->instance_properties()) {
1848 if (property->isOptional())
1854 ConstantInitBuilder reqPropertyListBuilder(CGM);
1855 auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1856 reqPropertiesList.addInt(IntTy, numReqProperties);
1857 reqPropertiesList.add(NULLPtr);
1858 auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1860 ConstantInitBuilder optPropertyListBuilder(CGM);
1861 auto optPropertiesList = optPropertyListBuilder.beginStruct();
1862 optPropertiesList.addInt(IntTy, numOptProperties);
1863 optPropertiesList.add(NULLPtr);
1864 auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1866 // Add all of the property methods need adding to the method list and to the
1867 // property metadata list.
1868 for (auto *property : PD->instance_properties()) {
1869 auto &propertiesArray =
1870 (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1871 auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1873 fields.add(MakePropertyEncodingString(property, nullptr));
1874 PushPropertyAttributes(fields, property);
1876 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1877 std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
1878 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1879 InstanceMethodTypes.push_back(typeEncoding);
1880 fields.add(MakeConstantString(getter->getSelector().getAsString()));
1881 fields.add(typeEncoding);
1883 fields.add(NULLPtr);
1884 fields.add(NULLPtr);
1886 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1887 std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
1888 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1889 InstanceMethodTypes.push_back(typeEncoding);
1890 fields.add(MakeConstantString(setter->getSelector().getAsString()));
1891 fields.add(typeEncoding);
1893 fields.add(NULLPtr);
1894 fields.add(NULLPtr);
1897 fields.finishAndAddTo(propertiesArray);
1900 reqPropertiesArray.finishAndAddTo(reqPropertiesList);
1902 reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1903 CGM.getPointerAlign());
1905 optPropertiesArray.finishAndAddTo(optPropertiesList);
1906 OptionalPropertyList =
1907 optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1908 CGM.getPointerAlign());
1911 // Protocols are objects containing lists of the methods implemented and
1912 // protocols adopted.
1913 // The isa pointer must be set to a magic number so the runtime knows it's
1914 // the correct layout.
1915 ConstantInitBuilder Builder(CGM);
1916 auto Elements = Builder.beginStruct();
1918 llvm::ConstantExpr::getIntToPtr(
1919 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1921 MakeConstantString(ProtocolName, ".objc_protocol_name"));
1922 Elements.add(ProtocolList);
1923 Elements.add(InstanceMethodList);
1924 Elements.add(ClassMethodList);
1925 Elements.add(OptionalInstanceMethodList);
1926 Elements.add(OptionalClassMethodList);
1927 Elements.add(PropertyList);
1928 Elements.add(OptionalPropertyList);
1929 ExistingProtocols[ProtocolName] =
1930 llvm::ConstantExpr::getBitCast(
1931 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1934 void CGObjCGNU::GenerateProtocolHolderCategory() {
1935 // Collect information about instance methods
1936 SmallVector<Selector, 1> MethodSels;
1937 SmallVector<llvm::Constant*, 1> MethodTypes;
1939 ConstantInitBuilder Builder(CGM);
1940 auto Elements = Builder.beginStruct();
1942 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1943 const std::string CategoryName = "AnotherHack";
1944 Elements.add(MakeConstantString(CategoryName));
1945 Elements.add(MakeConstantString(ClassName));
1946 // Instance method list
1947 Elements.addBitCast(GenerateMethodList(
1948 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
1949 // Class method list
1950 Elements.addBitCast(GenerateMethodList(
1951 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
1954 ConstantInitBuilder ProtocolListBuilder(CGM);
1955 auto ProtocolList = ProtocolListBuilder.beginStruct();
1956 ProtocolList.add(NULLPtr);
1957 ProtocolList.addInt(LongTy, ExistingProtocols.size());
1958 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1959 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1960 iter != endIter ; iter++) {
1961 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
1963 ProtocolElements.finishAndAddTo(ProtocolList);
1964 Elements.addBitCast(
1965 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1966 CGM.getPointerAlign()),
1968 Categories.push_back(llvm::ConstantExpr::getBitCast(
1969 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
1973 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1974 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1975 /// bits set to their values, LSB first, while larger ones are stored in a
1976 /// structure of this / form:
1978 /// struct { int32_t length; int32_t values[length]; };
1980 /// The values in the array are stored in host-endian format, with the least
1981 /// significant bit being assumed to come first in the bitfield. Therefore, a
1982 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1983 /// bitfield / with the 63rd bit set will be 1<<64.
1984 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1985 int bitCount = bits.size();
1986 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1987 if (bitCount < ptrBits) {
1989 for (int i=0 ; i<bitCount ; ++i) {
1990 if (bits[i]) val |= 1ULL<<(i+1);
1992 return llvm::ConstantInt::get(IntPtrTy, val);
1994 SmallVector<llvm::Constant *, 8> values;
1996 while (v < bitCount) {
1998 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1999 if (bits[v]) word |= 1<<i;
2002 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2005 ConstantInitBuilder builder(CGM);
2006 auto fields = builder.beginStruct();
2007 fields.addInt(Int32Ty, values.size());
2008 auto array = fields.beginArray();
2009 for (auto v : values) array.add(v);
2010 array.finishAndAddTo(fields);
2012 llvm::Constant *GS =
2013 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
2014 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2018 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2019 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2020 std::string CategoryName = OCD->getNameAsString();
2021 // Collect information about instance methods
2022 SmallVector<Selector, 16> InstanceMethodSels;
2023 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2024 for (const auto *I : OCD->instance_methods()) {
2025 InstanceMethodSels.push_back(I->getSelector());
2026 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2027 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2030 // Collect information about class methods
2031 SmallVector<Selector, 16> ClassMethodSels;
2032 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2033 for (const auto *I : OCD->class_methods()) {
2034 ClassMethodSels.push_back(I->getSelector());
2035 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2036 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2039 // Collect the names of referenced protocols
2040 SmallVector<std::string, 16> Protocols;
2041 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2042 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2043 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2044 E = Protos.end(); I != E; ++I)
2045 Protocols.push_back((*I)->getNameAsString());
2047 ConstantInitBuilder Builder(CGM);
2048 auto Elements = Builder.beginStruct();
2049 Elements.add(MakeConstantString(CategoryName));
2050 Elements.add(MakeConstantString(ClassName));
2051 // Instance method list
2052 Elements.addBitCast(
2053 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2054 InstanceMethodTypes, false),
2056 // Class method list
2057 Elements.addBitCast(
2058 GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2059 ClassMethodTypes, true),
2062 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
2063 Categories.push_back(llvm::ConstantExpr::getBitCast(
2064 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
2068 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2069 SmallVectorImpl<Selector> &InstanceMethodSels,
2070 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2071 ASTContext &Context = CGM.getContext();
2072 // Property metadata: name, attributes, attributes2, padding1, padding2,
2073 // setter name, setter types, getter name, getter types.
2074 llvm::StructType *propertyMetadataTy =
2075 llvm::StructType::get(CGM.getLLVMContext(),
2076 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2077 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2079 unsigned numProperties = 0;
2080 for (auto *propertyImpl : OID->property_impls()) {
2081 (void) propertyImpl;
2085 ConstantInitBuilder builder(CGM);
2086 auto propertyList = builder.beginStruct();
2087 propertyList.addInt(IntTy, numProperties);
2088 propertyList.add(NULLPtr);
2089 auto properties = propertyList.beginArray(propertyMetadataTy);
2091 // Add all of the property methods need adding to the method list and to the
2092 // property metadata list.
2093 for (auto *propertyImpl : OID->property_impls()) {
2094 auto fields = properties.beginStruct(propertyMetadataTy);
2095 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2096 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2097 ObjCPropertyImplDecl::Synthesize);
2098 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2099 ObjCPropertyImplDecl::Dynamic);
2101 fields.add(MakePropertyEncodingString(property, OID));
2102 PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
2103 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2104 std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
2105 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2106 if (isSynthesized) {
2107 InstanceMethodTypes.push_back(TypeEncoding);
2108 InstanceMethodSels.push_back(getter->getSelector());
2110 fields.add(MakeConstantString(getter->getSelector().getAsString()));
2111 fields.add(TypeEncoding);
2113 fields.add(NULLPtr);
2114 fields.add(NULLPtr);
2116 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2117 std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
2118 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2119 if (isSynthesized) {
2120 InstanceMethodTypes.push_back(TypeEncoding);
2121 InstanceMethodSels.push_back(setter->getSelector());
2123 fields.add(MakeConstantString(setter->getSelector().getAsString()));
2124 fields.add(TypeEncoding);
2126 fields.add(NULLPtr);
2127 fields.add(NULLPtr);
2129 fields.finishAndAddTo(properties);
2131 properties.finishAndAddTo(propertyList);
2133 return propertyList.finishAndCreateGlobal(".objc_property_list",
2134 CGM.getPointerAlign());
2137 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2138 // Get the class declaration for which the alias is specified.
2139 ObjCInterfaceDecl *ClassDecl =
2140 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2141 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2142 OAD->getNameAsString());
2145 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2146 ASTContext &Context = CGM.getContext();
2148 // Get the superclass name.
2149 const ObjCInterfaceDecl * SuperClassDecl =
2150 OID->getClassInterface()->getSuperClass();
2151 std::string SuperClassName;
2152 if (SuperClassDecl) {
2153 SuperClassName = SuperClassDecl->getNameAsString();
2154 EmitClassRef(SuperClassName);
2157 // Get the class name
2158 ObjCInterfaceDecl *ClassDecl =
2159 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2160 std::string ClassName = ClassDecl->getNameAsString();
2162 // Emit the symbol that is used to generate linker errors if this class is
2163 // referenced in other modules but not declared.
2164 std::string classSymbolName = "__objc_class_name_" + ClassName;
2165 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
2166 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2168 new llvm::GlobalVariable(TheModule, LongTy, false,
2169 llvm::GlobalValue::ExternalLinkage,
2170 llvm::ConstantInt::get(LongTy, 0),
2174 // Get the size of instances.
2176 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2178 // Collect information about instance variables.
2179 SmallVector<llvm::Constant*, 16> IvarNames;
2180 SmallVector<llvm::Constant*, 16> IvarTypes;
2181 SmallVector<llvm::Constant*, 16> IvarOffsets;
2183 ConstantInitBuilder IvarOffsetBuilder(CGM);
2184 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
2185 SmallVector<bool, 16> WeakIvars;
2186 SmallVector<bool, 16> StrongIvars;
2188 int superInstanceSize = !SuperClassDecl ? 0 :
2189 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2190 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2191 // class}. The runtime will then set this to the correct value on load.
2192 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2193 instanceSize = 0 - (instanceSize - superInstanceSize);
2196 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2197 IVD = IVD->getNextIvar()) {
2199 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2200 // Get the type encoding for this ivar
2201 std::string TypeStr;
2202 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
2203 IvarTypes.push_back(MakeConstantString(TypeStr));
2205 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2206 uint64_t Offset = BaseOffset;
2207 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2208 Offset = BaseOffset - superInstanceSize;
2210 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2211 // Create the direct offset value
2212 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2213 IVD->getNameAsString();
2214 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2216 OffsetVar->setInitializer(OffsetValue);
2217 // If this is the real definition, change its linkage type so that
2218 // different modules will use this one, rather than their private
2220 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2222 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2223 false, llvm::GlobalValue::ExternalLinkage,
2225 "__objc_ivar_offset_value_" + ClassName +"." +
2226 IVD->getNameAsString());
2227 IvarOffsets.push_back(OffsetValue);
2228 IvarOffsetValues.add(OffsetVar);
2229 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2231 case Qualifiers::OCL_Strong:
2232 StrongIvars.push_back(true);
2233 WeakIvars.push_back(false);
2235 case Qualifiers::OCL_Weak:
2236 StrongIvars.push_back(false);
2237 WeakIvars.push_back(true);
2240 StrongIvars.push_back(false);
2241 WeakIvars.push_back(false);
2244 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2245 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2246 llvm::GlobalVariable *IvarOffsetArray =
2247 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2248 CGM.getPointerAlign());
2250 // Collect information about instance methods
2251 SmallVector<Selector, 16> InstanceMethodSels;
2252 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2253 for (const auto *I : OID->instance_methods()) {
2254 InstanceMethodSels.push_back(I->getSelector());
2255 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2256 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2259 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2260 InstanceMethodTypes);
2262 // Collect information about class methods
2263 SmallVector<Selector, 16> ClassMethodSels;
2264 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2265 for (const auto *I : OID->class_methods()) {
2266 ClassMethodSels.push_back(I->getSelector());
2267 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2268 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2270 // Collect the names of referenced protocols
2271 SmallVector<std::string, 16> Protocols;
2272 for (const auto *I : ClassDecl->protocols())
2273 Protocols.push_back(I->getNameAsString());
2275 // Get the superclass pointer.
2276 llvm::Constant *SuperClass;
2277 if (!SuperClassName.empty()) {
2278 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2280 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2282 // Empty vector used to construct empty method lists
2283 SmallVector<llvm::Constant*, 1> empty;
2284 // Generate the method and instance variable lists
2285 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2286 InstanceMethodSels, InstanceMethodTypes, false);
2287 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2288 ClassMethodSels, ClassMethodTypes, true);
2289 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2291 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2292 // we emit a symbol containing the offset for each ivar in the class. This
2293 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2294 // for the legacy ABI, without causing problems. The converse is also
2295 // possible, but causes all ivar accesses to be fragile.
2297 // Offset pointer for getting at the correct field in the ivar list when
2298 // setting up the alias. These are: The base address for the global, the
2299 // ivar array (second field), the ivar in this list (set for each ivar), and
2300 // the offset (third field in ivar structure)
2301 llvm::Type *IndexTy = Int32Ty;
2302 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2303 llvm::ConstantInt::get(IndexTy, 1), nullptr,
2304 llvm::ConstantInt::get(IndexTy, 2) };
2306 unsigned ivarIndex = 0;
2307 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2308 IVD = IVD->getNextIvar()) {
2309 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2310 + IVD->getNameAsString();
2311 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2312 // Get the correct ivar field
2313 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2314 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2315 offsetPointerIndexes);
2316 // Get the existing variable, if one exists.
2317 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2319 offset->setInitializer(offsetValue);
2320 // If this is the real definition, change its linkage type so that
2321 // different modules will use this one, rather than their private
2323 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2325 // Add a new alias if there isn't one already.
2326 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2327 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2328 (void) offset; // Silence dead store warning.
2332 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2334 //Generate metaclass for class methods
2335 llvm::Constant *MetaClassStruct = GenerateClassStructure(
2336 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2337 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2338 NULLPtr, ZeroPtr, ZeroPtr, true);
2339 if (CGM.getTriple().isOSBinFormatCOFF()) {
2340 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2341 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2342 Storage = llvm::GlobalValue::DLLImportStorageClass;
2343 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2344 Storage = llvm::GlobalValue::DLLExportStorageClass;
2345 cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2348 // Generate the class structure
2349 llvm::Constant *ClassStruct = GenerateClassStructure(
2350 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2351 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2352 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2353 StrongIvarBitmap, WeakIvarBitmap);
2354 if (CGM.getTriple().isOSBinFormatCOFF()) {
2355 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2356 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2357 Storage = llvm::GlobalValue::DLLImportStorageClass;
2358 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2359 Storage = llvm::GlobalValue::DLLExportStorageClass;
2360 cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2363 // Resolve the class aliases, if they exist.
2364 if (ClassPtrAlias) {
2365 ClassPtrAlias->replaceAllUsesWith(
2366 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2367 ClassPtrAlias->eraseFromParent();
2368 ClassPtrAlias = nullptr;
2370 if (MetaClassPtrAlias) {
2371 MetaClassPtrAlias->replaceAllUsesWith(
2372 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2373 MetaClassPtrAlias->eraseFromParent();
2374 MetaClassPtrAlias = nullptr;
2377 // Add class structure to list to be added to the symtab later
2378 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2379 Classes.push_back(ClassStruct);
2382 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2383 // Only emit an ObjC load function if no Objective-C stuff has been called
2384 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2385 ExistingProtocols.empty() && SelectorTable.empty())
2388 // Add all referenced protocols to a category.
2389 GenerateProtocolHolderCategory();
2391 llvm::StructType *selStructTy =
2392 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2393 llvm::Type *selStructPtrTy = SelectorTy;
2395 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2396 { PtrToInt8Ty, PtrToInt8Ty });
2397 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
2400 // Generate statics list:
2401 llvm::Constant *statics = NULLPtr;
2402 if (!ConstantStrings.empty()) {
2403 llvm::GlobalVariable *fileStatics = [&] {
2404 ConstantInitBuilder builder(CGM);
2405 auto staticsStruct = builder.beginStruct();
2407 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2408 if (stringClass.empty()) stringClass = "NXConstantString";
2409 staticsStruct.add(MakeConstantString(stringClass,
2410 ".objc_static_class_name"));
2412 auto array = staticsStruct.beginArray();
2413 array.addAll(ConstantStrings);
2415 array.finishAndAddTo(staticsStruct);
2417 return staticsStruct.finishAndCreateGlobal(".objc_statics",
2418 CGM.getPointerAlign());
2421 ConstantInitBuilder builder(CGM);
2422 auto allStaticsArray = builder.beginArray(fileStatics->getType());
2423 allStaticsArray.add(fileStatics);
2424 allStaticsArray.addNullPointer(fileStatics->getType());
2426 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2427 CGM.getPointerAlign());
2428 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
2431 // Array of classes, categories, and constant objects.
2433 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2434 unsigned selectorCount;
2436 // Pointer to an array of selectors used in this module.
2437 llvm::GlobalVariable *selectorList = [&] {
2438 ConstantInitBuilder builder(CGM);
2439 auto selectors = builder.beginArray(selStructTy);
2440 auto &table = SelectorTable; // MSVC workaround
2441 for (auto &entry : table) {
2443 std::string selNameStr = entry.first.getAsString();
2444 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
2446 for (TypedSelector &sel : entry.second) {
2447 llvm::Constant *selectorTypeEncoding = NULLPtr;
2448 if (!sel.first.empty())
2449 selectorTypeEncoding =
2450 MakeConstantString(sel.first, ".objc_sel_types");
2452 auto selStruct = selectors.beginStruct(selStructTy);
2453 selStruct.add(selName);
2454 selStruct.add(selectorTypeEncoding);
2455 selStruct.finishAndAddTo(selectors);
2457 // Store the selector alias for later replacement
2458 selectorAliases.push_back(sel.second);
2462 // Remember the number of entries in the selector table.
2463 selectorCount = selectors.size();
2465 // NULL-terminate the selector list. This should not actually be required,
2466 // because the selector list has a length field. Unfortunately, the GCC
2467 // runtime decides to ignore the length field and expects a NULL terminator,
2468 // and GCC cooperates with this by always setting the length to 0.
2469 auto selStruct = selectors.beginStruct(selStructTy);
2470 selStruct.add(NULLPtr);
2471 selStruct.add(NULLPtr);
2472 selStruct.finishAndAddTo(selectors);
2474 return selectors.finishAndCreateGlobal(".objc_selector_list",
2475 CGM.getPointerAlign());
2478 // Now that all of the static selectors exist, create pointers to them.
2479 for (unsigned i = 0; i < selectorCount; ++i) {
2480 llvm::Constant *idxs[] = {
2482 llvm::ConstantInt::get(Int32Ty, i)
2484 // FIXME: We're generating redundant loads and stores here!
2485 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2486 selectorList->getValueType(), selectorList, idxs);
2487 // If selectors are defined as an opaque type, cast the pointer to this
2489 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2490 selectorAliases[i]->replaceAllUsesWith(selPtr);
2491 selectorAliases[i]->eraseFromParent();
2494 llvm::GlobalVariable *symtab = [&] {
2495 ConstantInitBuilder builder(CGM);
2496 auto symtab = builder.beginStruct();
2498 // Number of static selectors
2499 symtab.addInt(LongTy, selectorCount);
2501 symtab.addBitCast(selectorList, selStructPtrTy);
2503 // Number of classes defined.
2504 symtab.addInt(CGM.Int16Ty, Classes.size());
2505 // Number of categories defined
2506 symtab.addInt(CGM.Int16Ty, Categories.size());
2508 // Create an array of classes, then categories, then static object instances
2509 auto classList = symtab.beginArray(PtrToInt8Ty);
2510 classList.addAll(Classes);
2511 classList.addAll(Categories);
2512 // NULL-terminated list of static object instances (mainly constant strings)
2513 classList.add(statics);
2514 classList.add(NULLPtr);
2515 classList.finishAndAddTo(symtab);
2517 // Construct the symbol table.
2518 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2521 // The symbol table is contained in a module which has some version-checking
2523 llvm::Constant *module = [&] {
2524 llvm::Type *moduleEltTys[] = {
2525 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2527 llvm::StructType *moduleTy =
2528 llvm::StructType::get(CGM.getLLVMContext(),
2529 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
2531 ConstantInitBuilder builder(CGM);
2532 auto module = builder.beginStruct(moduleTy);
2533 // Runtime version, used for ABI compatibility checking.
2534 module.addInt(LongTy, RuntimeVersion);
2536 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2538 // The path to the source file where this module was declared
2539 SourceManager &SM = CGM.getContext().getSourceManager();
2540 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2542 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
2543 module.add(MakeConstantString(path, ".objc_source_file_name"));
2546 if (RuntimeVersion >= 10) {
2547 switch (CGM.getLangOpts().getGC()) {
2548 case LangOptions::GCOnly:
2549 module.addInt(IntTy, 2);
2551 case LangOptions::NonGC:
2552 if (CGM.getLangOpts().ObjCAutoRefCount)
2553 module.addInt(IntTy, 1);
2555 module.addInt(IntTy, 0);
2557 case LangOptions::HybridGC:
2558 module.addInt(IntTy, 1);
2563 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2566 // Create the load function calling the runtime entry point with the module
2568 llvm::Function * LoadFunction = llvm::Function::Create(
2569 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2570 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2572 llvm::BasicBlock *EntryBB =
2573 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2574 CGBuilderTy Builder(CGM, VMContext);
2575 Builder.SetInsertPoint(EntryBB);
2577 llvm::FunctionType *FT =
2578 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
2579 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2580 Builder.CreateCall(Register, module);
2582 if (!ClassAliases.empty()) {
2583 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2584 llvm::FunctionType *RegisterAliasTy =
2585 llvm::FunctionType::get(Builder.getVoidTy(),
2587 llvm::Function *RegisterAlias = llvm::Function::Create(
2589 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2591 llvm::BasicBlock *AliasBB =
2592 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2593 llvm::BasicBlock *NoAliasBB =
2594 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2596 // Branch based on whether the runtime provided class_registerAlias_np()
2597 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2598 llvm::Constant::getNullValue(RegisterAlias->getType()));
2599 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2601 // The true branch (has alias registration function):
2602 Builder.SetInsertPoint(AliasBB);
2603 // Emit alias registration calls:
2604 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2605 iter != ClassAliases.end(); ++iter) {
2606 llvm::Constant *TheClass =
2607 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
2609 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2610 Builder.CreateCall(RegisterAlias,
2611 {TheClass, MakeConstantString(iter->second)});
2615 Builder.CreateBr(NoAliasBB);
2617 // Missing alias registration function, just return from the function:
2618 Builder.SetInsertPoint(NoAliasBB);
2620 Builder.CreateRetVoid();
2622 return LoadFunction;
2625 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2626 const ObjCContainerDecl *CD) {
2627 const ObjCCategoryImplDecl *OCD =
2628 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2629 StringRef CategoryName = OCD ? OCD->getName() : "";
2630 StringRef ClassName = CD->getName();
2631 Selector MethodName = OMD->getSelector();
2632 bool isClassMethod = !OMD->isInstanceMethod();
2634 CodeGenTypes &Types = CGM.getTypes();
2635 llvm::FunctionType *MethodTy =
2636 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2637 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2638 MethodName, isClassMethod);
2640 llvm::Function *Method
2641 = llvm::Function::Create(MethodTy,
2642 llvm::GlobalValue::InternalLinkage,
2648 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2649 return GetPropertyFn;
2652 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2653 return SetPropertyFn;
2656 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2661 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2662 return GetStructPropertyFn;
2665 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2666 return SetStructPropertyFn;
2669 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2673 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2677 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2678 return EnumerationMutationFn;
2681 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2682 const ObjCAtSynchronizedStmt &S) {
2683 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2687 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2688 const ObjCAtTryStmt &S) {
2689 // Unlike the Apple non-fragile runtimes, which also uses
2690 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2691 // EH support isn't a veneer over C++ EH. Instead, exception
2692 // objects are created by objc_exception_throw and destroyed by
2693 // the personality function; this avoids the need for bracketing
2694 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2695 // (or even _Unwind_DeleteException), but probably doesn't
2696 // interoperate very well with foreign exceptions.
2698 // In Objective-C++ mode, we actually emit something equivalent to the C++
2699 // exception handler.
2700 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2703 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2704 const ObjCAtThrowStmt &S,
2705 bool ClearInsertionPoint) {
2706 llvm::Value *ExceptionAsObject;
2708 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2709 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2710 ExceptionAsObject = Exception;
2712 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2713 "Unexpected rethrow outside @catch block.");
2714 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2716 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2717 llvm::CallSite Throw =
2718 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2719 Throw.setDoesNotReturn();
2720 CGF.Builder.CreateUnreachable();
2721 if (ClearInsertionPoint)
2722 CGF.Builder.ClearInsertionPoint();
2725 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2726 Address AddrWeakObj) {
2727 CGBuilderTy &B = CGF.Builder;
2728 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2729 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2730 AddrWeakObj.getPointer());
2733 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2734 llvm::Value *src, Address dst) {
2735 CGBuilderTy &B = CGF.Builder;
2736 src = EnforceType(B, src, IdTy);
2737 dst = EnforceType(B, dst, PtrToIdTy);
2738 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2739 {src, dst.getPointer()});
2742 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2743 llvm::Value *src, Address dst,
2745 CGBuilderTy &B = CGF.Builder;
2746 src = EnforceType(B, src, IdTy);
2747 dst = EnforceType(B, dst, PtrToIdTy);
2748 // FIXME. Add threadloca assign API
2749 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
2750 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2751 {src, dst.getPointer()});
2754 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2755 llvm::Value *src, Address dst,
2756 llvm::Value *ivarOffset) {
2757 CGBuilderTy &B = CGF.Builder;
2758 src = EnforceType(B, src, IdTy);
2759 dst = EnforceType(B, dst, IdTy);
2760 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2761 {src, dst.getPointer(), ivarOffset});
2764 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2765 llvm::Value *src, Address dst) {
2766 CGBuilderTy &B = CGF.Builder;
2767 src = EnforceType(B, src, IdTy);
2768 dst = EnforceType(B, dst, PtrToIdTy);
2769 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2770 {src, dst.getPointer()});
2773 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2776 llvm::Value *Size) {
2777 CGBuilderTy &B = CGF.Builder;
2778 DestPtr = EnforceType(B, DestPtr, PtrTy);
2779 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2781 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2782 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
2785 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2786 const ObjCInterfaceDecl *ID,
2787 const ObjCIvarDecl *Ivar) {
2788 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2789 + '.' + Ivar->getNameAsString();
2790 // Emit the variable and initialize it with what we think the correct value
2791 // is. This allows code compiled with non-fragile ivars to work correctly
2792 // when linked against code which isn't (most of the time).
2793 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2794 if (!IvarOffsetPointer) {
2795 // This will cause a run-time crash if we accidentally use it. A value of
2796 // 0 would seem more sensible, but will silently overwrite the isa pointer
2797 // causing a great deal of confusion.
2798 uint64_t Offset = -1;
2799 // We can't call ComputeIvarBaseOffset() here if we have the
2800 // implementation, because it will create an invalid ASTRecordLayout object
2801 // that we are then stuck with forever, so we only initialize the ivar
2802 // offset variable with a guess if we only have the interface. The
2803 // initializer will be reset later anyway, when we are generating the class
2805 if (!CGM.getContext().getObjCImplementation(
2806 const_cast<ObjCInterfaceDecl *>(ID)))
2807 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2809 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2811 // Don't emit the guess in non-PIC code because the linker will not be able
2812 // to replace it with the real version for a library. In non-PIC code you
2813 // must compile with the fragile ABI if you want to use ivars from a
2814 // GCC-compiled class.
2815 if (CGM.getLangOpts().PICLevel) {
2816 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2818 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2819 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2820 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2821 IvarOffsetGV, Name);
2823 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2824 llvm::Type::getInt32PtrTy(VMContext), false,
2825 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
2828 return IvarOffsetPointer;
2831 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2833 llvm::Value *BaseValue,
2834 const ObjCIvarDecl *Ivar,
2835 unsigned CVRQualifiers) {
2836 const ObjCInterfaceDecl *ID =
2837 ObjectTy->getAs<ObjCObjectType>()->getInterface();
2838 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2839 EmitIvarOffset(CGF, ID, Ivar));
2842 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2843 const ObjCInterfaceDecl *OID,
2844 const ObjCIvarDecl *OIVD) {
2845 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2846 next = next->getNextIvar()) {
2851 // Otherwise check in the super class.
2852 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2853 return FindIvarInterface(Context, Super, OIVD);
2858 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2859 const ObjCInterfaceDecl *Interface,
2860 const ObjCIvarDecl *Ivar) {
2861 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2862 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2864 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2865 // and ExternalLinkage, so create a reference to the ivar global and rely on
2866 // the definition being created as part of GenerateClass.
2867 if (RuntimeVersion < 10 ||
2868 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
2869 return CGF.Builder.CreateZExtOrBitCast(
2870 CGF.Builder.CreateAlignedLoad(
2871 Int32Ty, CGF.Builder.CreateAlignedLoad(
2872 ObjCIvarOffsetVariable(Interface, Ivar),
2873 CGF.getPointerAlign(), "ivar"),
2874 CharUnits::fromQuantity(4)),
2876 std::string name = "__objc_ivar_offset_value_" +
2877 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2878 CharUnits Align = CGM.getIntAlign();
2879 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2881 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
2882 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2883 llvm::Constant::getNullValue(IntTy), name);
2884 GV->setAlignment(Align.getQuantity());
2887 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
2888 if (Offset->getType() != PtrDiffTy)
2889 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2892 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2893 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2897 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2898 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2899 case ObjCRuntime::GNUstep:
2900 return new CGObjCGNUstep(CGM);
2902 case ObjCRuntime::GCC:
2903 return new CGObjCGCC(CGM);
2905 case ObjCRuntime::ObjFW:
2906 return new CGObjCObjFW(CGM);
2908 case ObjCRuntime::FragileMacOSX:
2909 case ObjCRuntime::MacOSX:
2910 case ObjCRuntime::iOS:
2911 case ObjCRuntime::WatchOS:
2912 llvm_unreachable("these runtimes are not GNU runtimes");
2914 llvm_unreachable("bad runtime");