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