clang 24.0.0git
CGObjCGNU.cpp
Go to the documentation of this file.
1//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides Objective-C code generation targeting the GNU runtime. The
10// class in this file generates structures used by the GNU Objective-C runtime
11// library. These structures are defined in objc/objc.h and objc/objc-api.h in
12// the GNU runtime distribution.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CGCXXABI.h"
17#include "CGCleanup.h"
18#include "CGObjCRuntime.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "CodeGenTypes.h"
22#include "SanitizerMetadata.h"
24#include "clang/AST/Attr.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclObjC.h"
28#include "clang/AST/StmtObjC.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringMap.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/ConvertUTF.h"
39#include <cctype>
40
41using namespace clang;
42using namespace CodeGen;
43
44namespace {
45
46/// Class that lazily initialises the runtime function. Avoids inserting the
47/// types and the function declaration into a module if they're not used, and
48/// avoids constructing the type more than once if it's used more than once.
49class LazyRuntimeFunction {
50 CodeGenModule *CGM = nullptr;
51 llvm::FunctionType *FTy = nullptr;
52 const char *FunctionName = nullptr;
53 llvm::FunctionCallee Function = nullptr;
54
55public:
56 LazyRuntimeFunction() = default;
57
58 /// Initialises the lazy function with the name, return type, and the types
59 /// of the arguments.
60 template <typename... Tys>
61 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
62 Tys *... Types) {
63 CGM = Mod;
64 FunctionName = name;
65 Function = nullptr;
66 if(sizeof...(Tys)) {
67 SmallVector<llvm::Type *, 8> ArgTys({Types...});
68 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69 }
70 else {
71 FTy = llvm::FunctionType::get(RetTy, {}, false);
72 }
73 }
74
75 llvm::FunctionType *getType() { return FTy; }
76
77 /// Overloaded cast operator, allows the class to be implicitly cast to an
78 /// LLVM constant.
79 operator llvm::FunctionCallee() {
80 if (!Function) {
81 if (!FunctionName)
82 return nullptr;
83 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
84 }
85 return Function;
86 }
87};
88
89
90/// GNU Objective-C runtime code generation. This class implements the parts of
91/// Objective-C support that are specific to the GNU family of runtimes (GCC,
92/// GNUstep and ObjFW).
93class CGObjCGNU : public CGObjCRuntime {
94protected:
95 /// The LLVM module into which output is inserted
96 llvm::Module &TheModule;
97 /// strut objc_super. Used for sending messages to super. This structure
98 /// contains the receiver (object) and the expected class.
99 llvm::StructType *ObjCSuperTy;
100 /// struct objc_super*. The type of the argument to the superclass message
101 /// lookup functions.
102 llvm::PointerType *PtrToObjCSuperTy;
103 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
104 /// SEL is included in a header somewhere, in which case it will be whatever
105 /// type is declared in that header, most likely {i8*, i8*}.
106 llvm::PointerType *SelectorTy;
107 /// Element type of SelectorTy.
108 llvm::Type *SelectorElemTy;
109 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
110 /// places where it's used
111 llvm::IntegerType *Int8Ty;
112 /// Pointer to i8 - LLVM type of char*, for all of the places where the
113 /// runtime needs to deal with C strings.
114 llvm::PointerType *PtrToInt8Ty;
115 /// struct objc_protocol type
116 llvm::StructType *ProtocolTy;
117 /// Protocol * type.
118 llvm::PointerType *ProtocolPtrTy;
119 /// Instance Method Pointer type. This is a pointer to a function that takes,
120 /// at a minimum, an object and a selector, and is the generic type for
121 /// Objective-C methods. Due to differences between variadic / non-variadic
122 /// calling conventions, it must always be cast to the correct type before
123 /// actually being used.
124 llvm::PointerType *IMPTy;
125 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
126 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
127 /// but if the runtime header declaring it is included then it may be a
128 /// pointer to a structure.
129 llvm::PointerType *IdTy;
130 /// Element type of IdTy.
131 llvm::Type *IdElemTy;
132 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
133 /// message lookup function and some GC-related functions.
134 llvm::PointerType *PtrToIdTy;
135 /// The clang type of id. Used when using the clang CGCall infrastructure to
136 /// call Objective-C methods.
137 CanQualType ASTIdTy;
138 /// LLVM type for C int type.
139 llvm::IntegerType *IntTy;
140 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
141 /// used in the code to document the difference between i8* meaning a pointer
142 /// to a C string and i8* meaning a pointer to some opaque type.
143 llvm::PointerType *PtrTy;
144 /// LLVM type for C long type. The runtime uses this in a lot of places where
145 /// it should be using intptr_t, but we can't fix this without breaking
146 /// compatibility with GCC...
147 llvm::IntegerType *LongTy;
148 /// LLVM type for C size_t. Used in various runtime data structures.
149 llvm::IntegerType *SizeTy;
150 /// LLVM type for C intptr_t.
151 llvm::IntegerType *IntPtrTy;
152 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
153 llvm::IntegerType *PtrDiffTy;
154 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
155 /// variables.
156 llvm::PointerType *PtrToIntTy;
157 /// LLVM type for Objective-C BOOL type.
158 llvm::Type *BoolTy;
159 /// 32-bit integer type, to save us needing to look it up every time it's used.
160 llvm::IntegerType *Int32Ty;
161 /// 64-bit integer type, to save us needing to look it up every time it's used.
162 llvm::IntegerType *Int64Ty;
163 /// The type of struct objc_property.
164 llvm::StructType *PropertyMetadataTy;
165 /// Metadata kind used to tie method lookups to message sends. The GNUstep
166 /// runtime provides some LLVM passes that can use this to do things like
167 /// automatic IMP caching and speculative inlining.
168 unsigned msgSendMDKind;
169 /// Does the current target use SEH-based exceptions? False implies
170 /// Itanium-style DWARF unwinding.
171 bool usesSEHExceptions;
172 /// Does the current target uses C++-based exceptions?
173 bool usesCxxExceptions;
174
175 /// Helper to check if we are targeting a specific runtime version or later.
176 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
177 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
178 return (R.getKind() == kind) &&
179 (R.getVersion() >= VersionTuple(major, minor));
180 }
181
182 std::string ManglePublicSymbol(StringRef Name) {
183 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
184 }
185
186 std::string SymbolForProtocol(Twine Name) {
187 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
188 }
189
190 std::string SymbolForProtocolRef(StringRef Name) {
191 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
192 }
193
194
195 /// Helper function that generates a constant string and returns a pointer to
196 /// the start of the string. The result of this function can be used anywhere
197 /// where the C code specifies const char*.
198 llvm::Constant *MakeConstantString(StringRef Str, StringRef Name = "") {
199 ConstantAddress Array =
200 CGM.GetAddrOfConstantCString(std::string(Str), Name);
201 return Array.getPointer();
202 }
203
204 /// Emits a linkonce_odr string, whose name is the prefix followed by the
205 /// string value. This allows the linker to combine the strings between
206 /// different modules. Used for EH typeinfo names, selector strings, and a
207 /// few other things.
208 llvm::Constant *ExportUniqueString(const std::string &Str,
209 const std::string &prefix,
210 bool Private=false) {
211 std::string name = prefix + Str;
212 auto *ConstStr = TheModule.getGlobalVariable(name);
213 if (!ConstStr) {
214 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
215 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
216 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
217 GV->setComdat(TheModule.getOrInsertComdat(name));
218 if (Private)
219 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
220 ConstStr = GV;
221 }
222 return ConstStr;
223 }
224
225 /// Returns a property name and encoding string.
226 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
227 const Decl *Container) {
228 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
229 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
230 std::string NameAndAttributes;
231 std::string TypeStr =
232 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
233 NameAndAttributes += '\0';
234 NameAndAttributes += TypeStr.length() + 3;
235 NameAndAttributes += TypeStr;
236 NameAndAttributes += '\0';
237 NameAndAttributes += PD->getNameAsString();
238 return MakeConstantString(NameAndAttributes);
239 }
240 return MakeConstantString(PD->getNameAsString());
241 }
242
243 /// Push the property attributes into two structure fields.
244 void PushPropertyAttributes(ConstantStructBuilder &Fields,
245 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
246 isDynamic=true) {
247 int attrs = property->getPropertyAttributes();
248 // For read-only properties, clear the copy and retain flags
250 attrs &= ~ObjCPropertyAttribute::kind_copy;
251 attrs &= ~ObjCPropertyAttribute::kind_retain;
252 attrs &= ~ObjCPropertyAttribute::kind_weak;
253 attrs &= ~ObjCPropertyAttribute::kind_strong;
254 }
255 // The first flags field has the same attribute values as clang uses internally
256 Fields.addInt(Int8Ty, attrs & 0xff);
257 attrs >>= 8;
258 attrs <<= 2;
259 // For protocol properties, synthesized and dynamic have no meaning, so we
260 // reuse these flags to indicate that this is a protocol property (both set
261 // has no meaning, as a property can't be both synthesized and dynamic)
262 attrs |= isSynthesized ? (1<<0) : 0;
263 attrs |= isDynamic ? (1<<1) : 0;
264 // The second field is the next four fields left shifted by two, with the
265 // low bit set to indicate whether the field is synthesized or dynamic.
266 Fields.addInt(Int8Ty, attrs & 0xff);
267 // Two padding fields
268 Fields.addInt(Int8Ty, 0);
269 Fields.addInt(Int8Ty, 0);
270 }
271
272 virtual llvm::Constant *GenerateCategoryProtocolList(const
273 ObjCCategoryDecl *OCD);
274 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
275 int count) {
276 // int count;
277 Fields.addInt(IntTy, count);
278 // int size; (only in GNUstep v2 ABI.
279 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
280 const llvm::DataLayout &DL = TheModule.getDataLayout();
281 Fields.addInt(IntTy, DL.getTypeSizeInBits(PropertyMetadataTy) /
282 CGM.getContext().getCharWidth());
283 }
284 // struct objc_property_list *next;
285 Fields.add(NULLPtr);
286 // struct objc_property properties[]
287 return Fields.beginArray(PropertyMetadataTy);
288 }
289 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
290 const ObjCPropertyDecl *property,
291 const Decl *OCD,
292 bool isSynthesized=true, bool
293 isDynamic=true) {
294 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
295 ASTContext &Context = CGM.getContext();
296 Fields.add(MakePropertyEncodingString(property, OCD));
297 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
298 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
299 if (accessor) {
300 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
301 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
302 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
303 Fields.add(TypeEncoding);
304 } else {
305 Fields.add(NULLPtr);
306 Fields.add(NULLPtr);
307 }
308 };
309 addPropertyMethod(property->getGetterMethodDecl());
310 addPropertyMethod(property->getSetterMethodDecl());
311 Fields.finishAndAddTo(PropertiesArray);
312 }
313
314 /// Ensures that the value has the required type, by inserting a bitcast if
315 /// required. This function lets us avoid inserting bitcasts that are
316 /// redundant.
317 llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
318 if (V->getType() == Ty)
319 return V;
320 return B.CreateBitCast(V, Ty);
321 }
322
323 // Some zeros used for GEPs in lots of places.
324 llvm::Constant *Zeros[2];
325 /// Null pointer value. Mainly used as a terminator in various arrays.
326 llvm::Constant *NULLPtr;
327 /// LLVM context.
328 llvm::LLVMContext &VMContext;
329
330protected:
331
332 /// Placeholder for the class. Lots of things refer to the class before we've
333 /// actually emitted it. We use this alias as a placeholder, and then replace
334 /// it with a pointer to the class structure before finally emitting the
335 /// module.
336 llvm::GlobalAlias *ClassPtrAlias;
337 /// Placeholder for the metaclass. Lots of things refer to the class before
338 /// we've / actually emitted it. We use this alias as a placeholder, and then
339 /// replace / it with a pointer to the metaclass structure before finally
340 /// emitting the / module.
341 llvm::GlobalAlias *MetaClassPtrAlias;
342 /// All of the classes that have been generated for this compilation units.
343 std::vector<llvm::Constant*> Classes;
344 /// All of the categories that have been generated for this compilation units.
345 std::vector<llvm::Constant*> Categories;
346 /// All of the Objective-C constant strings that have been generated for this
347 /// compilation units.
348 std::vector<llvm::Constant*> ConstantStrings;
349 /// Map from string values to Objective-C constant strings in the output.
350 /// Used to prevent emitting Objective-C strings more than once. This should
351 /// not be required at all - CodeGenModule should manage this list.
352 llvm::StringMap<llvm::Constant*> ObjCStrings;
353 /// All of the protocols that have been declared.
354 llvm::StringMap<llvm::Constant*> ExistingProtocols;
355 /// For each variant of a selector, we store the type encoding and a
356 /// placeholder value. For an untyped selector, the type will be the empty
357 /// string. Selector references are all done via the module's selector table,
358 /// so we create an alias as a placeholder and then replace it with the real
359 /// value later.
360 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
361 /// Type of the selector map. This is roughly equivalent to the structure
362 /// used in the GNUstep runtime, which maintains a list of all of the valid
363 /// types for a selector in a table.
364 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
365 SelectorMap;
366 /// A map from selectors to selector types. This allows us to emit all
367 /// selectors of the same name and type together.
368 SelectorMap SelectorTable;
369
370 /// Selectors related to memory management. When compiling in GC mode, we
371 /// omit these.
372 Selector RetainSel, ReleaseSel, AutoreleaseSel;
373 /// Runtime functions used for memory management in GC mode. Note that clang
374 /// supports code generation for calling these functions, but neither GNU
375 /// runtime actually supports this API properly yet.
376 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
377 WeakAssignFn, GlobalAssignFn;
378
379 typedef std::pair<std::string, std::string> ClassAliasPair;
380 /// All classes that have aliases set for them.
381 std::vector<ClassAliasPair> ClassAliases;
382
383protected:
384 /// Function used for throwing Objective-C exceptions.
385 LazyRuntimeFunction ExceptionThrowFn;
386 /// Function used for rethrowing exceptions, used at the end of \@finally or
387 /// \@synchronize blocks.
388 LazyRuntimeFunction ExceptionReThrowFn;
389 /// Function called when entering a catch function. This is required for
390 /// differentiating Objective-C exceptions and foreign exceptions.
391 LazyRuntimeFunction EnterCatchFn;
392 /// Function called when exiting from a catch block. Used to do exception
393 /// cleanup.
394 LazyRuntimeFunction ExitCatchFn;
395 /// Function called when entering an \@synchronize block. Acquires the lock.
396 LazyRuntimeFunction SyncEnterFn;
397 /// Function called when exiting an \@synchronize block. Releases the lock.
398 LazyRuntimeFunction SyncExitFn;
399
400private:
401 /// Function called if fast enumeration detects that the collection is
402 /// modified during the update.
403 LazyRuntimeFunction EnumerationMutationFn;
404 /// Function for implementing synthesized property getters that return an
405 /// object.
406 LazyRuntimeFunction GetPropertyFn;
407 /// Function for implementing synthesized property setters that return an
408 /// object.
409 LazyRuntimeFunction SetPropertyFn;
410 /// Function used for non-object declared property getters.
411 LazyRuntimeFunction GetStructPropertyFn;
412 /// Function used for non-object declared property setters.
413 LazyRuntimeFunction SetStructPropertyFn;
414
415protected:
416 /// The version of the runtime that this class targets. Must match the
417 /// version in the runtime.
418 int RuntimeVersion;
419 /// The version of the protocol class. Used to differentiate between ObjC1
420 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
421 /// components and can not contain declared properties. We always emit
422 /// Objective-C 2 property structures, but we have to pretend that they're
423 /// Objective-C 1 property structures when targeting the GCC runtime or it
424 /// will abort.
425 const int ProtocolVersion;
426 /// The version of the class ABI. This value is used in the class structure
427 /// and indicates how various fields should be interpreted.
428 const int ClassABIVersion;
429 /// Generates an instance variable list structure. This is a structure
430 /// containing a size and an array of structures containing instance variable
431 /// metadata. This is used purely for introspection in the fragile ABI. In
432 /// the non-fragile ABI, it's used for instance variable fixup.
433 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
434 ArrayRef<llvm::Constant *> IvarTypes,
435 ArrayRef<llvm::Constant *> IvarOffsets,
436 ArrayRef<llvm::Constant *> IvarAlign,
437 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
438
439 /// Generates a method list structure. This is a structure containing a size
440 /// and an array of structures containing method metadata.
441 ///
442 /// This structure is used by both classes and categories, and contains a next
443 /// pointer allowing them to be chained together in a linked list.
444 llvm::Constant *GenerateMethodList(StringRef ClassName,
445 StringRef CategoryName,
446 ArrayRef<const ObjCMethodDecl*> Methods,
447 bool isClassMethodList);
448
449 /// Emits an empty protocol. This is used for \@protocol() where no protocol
450 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
451 /// real protocol.
452 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
453
454 /// Generates a list of property metadata structures. This follows the same
455 /// pattern as method and instance variable metadata lists.
456 llvm::Constant *GeneratePropertyList(const Decl *Container,
457 const ObjCContainerDecl *OCD,
458 bool isClassProperty=false,
459 bool protocolOptionalProperties=false);
460
461 /// Generates a list of referenced protocols. Classes, categories, and
462 /// protocols all use this structure.
463 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
464
465 /// To ensure that all protocols are seen by the runtime, we add a category on
466 /// a class defined in the runtime, declaring no methods, but adopting the
467 /// protocols. This is a horribly ugly hack, but it allows us to collect all
468 /// of the protocols without changing the ABI.
469 void GenerateProtocolHolderCategory();
470
471 /// Generates a class structure.
472 llvm::Constant *GenerateClassStructure(
473 llvm::Constant *MetaClass,
474 llvm::Constant *SuperClass,
475 unsigned info,
476 const char *Name,
477 llvm::Constant *Version,
478 llvm::Constant *InstanceSize,
479 llvm::Constant *IVars,
480 llvm::Constant *Methods,
481 llvm::Constant *Protocols,
482 llvm::Constant *IvarOffsets,
483 llvm::Constant *Properties,
484 llvm::Constant *StrongIvarBitmap,
485 llvm::Constant *WeakIvarBitmap,
486 bool isMeta=false);
487
488 /// Generates a method list. This is used by protocols to define the required
489 /// and optional methods.
490 virtual llvm::Constant *GenerateProtocolMethodList(
491 ArrayRef<const ObjCMethodDecl*> Methods);
492 /// Emits optional and required method lists.
493 template<class T>
494 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
495 llvm::Constant *&Optional) {
496 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
497 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
498 for (const auto *I : Methods)
499 if (I->isOptional())
500 OptionalMethods.push_back(I);
501 else
502 RequiredMethods.push_back(I);
503 Required = GenerateProtocolMethodList(RequiredMethods);
504 Optional = GenerateProtocolMethodList(OptionalMethods);
505 }
506
507 /// Returns a selector with the specified type encoding. An empty string is
508 /// used to return an untyped selector (with the types field set to NULL).
509 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
510 const std::string &TypeEncoding);
511
512 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
513 /// contains the class and ivar names, in the v2 ABI this contains the type
514 /// encoding as well.
515 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
516 const ObjCIvarDecl *Ivar) {
517 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
518 + '.' + Ivar->getNameAsString();
519 return Name;
520 }
521 /// Returns the variable used to store the offset of an instance variable.
522 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
523 const ObjCIvarDecl *Ivar);
524 /// Emits a reference to a class. This allows the linker to object if there
525 /// is no class of the matching name.
526 void EmitClassRef(const std::string &className);
527
528 /// Emits a pointer to the named class
529 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
530 const std::string &Name, bool isWeak);
531
532 /// Looks up the method for sending a message to the specified object. This
533 /// mechanism differs between the GCC and GNU runtimes, so this method must be
534 /// overridden in subclasses.
535 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
536 llvm::Value *&Receiver,
537 llvm::Value *cmd,
538 llvm::MDNode *node,
539 MessageSendInfo &MSI) = 0;
540
541 /// Looks up the method for sending a message to a superclass. This
542 /// mechanism differs between the GCC and GNU runtimes, so this method must
543 /// be overridden in subclasses.
544 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
545 Address ObjCSuper,
546 llvm::Value *cmd,
547 MessageSendInfo &MSI) = 0;
548
549 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
550 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
551 /// bits set to their values, LSB first, while larger ones are stored in a
552 /// structure of this / form:
553 ///
554 /// struct { int32_t length; int32_t values[length]; };
555 ///
556 /// The values in the array are stored in host-endian format, with the least
557 /// significant bit being assumed to come first in the bitfield. Therefore,
558 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
559 /// while a bitfield / with the 63rd bit set will be 1<<64.
560 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
561
562public:
563 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
564 unsigned protocolClassVersion, unsigned classABI=1);
565
566 ConstantAddress GenerateConstantString(const StringLiteral *SL) override;
567
568 ConstantAddress GenerateConstantNumber(const bool Value,
569 const QualType &Ty) override;
570 ConstantAddress GenerateConstantNumber(const llvm::APSInt &Value,
571 const QualType &Ty) override;
572 ConstantAddress GenerateConstantNumber(const llvm::APFloat &Value,
573 const QualType &Ty) override;
574 ConstantAddress
575 GenerateConstantArray(const ArrayRef<llvm::Constant *> &Objects) override;
576 ConstantAddress GenerateConstantDictionary(
577 const ObjCDictionaryLiteral *E,
578 ArrayRef<std::pair<llvm::Constant *, llvm::Constant *>> KeysAndObjects)
579 override;
580
581 RValue
582 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
583 QualType ResultType, Selector Sel,
584 llvm::Value *Receiver, const CallArgList &CallArgs,
585 const ObjCInterfaceDecl *Class,
586 const ObjCMethodDecl *Method) override;
587 RValue
588 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
589 QualType ResultType, Selector Sel,
590 const ObjCInterfaceDecl *Class,
591 bool isCategoryImpl, llvm::Value *Receiver,
592 bool IsClassMessage, const CallArgList &CallArgs,
593 const ObjCMethodDecl *Method) override;
594 llvm::Value *GetClass(CodeGenFunction &CGF,
595 const ObjCInterfaceDecl *OID) override;
596 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
597 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
598 llvm::Value *GetSelector(CodeGenFunction &CGF,
599 const ObjCMethodDecl *Method) override;
600 virtual llvm::Constant *GetConstantSelector(Selector Sel,
601 const std::string &TypeEncoding) {
602 llvm_unreachable("Runtime unable to generate constant selector");
603 }
604 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
605 return GetConstantSelector(M->getSelector(),
607 }
608 llvm::Constant *GetEHType(QualType T) override;
609
610 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
611 const ObjCContainerDecl *CD) override;
612
613 // Map to unify direct method definitions.
614 llvm::DenseMap<const ObjCMethodDecl *, llvm::Function *>
615 DirectMethodDefinitions;
616 void GenerateDirectMethodsPreconditionCheck(
617 CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,
618 const ObjCContainerDecl *CD) override;
619 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
620 const ObjCMethodDecl *OMD,
621 const ObjCContainerDecl *CD) override;
622 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
623 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
624 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
625 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
626 const ObjCProtocolDecl *PD) override;
627 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
628
629 virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
630
631 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
632 return GenerateProtocolRef(PD);
633 }
634
635 llvm::Function *ModuleInitFunction() override;
636 llvm::FunctionCallee GetPropertyGetFunction() override;
637 llvm::FunctionCallee GetPropertySetFunction() override;
638 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
639 bool copy) override;
640 llvm::FunctionCallee GetSetStructFunction() override;
641 llvm::FunctionCallee GetGetStructFunction() override;
642 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
643 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
644 llvm::FunctionCallee EnumerationMutationFunction() override;
645
646 void EmitTryStmt(CodeGenFunction &CGF,
647 const ObjCAtTryStmt &S) override;
648 void EmitSynchronizedStmt(CodeGenFunction &CGF,
649 const ObjCAtSynchronizedStmt &S) override;
650 void EmitThrowStmt(CodeGenFunction &CGF,
651 const ObjCAtThrowStmt &S,
652 bool ClearInsertionPoint=true) override;
653 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
654 Address AddrWeakObj) override;
655 void EmitObjCWeakAssign(CodeGenFunction &CGF,
656 llvm::Value *src, Address dst) override;
657 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
658 llvm::Value *src, Address dest,
659 bool threadlocal=false) override;
660 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
661 Address dest, llvm::Value *ivarOffset) override;
662 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
663 llvm::Value *src, Address dest) override;
664 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
665 Address SrcPtr,
666 llvm::Value *Size) override;
667 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
668 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
669 unsigned CVRQualifiers) override;
670 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
671 const ObjCInterfaceDecl *Interface,
672 const ObjCIvarDecl *Ivar) override;
673 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
674 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
675 const CGBlockInfo &blockInfo) override {
676 return NULLPtr;
677 }
678 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
679 const CGBlockInfo &blockInfo) override {
680 return NULLPtr;
681 }
682
683 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
684 return NULLPtr;
685 }
686};
687
688/// Class representing the legacy GCC Objective-C ABI. This is the default when
689/// -fobjc-nonfragile-abi is not specified.
690///
691/// The GCC ABI target actually generates code that is approximately compatible
692/// with the new GNUstep runtime ABI, but refrains from using any features that
693/// would not work with the GCC runtime. For example, clang always generates
694/// the extended form of the class structure, and the extra fields are simply
695/// ignored by GCC libobjc.
696class CGObjCGCC : public CGObjCGNU {
697 /// The GCC ABI message lookup function. Returns an IMP pointing to the
698 /// method implementation for this message.
699 LazyRuntimeFunction MsgLookupFn;
700 /// The GCC ABI superclass message lookup function. Takes a pointer to a
701 /// structure describing the receiver and the class, and a selector as
702 /// arguments. Returns the IMP for the corresponding method.
703 LazyRuntimeFunction MsgLookupSuperFn;
704
705protected:
706 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
707 llvm::Value *cmd, llvm::MDNode *node,
708 MessageSendInfo &MSI) override {
709 CGBuilderTy &Builder = CGF.Builder;
710 llvm::Value *args[] = {
711 EnforceType(Builder, Receiver, IdTy),
712 EnforceType(Builder, cmd, SelectorTy) };
713 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
714 imp->setMetadata(msgSendMDKind, node);
715 return imp;
716 }
717
718 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
719 llvm::Value *cmd, MessageSendInfo &MSI) override {
720 CGBuilderTy &Builder = CGF.Builder;
721 llvm::Value *lookupArgs[] = {
722 EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),
723 cmd};
724 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
725 }
726
727public:
728 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
729 // IMP objc_msg_lookup(id, SEL);
730 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
731 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
732 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
733 PtrToObjCSuperTy, SelectorTy);
734 }
735};
736
737/// Class used when targeting the new GNUstep runtime ABI.
738class CGObjCGNUstep : public CGObjCGNU {
739 /// The slot lookup function. Returns a pointer to a cacheable structure
740 /// that contains (among other things) the IMP.
741 LazyRuntimeFunction SlotLookupFn;
742 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
743 /// a structure describing the receiver and the class, and a selector as
744 /// arguments. Returns the slot for the corresponding method. Superclass
745 /// message lookup rarely changes, so this is a good caching opportunity.
746 LazyRuntimeFunction SlotLookupSuperFn;
747 /// Specialised function for setting atomic retain properties
748 LazyRuntimeFunction SetPropertyAtomic;
749 /// Specialised function for setting atomic copy properties
750 LazyRuntimeFunction SetPropertyAtomicCopy;
751 /// Specialised function for setting nonatomic retain properties
752 LazyRuntimeFunction SetPropertyNonAtomic;
753 /// Specialised function for setting nonatomic copy properties
754 LazyRuntimeFunction SetPropertyNonAtomicCopy;
755 /// Function to perform atomic copies of C++ objects with nontrivial copy
756 /// constructors from Objective-C ivars.
757 LazyRuntimeFunction CxxAtomicObjectGetFn;
758 /// Function to perform atomic copies of C++ objects with nontrivial copy
759 /// constructors to Objective-C ivars.
760 LazyRuntimeFunction CxxAtomicObjectSetFn;
761 /// Type of a slot structure pointer. This is returned by the various
762 /// lookup functions.
763 llvm::Type *SlotTy;
764 /// Type of a slot structure.
765 llvm::Type *SlotStructTy;
766
767 public:
768 llvm::Constant *GetEHType(QualType T) override;
769
770 protected:
771 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
772 llvm::Value *cmd, llvm::MDNode *node,
773 MessageSendInfo &MSI) override {
774 CGBuilderTy &Builder = CGF.Builder;
775 llvm::FunctionCallee LookupFn = SlotLookupFn;
776
777 // Store the receiver on the stack so that we can reload it later
778 RawAddress ReceiverPtr =
779 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
780 Builder.CreateStore(Receiver, ReceiverPtr);
781
782 llvm::Value *self;
783
785 self = CGF.LoadObjCSelf();
786 } else {
787 self = llvm::ConstantPointerNull::get(IdTy);
788 }
789
790 // The lookup function is guaranteed not to capture the receiver pointer.
791 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
792 LookupFn2->addParamAttr(
793 0, llvm::Attribute::getWithCaptureInfo(CGF.getLLVMContext(),
794 llvm::CaptureInfo::none()));
795
796 llvm::Value *args[] = {
797 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
798 EnforceType(Builder, cmd, SelectorTy),
799 EnforceType(Builder, self, IdTy)};
800 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
801 slot->setOnlyReadsMemory();
802 slot->setMetadata(msgSendMDKind, node);
803
804 // Load the imp from the slot
805 llvm::Value *imp = Builder.CreateAlignedLoad(
806 IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
807 CGF.getPointerAlign());
808
809 // The lookup function may have changed the receiver, so make sure we use
810 // the new one.
811 Receiver = Builder.CreateLoad(ReceiverPtr, true);
812 return imp;
813 }
814
815 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
816 llvm::Value *cmd,
817 MessageSendInfo &MSI) override {
818 CGBuilderTy &Builder = CGF.Builder;
819 llvm::Value *lookupArgs[] = {ObjCSuper.emitRawPointer(CGF), cmd};
820
821 llvm::CallInst *slot =
822 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
823 slot->setOnlyReadsMemory();
824
825 return Builder.CreateAlignedLoad(
826 IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
827 CGF.getPointerAlign());
828 }
829
830 public:
831 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
832 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
833 unsigned ClassABI) :
834 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
835 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
836
837 SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
838 SlotTy = PtrTy;
839 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
840 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
841 SelectorTy, IdTy);
842 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
843 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
844 PtrToObjCSuperTy, SelectorTy);
845 // If we're in ObjC++ mode, then we want to make
846 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
847 if (usesCxxExceptions) {
848 // void *__cxa_begin_catch(void *e)
849 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
850 // void __cxa_end_catch(void)
851 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
852 // void __cxa_rethrow(void)
853 ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", VoidTy);
854 } else if (usesSEHExceptions) {
855 // void objc_exception_rethrow(void)
856 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
857 } else if (CGM.getLangOpts().CPlusPlus) {
858 // void *__cxa_begin_catch(void *e)
859 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
860 // void __cxa_end_catch(void)
861 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
862 // void _Unwind_Resume_or_Rethrow(void*)
863 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
864 PtrTy);
865 } else if (R.getVersion() >= VersionTuple(1, 7)) {
866 // id objc_begin_catch(void *e)
867 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
868 // void objc_end_catch(void)
869 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
870 // void _Unwind_Resume_or_Rethrow(void*)
871 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
872 }
873 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
874 SelectorTy, IdTy, PtrDiffTy);
875 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
876 IdTy, SelectorTy, IdTy, PtrDiffTy);
877 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
878 IdTy, SelectorTy, IdTy, PtrDiffTy);
879 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
880 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
881 // void objc_setCppObjectAtomic(void *dest, const void *src, void
882 // *helper);
883 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
884 PtrTy, PtrTy);
885 // void objc_getCppObjectAtomic(void *dest, const void *src, void
886 // *helper);
887 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
888 PtrTy, PtrTy);
889 }
890
891 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
892 // The optimised functions were added in version 1.7 of the GNUstep
893 // runtime.
894 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
895 VersionTuple(1, 7));
896 return CxxAtomicObjectGetFn;
897 }
898
899 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
900 // The optimised functions were added in version 1.7 of the GNUstep
901 // runtime.
902 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
903 VersionTuple(1, 7));
904 return CxxAtomicObjectSetFn;
905 }
906
907 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
908 bool copy) override {
909 // The optimised property functions omit the GC check, and so are not
910 // safe to use in GC mode. The standard functions are fast in GC mode,
911 // so there is less advantage in using them.
912 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
913 // The optimised functions were added in version 1.7 of the GNUstep
914 // runtime.
915 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
916 VersionTuple(1, 7));
917
918 if (atomic) {
919 if (copy) return SetPropertyAtomicCopy;
920 return SetPropertyAtomic;
921 }
922
923 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
924 }
925};
926
927/// GNUstep Objective-C ABI version 2 implementation.
928/// This is the ABI that provides a clean break with the legacy GCC ABI and
929/// cleans up a number of things that were added to work around 1980s linkers.
930class CGObjCGNUstep2 : public CGObjCGNUstep {
931 enum SectionKind
932 {
933 SelectorSection = 0,
934 ClassSection,
935 ClassReferenceSection,
936 CategorySection,
937 ProtocolSection,
938 ProtocolReferenceSection,
939 ClassAliasSection,
940 ConstantStringSection
941 };
942 /// The subset of `objc_class_flags` used at compile time.
943 enum ClassFlags {
944 /// This is a metaclass
945 ClassFlagMeta = (1 << 0),
946 /// This class has been initialised by the runtime (+initialize has been
947 /// sent if necessary).
948 ClassFlagInitialized = (1 << 8),
949 };
950 static const char *const SectionsBaseNames[8];
951 static const char *const PECOFFSectionsBaseNames[8];
952 template<SectionKind K>
953 std::string sectionName() {
954 if (CGM.getTriple().isOSBinFormatCOFF()) {
955 std::string name(PECOFFSectionsBaseNames[K]);
956 name += "$m";
957 return name;
958 }
959 return SectionsBaseNames[K];
960 }
961 /// The GCC ABI superclass message lookup function. Takes a pointer to a
962 /// structure describing the receiver and the class, and a selector as
963 /// arguments. Returns the IMP for the corresponding method.
964 LazyRuntimeFunction MsgLookupSuperFn;
965 /// Function to ensure that +initialize is sent to a class.
966 LazyRuntimeFunction SentInitializeFn;
967 /// A flag indicating if we've emitted at least one protocol.
968 /// If we haven't, then we need to emit an empty protocol, to ensure that the
969 /// __start__objc_protocols and __stop__objc_protocols sections exist.
970 bool EmittedProtocol = false;
971 /// A flag indicating if we've emitted at least one protocol reference.
972 /// If we haven't, then we need to emit an empty protocol, to ensure that the
973 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
974 /// exist.
975 bool EmittedProtocolRef = false;
976 /// A flag indicating if we've emitted at least one class.
977 /// If we haven't, then we need to emit an empty protocol, to ensure that the
978 /// __start__objc_classes and __stop__objc_classes sections / exist.
979 bool EmittedClass = false;
980 /// Generate the name of a symbol for a reference to a class. Accesses to
981 /// classes should be indirected via this.
982
983 typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>
984 EarlyInitPair;
985 std::vector<EarlyInitPair> EarlyInitList;
986
987 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
988 if (isWeak)
989 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
990 else
991 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
992 }
993 /// Generate the name of a class symbol.
994 std::string SymbolForClass(StringRef Name) {
995 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
996 }
997 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
998 ArrayRef<llvm::Value*> Args) {
999 SmallVector<llvm::Type *,8> Types;
1000 for (auto *Arg : Args)
1001 Types.push_back(Arg->getType());
1002 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
1003 false);
1004 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
1005 B.CreateCall(Fn, Args);
1006 }
1007
1008 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
1009
1010 auto Str = SL->getString();
1011 CharUnits Align = CGM.getPointerAlign();
1012
1013 // Look for an existing one
1014 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1015 if (old != ObjCStrings.end())
1016 return ConstantAddress(old->getValue(), IdElemTy, Align);
1017
1018 bool isNonASCII = SL->containsNonAscii();
1019
1020 auto LiteralLength = SL->getLength();
1021
1022 if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&
1023 (LiteralLength < 9) && !isNonASCII) {
1024 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
1025 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
1026 // 3-bit tag (which is always 4).
1027 uint64_t str = 0;
1028 // Fill in the characters
1029 for (unsigned i=0 ; i<LiteralLength ; i++)
1030 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
1031 // Fill in the length
1032 str |= LiteralLength << 3;
1033 // Set the tag
1034 str |= 4;
1035 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
1036 llvm::ConstantInt::get(Int64Ty, str), IdTy);
1037 ObjCStrings[Str] = ObjCStr;
1038 return ConstantAddress(ObjCStr, IdElemTy, Align);
1039 }
1040
1041 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1042
1043 if (StringClass.empty()) StringClass = "NSConstantString";
1044
1045 std::string Sym = SymbolForClass(StringClass);
1046
1047 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1048
1049 if (!isa) {
1050 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1051 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1052 if (CGM.getTriple().isOSBinFormatCOFF()) {
1053 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1054 }
1055 }
1056
1057 // struct
1058 // {
1059 // Class isa;
1060 // uint32_t flags;
1061 // uint32_t length; // Number of codepoints
1062 // uint32_t size; // Number of bytes
1063 // uint32_t hash;
1064 // const char *data;
1065 // };
1066
1067 ConstantInitBuilder Builder(CGM);
1068 auto Fields = Builder.beginStruct();
1069 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1070 Fields.add(isa);
1071 } else {
1072 Fields.addNullPointer(PtrTy);
1073 }
1074 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1075 // number of bytes is simply double the number of UTF-16 codepoints. In
1076 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1077 // codepoints.
1078 if (isNonASCII) {
1079 unsigned NumU8CodeUnits = Str.size();
1080 // A UTF-16 representation of a unicode string contains at most the same
1081 // number of code units as a UTF-8 representation. Allocate that much
1082 // space, plus one for the final null character.
1083 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1084 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1085 llvm::UTF16 *ToPtr = &ToBuf[0];
1086 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1087 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1088 uint32_t StringLength = ToPtr - &ToBuf[0];
1089 // Add null terminator
1090 *ToPtr = 0;
1091 // Flags: 2 indicates UTF-16 encoding
1092 Fields.addInt(Int32Ty, 2);
1093 // Number of UTF-16 codepoints
1094 Fields.addInt(Int32Ty, StringLength);
1095 // Number of bytes
1096 Fields.addInt(Int32Ty, StringLength * 2);
1097 // Hash. Not currently initialised by the compiler.
1098 Fields.addInt(Int32Ty, 0);
1099 // pointer to the data string.
1100 auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);
1101 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1102 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1103 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1104 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1105 Fields.add(Buffer);
1106 } else {
1107 // Flags: 0 indicates ASCII encoding
1108 Fields.addInt(Int32Ty, 0);
1109 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1110 Fields.addInt(Int32Ty, Str.size());
1111 // Number of bytes
1112 Fields.addInt(Int32Ty, Str.size());
1113 // Hash. Not currently initialised by the compiler.
1114 Fields.addInt(Int32Ty, 0);
1115 // Data pointer
1116 Fields.add(MakeConstantString(Str));
1117 }
1118 std::string StringName;
1119 bool isNamed = !isNonASCII;
1120 if (isNamed) {
1121 StringName = ".objc_str_";
1122 for (unsigned char c : Str) {
1123 if (isalnum(c))
1124 StringName += c;
1125 else if (c == ' ')
1126 StringName += '_';
1127 else {
1128 isNamed = false;
1129 break;
1130 }
1131 }
1132 }
1133 llvm::GlobalVariable *ObjCStrGV =
1134 Fields.finishAndCreateGlobal(
1135 isNamed ? StringRef(StringName) : ".objc_string",
1136 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1137 : llvm::GlobalValue::PrivateLinkage);
1138 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1139 if (isNamed) {
1140 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1141 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1142 }
1143 if (CGM.getTriple().isOSBinFormatCOFF()) {
1144 std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
1145 EarlyInitList.emplace_back(Sym, v);
1146 }
1147 ObjCStrings[Str] = ObjCStrGV;
1148 ConstantStrings.push_back(ObjCStrGV);
1149 return ConstantAddress(ObjCStrGV, IdElemTy, Align);
1150 }
1151
1152 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1153 const ObjCPropertyDecl *property,
1154 const Decl *OCD,
1155 bool isSynthesized=true, bool
1156 isDynamic=true) override {
1157 // struct objc_property
1158 // {
1159 // const char *name;
1160 // const char *attributes;
1161 // const char *type;
1162 // SEL getter;
1163 // SEL setter;
1164 // };
1165 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1166 ASTContext &Context = CGM.getContext();
1167 Fields.add(MakeConstantString(property->getNameAsString()));
1168 std::string TypeStr =
1169 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1170 Fields.add(MakeConstantString(TypeStr));
1171 std::string typeStr;
1172 Context.getObjCEncodingForType(property->getType(), typeStr);
1173 Fields.add(MakeConstantString(typeStr));
1174 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1175 if (accessor) {
1176 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1177 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1178 } else {
1179 Fields.add(NULLPtr);
1180 }
1181 };
1182 addPropertyMethod(property->getGetterMethodDecl());
1183 addPropertyMethod(property->getSetterMethodDecl());
1184 Fields.finishAndAddTo(PropertiesArray);
1185 }
1186
1187 llvm::Constant *
1188 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1189 // struct objc_protocol_method_description
1190 // {
1191 // SEL selector;
1192 // const char *types;
1193 // };
1194 llvm::StructType *ObjCMethodDescTy =
1195 llvm::StructType::get(CGM.getLLVMContext(),
1196 { PtrToInt8Ty, PtrToInt8Ty });
1197 ASTContext &Context = CGM.getContext();
1198 ConstantInitBuilder Builder(CGM);
1199 // struct objc_protocol_method_description_list
1200 // {
1201 // int count;
1202 // int size;
1203 // struct objc_protocol_method_description methods[];
1204 // };
1205 auto MethodList = Builder.beginStruct();
1206 // int count;
1207 MethodList.addInt(IntTy, Methods.size());
1208 // int size; // sizeof(struct objc_method_description)
1209 const llvm::DataLayout &DL = TheModule.getDataLayout();
1210 MethodList.addInt(IntTy, DL.getTypeSizeInBits(ObjCMethodDescTy) /
1211 CGM.getContext().getCharWidth());
1212 // struct objc_method_description[]
1213 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1214 for (auto *M : Methods) {
1215 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1216 Method.add(CGObjCGNU::GetConstantSelector(M));
1217 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1218 Method.finishAndAddTo(MethodArray);
1219 }
1220 MethodArray.finishAndAddTo(MethodList);
1221 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1222 CGM.getPointerAlign());
1223 }
1224 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1225 override {
1226 const auto &ReferencedProtocols = OCD->getReferencedProtocols();
1227 auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
1228 ReferencedProtocols.end());
1229 SmallVector<llvm::Constant *, 16> Protocols;
1230 for (const auto *PI : RuntimeProtocols)
1231 Protocols.push_back(GenerateProtocolRef(PI));
1232 return GenerateProtocolList(Protocols);
1233 }
1234
1235 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1236 llvm::Value *cmd, MessageSendInfo &MSI) override {
1237 // Don't access the slot unless we're trying to cache the result.
1238 CGBuilderTy &Builder = CGF.Builder;
1239 llvm::Value *lookupArgs[] = {
1240 CGObjCGNU::EnforceType(Builder, ObjCSuper.emitRawPointer(CGF),
1241 PtrToObjCSuperTy),
1242 cmd};
1243 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1244 }
1245
1246 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1247 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1248 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1249 if (ClassSymbol)
1250 return ClassSymbol;
1251 ClassSymbol = new llvm::GlobalVariable(TheModule,
1252 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1253 nullptr, SymbolName);
1254 // If this is a weak symbol, then we are creating a valid definition for
1255 // the symbol, pointing to a weak definition of the real class pointer. If
1256 // this is not a weak reference, then we are expecting another compilation
1257 // unit to provide the real indirection symbol.
1258 if (isWeak)
1259 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1260 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1261 nullptr, SymbolForClass(Name)));
1262 else {
1263 if (CGM.getTriple().isOSBinFormatCOFF()) {
1264 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1265 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1266 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1267
1268 const ObjCInterfaceDecl *OID = nullptr;
1269 for (const auto *Result : DC->lookup(&II))
1270 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1271 break;
1272
1273 // The first Interface we find may be a @class,
1274 // which should only be treated as the source of
1275 // truth in the absence of a true declaration.
1276 assert(OID && "Failed to find ObjCInterfaceDecl");
1277 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1278 if (OIDDef != nullptr)
1279 OID = OIDDef;
1280
1281 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1282 if (OID->hasAttr<DLLImportAttr>())
1283 Storage = llvm::GlobalValue::DLLImportStorageClass;
1284 else if (OID->hasAttr<DLLExportAttr>())
1285 Storage = llvm::GlobalValue::DLLExportStorageClass;
1286
1287 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1288 }
1289 }
1290 assert(ClassSymbol->getName() == SymbolName);
1291 return ClassSymbol;
1292 }
1293 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1294 const std::string &Name,
1295 bool isWeak) override {
1296 return CGF.Builder.CreateLoad(
1297 Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
1298 }
1299 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1300 // typedef enum {
1301 // ownership_invalid = 0,
1302 // ownership_strong = 1,
1303 // ownership_weak = 2,
1304 // ownership_unsafe = 3
1305 // } ivar_ownership;
1306 int Flag;
1307 switch (Ownership) {
1309 Flag = 1;
1310 break;
1312 Flag = 2;
1313 break;
1315 Flag = 3;
1316 break;
1319 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1320 Flag = 0;
1321 }
1322 return Flag;
1323 }
1324 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1325 ArrayRef<llvm::Constant *> IvarTypes,
1326 ArrayRef<llvm::Constant *> IvarOffsets,
1327 ArrayRef<llvm::Constant *> IvarAlign,
1328 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1329 llvm_unreachable("Method should not be called!");
1330 }
1331
1332 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1333 std::string Name = SymbolForProtocol(ProtocolName);
1334 auto *GV = TheModule.getGlobalVariable(Name);
1335 if (!GV) {
1336 // Emit a placeholder symbol.
1337 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1338 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1339 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1340 }
1341 return GV;
1342 }
1343
1344 /// Existing protocol references.
1345 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1346
1347 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1348 const ObjCProtocolDecl *PD) override {
1349 auto Name = PD->getNameAsString();
1350 auto *&Ref = ExistingProtocolRefs[Name];
1351 if (!Ref) {
1352 auto *&Protocol = ExistingProtocols[Name];
1353 if (!Protocol)
1354 Protocol = GenerateProtocolRef(PD);
1355 std::string RefName = SymbolForProtocolRef(Name);
1356 assert(!TheModule.getGlobalVariable(RefName));
1357 // Emit a reference symbol.
1358 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, false,
1359 llvm::GlobalValue::LinkOnceODRLinkage,
1360 Protocol, RefName);
1361 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1362 GV->setSection(sectionName<ProtocolReferenceSection>());
1363 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1364 Ref = GV;
1365 }
1366 EmittedProtocolRef = true;
1367 return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
1368 CGM.getPointerAlign());
1369 }
1370
1371 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1372 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1373 Protocols.size());
1374 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1375 Protocols);
1376 ConstantInitBuilder builder(CGM);
1377 auto ProtocolBuilder = builder.beginStruct();
1378 ProtocolBuilder.addNullPointer(PtrTy);
1379 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1380 ProtocolBuilder.add(ProtocolArray);
1381 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1382 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1383 }
1384
1385 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1386 // Do nothing - we only emit referenced protocols.
1387 }
1388 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
1389 std::string ProtocolName = PD->getNameAsString();
1390 auto *&Protocol = ExistingProtocols[ProtocolName];
1391 if (Protocol)
1392 return Protocol;
1393
1394 EmittedProtocol = true;
1395
1396 auto SymName = SymbolForProtocol(ProtocolName);
1397 auto *OldGV = TheModule.getGlobalVariable(SymName);
1398
1399 // Use the protocol definition, if there is one.
1400 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1401 PD = Def;
1402 else {
1403 // If there is no definition, then create an external linkage symbol and
1404 // hope that someone else fills it in for us (and fail to link if they
1405 // don't).
1406 assert(!OldGV);
1407 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1408 /*isConstant*/false,
1409 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1410 return Protocol;
1411 }
1412
1413 SmallVector<llvm::Constant*, 16> Protocols;
1414 auto RuntimeProtocols =
1415 GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
1416 for (const auto *PI : RuntimeProtocols)
1417 Protocols.push_back(GenerateProtocolRef(PI));
1418 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1419
1420 // Collect information about methods
1421 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1422 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1423 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1424 OptionalInstanceMethodList);
1425 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1426 OptionalClassMethodList);
1427
1428 // The isa pointer must be set to a magic number so the runtime knows it's
1429 // the correct layout.
1430 ConstantInitBuilder builder(CGM);
1431 auto ProtocolBuilder = builder.beginStruct();
1432 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1433 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1434 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1435 ProtocolBuilder.add(ProtocolList);
1436 ProtocolBuilder.add(InstanceMethodList);
1437 ProtocolBuilder.add(ClassMethodList);
1438 ProtocolBuilder.add(OptionalInstanceMethodList);
1439 ProtocolBuilder.add(OptionalClassMethodList);
1440 // Required instance properties
1441 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1442 // Optional instance properties
1443 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1444 // Required class properties
1445 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1446 // Optional class properties
1447 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1448
1449 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1450 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1451 GV->setSection(sectionName<ProtocolSection>());
1452 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1453 if (OldGV) {
1454 OldGV->replaceAllUsesWith(GV);
1455 OldGV->removeFromParent();
1456 GV->setName(SymName);
1457 }
1458 Protocol = GV;
1459 return GV;
1460 }
1461 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1462 const std::string &TypeEncoding) override {
1463 return GetConstantSelector(Sel, TypeEncoding);
1464 }
1465 std::string GetSymbolNameForTypeEncoding(const std::string &TypeEncoding) {
1466 std::string MangledTypes = std::string(TypeEncoding);
1467 // @ is used as a special character in ELF symbol names (used for symbol
1468 // versioning), so mangle the name to not include it. Replace it with a
1469 // character that is not a valid type encoding character (and, being
1470 // non-printable, never will be!)
1471 if (CGM.getTriple().isOSBinFormatELF())
1472 llvm::replace(MangledTypes, '@', '\1');
1473 // = in dll exported names causes lld to fail when linking on Windows.
1474 if (CGM.getTriple().isOSWindows())
1475 llvm::replace(MangledTypes, '=', '\2');
1476 return MangledTypes;
1477 }
1478 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1479 if (TypeEncoding.empty())
1480 return NULLPtr;
1481 std::string MangledTypes =
1482 GetSymbolNameForTypeEncoding(std::string(TypeEncoding));
1483 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1484 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1485 if (!TypesGlobal) {
1486 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1487 TypeEncoding);
1488 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1489 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1490 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1491 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1492 TypesGlobal = GV;
1493 }
1494 return TypesGlobal;
1495 }
1496 llvm::Constant *GetConstantSelector(Selector Sel,
1497 const std::string &TypeEncoding) override {
1498 std::string MangledTypes = GetSymbolNameForTypeEncoding(TypeEncoding);
1499 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1500 MangledTypes).str();
1501 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1502 return GV;
1503 ConstantInitBuilder builder(CGM);
1504 auto SelBuilder = builder.beginStruct();
1505 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1506 true));
1507 SelBuilder.add(GetTypeString(TypeEncoding));
1508 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1509 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1510 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1511 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1512 GV->setSection(sectionName<SelectorSection>());
1513 return GV;
1514 }
1515 llvm::StructType *emptyStruct = nullptr;
1516
1517 /// Return pointers to the start and end of a section. On ELF platforms, we
1518 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1519 /// to the start and end of section names, as long as those section names are
1520 /// valid identifiers and the symbols are referenced but not defined. On
1521 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1522 /// by subsections and place everything that we want to reference in a middle
1523 /// subsection and then insert zero-sized symbols in subsections a and z.
1524 std::pair<llvm::Constant*,llvm::Constant*>
1525 GetSectionBounds(StringRef Section) {
1526 if (CGM.getTriple().isOSBinFormatCOFF()) {
1527 if (emptyStruct == nullptr) {
1528 emptyStruct = llvm::StructType::create(
1529 VMContext, {}, ".objc_section_sentinel", /*isPacked=*/true);
1530 }
1531 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1532 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1533 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1534 /*isConstant*/false,
1535 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1536 Section);
1537 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1538 Sym->setSection((Section + SecSuffix).str());
1539 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1540 Section).str()));
1541 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1542 return Sym;
1543 };
1544 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1545 }
1546 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1547 /*isConstant*/false,
1548 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1549 Section);
1550 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1551 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1552 /*isConstant*/false,
1553 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1554 Section);
1555 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1556 return { Start, Stop };
1557 }
1558 CatchTypeInfo getCatchAllTypeInfo() override {
1559 return CGM.getCXXABI().getCatchAllTypeInfo();
1560 }
1561 llvm::Function *ModuleInitFunction() override {
1562 llvm::Function *LoadFunction = llvm::Function::Create(
1563 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1564 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1565 &TheModule);
1566 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1567 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1568
1569 llvm::BasicBlock *EntryBB =
1570 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1571 CGBuilderTy B(CGM, VMContext);
1572 B.SetInsertPoint(EntryBB);
1573 ConstantInitBuilder builder(CGM);
1574 auto InitStructBuilder = builder.beginStruct();
1575 InitStructBuilder.addInt(Int64Ty, 0);
1576 auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1577 for (auto *s : sectionVec) {
1578 auto bounds = GetSectionBounds(s);
1579 InitStructBuilder.add(bounds.first);
1580 InitStructBuilder.add(bounds.second);
1581 }
1582 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1583 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1584 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1585 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1586
1587 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1588 B.CreateRetVoid();
1589 // Make sure that the optimisers don't delete this function.
1590 CGM.addCompilerUsedGlobal(LoadFunction);
1591 // FIXME: Currently ELF only!
1592 // We have to do this by hand, rather than with @llvm.ctors, so that the
1593 // linker can remove the duplicate invocations.
1594 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1595 /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
1596 LoadFunction, ".objc_ctor");
1597 // Check that this hasn't been renamed. This shouldn't happen, because
1598 // this function should be called precisely once.
1599 assert(InitVar->getName() == ".objc_ctor");
1600 // In Windows, initialisers are sorted by the suffix. XCL is for library
1601 // initialisers, which run before user initialisers. We are running
1602 // Objective-C loads at the end of library load. This means +load methods
1603 // will run before any other static constructors, but that static
1604 // constructors can see a fully initialised Objective-C state.
1605 if (CGM.getTriple().isOSBinFormatCOFF())
1606 InitVar->setSection(".CRT$XCLz");
1607 else
1608 {
1609 if (CGM.getCodeGenOpts().UseInitArray)
1610 InitVar->setSection(".init_array");
1611 else
1612 InitVar->setSection(".ctors");
1613 }
1614 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1615 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1616 CGM.addUsedGlobal(InitVar);
1617 for (auto *C : Categories) {
1618 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1619 Cat->setSection(sectionName<CategorySection>());
1620 CGM.addUsedGlobal(Cat);
1621 }
1622 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1623 StringRef Section) {
1624 auto nullBuilder = builder.beginStruct();
1625 for (auto *F : Init)
1626 nullBuilder.add(F);
1627 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1628 false, llvm::GlobalValue::LinkOnceODRLinkage);
1629 GV->setSection(Section);
1630 GV->setComdat(TheModule.getOrInsertComdat(Name));
1631 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1632 CGM.addUsedGlobal(GV);
1633 return GV;
1634 };
1635 for (auto clsAlias : ClassAliases)
1636 createNullGlobal(std::string(".objc_class_alias") +
1637 clsAlias.second, { MakeConstantString(clsAlias.second),
1638 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1639 // On ELF platforms, add a null value for each special section so that we
1640 // can always guarantee that the _start and _stop symbols will exist and be
1641 // meaningful. This is not required on COFF platforms, where our start and
1642 // stop symbols will create the section.
1643 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1644 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1645 sectionName<SelectorSection>());
1646 if (Categories.empty())
1647 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1648 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1649 sectionName<CategorySection>());
1650 if (!EmittedClass) {
1651 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1652 sectionName<ClassSection>());
1653 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1654 sectionName<ClassReferenceSection>());
1655 }
1656 if (!EmittedProtocol)
1657 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1658 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1659 NULLPtr}, sectionName<ProtocolSection>());
1660 if (!EmittedProtocolRef)
1661 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1662 sectionName<ProtocolReferenceSection>());
1663 if (ClassAliases.empty())
1664 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1665 sectionName<ClassAliasSection>());
1666 if (ConstantStrings.empty()) {
1667 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1668 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1669 i32Zero, i32Zero, i32Zero, NULLPtr },
1670 sectionName<ConstantStringSection>());
1671 }
1672 }
1673 ConstantStrings.clear();
1674 Categories.clear();
1675 Classes.clear();
1676
1677 if (EarlyInitList.size() > 0) {
1678 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1679 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1680 &CGM.getModule());
1681 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1682 Init));
1683 for (const auto &lateInit : EarlyInitList) {
1684 auto *global = TheModule.getGlobalVariable(lateInit.first);
1685 if (global) {
1686 llvm::GlobalVariable *GV = lateInit.second.first;
1687 b.CreateAlignedStore(
1688 global,
1689 b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
1690 CGM.getPointerAlign().getAsAlign());
1691 }
1692 }
1693 b.CreateRetVoid();
1694 // We can't use the normal LLVM global initialisation array, because we
1695 // need to specify that this runs early in library initialisation.
1696 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1697 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1698 Init, ".objc_early_init_ptr");
1699 InitVar->setSection(".CRT$XCLb");
1700 CGM.addUsedGlobal(InitVar);
1701 }
1702 return nullptr;
1703 }
1704 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1705 /// to trigger linker failures if the types don't match.
1706 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1707 const ObjCIvarDecl *Ivar) override {
1708 std::string TypeEncoding;
1709 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1710 TypeEncoding = GetSymbolNameForTypeEncoding(TypeEncoding);
1711 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1712 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1713 return Name;
1714 }
1715 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1716 const ObjCInterfaceDecl *Interface,
1717 const ObjCIvarDecl *Ivar) override {
1718 const ObjCInterfaceDecl *ContainingInterface =
1719 Ivar->getContainingInterface();
1720 const std::string Name =
1721 GetIVarOffsetVariableName(ContainingInterface, Ivar);
1722 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1723 if (!IvarOffsetPointer) {
1724 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1725 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1726 if (Ivar->getAccessControl() != ObjCIvarDecl::Private &&
1728 CGM.setGVProperties(IvarOffsetPointer, ContainingInterface);
1729 }
1730 CharUnits Align = CGM.getIntAlign();
1731 llvm::Value *Offset =
1732 CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
1733 if (Offset->getType() != PtrDiffTy)
1734 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1735 return Offset;
1736 }
1737 void GenerateClass(const ObjCImplementationDecl *OID) override {
1738 ASTContext &Context = CGM.getContext();
1739 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1740
1741 // Get the class name
1742 ObjCInterfaceDecl *classDecl =
1743 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1744 std::string className = classDecl->getNameAsString();
1745 auto *classNameConstant = MakeConstantString(className);
1746
1747 ConstantInitBuilder builder(CGM);
1748 auto metaclassFields = builder.beginStruct();
1749 // struct objc_class *isa;
1750 metaclassFields.addNullPointer(PtrTy);
1751 // struct objc_class *super_class;
1752 metaclassFields.addNullPointer(PtrTy);
1753 // const char *name;
1754 metaclassFields.add(classNameConstant);
1755 // long version;
1756 metaclassFields.addInt(LongTy, 0);
1757 // unsigned long info;
1758 // objc_class_flag_meta
1759 metaclassFields.addInt(LongTy, ClassFlags::ClassFlagMeta);
1760 // long instance_size;
1761 // Setting this to zero is consistent with the older ABI, but it might be
1762 // more sensible to set this to sizeof(struct objc_class)
1763 metaclassFields.addInt(LongTy, 0);
1764 // struct objc_ivar_list *ivars;
1765 metaclassFields.addNullPointer(PtrTy);
1766 // struct objc_method_list *methods
1767 // FIXME: Almost identical code is copied and pasted below for the
1768 // class, but refactoring it cleanly requires C++14 generic lambdas.
1769 if (OID->class_methods().empty())
1770 metaclassFields.addNullPointer(PtrTy);
1771 else {
1772 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1773 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1774 OID->classmeth_end());
1775 metaclassFields.add(
1776 GenerateMethodList(className, "", ClassMethods, true));
1777 }
1778 // void *dtable;
1779 metaclassFields.addNullPointer(PtrTy);
1780 // IMP cxx_construct;
1781 metaclassFields.addNullPointer(PtrTy);
1782 // IMP cxx_destruct;
1783 metaclassFields.addNullPointer(PtrTy);
1784 // struct objc_class *subclass_list
1785 metaclassFields.addNullPointer(PtrTy);
1786 // struct objc_class *sibling_class
1787 metaclassFields.addNullPointer(PtrTy);
1788 // struct objc_protocol_list *protocols;
1789 metaclassFields.addNullPointer(PtrTy);
1790 // struct reference_list *extra_data;
1791 metaclassFields.addNullPointer(PtrTy);
1792 // long abi_version;
1793 metaclassFields.addInt(LongTy, 0);
1794 // struct objc_property_list *properties
1795 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1796
1797 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1798 ManglePublicSymbol("OBJC_METACLASS_") + className,
1799 CGM.getPointerAlign());
1800
1801 auto classFields = builder.beginStruct();
1802 // struct objc_class *isa;
1803 classFields.add(metaclass);
1804 // struct objc_class *super_class;
1805 // Get the superclass name.
1806 const ObjCInterfaceDecl * SuperClassDecl =
1808 llvm::Constant *SuperClass = nullptr;
1809 if (SuperClassDecl) {
1810 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1811 SuperClass = TheModule.getNamedGlobal(SuperClassName);
1812 if (!SuperClass)
1813 {
1814 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1815 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1816 if (IsCOFF) {
1817 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1818 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1819 Storage = llvm::GlobalValue::DLLImportStorageClass;
1820 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1821 Storage = llvm::GlobalValue::DLLExportStorageClass;
1822
1823 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1824 }
1825 }
1826 if (!IsCOFF)
1827 classFields.add(SuperClass);
1828 else
1829 classFields.addNullPointer(PtrTy);
1830 } else
1831 classFields.addNullPointer(PtrTy);
1832 // const char *name;
1833 classFields.add(classNameConstant);
1834 // long version;
1835 classFields.addInt(LongTy, 0);
1836 // unsigned long info;
1837 // !objc_class_flag_meta
1838 classFields.addInt(LongTy, 0);
1839 // long instance_size;
1840 int superInstanceSize = !SuperClassDecl ? 0 :
1841 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1842 // Instance size is negative for classes that have not yet had their ivar
1843 // layout calculated.
1844 classFields.addInt(
1845 LongTy,
1846 0 - (Context.getASTObjCInterfaceLayout(OID->getClassInterface())
1847 .getSize()
1848 .getQuantity() -
1849 superInstanceSize),
1850 /*isSigned=*/true);
1851
1852 if (classDecl->all_declared_ivar_begin() == nullptr)
1853 classFields.addNullPointer(PtrTy);
1854 else {
1855 int ivar_count = 0;
1856 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1857 IVD = IVD->getNextIvar()) ivar_count++;
1858 const llvm::DataLayout &DL = TheModule.getDataLayout();
1859 // struct objc_ivar_list *ivars;
1860 ConstantInitBuilder b(CGM);
1861 auto ivarListBuilder = b.beginStruct();
1862 // int count;
1863 ivarListBuilder.addInt(IntTy, ivar_count);
1864 // size_t size;
1865 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1866 PtrToInt8Ty,
1867 PtrToInt8Ty,
1868 PtrToInt8Ty,
1869 Int32Ty,
1870 Int32Ty);
1871 ivarListBuilder.addInt(SizeTy, DL.getTypeSizeInBits(ObjCIvarTy) /
1872 CGM.getContext().getCharWidth());
1873 // struct objc_ivar ivars[]
1874 auto ivarArrayBuilder = ivarListBuilder.beginArray();
1875 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1876 IVD = IVD->getNextIvar()) {
1877 auto ivarTy = IVD->getType();
1878 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1879 // const char *name;
1880 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1881 // const char *type;
1882 std::string TypeStr;
1883 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1884 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1885 ivarBuilder.add(MakeConstantString(TypeStr));
1886 // int *offset;
1887 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1888 int64_t Offset = static_cast<int64_t>(BaseOffset) - superInstanceSize;
1889 llvm::Constant *OffsetValue =
1890 llvm::ConstantInt::getSigned(IntTy, Offset);
1891 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1892 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1893 if (OffsetVar)
1894 OffsetVar->setInitializer(OffsetValue);
1895 else
1896 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1897 false, llvm::GlobalValue::ExternalLinkage,
1898 OffsetValue, OffsetName);
1899 auto ivarVisibility =
1900 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1901 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1902 classDecl->getVisibility() == HiddenVisibility) ?
1903 llvm::GlobalValue::HiddenVisibility :
1904 llvm::GlobalValue::DefaultVisibility;
1905 OffsetVar->setVisibility(ivarVisibility);
1906 if (ivarVisibility != llvm::GlobalValue::HiddenVisibility)
1907 CGM.setGVProperties(OffsetVar, OID->getClassInterface());
1908 ivarBuilder.add(OffsetVar);
1909 // Ivar size
1910 ivarBuilder.addInt(Int32Ty,
1911 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1912 // Alignment will be stored as a base-2 log of the alignment.
1913 unsigned align =
1914 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1915 // Objects that require more than 2^64-byte alignment should be impossible!
1916 assert(align < 64);
1917 // uint32_t flags;
1918 // Bits 0-1 are ownership.
1919 // Bit 2 indicates an extended type encoding
1920 // Bits 3-8 contain log2(aligment)
1921 ivarBuilder.addInt(Int32Ty,
1922 (align << 3) | (1<<2) |
1923 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1924 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1925 }
1926 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1927 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1928 CGM.getPointerAlign(), /*constant*/ false,
1929 llvm::GlobalValue::PrivateLinkage);
1930 classFields.add(ivarList);
1931 }
1932 // struct objc_method_list *methods
1933 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1934 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1935 OID->instmeth_end());
1936 for (auto *propImpl : OID->property_impls())
1937 if (propImpl->getPropertyImplementation() ==
1939 auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1940 if (OMD && OMD->hasBody())
1941 InstanceMethods.push_back(OMD);
1942 };
1943 addIfExists(propImpl->getGetterMethodDecl());
1944 addIfExists(propImpl->getSetterMethodDecl());
1945 }
1946
1947 if (InstanceMethods.size() == 0)
1948 classFields.addNullPointer(PtrTy);
1949 else
1950 classFields.add(
1951 GenerateMethodList(className, "", InstanceMethods, false));
1952
1953 // void *dtable;
1954 classFields.addNullPointer(PtrTy);
1955 // IMP cxx_construct;
1956 classFields.addNullPointer(PtrTy);
1957 // IMP cxx_destruct;
1958 classFields.addNullPointer(PtrTy);
1959 // struct objc_class *subclass_list
1960 classFields.addNullPointer(PtrTy);
1961 // struct objc_class *sibling_class
1962 classFields.addNullPointer(PtrTy);
1963 // struct objc_protocol_list *protocols;
1964 auto RuntimeProtocols =
1965 GetRuntimeProtocolList(classDecl->all_referenced_protocol_begin(),
1966 classDecl->all_referenced_protocol_end());
1967 SmallVector<llvm::Constant *, 16> Protocols;
1968 for (const auto *I : RuntimeProtocols)
1969 Protocols.push_back(GenerateProtocolRef(I));
1970
1971 if (Protocols.empty())
1972 classFields.addNullPointer(PtrTy);
1973 else
1974 classFields.add(GenerateProtocolList(Protocols));
1975 // struct reference_list *extra_data;
1976 classFields.addNullPointer(PtrTy);
1977 // long abi_version;
1978 classFields.addInt(LongTy, 0);
1979 // struct objc_property_list *properties
1980 classFields.add(GeneratePropertyList(OID, classDecl));
1981
1982 llvm::GlobalVariable *classStruct =
1983 classFields.finishAndCreateGlobal(SymbolForClass(className),
1984 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1985
1986 auto *classRefSymbol = GetClassVar(className);
1987 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1988 classRefSymbol->setInitializer(classStruct);
1989
1990 if (IsCOFF) {
1991 // we can't import a class struct.
1992 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1993 classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1994 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1995 }
1996
1997 if (SuperClass) {
1998 std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
1999 EarlyInitList.emplace_back(std::string(SuperClass->getName()),
2000 std::move(v));
2001 }
2002
2003 }
2004
2005
2006 // Resolve the class aliases, if they exist.
2007 // FIXME: Class pointer aliases shouldn't exist!
2008 if (ClassPtrAlias) {
2009 ClassPtrAlias->replaceAllUsesWith(classStruct);
2010 ClassPtrAlias->eraseFromParent();
2011 ClassPtrAlias = nullptr;
2012 }
2013 if (auto Placeholder =
2014 TheModule.getNamedGlobal(SymbolForClass(className)))
2015 if (Placeholder != classStruct) {
2016 Placeholder->replaceAllUsesWith(classStruct);
2017 Placeholder->eraseFromParent();
2018 classStruct->setName(SymbolForClass(className));
2019 }
2020 if (MetaClassPtrAlias) {
2021 MetaClassPtrAlias->replaceAllUsesWith(metaclass);
2022 MetaClassPtrAlias->eraseFromParent();
2023 MetaClassPtrAlias = nullptr;
2024 }
2025 assert(classStruct->getName() == SymbolForClass(className));
2026
2027 auto classInitRef = new llvm::GlobalVariable(TheModule,
2028 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
2029 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
2030 classInitRef->setSection(sectionName<ClassSection>());
2031 CGM.addUsedGlobal(classInitRef);
2032
2033 EmittedClass = true;
2034 }
2035 public:
2036 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
2037 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2038 PtrToObjCSuperTy, SelectorTy);
2039 SentInitializeFn.init(&CGM, "objc_send_initialize",
2040 llvm::Type::getVoidTy(VMContext), IdTy);
2041 // struct objc_property
2042 // {
2043 // const char *name;
2044 // const char *attributes;
2045 // const char *type;
2046 // SEL getter;
2047 // SEL setter;
2048 // }
2049 PropertyMetadataTy =
2050 llvm::StructType::get(CGM.getLLVMContext(),
2051 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2052 }
2053
2054 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
2055 const ObjCMethodDecl *OMD,
2056 const ObjCContainerDecl *CD) override {
2057 auto &Builder = CGF.Builder;
2058 bool ReceiverCanBeNull = true;
2059 auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());
2060 auto selfValue = Builder.CreateLoad(selfAddr);
2061
2062 // Generate:
2063 //
2064 // /* unless the receiver is never NULL */
2065 // if (self == nil) {
2066 // return (ReturnType){ };
2067 // }
2068 //
2069 // /* for class methods only to force class lazy initialization */
2070 // if (!__objc_{class}_initialized)
2071 // {
2072 // objc_send_initialize(class);
2073 // __objc_{class}_initialized = 1;
2074 // }
2075 //
2076 // _cmd = @selector(...)
2077 // ...
2078
2079 if (OMD->isClassMethod()) {
2080 const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);
2081
2082 // Nullable `Class` expressions cannot be messaged with a direct method
2083 // so the only reason why the receive can be null would be because
2084 // of weak linking.
2085 ReceiverCanBeNull = isWeakLinkedClass(OID);
2086 }
2087
2088 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2089 if (ReceiverCanBeNull) {
2090 llvm::BasicBlock *SelfIsNilBlock =
2091 CGF.createBasicBlock("objc_direct_method.self_is_nil");
2092 llvm::BasicBlock *ContBlock =
2093 CGF.createBasicBlock("objc_direct_method.cont");
2094
2095 // if (self == nil) {
2096 auto selfTy = cast<llvm::PointerType>(selfValue->getType());
2097 auto Zero = llvm::ConstantPointerNull::get(selfTy);
2098
2099 Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),
2100 SelfIsNilBlock, ContBlock,
2101 MDHelper.createUnlikelyBranchWeights());
2102
2103 CGF.EmitBlock(SelfIsNilBlock);
2104
2105 // return (ReturnType){ };
2106 auto retTy = OMD->getReturnType();
2107 Builder.SetInsertPoint(SelfIsNilBlock);
2108 if (!retTy->isVoidType()) {
2109 CGF.EmitNullInitialization(CGF.ReturnValue, retTy);
2110 }
2112 // }
2113
2114 // rest of the body
2115 CGF.EmitBlock(ContBlock);
2116 Builder.SetInsertPoint(ContBlock);
2117 }
2118
2119 if (OMD->isClassMethod()) {
2120 // Prefix of the class type.
2121 auto *classStart =
2122 llvm::StructType::get(PtrTy, PtrTy, PtrTy, LongTy, LongTy);
2123 auto &astContext = CGM.getContext();
2124 // FIXME: The following few lines up to and including the call to
2125 // `CreateLoad` were known to miscompile when MSVC 19.40.33813 is used
2126 // to build Clang. When the bug is fixed in future MSVC releases, we
2127 // should revert these lines to their previous state. See discussion in
2128 // https://github.com/llvm/llvm-project/pull/102681
2129 llvm::Value *Val = Builder.CreateStructGEP(classStart, selfValue, 4);
2130 auto Align = CharUnits::fromQuantity(
2131 astContext.getTypeAlign(astContext.UnsignedLongTy));
2132 auto flags = Builder.CreateLoad(Address{Val, LongTy, Align});
2133 auto isInitialized =
2134 Builder.CreateAnd(flags, ClassFlags::ClassFlagInitialized);
2135 llvm::BasicBlock *notInitializedBlock =
2136 CGF.createBasicBlock("objc_direct_method.class_uninitialized");
2137 llvm::BasicBlock *initializedBlock =
2138 CGF.createBasicBlock("objc_direct_method.class_initialized");
2139 Builder.CreateCondBr(Builder.CreateICmpEQ(isInitialized, Zeros[0]),
2140 notInitializedBlock, initializedBlock,
2141 MDHelper.createUnlikelyBranchWeights());
2142 CGF.EmitBlock(notInitializedBlock);
2143 Builder.SetInsertPoint(notInitializedBlock);
2144 CGF.EmitRuntimeCall(SentInitializeFn, selfValue);
2145 Builder.CreateBr(initializedBlock);
2146 CGF.EmitBlock(initializedBlock);
2147 Builder.SetInsertPoint(initializedBlock);
2148 }
2149
2150 // only synthesize _cmd if it's referenced
2151 if (OMD->getCmdDecl()->isUsed()) {
2152 // `_cmd` is not a parameter to direct methods, so storage must be
2153 // explicitly declared for it.
2154 CGF.EmitVarDecl(*OMD->getCmdDecl());
2155 Builder.CreateStore(GetSelector(CGF, OMD),
2156 CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));
2157 }
2158 }
2159};
2160
2161const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2162{
2163"__objc_selectors",
2164"__objc_classes",
2165"__objc_class_refs",
2166"__objc_cats",
2167"__objc_protocols",
2168"__objc_protocol_refs",
2169"__objc_class_aliases",
2170"__objc_constant_string"
2171};
2172
2173const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2174{
2175".objcrt$SEL",
2176".objcrt$CLS",
2177".objcrt$CLR",
2178".objcrt$CAT",
2179".objcrt$PCL",
2180".objcrt$PCR",
2181".objcrt$CAL",
2182".objcrt$STR"
2183};
2184
2185/// Support for the ObjFW runtime.
2186class CGObjCObjFW: public CGObjCGNU {
2187protected:
2188 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2189 /// method implementation for this message.
2190 LazyRuntimeFunction MsgLookupFn;
2191 /// stret lookup function. While this does not seem to make sense at the
2192 /// first look, this is required to call the correct forwarding function.
2193 LazyRuntimeFunction MsgLookupFnSRet;
2194 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2195 /// structure describing the receiver and the class, and a selector as
2196 /// arguments. Returns the IMP for the corresponding method.
2197 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2198
2199 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2200 llvm::Value *cmd, llvm::MDNode *node,
2201 MessageSendInfo &MSI) override {
2202 CGBuilderTy &Builder = CGF.Builder;
2203 llvm::Value *args[] = {
2204 EnforceType(Builder, Receiver, IdTy),
2205 EnforceType(Builder, cmd, SelectorTy) };
2206
2207 llvm::CallBase *imp;
2208 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2209 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2210 else
2211 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2212
2213 imp->setMetadata(msgSendMDKind, node);
2214 return imp;
2215 }
2216
2217 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2218 llvm::Value *cmd, MessageSendInfo &MSI) override {
2219 CGBuilderTy &Builder = CGF.Builder;
2220 llvm::Value *lookupArgs[] = {
2221 EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),
2222 cmd,
2223 };
2224
2225 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2226 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2227 else
2228 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2229 }
2230
2231 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2232 bool isWeak) override {
2233 if (isWeak)
2234 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2235
2236 EmitClassRef(Name);
2237 std::string SymbolName = "_OBJC_CLASS_" + Name;
2238 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2239 if (!ClassSymbol)
2240 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2241 llvm::GlobalValue::ExternalLinkage,
2242 nullptr, SymbolName);
2243 return ClassSymbol;
2244 }
2245
2246 void GenerateDirectMethodPrologue(
2247 CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,
2248 const ObjCContainerDecl *CD) override {
2249 auto &Builder = CGF.Builder;
2250 bool ReceiverCanBeNull = true;
2251 auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());
2252 auto selfValue = Builder.CreateLoad(selfAddr);
2253
2254 // Generate:
2255 //
2256 // /* for class methods only to force class lazy initialization */
2257 // self = [self self];
2258 //
2259 // /* unless the receiver is never NULL */
2260 // if (self == nil) {
2261 // return (ReturnType){ };
2262 // }
2263 //
2264 // _cmd = @selector(...)
2265 // ...
2266
2267 if (OMD->isClassMethod()) {
2268 const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);
2269 assert(
2270 OID &&
2271 "GenerateDirectMethod() should be called with the Class Interface");
2272 Selector SelfSel = GetNullarySelector("self", CGM.getContext());
2273 auto ResultType = CGF.getContext().getObjCIdType();
2274 RValue result;
2275 CallArgList Args;
2276
2277 // TODO: If this method is inlined, the caller might know that `self` is
2278 // already initialized; for example, it might be an ordinary Objective-C
2279 // method which always receives an initialized `self`, or it might have
2280 // just forced initialization on its own.
2281 //
2282 // We should find a way to eliminate this unnecessary initialization in
2283 // such cases in LLVM.
2284 result = GeneratePossiblySpecializedMessageSend(
2285 CGF, ReturnValueSlot(), ResultType, SelfSel, selfValue, Args, OID,
2286 nullptr, true);
2287 Builder.CreateStore(result.getScalarVal(), selfAddr);
2288
2289 // Nullable `Class` expressions cannot be messaged with a direct method
2290 // so the only reason why the receive can be null would be because
2291 // of weak linking.
2292 ReceiverCanBeNull = isWeakLinkedClass(OID);
2293 }
2294
2295 if (ReceiverCanBeNull) {
2296 llvm::BasicBlock *SelfIsNilBlock =
2297 CGF.createBasicBlock("objc_direct_method.self_is_nil");
2298 llvm::BasicBlock *ContBlock =
2299 CGF.createBasicBlock("objc_direct_method.cont");
2300
2301 // if (self == nil) {
2302 auto selfTy = cast<llvm::PointerType>(selfValue->getType());
2303 auto Zero = llvm::ConstantPointerNull::get(selfTy);
2304
2305 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2306 Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),
2307 SelfIsNilBlock, ContBlock,
2308 MDHelper.createUnlikelyBranchWeights());
2309
2310 CGF.EmitBlock(SelfIsNilBlock);
2311
2312 // return (ReturnType){ };
2313 auto retTy = OMD->getReturnType();
2314 Builder.SetInsertPoint(SelfIsNilBlock);
2315 if (!retTy->isVoidType()) {
2316 CGF.EmitNullInitialization(CGF.ReturnValue, retTy);
2317 }
2319 // }
2320
2321 // rest of the body
2322 CGF.EmitBlock(ContBlock);
2323 Builder.SetInsertPoint(ContBlock);
2324 }
2325
2326 // only synthesize _cmd if it's referenced
2327 if (OMD->getCmdDecl()->isUsed()) {
2328 // `_cmd` is not a parameter to direct methods, so storage must be
2329 // explicitly declared for it.
2330 CGF.EmitVarDecl(*OMD->getCmdDecl());
2331 Builder.CreateStore(GetSelector(CGF, OMD),
2332 CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));
2333 }
2334 }
2335
2336public:
2337 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2338 // IMP objc_msg_lookup(id, SEL);
2339 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2340 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2341 SelectorTy);
2342 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2343 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2344 PtrToObjCSuperTy, SelectorTy);
2345 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2346 PtrToObjCSuperTy, SelectorTy);
2347 }
2348};
2349} // end anonymous namespace
2350
2351/// Emits a reference to a dummy variable which is emitted with each class.
2352/// This ensures that a linker error will be generated when trying to link
2353/// together modules where a referenced class is not defined.
2354void CGObjCGNU::EmitClassRef(const std::string &className) {
2355 std::string symbolRef = "__objc_class_ref_" + className;
2356 // Don't emit two copies of the same symbol
2357 if (TheModule.getGlobalVariable(symbolRef))
2358 return;
2359 std::string symbolName = "__objc_class_name_" + className;
2360 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2361 if (!ClassSymbol) {
2362 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2363 llvm::GlobalValue::ExternalLinkage,
2364 nullptr, symbolName);
2365 }
2366 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2367 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2368}
2369
2370CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2371 unsigned protocolClassVersion, unsigned classABI)
2372 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2373 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2374 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2375 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2376
2377 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2378 usesSEHExceptions =
2379 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2380 usesCxxExceptions =
2381 cgm.getContext().getTargetInfo().getTriple().isOSCygMing() &&
2382 isRuntime(ObjCRuntime::GNUstep, 2);
2383
2384 CodeGenTypes &Types = CGM.getTypes();
2386 Types.ConvertType(CGM.getContext().IntTy));
2387 LongTy = cast<llvm::IntegerType>(
2388 Types.ConvertType(CGM.getContext().LongTy));
2389 SizeTy = cast<llvm::IntegerType>(
2390 Types.ConvertType(CGM.getContext().getSizeType()));
2391 PtrDiffTy = cast<llvm::IntegerType>(
2393 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2394
2395 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2396
2397 PtrTy = llvm::PointerType::getUnqual(cgm.getLLVMContext());
2398 PtrToIntTy = PtrTy;
2399 // C string type. Used in lots of places.
2400 PtrToInt8Ty = PtrTy;
2401 ProtocolPtrTy = PtrTy;
2402
2403 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2404 Zeros[1] = Zeros[0];
2405 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2406 // Get the selector Type.
2407 QualType selTy = CGM.getContext().getObjCSelType();
2408 if (QualType() == selTy) {
2409 SelectorTy = PtrToInt8Ty;
2410 SelectorElemTy = Int8Ty;
2411 } else {
2412 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2413 SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
2414 }
2415
2416 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2417 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2418
2419 IntPtrTy =
2420 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2421
2422 // Object type
2423 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2424 ASTIdTy = CanQualType();
2425 if (UnqualIdTy != QualType()) {
2426 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2427 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2428 IdElemTy = CGM.getTypes().ConvertTypeForMem(
2429 ASTIdTy.getTypePtr()->getPointeeType());
2430 } else {
2431 IdTy = PtrToInt8Ty;
2432 IdElemTy = Int8Ty;
2433 }
2434 PtrToIdTy = PtrTy;
2435 ProtocolTy = llvm::StructType::get(IdTy,
2436 PtrToInt8Ty, // name
2437 PtrToInt8Ty, // protocols
2438 PtrToInt8Ty, // instance methods
2439 PtrToInt8Ty, // class methods
2440 PtrToInt8Ty, // optional instance methods
2441 PtrToInt8Ty, // optional class methods
2442 PtrToInt8Ty, // properties
2443 PtrToInt8Ty);// optional properties
2444
2445 // struct objc_property_gsv1
2446 // {
2447 // const char *name;
2448 // char attributes;
2449 // char attributes2;
2450 // char unused1;
2451 // char unused2;
2452 // const char *getter_name;
2453 // const char *getter_types;
2454 // const char *setter_name;
2455 // const char *setter_types;
2456 // }
2457 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2458 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2459 PtrToInt8Ty, PtrToInt8Ty });
2460
2461 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2462 PtrToObjCSuperTy = PtrTy;
2463
2464 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2465
2466 // void objc_exception_throw(id);
2467 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2468 ExceptionReThrowFn.init(&CGM,
2469 usesCxxExceptions ? "objc_exception_rethrow"
2470 : "objc_exception_throw",
2471 VoidTy, IdTy);
2472 // int objc_sync_enter(id);
2473 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2474 // int objc_sync_exit(id);
2475 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2476
2477 // void objc_enumerationMutation (id)
2478 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2479
2480 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2481 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2482 PtrDiffTy, BoolTy);
2483 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2484 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2485 PtrDiffTy, IdTy, BoolTy, BoolTy);
2486 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2487 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2488 PtrDiffTy, BoolTy, BoolTy);
2489 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2490 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2491 PtrDiffTy, BoolTy, BoolTy);
2492
2493 // IMP type
2494 IMPTy = PtrTy;
2495
2496 const LangOptions &Opts = CGM.getLangOpts();
2497 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2498 RuntimeVersion = 10;
2499
2500 // Don't bother initialising the GC stuff unless we're compiling in GC mode
2501 if (Opts.getGC() != LangOptions::NonGC) {
2502 // This is a bit of an hack. We should sort this out by having a proper
2503 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2504 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2505 // Get selectors needed in GC mode
2506 RetainSel = GetNullarySelector("retain", CGM.getContext());
2507 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2508 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2509
2510 // Get functions needed in GC mode
2511
2512 // id objc_assign_ivar(id, id, ptrdiff_t);
2513 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2514 // id objc_assign_strongCast (id, id*)
2515 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2516 PtrToIdTy);
2517 // id objc_assign_global(id, id*);
2518 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2519 // id objc_assign_weak(id, id*);
2520 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2521 // id objc_read_weak(id*);
2522 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2523 // void *objc_memmove_collectable(void*, void *, size_t);
2524 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2525 SizeTy);
2526 }
2527}
2528
2529llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2530 const std::string &Name, bool isWeak) {
2531 llvm::Constant *ClassName = MakeConstantString(Name);
2532 // With the incompatible ABI, this will need to be replaced with a direct
2533 // reference to the class symbol. For the compatible nonfragile ABI we are
2534 // still performing this lookup at run time but emitting the symbol for the
2535 // class externally so that we can make the switch later.
2536 //
2537 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2538 // with memoized versions or with static references if it's safe to do so.
2539 if (!isWeak)
2540 EmitClassRef(Name);
2541
2542 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2543 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2544 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2545}
2546
2547// This has to perform the lookup every time, since posing and related
2548// techniques can modify the name -> class mapping.
2549llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2550 const ObjCInterfaceDecl *OID) {
2551 auto *Value =
2552 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2553 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2554 CGM.setGVProperties(ClassSymbol, OID);
2555 return Value;
2556}
2557
2558llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2559 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2560 if (CGM.getTriple().isOSBinFormatCOFF()) {
2561 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2562 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2563 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2564 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2565
2566 const VarDecl *VD = nullptr;
2567 for (const auto *Result : DC->lookup(&II))
2568 if ((VD = dyn_cast<VarDecl>(Result)))
2569 break;
2570
2571 CGM.setGVProperties(ClassSymbol, VD);
2572 }
2573 }
2574 return Value;
2575}
2576
2577llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2578 const std::string &TypeEncoding) {
2579 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2580 llvm::GlobalAlias *SelValue = nullptr;
2581
2582 for (const TypedSelector &Type : Types) {
2583 if (Type.first == TypeEncoding) {
2584 SelValue = Type.second;
2585 break;
2586 }
2587 }
2588 if (!SelValue) {
2589 SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
2590 llvm::GlobalValue::PrivateLinkage,
2591 ".objc_selector_" + Sel.getAsString(),
2592 &TheModule);
2593 Types.emplace_back(TypeEncoding, SelValue);
2594 }
2595
2596 return SelValue;
2597}
2598
2599Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2600 llvm::Value *SelValue = GetSelector(CGF, Sel);
2601
2602 // Store it to a temporary. Does this satisfy the semantics of
2603 // GetAddrOfSelector? Hopefully.
2604 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2605 CGF.getPointerAlign());
2606 CGF.Builder.CreateStore(SelValue, tmp);
2607 return tmp;
2608}
2609
2610llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2611 return GetTypedSelector(CGF, Sel, std::string());
2612}
2613
2614llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2615 const ObjCMethodDecl *Method) {
2616 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2617 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2618}
2619
2620llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2621 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2622 // With the old ABI, there was only one kind of catchall, which broke
2623 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2624 // a pointer indicating object catchalls, and NULL to indicate real
2625 // catchalls
2626 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2627 return MakeConstantString("@id");
2628 } else {
2629 return nullptr;
2630 }
2631 }
2632
2633 // All other types should be Objective-C interface pointer types.
2634 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2635 assert(OPT && "Invalid @catch type.");
2636 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2637 assert(IDecl && "Invalid @catch type.");
2638 return MakeConstantString(IDecl->getIdentifier()->getName());
2639}
2640
2641llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2642 if (usesSEHExceptions)
2643 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2644
2645 if (!CGM.getLangOpts().CPlusPlus && !usesCxxExceptions)
2646 return CGObjCGNU::GetEHType(T);
2647
2648 // For Objective-C++, we want to provide the ability to catch both C++ and
2649 // Objective-C objects in the same function.
2650
2651 // There's a particular fixed type info for 'id'.
2652 if (T->isObjCIdType() ||
2654 llvm::Constant *IDEHType =
2655 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2656 if (!IDEHType)
2657 IDEHType =
2658 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2659 false,
2660 llvm::GlobalValue::ExternalLinkage,
2661 nullptr, "__objc_id_type_info");
2662 return IDEHType;
2663 }
2664
2665 const ObjCObjectPointerType *PT =
2666 T->getAs<ObjCObjectPointerType>();
2667 assert(PT && "Invalid @catch type.");
2668 const ObjCInterfaceType *IT = PT->getInterfaceType();
2669 assert(IT && "Invalid @catch type.");
2670 std::string className =
2671 std::string(IT->getDecl()->getIdentifier()->getName());
2672
2673 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2674
2675 // Return the existing typeinfo if it exists
2676 if (llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName))
2677 return typeinfo;
2678
2679 // Otherwise create it.
2680
2681 // vtable for gnustep::libobjc::__objc_class_type_info
2682 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2683 // platform's name mangling.
2684 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2685 auto *Vtable = TheModule.getGlobalVariable(vtableName);
2686 if (!Vtable) {
2687 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2688 llvm::GlobalValue::ExternalLinkage,
2689 nullptr, vtableName);
2690 }
2691 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2692 auto *BVtable =
2693 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two);
2694
2695 llvm::Constant *typeName =
2696 ExportUniqueString(className, "__objc_eh_typename_");
2697
2698 ConstantInitBuilder builder(CGM);
2699 auto fields = builder.beginStruct();
2700 fields.add(BVtable);
2701 fields.add(typeName);
2702 llvm::Constant *TI =
2703 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2704 CGM.getPointerAlign(),
2705 /*constant*/ false,
2706 llvm::GlobalValue::LinkOnceODRLinkage);
2707 return TI;
2708}
2709
2710/// Generate an NSConstantString object.
2711ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2712
2713 std::string Str = SL->getString().str();
2714 CharUnits Align = CGM.getPointerAlign();
2715
2716 // Look for an existing one
2717 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2718 if (old != ObjCStrings.end())
2719 return ConstantAddress(old->getValue(), Int8Ty, Align);
2720
2721 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2722
2723 if (StringClass.empty()) StringClass = "NSConstantString";
2724
2725 std::string Sym = "_OBJC_CLASS_";
2726 Sym += StringClass;
2727
2728 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2729
2730 if (!isa)
2731 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */ false,
2732 llvm::GlobalValue::ExternalWeakLinkage,
2733 nullptr, Sym);
2734
2735 ConstantInitBuilder Builder(CGM);
2736 auto Fields = Builder.beginStruct();
2737 Fields.add(isa);
2738 Fields.add(MakeConstantString(Str));
2739 Fields.addInt(IntTy, Str.size());
2740 llvm::Constant *ObjCStr = Fields.finishAndCreateGlobal(".objc_str", Align);
2741 ObjCStrings[Str] = ObjCStr;
2742 ConstantStrings.push_back(ObjCStr);
2743 return ConstantAddress(ObjCStr, Int8Ty, Align);
2744}
2745
2746ConstantAddress CGObjCGNU::GenerateConstantNumber(const bool Value,
2747 const QualType &Ty) {
2748 llvm_unreachable("Method should not be called, no GNU runtimes provide these "
2749 "or support ObjC number literal constant initializers");
2750}
2751
2752ConstantAddress CGObjCGNU::GenerateConstantNumber(const llvm::APSInt &Value,
2753 const QualType &Ty) {
2754 llvm_unreachable("Method should not be called, no GNU runtimes provide these "
2755 "or support ObjC number literal constant initializers");
2756}
2757
2758ConstantAddress CGObjCGNU::GenerateConstantNumber(const llvm::APFloat &Value,
2759 const QualType &Ty) {
2760 llvm_unreachable("Method should not be called, no GNU runtimes provide these "
2761 "or support ObjC number literal constant initializers");
2762}
2763
2764ConstantAddress
2765CGObjCGNU::GenerateConstantArray(const ArrayRef<llvm::Constant *> &Objects) {
2766 llvm_unreachable("Method should not be called, no GNU runtimes provide these "
2767 "or support ObjC array literal constant initializers");
2768}
2769
2770ConstantAddress CGObjCGNU::GenerateConstantDictionary(
2771 const ObjCDictionaryLiteral *E,
2772 ArrayRef<std::pair<llvm::Constant *, llvm::Constant *>> KeysAndObjects) {
2773 llvm_unreachable("Method should not be called, no GNU runtimes provide these "
2774 "or support ObjC dictionary literal constant initializers");
2775}
2776
2777///Generates a message send where the super is the receiver. This is a message
2778///send to self with special delivery semantics indicating which class's method
2779///should be called.
2780RValue
2781CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2782 ReturnValueSlot Return,
2783 QualType ResultType,
2784 Selector Sel,
2785 const ObjCInterfaceDecl *Class,
2786 bool isCategoryImpl,
2787 llvm::Value *Receiver,
2788 bool IsClassMessage,
2789 const CallArgList &CallArgs,
2790 const ObjCMethodDecl *Method) {
2791 CGBuilderTy &Builder = CGF.Builder;
2792 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2793 if (Sel == RetainSel || Sel == AutoreleaseSel) {
2794 return RValue::get(EnforceType(Builder, Receiver,
2795 CGM.getTypes().ConvertType(ResultType)));
2796 }
2797 if (Sel == ReleaseSel) {
2798 return RValue::get(nullptr);
2799 }
2800 }
2801
2802 llvm::Value *cmd = GetSelector(CGF, Sel);
2803 CallArgList ActualArgs;
2804
2805 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2806 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2807 ActualArgs.addFrom(CallArgs);
2808
2809 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2810
2811 llvm::Value *ReceiverClass = nullptr;
2812 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2813 if (isV2ABI) {
2814 ReceiverClass = GetClassNamed(CGF,
2815 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2816 if (IsClassMessage) {
2817 // Load the isa pointer of the superclass is this is a class method.
2818 ReceiverClass =
2819 Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2820 }
2821 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2822 } else {
2823 if (isCategoryImpl) {
2824 llvm::FunctionCallee classLookupFunction = nullptr;
2825 if (IsClassMessage) {
2826 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2827 IdTy, PtrTy, true), "objc_get_meta_class");
2828 } else {
2829 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2830 IdTy, PtrTy, true), "objc_get_class");
2831 }
2832 ReceiverClass = Builder.CreateCall(classLookupFunction,
2833 MakeConstantString(Class->getNameAsString()));
2834 } else {
2835 // Set up global aliases for the metaclass or class pointer if they do not
2836 // already exist. These will are forward-references which will be set to
2837 // pointers to the class and metaclass structure created for the runtime
2838 // load function. To send a message to super, we look up the value of the
2839 // super_class pointer from either the class or metaclass structure.
2840 if (IsClassMessage) {
2841 if (!MetaClassPtrAlias) {
2842 MetaClassPtrAlias = llvm::GlobalAlias::create(
2843 IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2844 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2845 }
2846 ReceiverClass = MetaClassPtrAlias;
2847 } else {
2848 if (!ClassPtrAlias) {
2849 ClassPtrAlias = llvm::GlobalAlias::create(
2850 IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2851 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2852 }
2853 ReceiverClass = ClassPtrAlias;
2854 }
2855 }
2856 // Cast the pointer to a simplified version of the class structure
2857 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2858 // Get the superclass pointer
2859 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2860 // Load the superclass pointer
2861 ReceiverClass =
2862 Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2863 }
2864 // Construct the structure used to look up the IMP
2865 llvm::StructType *ObjCSuperTy =
2866 llvm::StructType::get(Receiver->getType(), IdTy);
2867
2868 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2869 CGF.getPointerAlign());
2870
2871 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2872 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2873
2874 // Get the IMP
2875 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2876 imp = EnforceType(Builder, imp, MSI.MessengerType);
2877
2878 llvm::Metadata *impMD[] = {
2879 llvm::MDString::get(VMContext, Sel.getAsString()),
2880 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2881 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2882 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2883 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2884
2885 CGCallee callee(CGCalleeInfo(), imp);
2886
2887 llvm::CallBase *call;
2888 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2889 call->setMetadata(msgSendMDKind, node);
2890 return msgRet;
2891}
2892
2893/// Generate code for a message send expression.
2894RValue
2895CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2896 ReturnValueSlot Return,
2897 QualType ResultType,
2898 Selector Sel,
2899 llvm::Value *Receiver,
2900 const CallArgList &CallArgs,
2901 const ObjCInterfaceDecl *Class,
2902 const ObjCMethodDecl *Method) {
2903 CGBuilderTy &Builder = CGF.Builder;
2904
2905 // Strip out message sends to retain / release in GC mode
2906 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2907 if (Sel == RetainSel || Sel == AutoreleaseSel) {
2908 return RValue::get(EnforceType(Builder, Receiver,
2909 CGM.getTypes().ConvertType(ResultType)));
2910 }
2911 if (Sel == ReleaseSel) {
2912 return RValue::get(nullptr);
2913 }
2914 }
2915
2916 bool isDirect = Method && Method->isDirectMethod();
2917
2918 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2919 llvm::Value *cmd;
2920 if (!isDirect) {
2921 if (Method)
2922 cmd = GetSelector(CGF, Method);
2923 else
2924 cmd = GetSelector(CGF, Sel);
2925 cmd = EnforceType(Builder, cmd, SelectorTy);
2926 }
2927
2928 Receiver = EnforceType(Builder, Receiver, IdTy);
2929
2930 llvm::Metadata *impMD[] = {
2931 llvm::MDString::get(VMContext, Sel.getAsString()),
2932 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2933 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2934 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2935 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2936
2937 CallArgList ActualArgs;
2938 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2939 if (!isDirect)
2940 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2941 ActualArgs.addFrom(CallArgs);
2942
2943 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2944
2945 // Message sends are expected to return a zero value when the
2946 // receiver is nil. At one point, this was only guaranteed for
2947 // simple integer and pointer types, but expectations have grown
2948 // over time.
2949 //
2950 // Given a nil receiver, the GNU runtime's message lookup will
2951 // return a stub function that simply sets various return-value
2952 // registers to zero and then returns. That's good enough for us
2953 // if and only if (1) the calling conventions of that stub are
2954 // compatible with the signature we're using and (2) the registers
2955 // it sets are sufficient to produce a zero value of the return type.
2956 // Rather than doing a whole target-specific analysis, we assume it
2957 // only works for void, integer, and pointer types, and in all
2958 // other cases we do an explicit nil check is emitted code. In
2959 // addition to ensuring we produce a zero value for other types, this
2960 // sidesteps the few outright CC incompatibilities we know about that
2961 // could otherwise lead to crashes, like when a method is expected to
2962 // return on the x87 floating point stack or adjust the stack pointer
2963 // because of an indirect return.
2964 bool hasParamDestroyedInCallee = false;
2965 bool requiresExplicitZeroResult = false;
2966 bool requiresNilReceiverCheck = [&] {
2967 // We never need a check if we statically know the receiver isn't nil.
2968 if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,
2969 Class, Receiver))
2970 return false;
2971
2972 // If there's a consumed argument, we need a nil check.
2973 if (Method && Method->hasParamDestroyedInCallee()) {
2974 hasParamDestroyedInCallee = true;
2975 }
2976
2977 // If the return value isn't flagged as unused, and the result
2978 // type isn't in our narrow set where we assume compatibility,
2979 // we need a nil check to ensure a nil value.
2980 if (!Return.isUnused()) {
2981 if (ResultType->isVoidType()) {
2982 // void results are definitely okay.
2983 } else if (ResultType->hasPointerRepresentation() &&
2984 CGM.getTypes().isZeroInitializable(ResultType)) {
2985 // Pointer types should be fine as long as they have
2986 // bitwise-zero null pointers. But do we need to worry
2987 // about unusual address spaces?
2988 } else if (ResultType->isIntegralOrEnumerationType()) {
2989 // Bitwise zero should always be zero for integral types.
2990 // FIXME: we probably need a size limit here, but we've
2991 // never imposed one before
2992 } else {
2993 // Otherwise, use an explicit check just to be sure, unless we're
2994 // calling a direct method, where the implementation does this for us.
2995 requiresExplicitZeroResult = !isDirect;
2996 }
2997 }
2998
2999 return hasParamDestroyedInCallee || requiresExplicitZeroResult;
3000 }();
3001
3002 // We will need to explicitly zero-initialize an aggregate result slot
3003 // if we generally require explicit zeroing and we have an aggregate
3004 // result.
3005 bool requiresExplicitAggZeroing =
3006 requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
3007
3008 // The block we're going to end up in after any message send or nil path.
3009 llvm::BasicBlock *continueBB = nullptr;
3010 // The block that eventually branched to continueBB along the nil path.
3011 llvm::BasicBlock *nilPathBB = nullptr;
3012 // The block to do explicit work in along the nil path, if necessary.
3013 llvm::BasicBlock *nilCleanupBB = nullptr;
3014
3015 // Emit the nil-receiver check.
3016 if (requiresNilReceiverCheck) {
3017 llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
3018 continueBB = CGF.createBasicBlock("continue");
3019
3020 // If we need to zero-initialize an aggregate result or destroy
3021 // consumed arguments, we'll need a separate cleanup block.
3022 // Otherwise we can just branch directly to the continuation block.
3023 if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
3024 nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
3025 } else {
3026 nilPathBB = Builder.GetInsertBlock();
3027 }
3028
3029 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
3030 llvm::Constant::getNullValue(Receiver->getType()));
3031 Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
3032 messageBB);
3033 CGF.EmitBlock(messageBB);
3034 }
3035
3036 // Get the IMP to call
3037 llvm::Value *imp;
3038
3039 // If this is a direct method, just emit it here.
3040 if (isDirect)
3041 imp = GenerateMethod(Method, Method->getClassInterface());
3042 else
3043 // If we have non-legacy dispatch specified, we try using the
3044 // objc_msgSend() functions. These are not supported on all platforms
3045 // (or all runtimes on a given platform), so we
3046 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
3048 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
3049 break;
3052 StringRef name = "objc_msgSend";
3053 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
3054 name = "objc_msgSend_fpret";
3055 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
3056 name = "objc_msgSend_stret";
3057
3058 // The address of the memory block is be passed in x8 for POD type,
3059 // or in x0 for non-POD type (marked as inreg).
3060 bool shouldCheckForInReg =
3061 CGM.getContext()
3062 .getTargetInfo()
3063 .getTriple()
3064 .isWindowsMSVCEnvironment() &&
3065 CGM.getContext().getTargetInfo().getTriple().isAArch64();
3066 if (shouldCheckForInReg && CGM.ReturnTypeHasInReg(MSI.CallInfo)) {
3067 name = "objc_msgSend_stret2";
3068 }
3069 }
3070 // The actual types here don't matter - we're going to bitcast the
3071 // function anyway
3072 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
3073 name)
3074 .getCallee();
3075 }
3076
3077 // Reset the receiver in case the lookup modified it
3078 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
3079
3080 imp = EnforceType(Builder, imp, MSI.MessengerType);
3081
3082 llvm::CallBase *call;
3083 CGCallee callee(CGCalleeInfo(), imp);
3084 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
3085 if (!isDirect)
3086 call->setMetadata(msgSendMDKind, node);
3087
3088 if (requiresNilReceiverCheck) {
3089 llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
3090 CGF.Builder.CreateBr(continueBB);
3091
3092 // Emit the nil path if we decided it was necessary above.
3093 if (nilCleanupBB) {
3094 CGF.EmitBlock(nilCleanupBB);
3095
3096 if (hasParamDestroyedInCallee) {
3097 destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
3098 }
3099
3100 if (requiresExplicitAggZeroing) {
3101 assert(msgRet.isAggregate());
3102 Address addr = msgRet.getAggregateAddress();
3103 CGF.EmitNullInitialization(addr, ResultType);
3104 }
3105
3106 nilPathBB = CGF.Builder.GetInsertBlock();
3107 CGF.Builder.CreateBr(continueBB);
3108 }
3109
3110 // Enter the continuation block and emit a phi if required.
3111 CGF.EmitBlock(continueBB);
3112 if (msgRet.isScalar()) {
3113 // If the return type is void, do nothing
3114 if (llvm::Value *v = msgRet.getScalarVal()) {
3115 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
3116 phi->addIncoming(v, nonNilPathBB);
3117 phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
3118 msgRet = RValue::get(phi);
3119 }
3120 } else if (msgRet.isAggregate()) {
3121 // Aggregate zeroing is handled in nilCleanupBB when it's required.
3122 } else /* isComplex() */ {
3123 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
3124 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
3125 phi->addIncoming(v.first, nonNilPathBB);
3126 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
3127 nilPathBB);
3128 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
3129 phi2->addIncoming(v.second, nonNilPathBB);
3130 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
3131 nilPathBB);
3132 msgRet = RValue::getComplex(phi, phi2);
3133 }
3134 }
3135 return msgRet;
3136}
3137
3138/// Generates a MethodList. Used in construction of a objc_class and
3139/// objc_category structures.
3140llvm::Constant *CGObjCGNU::
3141GenerateMethodList(StringRef ClassName,
3142 StringRef CategoryName,
3143 ArrayRef<const ObjCMethodDecl*> Methods,
3144 bool isClassMethodList) {
3145 if (Methods.empty())
3146 return NULLPtr;
3147
3148 ConstantInitBuilder Builder(CGM);
3149
3150 auto MethodList = Builder.beginStruct();
3151 MethodList.addNullPointer(CGM.Int8PtrTy);
3152 MethodList.addInt(Int32Ty, Methods.size());
3153
3154 // Get the method structure type.
3155 llvm::StructType *ObjCMethodTy =
3156 llvm::StructType::get(CGM.getLLVMContext(), {
3157 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
3158 PtrToInt8Ty, // Method types
3159 IMPTy // Method pointer
3160 });
3161 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
3162 if (isV2ABI) {
3163 // size_t size;
3164 const llvm::DataLayout &DL = TheModule.getDataLayout();
3165 MethodList.addInt(SizeTy, DL.getTypeSizeInBits(ObjCMethodTy) /
3166 CGM.getContext().getCharWidth());
3167 ObjCMethodTy =
3168 llvm::StructType::get(CGM.getLLVMContext(), {
3169 IMPTy, // Method pointer
3170 PtrToInt8Ty, // Selector
3171 PtrToInt8Ty // Extended type encoding
3172 });
3173 } else {
3174 ObjCMethodTy =
3175 llvm::StructType::get(CGM.getLLVMContext(), {
3176 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
3177 PtrToInt8Ty, // Method types
3178 IMPTy // Method pointer
3179 });
3180 }
3181 auto MethodArray = MethodList.beginArray();
3182 ASTContext &Context = CGM.getContext();
3183 for (const auto *OMD : Methods) {
3184 llvm::Constant *FnPtr =
3185 TheModule.getFunction(getSymbolNameForMethod(OMD));
3186 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
3187 auto Method = MethodArray.beginStruct(ObjCMethodTy);
3188 if (isV2ABI) {
3189 Method.add(FnPtr);
3190 Method.add(GetConstantSelector(OMD->getSelector(),
3191 Context.getObjCEncodingForMethodDecl(OMD)));
3192 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
3193 } else {
3194 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
3195 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
3196 Method.add(FnPtr);
3197 }
3198 Method.finishAndAddTo(MethodArray);
3199 }
3200 MethodArray.finishAndAddTo(MethodList);
3201
3202 // Create an instance of the structure
3203 return MethodList.finishAndCreateGlobal(".objc_method_list",
3204 CGM.getPointerAlign());
3205}
3206
3207/// Generates an IvarList. Used in construction of a objc_class.
3208llvm::Constant *CGObjCGNU::
3209GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
3210 ArrayRef<llvm::Constant *> IvarTypes,
3211 ArrayRef<llvm::Constant *> IvarOffsets,
3212 ArrayRef<llvm::Constant *> IvarAlign,
3213 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
3214 if (IvarNames.empty())
3215 return NULLPtr;
3216
3217 ConstantInitBuilder Builder(CGM);
3218
3219 // Structure containing array count followed by array.
3220 auto IvarList = Builder.beginStruct();
3221 IvarList.addInt(IntTy, (int)IvarNames.size());
3222
3223 // Get the ivar structure type.
3224 llvm::StructType *ObjCIvarTy =
3225 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
3226
3227 // Array of ivar structures.
3228 auto Ivars = IvarList.beginArray(ObjCIvarTy);
3229 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
3230 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
3231 Ivar.add(IvarNames[i]);
3232 Ivar.add(IvarTypes[i]);
3233 Ivar.add(IvarOffsets[i]);
3234 Ivar.finishAndAddTo(Ivars);
3235 }
3236 Ivars.finishAndAddTo(IvarList);
3237
3238 // Create an instance of the structure
3239 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
3240 CGM.getPointerAlign());
3241}
3242
3243/// Generate a class structure
3244llvm::Constant *CGObjCGNU::GenerateClassStructure(
3245 llvm::Constant *MetaClass,
3246 llvm::Constant *SuperClass,
3247 unsigned info,
3248 const char *Name,
3249 llvm::Constant *Version,
3250 llvm::Constant *InstanceSize,
3251 llvm::Constant *IVars,
3252 llvm::Constant *Methods,
3253 llvm::Constant *Protocols,
3254 llvm::Constant *IvarOffsets,
3255 llvm::Constant *Properties,
3256 llvm::Constant *StrongIvarBitmap,
3257 llvm::Constant *WeakIvarBitmap,
3258 bool isMeta) {
3259 // Set up the class structure
3260 // Note: Several of these are char*s when they should be ids. This is
3261 // because the runtime performs this translation on load.
3262 //
3263 // Fields marked New ABI are part of the GNUstep runtime. We emit them
3264 // anyway; the classes will still work with the GNU runtime, they will just
3265 // be ignored.
3266 llvm::StructType *ClassTy = llvm::StructType::get(
3267 PtrToInt8Ty, // isa
3268 PtrToInt8Ty, // super_class
3269 PtrToInt8Ty, // name
3270 LongTy, // version
3271 LongTy, // info
3272 LongTy, // instance_size
3273 IVars->getType(), // ivars
3274 Methods->getType(), // methods
3275 // These are all filled in by the runtime, so we pretend
3276 PtrTy, // dtable
3277 PtrTy, // subclass_list
3278 PtrTy, // sibling_class
3279 PtrTy, // protocols
3280 PtrTy, // gc_object_type
3281 // New ABI:
3282 LongTy, // abi_version
3283 IvarOffsets->getType(), // ivar_offsets
3284 Properties->getType(), // properties
3285 IntPtrTy, // strong_pointers
3286 IntPtrTy // weak_pointers
3287 );
3288
3289 ConstantInitBuilder Builder(CGM);
3290 auto Elements = Builder.beginStruct(ClassTy);
3291
3292 // Fill in the structure
3293
3294 // isa
3295 Elements.add(MetaClass);
3296 // super_class
3297 Elements.add(SuperClass);
3298 // name
3299 Elements.add(MakeConstantString(Name, ".class_name"));
3300 // version
3301 Elements.addInt(LongTy, 0);
3302 // info
3303 Elements.addInt(LongTy, info);
3304 // instance_size
3305 if (isMeta) {
3306 const llvm::DataLayout &DL = TheModule.getDataLayout();
3307 Elements.addInt(LongTy, DL.getTypeSizeInBits(ClassTy) /
3308 CGM.getContext().getCharWidth());
3309 } else
3310 Elements.add(InstanceSize);
3311 // ivars
3312 Elements.add(IVars);
3313 // methods
3314 Elements.add(Methods);
3315 // These are all filled in by the runtime, so we pretend
3316 // dtable
3317 Elements.add(NULLPtr);
3318 // subclass_list
3319 Elements.add(NULLPtr);
3320 // sibling_class
3321 Elements.add(NULLPtr);
3322 // protocols
3323 Elements.add(Protocols);
3324 // gc_object_type
3325 Elements.add(NULLPtr);
3326 // abi_version
3327 Elements.addInt(LongTy, ClassABIVersion);
3328 // ivar_offsets
3329 Elements.add(IvarOffsets);
3330 // properties
3331 Elements.add(Properties);
3332 // strong_pointers
3333 Elements.add(StrongIvarBitmap);
3334 // weak_pointers
3335 Elements.add(WeakIvarBitmap);
3336 // Create an instance of the structure
3337 // This is now an externally visible symbol, so that we can speed up class
3338 // messages in the next ABI. We may already have some weak references to
3339 // this, so check and fix them properly.
3340 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3341 std::string(Name));
3342 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
3343 llvm::Constant *Class =
3344 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
3345 llvm::GlobalValue::ExternalLinkage);
3346 if (ClassRef) {
3347 ClassRef->replaceAllUsesWith(Class);
3348 ClassRef->removeFromParent();
3349 Class->setName(ClassSym);
3350 }
3351 return Class;
3352}
3353
3354llvm::Constant *CGObjCGNU::
3355GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3356 // Get the method structure type.
3357 llvm::StructType *ObjCMethodDescTy =
3358 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3359 ASTContext &Context = CGM.getContext();
3360 ConstantInitBuilder Builder(CGM);
3361 auto MethodList = Builder.beginStruct();
3362 MethodList.addInt(IntTy, Methods.size());
3363 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3364 for (auto *M : Methods) {
3365 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3366 Method.add(MakeConstantString(M->getSelector().getAsString()));
3367 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3368 Method.finishAndAddTo(MethodArray);
3369 }
3370 MethodArray.finishAndAddTo(MethodList);
3371 return MethodList.finishAndCreateGlobal(".objc_method_list",
3372 CGM.getPointerAlign());
3373}
3374
3375// Create the protocol list structure used in classes, categories and so on
3376llvm::Constant *
3377CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3378
3379 ConstantInitBuilder Builder(CGM);
3380 auto ProtocolList = Builder.beginStruct();
3381 ProtocolList.add(NULLPtr);
3382 ProtocolList.addInt(LongTy, Protocols.size());
3383
3384 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3385 for (const std::string &Protocol : Protocols) {
3386 llvm::Constant *protocol = nullptr;
3387 llvm::StringMap<llvm::Constant *>::iterator value =
3388 ExistingProtocols.find(Protocol);
3389 if (value == ExistingProtocols.end()) {
3390 protocol = GenerateEmptyProtocol(Protocol);
3391 } else {
3392 protocol = value->getValue();
3393 }
3394 Elements.add(protocol);
3395 }
3396 Elements.finishAndAddTo(ProtocolList);
3397 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3398 CGM.getPointerAlign());
3399}
3400
3401llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3402 const ObjCProtocolDecl *PD) {
3403 return GenerateProtocolRef(PD);
3404}
3405
3406llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3407 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3408 if (!protocol)
3409 GenerateProtocol(PD);
3410 assert(protocol && "Unknown protocol");
3411 return protocol;
3412}
3413
3414llvm::Constant *
3415CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3416 llvm::Constant *ProtocolList = GenerateProtocolList({});
3417 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3418 // Protocols are objects containing lists of the methods implemented and
3419 // protocols adopted.
3420 ConstantInitBuilder Builder(CGM);
3421 auto Elements = Builder.beginStruct();
3422
3423 // The isa pointer must be set to a magic number so the runtime knows it's
3424 // the correct layout.
3425 Elements.add(llvm::ConstantExpr::getIntToPtr(
3426 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3427
3428 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3429 Elements.add(ProtocolList); /* .protocol_list */
3430 Elements.add(MethodList); /* .instance_methods */
3431 Elements.add(MethodList); /* .class_methods */
3432 Elements.add(MethodList); /* .optional_instance_methods */
3433 Elements.add(MethodList); /* .optional_class_methods */
3434 Elements.add(NULLPtr); /* .properties */
3435 Elements.add(NULLPtr); /* .optional_properties */
3436 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3437 CGM.getPointerAlign());
3438}
3439
3440void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3441 if (PD->isNonRuntimeProtocol())
3442 return;
3443
3444 std::string ProtocolName = PD->getNameAsString();
3445
3446 // Use the protocol definition, if there is one.
3447 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3448 PD = Def;
3449
3450 SmallVector<std::string, 16> Protocols;
3451 for (const auto *PI : PD->protocols())
3452 Protocols.push_back(PI->getNameAsString());
3453 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3454 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3455 for (const auto *I : PD->instance_methods())
3456 if (I->isOptional())
3457 OptionalInstanceMethods.push_back(I);
3458 else
3459 InstanceMethods.push_back(I);
3460 // Collect information about class methods:
3461 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3462 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3463 for (const auto *I : PD->class_methods())
3464 if (I->isOptional())
3465 OptionalClassMethods.push_back(I);
3466 else
3467 ClassMethods.push_back(I);
3468
3469 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3470 llvm::Constant *InstanceMethodList =
3471 GenerateProtocolMethodList(InstanceMethods);
3472 llvm::Constant *ClassMethodList =
3473 GenerateProtocolMethodList(ClassMethods);
3474 llvm::Constant *OptionalInstanceMethodList =
3475 GenerateProtocolMethodList(OptionalInstanceMethods);
3476 llvm::Constant *OptionalClassMethodList =
3477 GenerateProtocolMethodList(OptionalClassMethods);
3478
3479 // Property metadata: name, attributes, isSynthesized, setter name, setter
3480 // types, getter name, getter types.
3481 // The isSynthesized value is always set to 0 in a protocol. It exists to
3482 // simplify the runtime library by allowing it to use the same data
3483 // structures for protocol metadata everywhere.
3484
3485 llvm::Constant *PropertyList =
3486 GeneratePropertyList(nullptr, PD, false, false);
3487 llvm::Constant *OptionalPropertyList =
3488 GeneratePropertyList(nullptr, PD, false, true);
3489
3490 // Protocols are objects containing lists of the methods implemented and
3491 // protocols adopted.
3492 // The isa pointer must be set to a magic number so the runtime knows it's
3493 // the correct layout.
3494 ConstantInitBuilder Builder(CGM);
3495 auto Elements = Builder.beginStruct();
3496 Elements.add(
3497 llvm::ConstantExpr::getIntToPtr(
3498 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3499 Elements.add(MakeConstantString(ProtocolName));
3500 Elements.add(ProtocolList);
3501 Elements.add(InstanceMethodList);
3502 Elements.add(ClassMethodList);
3503 Elements.add(OptionalInstanceMethodList);
3504 Elements.add(OptionalClassMethodList);
3505 Elements.add(PropertyList);
3506 Elements.add(OptionalPropertyList);
3507 ExistingProtocols[ProtocolName] =
3508 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign());
3509}
3510void CGObjCGNU::GenerateProtocolHolderCategory() {
3511 // Collect information about instance methods
3512
3513 ConstantInitBuilder Builder(CGM);
3514 auto Elements = Builder.beginStruct();
3515
3516 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3517 const std::string CategoryName = "AnotherHack";
3518 Elements.add(MakeConstantString(CategoryName));
3519 Elements.add(MakeConstantString(ClassName));
3520 // Instance method list
3521 Elements.add(GenerateMethodList(ClassName, CategoryName, {}, false));
3522 // Class method list
3523 Elements.add(GenerateMethodList(ClassName, CategoryName, {}, true));
3524
3525 // Protocol list
3526 ConstantInitBuilder ProtocolListBuilder(CGM);
3527 auto ProtocolList = ProtocolListBuilder.beginStruct();
3528 ProtocolList.add(NULLPtr);
3529 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3530 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3531 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3532 iter != endIter ; iter++) {
3533 ProtocolElements.add(iter->getValue());
3534 }
3535 ProtocolElements.finishAndAddTo(ProtocolList);
3536 Elements.add(ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3537 CGM.getPointerAlign()));
3538 Categories.push_back(
3539 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()));
3540}
3541
3542/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3543/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3544/// bits set to their values, LSB first, while larger ones are stored in a
3545/// structure of this / form:
3546///
3547/// struct { int32_t length; int32_t values[length]; };
3548///
3549/// The values in the array are stored in host-endian format, with the least
3550/// significant bit being assumed to come first in the bitfield. Therefore, a
3551/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3552/// bitfield / with the 63rd bit set will be 1<<64.
3553llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3554 int bitCount = bits.size();
3555 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3556 if (bitCount < ptrBits) {
3557 uint64_t val = 1;
3558 for (int i=0 ; i<bitCount ; ++i) {
3559 if (bits[i]) val |= 1ULL<<(i+1);
3560 }
3561 return llvm::ConstantInt::get(IntPtrTy, val);
3562 }
3563 SmallVector<llvm::Constant *, 8> values;
3564 int v=0;
3565 while (v < bitCount) {
3566 int32_t word = 0;
3567 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3568 if (bits[v]) word |= 1<<i;
3569 v++;
3570 }
3571 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3572 }
3573
3574 ConstantInitBuilder builder(CGM);
3575 auto fields = builder.beginStruct();
3576 fields.addInt(Int32Ty, values.size());
3577 auto array = fields.beginArray();
3578 for (auto *v : values) array.add(v);
3579 array.finishAndAddTo(fields);
3580
3581 llvm::Constant *GS =
3582 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3583 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3584 return ptr;
3585}
3586
3587llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3588 ObjCCategoryDecl *OCD) {
3589 const auto &RefPro = OCD->getReferencedProtocols();
3590 const auto RuntimeProtos =
3591 GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3592 SmallVector<std::string, 16> Protocols;
3593 for (const auto *PD : RuntimeProtos)
3594 Protocols.push_back(PD->getNameAsString());
3595 return GenerateProtocolList(Protocols);
3596}
3597
3598void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3599 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3600 std::string ClassName = Class->getNameAsString();
3601 std::string CategoryName = OCD->getNameAsString();
3602
3603 // Collect the names of referenced protocols
3604 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3605
3606 ConstantInitBuilder Builder(CGM);
3607 auto Elements = Builder.beginStruct();
3608 Elements.add(MakeConstantString(CategoryName));
3609 Elements.add(MakeConstantString(ClassName));
3610 // Instance method list
3611 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3612 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3613 OCD->instmeth_end());
3614 Elements.add(
3615 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false));
3616
3617 // Class method list
3618
3619 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3620 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3621 OCD->classmeth_end());
3622 Elements.add(GenerateMethodList(ClassName, CategoryName, ClassMethods, true));
3623
3624 // Protocol list
3625 Elements.add(GenerateCategoryProtocolList(CatDecl));
3626 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3627 const ObjCCategoryDecl *Category =
3628 Class->FindCategoryDeclaration(OCD->getIdentifier());
3629 if (Category) {
3630 // Instance properties
3631 Elements.add(GeneratePropertyList(OCD, Category, false));
3632 // Class properties
3633 Elements.add(GeneratePropertyList(OCD, Category, true));
3634 } else {
3635 Elements.addNullPointer(PtrTy);
3636 Elements.addNullPointer(PtrTy);
3637 }
3638 }
3639
3640 Categories.push_back(Elements.finishAndCreateGlobal(
3641 std::string(".objc_category_") + ClassName + CategoryName,
3642 CGM.getPointerAlign()));
3643}
3644
3645llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3646 const ObjCContainerDecl *OCD,
3647 bool isClassProperty,
3648 bool protocolOptionalProperties) {
3649
3650 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3651 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3652 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3653 ASTContext &Context = CGM.getContext();
3654
3655 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3656 = [&](const ObjCProtocolDecl *Proto) {
3657 for (const auto *P : Proto->protocols())
3658 collectProtocolProperties(P);
3659 for (const auto *PD : Proto->properties()) {
3660 if (isClassProperty != PD->isClassProperty())
3661 continue;
3662 // Skip any properties that are declared in protocols that this class
3663 // conforms to but are not actually implemented by this class.
3664 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3665 continue;
3666 if (!PropertySet.insert(PD->getIdentifier()).second)
3667 continue;
3668 Properties.push_back(PD);
3669 }
3670 };
3671
3672 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3673 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3674 for (auto *PD : ClassExt->properties()) {
3675 if (isClassProperty != PD->isClassProperty())
3676 continue;
3677 PropertySet.insert(PD->getIdentifier());
3678 Properties.push_back(PD);
3679 }
3680
3681 for (const auto *PD : OCD->properties()) {
3682 if (isClassProperty != PD->isClassProperty())
3683 continue;
3684 // If we're generating a list for a protocol, skip optional / required ones
3685 // when generating the other list.
3686 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3687 continue;
3688 // Don't emit duplicate metadata for properties that were already in a
3689 // class extension.
3690 if (!PropertySet.insert(PD->getIdentifier()).second)
3691 continue;
3692
3693 Properties.push_back(PD);
3694 }
3695
3696 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3697 for (const auto *P : OID->all_referenced_protocols())
3698 collectProtocolProperties(P);
3699 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3700 for (const auto *P : CD->protocols())
3701 collectProtocolProperties(P);
3702
3703 auto numProperties = Properties.size();
3704
3705 if (numProperties == 0)
3706 return NULLPtr;
3707
3708 ConstantInitBuilder builder(CGM);
3709 auto propertyList = builder.beginStruct();
3710 auto properties = PushPropertyListHeader(propertyList, numProperties);
3711
3712 // Add all of the property methods need adding to the method list and to the
3713 // property metadata list.
3714 for (auto *property : Properties) {
3715 bool isSynthesized = false;
3716 bool isDynamic = false;
3717 if (!isProtocol) {
3718 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3719 if (propertyImpl) {
3720 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3722 isDynamic = (propertyImpl->getPropertyImplementation() ==
3724 }
3725 }
3726 PushProperty(properties, property, Container, isSynthesized, isDynamic);
3727 }
3728 properties.finishAndAddTo(propertyList);
3729
3730 return propertyList.finishAndCreateGlobal(".objc_property_list",
3731 CGM.getPointerAlign());
3732}
3733
3734void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3735 // Get the class declaration for which the alias is specified.
3736 ObjCInterfaceDecl *ClassDecl =
3737 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3738 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3739 OAD->getNameAsString());
3740}
3741
3742void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3743 ASTContext &Context = CGM.getContext();
3744
3745 // Get the superclass name.
3746 const ObjCInterfaceDecl * SuperClassDecl =
3748 std::string SuperClassName;
3749 if (SuperClassDecl) {
3750 SuperClassName = SuperClassDecl->getNameAsString();
3751 EmitClassRef(SuperClassName);
3752 }
3753
3754 // Get the class name
3755 ObjCInterfaceDecl *ClassDecl =
3756 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3757 std::string ClassName = ClassDecl->getNameAsString();
3758
3759 // Emit the symbol that is used to generate linker errors if this class is
3760 // referenced in other modules but not declared.
3761 std::string classSymbolName = "__objc_class_name_" + ClassName;
3762 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3763 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3764 } else {
3765 new llvm::GlobalVariable(TheModule, LongTy, false,
3766 llvm::GlobalValue::ExternalLinkage,
3767 llvm::ConstantInt::get(LongTy, 0),
3768 classSymbolName);
3769 }
3770
3771 // Get the size of instances.
3772 int instanceSize = Context.getASTObjCInterfaceLayout(OID->getClassInterface())
3773 .getSize()
3774 .getQuantity();
3775
3776 // Collect information about instance variables.
3777 SmallVector<llvm::Constant*, 16> IvarNames;
3778 SmallVector<llvm::Constant*, 16> IvarTypes;
3779 SmallVector<llvm::Constant*, 16> IvarOffsets;
3780 SmallVector<llvm::Constant*, 16> IvarAligns;
3781 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3782
3783 ConstantInitBuilder IvarOffsetBuilder(CGM);
3784 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3785 SmallVector<bool, 16> WeakIvars;
3786 SmallVector<bool, 16> StrongIvars;
3787
3788 int superInstanceSize = !SuperClassDecl ? 0 :
3789 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3790 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3791 // class}. The runtime will then set this to the correct value on load.
3792 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3793 instanceSize = 0 - (instanceSize - superInstanceSize);
3794 }
3795
3796 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3797 IVD = IVD->getNextIvar()) {
3798 // Store the name
3799 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3800 // Get the type encoding for this ivar
3801 std::string TypeStr;
3802 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3803 IvarTypes.push_back(MakeConstantString(TypeStr));
3804 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3805 Context.getTypeSize(IVD->getType())));
3806 // Get the offset
3807 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3808 int64_t Offset = static_cast<int64_t>(BaseOffset);
3809 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3810 Offset = static_cast<int64_t>(BaseOffset) - superInstanceSize;
3811 }
3812 llvm::Constant *OffsetValue = llvm::ConstantInt::getSigned(IntTy, Offset);
3813 // Create the direct offset value
3814 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3815 IVD->getNameAsString();
3816
3817 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3818 if (OffsetVar) {
3819 OffsetVar->setInitializer(OffsetValue);
3820 // If this is the real definition, change its linkage type so that
3821 // different modules will use this one, rather than their private
3822 // copy.
3823 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3824 } else
3825 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3826 false, llvm::GlobalValue::ExternalLinkage,
3827 OffsetValue, OffsetName);
3828 IvarOffsets.push_back(OffsetValue);
3829 IvarOffsetValues.add(OffsetVar);
3830 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3831 IvarOwnership.push_back(lt);
3832 switch (lt) {
3834 StrongIvars.push_back(true);
3835 WeakIvars.push_back(false);
3836 break;
3838 StrongIvars.push_back(false);
3839 WeakIvars.push_back(true);
3840 break;
3841 default:
3842 StrongIvars.push_back(false);
3843 WeakIvars.push_back(false);
3844 }
3845 }
3846 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3847 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3848 llvm::GlobalVariable *IvarOffsetArray =
3849 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3850 CGM.getPointerAlign());
3851
3852 // Collect information about instance methods
3853 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3854 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3855 OID->instmeth_end());
3856
3857 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3858 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3859 OID->classmeth_end());
3860
3861 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3862
3863 // Collect the names of referenced protocols
3864 auto RefProtocols = ClassDecl->protocols();
3865 auto RuntimeProtocols =
3866 GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3867 SmallVector<std::string, 16> Protocols;
3868 for (const auto *I : RuntimeProtocols)
3869 Protocols.push_back(I->getNameAsString());
3870
3871 // Get the superclass pointer.
3872 llvm::Constant *SuperClass;
3873 if (!SuperClassName.empty()) {
3874 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3875 } else {
3876 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3877 }
3878 // Generate the method and instance variable lists
3879 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3880 InstanceMethods, false);
3881 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3882 ClassMethods, true);
3883 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3884 IvarOffsets, IvarAligns, IvarOwnership);
3885 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3886 // we emit a symbol containing the offset for each ivar in the class. This
3887 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3888 // for the legacy ABI, without causing problems. The converse is also
3889 // possible, but causes all ivar accesses to be fragile.
3890
3891 // Offset pointer for getting at the correct field in the ivar list when
3892 // setting up the alias. These are: The base address for the global, the
3893 // ivar array (second field), the ivar in this list (set for each ivar), and
3894 // the offset (third field in ivar structure)
3895 llvm::Type *IndexTy = Int32Ty;
3896 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3897 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3898 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3899
3900 unsigned ivarIndex = 0;
3901 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3902 IVD = IVD->getNextIvar()) {
3903 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3904 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3905 // Get the correct ivar field
3906 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3907 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3908 offsetPointerIndexes);
3909 // Get the existing variable, if one exists.
3910 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3911 if (offset) {
3912 offset->setInitializer(offsetValue);
3913 // If this is the real definition, change its linkage type so that
3914 // different modules will use this one, rather than their private
3915 // copy.
3916 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3917 } else
3918 // Add a new alias if there isn't one already.
3919 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3920 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3921 ++ivarIndex;
3922 }
3923 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3924
3925 //Generate metaclass for class methods
3926 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3927 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3928 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3929 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3930 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3931 OID->getClassInterface());
3932
3933 // Generate the class structure
3934 llvm::Constant *ClassStruct = GenerateClassStructure(
3935 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3936 llvm::ConstantInt::getSigned(LongTy, instanceSize), IvarList, MethodList,
3937 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3938 StrongIvarBitmap, WeakIvarBitmap);
3940 OID->getClassInterface());
3941
3942 // Resolve the class aliases, if they exist.
3943 if (ClassPtrAlias) {
3944 ClassPtrAlias->replaceAllUsesWith(ClassStruct);
3945 ClassPtrAlias->eraseFromParent();
3946 ClassPtrAlias = nullptr;
3947 }
3948 if (MetaClassPtrAlias) {
3949 MetaClassPtrAlias->replaceAllUsesWith(MetaClassStruct);
3950 MetaClassPtrAlias->eraseFromParent();
3951 MetaClassPtrAlias = nullptr;
3952 }
3953
3954 // Add class structure to list to be added to the symtab later
3955 Classes.push_back(ClassStruct);
3956}
3957
3958llvm::Function *CGObjCGNU::ModuleInitFunction() {
3959 // Only emit an ObjC load function if no Objective-C stuff has been called
3960 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3961 ExistingProtocols.empty() && SelectorTable.empty())
3962 return nullptr;
3963
3964 // Add all referenced protocols to a category.
3965 GenerateProtocolHolderCategory();
3966
3967 llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
3968 if (!selStructTy) {
3969 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3970 { PtrToInt8Ty, PtrToInt8Ty });
3971 }
3972
3973 // Generate statics list:
3974 llvm::Constant *statics = NULLPtr;
3975 if (!ConstantStrings.empty()) {
3976 llvm::GlobalVariable *fileStatics = [&] {
3977 ConstantInitBuilder builder(CGM);
3978 auto staticsStruct = builder.beginStruct();
3979
3980 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3981 if (stringClass.empty()) stringClass = "NXConstantString";
3982 staticsStruct.add(MakeConstantString(stringClass,
3983 ".objc_static_class_name"));
3984
3985 auto array = staticsStruct.beginArray();
3986 array.addAll(ConstantStrings);
3987 array.add(NULLPtr);
3988 array.finishAndAddTo(staticsStruct);
3989
3990 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3991 CGM.getPointerAlign());
3992 }();
3993
3994 ConstantInitBuilder builder(CGM);
3995 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3996 allStaticsArray.add(fileStatics);
3997 allStaticsArray.addNullPointer(fileStatics->getType());
3998
3999 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
4000 CGM.getPointerAlign());
4001 }
4002
4003 // Array of classes, categories, and constant objects.
4004
4005 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
4006 unsigned selectorCount;
4007
4008 // Pointer to an array of selectors used in this module.
4009 llvm::GlobalVariable *selectorList = [&] {
4010 ConstantInitBuilder builder(CGM);
4011 auto selectors = builder.beginArray(selStructTy);
4012 auto &table = SelectorTable; // MSVC workaround
4013 std::vector<Selector> allSelectors;
4014 for (auto &entry : table)
4015 allSelectors.push_back(entry.first);
4016 llvm::sort(allSelectors);
4017
4018 for (auto &untypedSel : allSelectors) {
4019 std::string selNameStr = untypedSel.getAsString();
4020 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
4021
4022 for (TypedSelector &sel : table[untypedSel]) {
4023 llvm::Constant *selectorTypeEncoding = NULLPtr;
4024 if (!sel.first.empty())
4025 selectorTypeEncoding =
4026 MakeConstantString(sel.first, ".objc_sel_types");
4027
4028 auto selStruct = selectors.beginStruct(selStructTy);
4029 selStruct.add(selName);
4030 selStruct.add(selectorTypeEncoding);
4031 selStruct.finishAndAddTo(selectors);
4032
4033 // Store the selector alias for later replacement
4034 selectorAliases.push_back(sel.second);
4035 }
4036 }
4037
4038 // Remember the number of entries in the selector table.
4039 selectorCount = selectors.size();
4040
4041 // NULL-terminate the selector list. This should not actually be required,
4042 // because the selector list has a length field. Unfortunately, the GCC
4043 // runtime decides to ignore the length field and expects a NULL terminator,
4044 // and GCC cooperates with this by always setting the length to 0.
4045 auto selStruct = selectors.beginStruct(selStructTy);
4046 selStruct.add(NULLPtr);
4047 selStruct.add(NULLPtr);
4048 selStruct.finishAndAddTo(selectors);
4049
4050 return selectors.finishAndCreateGlobal(".objc_selector_list",
4051 CGM.getPointerAlign());
4052 }();
4053
4054 // Now that all of the static selectors exist, create pointers to them.
4055 for (unsigned i = 0; i < selectorCount; ++i) {
4056 llvm::Constant *idxs[] = {
4057 Zeros[0],
4058 llvm::ConstantInt::get(Int32Ty, i)
4059 };
4060 // FIXME: We're generating redundant loads and stores here!
4061 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
4062 selectorList->getValueType(), selectorList, idxs);
4063 selectorAliases[i]->replaceAllUsesWith(selPtr);
4064 selectorAliases[i]->eraseFromParent();
4065 }
4066
4067 llvm::GlobalVariable *symtab = [&] {
4068 ConstantInitBuilder builder(CGM);
4069 auto symtab = builder.beginStruct();
4070
4071 // Number of static selectors
4072 symtab.addInt(LongTy, selectorCount);
4073
4074 symtab.add(selectorList);
4075
4076 // Number of classes defined.
4077 symtab.addInt(CGM.Int16Ty, Classes.size());
4078 // Number of categories defined
4079 symtab.addInt(CGM.Int16Ty, Categories.size());
4080
4081 // Create an array of classes, then categories, then static object instances
4082 auto classList = symtab.beginArray(PtrToInt8Ty);
4083 classList.addAll(Classes);
4084 classList.addAll(Categories);
4085 // NULL-terminated list of static object instances (mainly constant strings)
4086 classList.add(statics);
4087 classList.add(NULLPtr);
4088 classList.finishAndAddTo(symtab);
4089
4090 // Construct the symbol table.
4091 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
4092 }();
4093
4094 // The symbol table is contained in a module which has some version-checking
4095 // constants
4096 llvm::Constant *module = [&] {
4097 llvm::Type *moduleEltTys[] = {
4098 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
4099 };
4100 llvm::StructType *moduleTy = llvm::StructType::get(
4101 CGM.getLLVMContext(),
4102 ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
4103
4104 ConstantInitBuilder builder(CGM);
4105 auto module = builder.beginStruct(moduleTy);
4106 // Runtime version, used for ABI compatibility checking.
4107 module.addInt(LongTy, RuntimeVersion);
4108 // sizeof(ModuleTy)
4109 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
4110
4111 // The path to the source file where this module was declared
4112 SourceManager &SM = CGM.getContext().getSourceManager();
4114 std::string path =
4115 (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
4116 module.add(MakeConstantString(path, ".objc_source_file_name"));
4117 module.add(symtab);
4118
4119 if (RuntimeVersion >= 10) {
4120 switch (CGM.getLangOpts().getGC()) {
4121 case LangOptions::GCOnly:
4122 module.addInt(IntTy, 2);
4123 break;
4124 case LangOptions::NonGC:
4125 if (CGM.getLangOpts().ObjCAutoRefCount)
4126 module.addInt(IntTy, 1);
4127 else
4128 module.addInt(IntTy, 0);
4129 break;
4130 case LangOptions::HybridGC:
4131 module.addInt(IntTy, 1);
4132 break;
4133 }
4134 }
4135
4136 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
4137 }();
4138
4139 // Create the load function calling the runtime entry point with the module
4140 // structure
4141 llvm::Function * LoadFunction = llvm::Function::Create(
4142 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
4143 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
4144 &TheModule);
4145 llvm::BasicBlock *EntryBB =
4146 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
4147 CGBuilderTy Builder(CGM, VMContext);
4148 Builder.SetInsertPoint(EntryBB);
4149
4150 llvm::FunctionType *FT =
4151 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
4152 llvm::FunctionCallee Register =
4153 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
4154 Builder.CreateCall(Register, module);
4155
4156 if (!ClassAliases.empty()) {
4157 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
4158 llvm::FunctionType *RegisterAliasTy =
4159 llvm::FunctionType::get(Builder.getVoidTy(),
4160 ArgTypes, false);
4161 llvm::Function *RegisterAlias = llvm::Function::Create(
4162 RegisterAliasTy,
4163 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
4164 &TheModule);
4165 llvm::BasicBlock *AliasBB =
4166 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
4167 llvm::BasicBlock *NoAliasBB =
4168 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
4169
4170 // Branch based on whether the runtime provided class_registerAlias_np()
4171 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
4172 llvm::Constant::getNullValue(RegisterAlias->getType()));
4173 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
4174
4175 // The true branch (has alias registration function):
4176 Builder.SetInsertPoint(AliasBB);
4177 // Emit alias registration calls:
4178 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
4179 iter != ClassAliases.end(); ++iter) {
4180 llvm::Constant *TheClass =
4181 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
4182 if (TheClass) {
4183 Builder.CreateCall(RegisterAlias,
4184 {TheClass, MakeConstantString(iter->second)});
4185 }
4186 }
4187 // Jump to end:
4188 Builder.CreateBr(NoAliasBB);
4189
4190 // Missing alias registration function, just return from the function:
4191 Builder.SetInsertPoint(NoAliasBB);
4192 }
4193 Builder.CreateRetVoid();
4194
4195 return LoadFunction;
4196}
4197
4198llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
4199 const ObjCContainerDecl *CD) {
4200 CodeGenTypes &Types = CGM.getTypes();
4201 llvm::FunctionType *MethodTy =
4203
4204 bool isDirect = OMD->isDirectMethod();
4205 std::string FunctionName =
4206 getSymbolNameForMethod(OMD, /*include category*/ !isDirect);
4207
4208 if (!isDirect)
4209 return llvm::Function::Create(MethodTy,
4210 llvm::GlobalVariable::InternalLinkage,
4211 FunctionName, &TheModule);
4212
4213 auto *COMD = OMD->getCanonicalDecl();
4214 auto I = DirectMethodDefinitions.find(COMD);
4215 llvm::Function *OldFn = nullptr, *Fn = nullptr;
4216
4217 if (I == DirectMethodDefinitions.end()) {
4218 auto *F =
4219 llvm::Function::Create(MethodTy, llvm::GlobalVariable::ExternalLinkage,
4220 FunctionName, &TheModule);
4221 DirectMethodDefinitions.insert(std::make_pair(COMD, F));
4222 return F;
4223 }
4224
4225 // Objective-C allows for the declaration and implementation types
4226 // to differ slightly.
4227 //
4228 // If we're being asked for the Function associated for a method
4229 // implementation, a previous value might have been cached
4230 // based on the type of the canonical declaration.
4231 //
4232 // If these do not match, then we'll replace this function with
4233 // a new one that has the proper type below.
4234 if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())
4235 return I->second;
4236
4237 OldFn = I->second;
4238 Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage, "",
4239 &CGM.getModule());
4240 Fn->takeName(OldFn);
4241 OldFn->replaceAllUsesWith(Fn);
4242 OldFn->eraseFromParent();
4243
4244 // Replace the cached function in the map.
4245 I->second = Fn;
4246 return Fn;
4247}
4248
4249void CGObjCGNU::GenerateDirectMethodsPreconditionCheck(
4250 CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,
4251 const ObjCContainerDecl *CD) {
4252 llvm_unreachable(
4253 "Direct method precondition checks not supported in GNU runtime yet");
4254}
4255
4256void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
4257 llvm::Function *Fn,
4258 const ObjCMethodDecl *OMD,
4259 const ObjCContainerDecl *CD) {
4260 llvm_unreachable(
4261 "Direct method precondition checks not supported in GNU runtime yet");
4262}
4263
4264llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
4265 return GetPropertyFn;
4266}
4267
4268llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
4269 return SetPropertyFn;
4270}
4271
4272llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
4273 bool copy) {
4274 return nullptr;
4275}
4276
4277llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
4278 return GetStructPropertyFn;
4279}
4280
4281llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
4282 return SetStructPropertyFn;
4283}
4284
4285llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
4286 return nullptr;
4287}
4288
4289llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
4290 return nullptr;
4291}
4292
4293llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
4294 return EnumerationMutationFn;
4295}
4296
4297void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
4298 const ObjCAtSynchronizedStmt &S) {
4299 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
4300}
4301
4302
4303void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
4304 const ObjCAtTryStmt &S) {
4305 // Unlike the Apple non-fragile runtimes, which also uses
4306 // unwind-based zero cost exceptions, the GNU Objective C runtime's
4307 // EH support isn't a veneer over C++ EH. Instead, exception
4308 // objects are created by objc_exception_throw and destroyed by
4309 // the personality function; this avoids the need for bracketing
4310 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
4311 // (or even _Unwind_DeleteException), but probably doesn't
4312 // interoperate very well with foreign exceptions.
4313 //
4314 // In Objective-C++ mode, we actually emit something equivalent to the C++
4315 // exception handler.
4316 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
4317}
4318
4319void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
4320 const ObjCAtThrowStmt &S,
4321 bool ClearInsertionPoint) {
4322 llvm::Value *ExceptionAsObject;
4323 bool isRethrow = false;
4324
4325 if (const Expr *ThrowExpr = S.getThrowExpr()) {
4326 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4327 ExceptionAsObject = Exception;
4328 } else {
4329 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4330 "Unexpected rethrow outside @catch block.");
4331 ExceptionAsObject = CGF.ObjCEHValueStack.back();
4332 isRethrow = true;
4333 }
4334 if (isRethrow && (usesSEHExceptions || usesCxxExceptions)) {
4335 // For SEH, ExceptionAsObject may be undef, because the catch handler is
4336 // not passed it for catchalls and so it is not visible to the catch
4337 // funclet. The real thrown object will still be live on the stack at this
4338 // point and will be rethrown. If we are explicitly rethrowing the object
4339 // that was passed into the `@catch` block, then this code path is not
4340 // reached and we will instead call `objc_exception_throw` with an explicit
4341 // argument.
4342 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
4343 Throw->setDoesNotReturn();
4344 } else {
4345 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
4346 llvm::CallBase *Throw =
4347 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
4348 Throw->setDoesNotReturn();
4349 }
4350 CGF.Builder.CreateUnreachable();
4351 if (ClearInsertionPoint)
4352 CGF.Builder.ClearInsertionPoint();
4353}
4354
4355llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
4356 Address AddrWeakObj) {
4357 CGBuilderTy &B = CGF.Builder;
4358 return B.CreateCall(
4359 WeakReadFn, EnforceType(B, AddrWeakObj.emitRawPointer(CGF), PtrToIdTy));
4360}
4361
4362void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
4363 llvm::Value *src, Address dst) {
4364 CGBuilderTy &B = CGF.Builder;
4365 src = EnforceType(B, src, IdTy);
4366 llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);
4367 B.CreateCall(WeakAssignFn, {src, dstVal});
4368}
4369
4370void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4371 llvm::Value *src, Address dst,
4372 bool threadlocal) {
4373 CGBuilderTy &B = CGF.Builder;
4374 src = EnforceType(B, src, IdTy);
4375 llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);
4376 // FIXME. Add threadloca assign API
4377 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4378 B.CreateCall(GlobalAssignFn, {src, dstVal});
4379}
4380
4381void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4382 llvm::Value *src, Address dst,
4383 llvm::Value *ivarOffset) {
4384 CGBuilderTy &B = CGF.Builder;
4385 src = EnforceType(B, src, IdTy);
4386 llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), IdTy);
4387 B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
4388}
4389
4390void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4391 llvm::Value *src, Address dst) {
4392 CGBuilderTy &B = CGF.Builder;
4393 src = EnforceType(B, src, IdTy);
4394 llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);
4395 B.CreateCall(StrongCastAssignFn, {src, dstVal});
4396}
4397
4398void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4399 Address DestPtr,
4400 Address SrcPtr,
4401 llvm::Value *Size) {
4402 CGBuilderTy &B = CGF.Builder;
4403 llvm::Value *DestPtrVal = EnforceType(B, DestPtr.emitRawPointer(CGF), PtrTy);
4404 llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.emitRawPointer(CGF), PtrTy);
4405
4406 B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
4407}
4408
4409llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4410 const ObjCInterfaceDecl *ID,
4411 const ObjCIvarDecl *Ivar) {
4412 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4413 // Emit the variable and initialize it with what we think the correct value
4414 // is. This allows code compiled with non-fragile ivars to work correctly
4415 // when linked against code which isn't (most of the time).
4416 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4417 if (!IvarOffsetPointer)
4418 IvarOffsetPointer = new llvm::GlobalVariable(
4419 TheModule, llvm::PointerType::getUnqual(VMContext), false,
4420 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4421 return IvarOffsetPointer;
4422}
4423
4424LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4425 QualType ObjectTy,
4426 llvm::Value *BaseValue,
4427 const ObjCIvarDecl *Ivar,
4428 unsigned CVRQualifiers) {
4429 const ObjCInterfaceDecl *ID =
4430 ObjectTy->castAs<ObjCObjectType>()->getInterface();
4431 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4432 EmitIvarOffset(CGF, ID, Ivar));
4433}
4434
4436 const ObjCInterfaceDecl *OID,
4437 const ObjCIvarDecl *OIVD) {
4438 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4439 next = next->getNextIvar()) {
4440 if (OIVD == next)
4441 return OID;
4442 }
4443
4444 // Otherwise check in the super class.
4445 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4446 return FindIvarInterface(Context, Super, OIVD);
4447
4448 return nullptr;
4449}
4450
4451llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4452 const ObjCInterfaceDecl *Interface,
4453 const ObjCIvarDecl *Ivar) {
4454 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4456
4457 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4458 // and ExternalLinkage, so create a reference to the ivar global and rely on
4459 // the definition being created as part of GenerateClass.
4460 if (RuntimeVersion < 10 ||
4461 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4462 return CGF.Builder.CreateZExtOrBitCast(
4464 Int32Ty,
4466 llvm::PointerType::getUnqual(VMContext),
4467 ObjCIvarOffsetVariable(Interface, Ivar),
4468 CGF.getPointerAlign(), "ivar"),
4470 PtrDiffTy);
4471 std::string name = "__objc_ivar_offset_value_" +
4472 Interface->getNameAsString() +"." + Ivar->getNameAsString();
4473 CharUnits Align = CGM.getIntAlign();
4474 llvm::Value *Offset = TheModule.getGlobalVariable(name);
4475 if (!Offset) {
4476 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4477 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4478 llvm::Constant::getNullValue(IntTy), name);
4479 GV->setAlignment(Align.getAsAlign());
4480 Offset = GV;
4481 }
4482 Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4483 if (Offset->getType() != PtrDiffTy)
4484 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4485 return Offset;
4486 }
4487 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4488 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4489}
4490
4491CGObjCRuntime *
4493 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4494 switch (Runtime.getKind()) {
4496 if (Runtime.getVersion() >= VersionTuple(2, 0))
4497 return new CGObjCGNUstep2(CGM);
4498 return new CGObjCGNUstep(CGM);
4499
4500 case ObjCRuntime::GCC:
4501 return new CGObjCGCC(CGM);
4502
4503 case ObjCRuntime::ObjFW:
4504 return new CGObjCObjFW(CGM);
4505
4508 case ObjCRuntime::iOS:
4510 llvm_unreachable("these runtimes are not GNU runtimes");
4511 }
4512 llvm_unreachable("bad runtime");
4513}
Defines the clang::ASTContext interface.
#define V(N, I)
static const ObjCInterfaceDecl * FindIvarInterface(ASTContext &Context, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *OIVD)
static bool isNamed(const NamedDecl *ND, const char(&Str)[Len])
Definition Decl.cpp:3350
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static StringRef getTriple(const Command &Job)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
llvm::json::Array Array
Defines the SourceManager interface.
Defines the Objective-C statement AST node classes.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:885
TranslationUnitDecl * getTranslationUnitDecl() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType LongTy
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
IdentifierTable & Idents
Definition ASTContext.h:824
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
CanQualType BoolTy
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
CanQualType IntTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:943
uint64_t getCharWidth() const
Return the size of the character type, in bits.
CharUnits getSize() const
getSize - Get the record size in characters.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:138
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual CatchTypeInfo getCatchAllTypeInfo()
Definition CGCXXABI.cpp:346
Implements runtime-specific code generation functions.
void add(RValue rvalue, QualType type)
Definition CGCall.h:305
void addFrom(const CallArgList &other)
Add all the arguments from another CallArgList to this one.
Definition CGCall.h:314
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5505
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
Definition CGObjC.cpp:3561
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
JumpDest ReturnBlock
ReturnBlock - Unified return block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:160
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5661
llvm::Value * LoadObjCSelf()
LoadObjCSelf - Load the value of self.
Definition CGObjC.cpp:1807
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
SmallVector< llvm::Value *, 8 > ObjCEHValueStack
ObjCEHValueStack - Stack of Objective-C exception values, used for rethrows.
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
Definition CGDecl.cpp:211
static bool hasAggregateEvaluationKind(QualType T)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::LLVMContext & getLLVMContext()
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:651
This class organizes the cross-function state that is used while generating LLVM code.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
bool ReturnTypeUsesFPRet(QualType ResultType)
Return true iff the given type uses 'fpret' when used as a return type.
Definition CGCall.cpp:2017
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
const llvm::DataLayout & getDataLayout() const
const llvm::Triple & getTriple() const
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
Definition CGCall.cpp:2007
ASTContext & getContext() const
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses 'sret' when used as a return type.
Definition CGCall.cpp:2002
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:2050
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition CGCall.cpp:589
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
llvm::Constant * getPointer() const
Definition Address.h:308
void add(llvm::Constant *value)
Add a new value to this initializer.
void addInt(llvm::IntegerType *intTy, uint64_t value, bool isSigned=false)
Add an integer value of a specific type.
void addNullPointer(llvm::PointerType *ptrTy)
Add a null pointer of a specific type.
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
llvm::GlobalVariable * finishAndCreateGlobal(As &&...args)
Given that this builder was created by beginning an array or struct directly on a ConstantInitBuilder...
StructBuilder beginStruct(llvm::StructType *ty=nullptr)
void finishAndAddTo(AggregateBuilderBase &parent)
Given that this builder was created by beginning an array or struct component on the given parent bui...
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
llvm::Value * getPointer() const
Definition Address.h:66
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
static void add(Kind k)
Definition DeclBase.cpp:248
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition DeclBase.cpp:876
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
bool hasAttr() const
Definition DeclBase.h:585
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
DirectoryEntryRef getDir() const
Definition FileEntry.h:78
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
std::string ObjCConstantStringClass
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:317
const Expr * getThrowExpr() const
Definition StmtObjC.h:370
const ObjCProtocolList & getReferencedProtocols() const
Definition DeclObjC.h:2402
ObjCCategoryDecl * getCategoryDecl() const
const ObjCInterfaceDecl * getClassInterface() const
Definition DeclObjC.h:2799
classmeth_iterator classmeth_end() const
Definition DeclObjC.h:1064
classmeth_iterator classmeth_begin() const
Definition DeclObjC.h:1060
instmeth_range instance_methods() const
Definition DeclObjC.h:1039
instmeth_iterator instmeth_end() const
Definition DeclObjC.h:1047
instmeth_iterator instmeth_begin() const
Definition DeclObjC.h:1043
prop_range properties() const
Definition DeclObjC.h:973
classmeth_range class_methods() const
Definition DeclObjC.h:1056
propimpl_range property_impls() const
Definition DeclObjC.h:2519
const ObjCInterfaceDecl * getClassInterface() const
Definition DeclObjC.h:2492
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
all_protocol_iterator all_referenced_protocol_end() const
Definition DeclObjC.h:1441
all_protocol_range all_referenced_protocols() const
Definition DeclObjC.h:1423
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
protocol_range protocols() const
Definition DeclObjC.h:1365
all_protocol_iterator all_referenced_protocol_begin() const
Definition DeclObjC.h:1428
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition DeclObjC.h:1548
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:988
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
AccessControl getAccessControl() const
Definition DeclObjC.h:2006
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1993
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:421
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition DeclObjC.cpp:927
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition DeclObjC.cpp:889
Selector getSelector() const
Definition DeclObjC.h:330
ImplicitParamDecl * getCmdDecl() const
Definition DeclObjC.h:423
QualType getReturnType() const
Definition DeclObjC.h:332
bool isClassMethod() const
Definition DeclObjC.h:437
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8157
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1915
ObjCMethodDecl * getGetterMethodDecl() const
Definition DeclObjC.h:907
ObjCMethodDecl * getSetterMethodDecl() const
Definition DeclObjC.h:910
QualType getType() const
Definition DeclObjC.h:810
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition DeclObjC.h:2256
bool isNonRuntimeProtocol() const
This is true iff the protocol is tagged with the objc_non_runtime_protocol attribute.
protocol_iterator protocol_begin() const
Definition DeclObjC.h:2171
protocol_range protocols() const
Definition DeclObjC.h:2167
protocol_iterator protocol_end() const
Definition DeclObjC.h:2178
const VersionTuple & getVersion() const
Definition ObjCRuntime.h:78
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition ObjCRuntime.h:82
Kind
The basic Objective-C runtimes that we know about.
Definition ObjCRuntime.h:31
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
Definition ObjCRuntime.h:59
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition ObjCRuntime.h:45
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Definition ObjCRuntime.h:49
A (possibly-)qualified type.
Definition TypeBase.h:938
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
std::string getAsString() const
Derive the full selector name (e.g.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID getMainFileID() const
Returns the FileID of the main source file.
bool containsNonAscii() const
Definition Expr.h:1944
unsigned getLength() const
Definition Expr.h:1929
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1902
StringRef getString() const
Definition Expr.h:1887
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:495
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
Definition Decl.h:151
bool isVoidType() const
Definition TypeBase.h:9111
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9405
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8939
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9233
bool isObjCIdType() const
Definition TypeBase.h:8951
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9338
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9282
QualType getType() const
Definition Decl.h:723
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:203
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon, if any (for declarations and non-expression statements)...
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
@ Type
The name was classified as a type.
Definition Sema.h:558
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6025
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6031
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
unsigned long uint64_t
long int64_t
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 int32_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t