Coverage Report

Created: 2019-07-24 05:18

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