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