Coverage Report

Created: 2020-03-31 06:27

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