Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
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 file implements classes used to handle lowerings specific to common
10
// object file formats.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15
#include "llvm/ADT/SmallString.h"
16
#include "llvm/ADT/SmallVector.h"
17
#include "llvm/ADT/StringExtras.h"
18
#include "llvm/ADT/StringRef.h"
19
#include "llvm/ADT/Triple.h"
20
#include "llvm/BinaryFormat/COFF.h"
21
#include "llvm/BinaryFormat/Dwarf.h"
22
#include "llvm/BinaryFormat/ELF.h"
23
#include "llvm/BinaryFormat/MachO.h"
24
#include "llvm/CodeGen/MachineModuleInfo.h"
25
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
26
#include "llvm/IR/Comdat.h"
27
#include "llvm/IR/Constants.h"
28
#include "llvm/IR/DataLayout.h"
29
#include "llvm/IR/DerivedTypes.h"
30
#include "llvm/IR/Function.h"
31
#include "llvm/IR/GlobalAlias.h"
32
#include "llvm/IR/GlobalObject.h"
33
#include "llvm/IR/GlobalValue.h"
34
#include "llvm/IR/GlobalVariable.h"
35
#include "llvm/IR/Mangler.h"
36
#include "llvm/IR/Metadata.h"
37
#include "llvm/IR/Module.h"
38
#include "llvm/IR/Type.h"
39
#include "llvm/MC/MCAsmInfo.h"
40
#include "llvm/MC/MCContext.h"
41
#include "llvm/MC/MCExpr.h"
42
#include "llvm/MC/MCSectionCOFF.h"
43
#include "llvm/MC/MCSectionELF.h"
44
#include "llvm/MC/MCSectionMachO.h"
45
#include "llvm/MC/MCSectionWasm.h"
46
#include "llvm/MC/MCSectionXCOFF.h"
47
#include "llvm/MC/MCStreamer.h"
48
#include "llvm/MC/MCSymbol.h"
49
#include "llvm/MC/MCSymbolELF.h"
50
#include "llvm/MC/MCValue.h"
51
#include "llvm/MC/SectionKind.h"
52
#include "llvm/ProfileData/InstrProf.h"
53
#include "llvm/Support/Casting.h"
54
#include "llvm/Support/CodeGen.h"
55
#include "llvm/Support/Format.h"
56
#include "llvm/Support/ErrorHandling.h"
57
#include "llvm/Support/raw_ostream.h"
58
#include "llvm/Target/TargetMachine.h"
59
#include <cassert>
60
#include <string>
61
62
using namespace llvm;
63
using namespace dwarf;
64
65
static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
66
35.2k
                             StringRef &Section) {
67
35.2k
  SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
68
35.2k
  M.getModuleFlagsMetadata(ModuleFlags);
69
35.2k
70
43.6k
  for (const auto &MFE: ModuleFlags) {
71
43.6k
    // Ignore flags with 'Require' behaviour.
72
43.6k
    if (MFE.Behavior == Module::Require)
73
0
      continue;
74
43.6k
75
43.6k
    StringRef Key = MFE.Key->getString();
76
43.6k
    if (Key == "Objective-C Image Info Version") {
77
84
      Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78
43.5k
    } else if (Key == "Objective-C Garbage Collection" ||
79
43.5k
               
Key == "Objective-C GC Only"43.5k
||
80
43.5k
               
Key == "Objective-C Is Simulated"43.5k
||
81
43.5k
               
Key == "Objective-C Class Properties"43.5k
||
82
43.5k
               
Key == "Objective-C Image Swift Version"43.4k
) {
83
168
      Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84
43.4k
    } else if (Key == "Objective-C Image Info Section") {
85
84
      Section = cast<MDString>(MFE.Val)->getString();
86
84
    }
87
43.6k
  }
88
35.2k
}
89
90
//===----------------------------------------------------------------------===//
91
//                                  ELF
92
//===----------------------------------------------------------------------===//
93
94
void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
95
19.1k
                                             const TargetMachine &TgtM) {
96
19.1k
  TargetLoweringObjectFile::Initialize(Ctx, TgtM);
97
19.1k
  TM = &TgtM;
98
19.1k
99
19.1k
  CodeModel::Model CM = TgtM.getCodeModel();
100
19.1k
101
19.1k
  switch (TgtM.getTargetTriple().getArch()) {
102
19.1k
  case Triple::arm:
103
2.18k
  case Triple::armeb:
104
2.18k
  case Triple::thumb:
105
2.18k
  case Triple::thumbeb:
106
2.18k
    if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
107
2.16k
      break;
108
15
    // Fallthrough if not using EHABI
109
15
    LLVM_FALLTHROUGH;
110
1.98k
  case Triple::ppc:
111
1.98k
  case Triple::x86:
112
1.98k
    PersonalityEncoding = isPositionIndependent()
113
1.98k
                              ? dwarf::DW_EH_PE_indirect |
114
97
                                    dwarf::DW_EH_PE_pcrel |
115
97
                                    dwarf::DW_EH_PE_sdata4
116
1.98k
                              : 
dwarf::DW_EH_PE_absptr1.88k
;
117
1.98k
    LSDAEncoding = isPositionIndependent()
118
1.98k
                       ? 
dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata497
119
1.98k
                       : 
dwarf::DW_EH_PE_absptr1.88k
;
120
1.98k
    TTypeEncoding = isPositionIndependent()
121
1.98k
                        ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
122
97
                              dwarf::DW_EH_PE_sdata4
123
1.98k
                        : 
dwarf::DW_EH_PE_absptr1.88k
;
124
1.98k
    break;
125
5.08k
  case Triple::x86_64:
126
5.08k
    if (isPositionIndependent()) {
127
606
      PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
128
606
        ((CM == CodeModel::Small || 
CM == CodeModel::Medium8
)
129
606
         ? 
dwarf::DW_EH_PE_sdata4600
:
dwarf::DW_EH_PE_sdata86
);
130
606
      LSDAEncoding = dwarf::DW_EH_PE_pcrel |
131
606
        (CM == CodeModel::Small
132
606
         ? 
dwarf::DW_EH_PE_sdata4598
:
dwarf::DW_EH_PE_sdata88
);
133
606
      TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
134
606
        ((CM == CodeModel::Small || 
CM == CodeModel::Medium8
)
135
606
         ? 
dwarf::DW_EH_PE_sdata8600
:
dwarf::DW_EH_PE_sdata46
);
136
4.48k
    } else {
137
4.48k
      PersonalityEncoding =
138
4.48k
        (CM == CodeModel::Small || 
CM == CodeModel::Medium20
)
139
4.48k
        ? 
dwarf::DW_EH_PE_udata44.46k
:
dwarf::DW_EH_PE_absptr17
;
140
4.48k
      LSDAEncoding = (CM == CodeModel::Small)
141
4.48k
        ? 
dwarf::DW_EH_PE_udata44.46k
:
dwarf::DW_EH_PE_absptr20
;
142
4.48k
      TTypeEncoding = (CM == CodeModel::Small)
143
4.48k
        ? 
dwarf::DW_EH_PE_udata44.46k
:
dwarf::DW_EH_PE_absptr20
;
144
4.48k
    }
145
5.08k
    break;
146
1.98k
  case Triple::hexagon:
147
918
    PersonalityEncoding = dwarf::DW_EH_PE_absptr;
148
918
    LSDAEncoding = dwarf::DW_EH_PE_absptr;
149
918
    TTypeEncoding = dwarf::DW_EH_PE_absptr;
150
918
    if (isPositionIndependent()) {
151
18
      PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
152
18
      LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
153
18
      TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
154
18
    }
155
918
    break;
156
1.98k
  case Triple::aarch64:
157
1.05k
  case Triple::aarch64_be:
158
1.05k
    // The small model guarantees static code/data size < 4GB, but not where it
159
1.05k
    // will be in memory. Most of these could end up >2GB away so even a signed
160
1.05k
    // pc-relative 32-bit address is insufficient, theoretically.
161
1.05k
    if (isPositionIndependent()) {
162
44
      PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
163
44
        dwarf::DW_EH_PE_sdata8;
164
44
      LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
165
44
      TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
166
44
        dwarf::DW_EH_PE_sdata8;
167
1.00k
    } else {
168
1.00k
      PersonalityEncoding = dwarf::DW_EH_PE_absptr;
169
1.00k
      LSDAEncoding = dwarf::DW_EH_PE_absptr;
170
1.00k
      TTypeEncoding = dwarf::DW_EH_PE_absptr;
171
1.00k
    }
172
1.05k
    break;
173
1.05k
  case Triple::lanai:
174
22
    LSDAEncoding = dwarf::DW_EH_PE_absptr;
175
22
    PersonalityEncoding = dwarf::DW_EH_PE_absptr;
176
22
    TTypeEncoding = dwarf::DW_EH_PE_absptr;
177
22
    break;
178
2.01k
  case Triple::mips:
179
2.01k
  case Triple::mipsel:
180
2.01k
  case Triple::mips64:
181
2.01k
  case Triple::mips64el:
182
2.01k
    // MIPS uses indirect pointer to refer personality functions and types, so
183
2.01k
    // that the eh_frame section can be read-only. DW.ref.personality will be
184
2.01k
    // generated for relocation.
185
2.01k
    PersonalityEncoding = dwarf::DW_EH_PE_indirect;
186
2.01k
    // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
187
2.01k
    //        identify N64 from just a triple.
188
2.01k
    TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
189
2.01k
                    dwarf::DW_EH_PE_sdata4;
190
2.01k
    // We don't support PC-relative LSDA references in GAS so we use the default
191
2.01k
    // DW_EH_PE_absptr for those.
192
2.01k
193
2.01k
    // FreeBSD must be explicit about the data size and using pcrel since it's
194
2.01k
    // assembler/linker won't do the automatic conversion that the Linux tools
195
2.01k
    // do.
196
2.01k
    if (TgtM.getTargetTriple().isOSFreeBSD()) {
197
5
      PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
198
5
      LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
199
5
    }
200
2.01k
    break;
201
2.01k
  case Triple::ppc64:
202
1.37k
  case Triple::ppc64le:
203
1.37k
    PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
204
1.37k
      dwarf::DW_EH_PE_udata8;
205
1.37k
    LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
206
1.37k
    TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
207
1.37k
      dwarf::DW_EH_PE_udata8;
208
1.37k
    break;
209
1.37k
  case Triple::sparcel:
210
138
  case Triple::sparc:
211
138
    if (isPositionIndependent()) {
212
10
      LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
213
10
      PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
214
10
        dwarf::DW_EH_PE_sdata4;
215
10
      TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
216
10
        dwarf::DW_EH_PE_sdata4;
217
128
    } else {
218
128
      LSDAEncoding = dwarf::DW_EH_PE_absptr;
219
128
      PersonalityEncoding = dwarf::DW_EH_PE_absptr;
220
128
      TTypeEncoding = dwarf::DW_EH_PE_absptr;
221
128
    }
222
138
    CallSiteEncoding = dwarf::DW_EH_PE_udata4;
223
138
    break;
224
329
  case Triple::riscv32:
225
329
  case Triple::riscv64:
226
329
    LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
227
329
    PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
228
329
                          dwarf::DW_EH_PE_sdata4;
229
329
    TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
230
329
                    dwarf::DW_EH_PE_sdata4;
231
329
    CallSiteEncoding = dwarf::DW_EH_PE_udata4;
232
329
    break;
233
329
  case Triple::sparcv9:
234
60
    LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
235
60
    if (isPositionIndependent()) {
236
10
      PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
237
10
        dwarf::DW_EH_PE_sdata4;
238
10
      TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
239
10
        dwarf::DW_EH_PE_sdata4;
240
50
    } else {
241
50
      PersonalityEncoding = dwarf::DW_EH_PE_absptr;
242
50
      TTypeEncoding = dwarf::DW_EH_PE_absptr;
243
50
    }
244
60
    break;
245
1.00k
  case Triple::systemz:
246
1.00k
    // All currently-defined code models guarantee that 4-byte PC-relative
247
1.00k
    // values will be in range.
248
1.00k
    if (isPositionIndependent()) {
249
15
      PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
250
15
        dwarf::DW_EH_PE_sdata4;
251
15
      LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
252
15
      TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
253
15
        dwarf::DW_EH_PE_sdata4;
254
992
    } else {
255
992
      PersonalityEncoding = dwarf::DW_EH_PE_absptr;
256
992
      LSDAEncoding = dwarf::DW_EH_PE_absptr;
257
992
      TTypeEncoding = dwarf::DW_EH_PE_absptr;
258
992
    }
259
1.00k
    break;
260
3.03k
  default:
261
3.03k
    break;
262
19.1k
  }
263
19.1k
}
264
265
void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
266
19.0k
                                                     Module &M) const {
267
19.0k
  auto &C = getContext();
268
19.0k
269
19.0k
  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
270
6
    auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
271
6
                              ELF::SHF_EXCLUDE);
272
6
273
6
    Streamer.SwitchSection(S);
274
6
275
36
    for (const auto &Operand : LinkerOptions->operands()) {
276
36
      if (cast<MDNode>(Operand)->getNumOperands() != 2)
277
0
        report_fatal_error("invalid llvm.linker.options");
278
72
      
for (const auto &Option : cast<MDNode>(Operand)->operands())36
{
279
72
        Streamer.EmitBytes(cast<MDString>(Option)->getString());
280
72
        Streamer.EmitIntValue(0, 1);
281
72
      }
282
36
    }
283
6
  }
284
19.0k
285
19.0k
  if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
286
1
    auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
287
1
                              ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
288
1
289
1
    Streamer.SwitchSection(S);
290
1
291
3
    for (const auto &Operand : DependentLibraries->operands()) {
292
3
      Streamer.EmitBytes(
293
3
          cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
294
3
      Streamer.EmitIntValue(0, 1);
295
3
    }
296
1
  }
297
19.0k
298
19.0k
  unsigned Version = 0;
299
19.0k
  unsigned Flags = 0;
300
19.0k
  StringRef Section;
301
19.0k
302
19.0k
  GetObjCImageInfo(M, Version, Flags, Section);
303
19.0k
  if (!Section.empty()) {
304
5
    auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
305
5
    Streamer.SwitchSection(S);
306
5
    Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
307
5
    Streamer.EmitIntValue(Version, 4);
308
5
    Streamer.EmitIntValue(Flags, 4);
309
5
    Streamer.AddBlankLine();
310
5
  }
311
19.0k
312
19.0k
  SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
313
19.0k
  M.getModuleFlagsMetadata(ModuleFlags);
314
19.0k
315
19.0k
  MDNode *CFGProfile = nullptr;
316
19.0k
317
19.0k
  for (const auto &MFE : ModuleFlags) {
318
2.02k
    StringRef Key = MFE.Key->getString();
319
2.02k
    if (Key == "CG Profile") {
320
3
      CFGProfile = cast<MDNode>(MFE.Val);
321
3
      break;
322
3
    }
323
2.02k
  }
324
19.0k
325
19.0k
  if (!CFGProfile)
326
19.0k
    return;
327
4
328
18
  
auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * 4
{
329
18
    if (!MDO)
330
2
      return nullptr;
331
16
    auto V = cast<ValueAsMetadata>(MDO);
332
16
    const Function *F = cast<Function>(V->getValue());
333
16
    return TM->getSymbol(F);
334
16
  };
335
4
336
9
  for (const auto &Edge : CFGProfile->operands()) {
337
9
    MDNode *E = cast<MDNode>(Edge);
338
9
    const MCSymbol *From = GetSym(E->getOperand(0));
339
9
    const MCSymbol *To = GetSym(E->getOperand(1));
340
9
    // Skip null functions. This can happen if functions are dead stripped after
341
9
    // the CGProfile pass has been run.
342
9
    if (!From || !To)
343
2
      continue;
344
7
    uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
345
7
                         ->getValue()
346
7
                         ->getUniqueInteger()
347
7
                         .getZExtValue();
348
7
    Streamer.emitCGProfileEntry(
349
7
        MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
350
7
        MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
351
7
  }
352
4
}
353
354
MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
355
    const GlobalValue *GV, const TargetMachine &TM,
356
186
    MachineModuleInfo *MMI) const {
357
186
  unsigned Encoding = getPersonalityEncoding();
358
186
  if ((Encoding & 0x80) == DW_EH_PE_indirect)
359
52
    return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
360
52
                                          TM.getSymbol(GV)->getName());
361
134
  if ((Encoding & 0x70) == DW_EH_PE_absptr)
362
134
    return TM.getSymbol(GV);
363
0
  report_fatal_error("We do not support this DWARF encoding yet!");
364
0
}
365
366
void TargetLoweringObjectFileELF::emitPersonalityValue(
367
52
    MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
368
52
  SmallString<64> NameData("DW.ref.");
369
52
  NameData += Sym->getName();
370
52
  MCSymbolELF *Label =
371
52
      cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
372
52
  Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
373
52
  Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
374
52
  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
375
52
  MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
376
52
                                                   ELF::SHT_PROGBITS, Flags, 0);
377
52
  unsigned Size = DL.getPointerSize();
378
52
  Streamer.SwitchSection(Sec);
379
52
  Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
380
52
  Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
381
52
  const MCExpr *E = MCConstantExpr::create(Size, getContext());
382
52
  Streamer.emitELFSize(Label, E);
383
52
  Streamer.EmitLabel(Label);
384
52
385
52
  Streamer.EmitSymbolValue(Sym, Size);
386
52
}
387
388
const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
389
    const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
390
36
    MachineModuleInfo *MMI, MCStreamer &Streamer) const {
391
36
  if (Encoding & DW_EH_PE_indirect) {
392
15
    MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
393
15
394
15
    MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
395
15
396
15
    // Add information about the stub reference to ELFMMI so that the stub
397
15
    // gets emitted by the asmprinter.
398
15
    MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
399
15
    if (!StubSym.getPointer()) {
400
15
      MCSymbol *Sym = TM.getSymbol(GV);
401
15
      StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
402
15
    }
403
15
404
15
    return TargetLoweringObjectFile::
405
15
      getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
406
15
                        Encoding & ~DW_EH_PE_indirect, Streamer);
407
15
  }
408
21
409
21
  return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
410
21
                                                           MMI, Streamer);
411
21
}
412
413
336
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
414
336
  // N.B.: The defaults used in here are not the same ones used in MC.
415
336
  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
416
336
  // both gas and MC will produce a section with no flags. Given
417
336
  // section(".eh_frame") gcc will produce:
418
336
  //
419
336
  //   .section   .eh_frame,"a",@progbits
420
336
421
336
  if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
422
336
                                      /*AddSegmentInfo=*/false))
423
1
    return SectionKind::getMetadata();
424
335
425
335
  if (Name.empty() || Name[0] != '.') 
return K193
;
426
142
427
142
  // Default implementation based on some magic section names.
428
142
  if (Name == ".bss" ||
429
142
      
Name.startswith(".bss.")141
||
430
142
      
Name.startswith(".gnu.linkonce.b.")140
||
431
142
      
Name.startswith(".llvm.linkonce.b.")140
||
432
142
      
Name == ".sbss"140
||
433
142
      
Name.startswith(".sbss.")139
||
434
142
      
Name.startswith(".gnu.linkonce.sb.")139
||
435
142
      
Name.startswith(".llvm.linkonce.sb.")139
)
436
3
    return SectionKind::getBSS();
437
139
438
139
  if (Name == ".tdata" ||
439
139
      Name.startswith(".tdata.") ||
440
139
      Name.startswith(".gnu.linkonce.td.") ||
441
139
      Name.startswith(".llvm.linkonce.td."))
442
0
    return SectionKind::getThreadData();
443
139
444
139
  if (Name == ".tbss" ||
445
139
      Name.startswith(".tbss.") ||
446
139
      Name.startswith(".gnu.linkonce.tb.") ||
447
139
      Name.startswith(".llvm.linkonce.tb."))
448
0
    return SectionKind::getThreadBSS();
449
139
450
139
  return K;
451
139
}
452
453
203k
static unsigned getELFSectionType(StringRef Name, SectionKind K) {
454
203k
  // Use SHT_NOTE for section whose name starts with ".note" to allow
455
203k
  // emitting ELF notes from C variable declaration.
456
203k
  // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
457
203k
  if (Name.startswith(".note"))
458
1
    return ELF::SHT_NOTE;
459
203k
460
203k
  if (Name == ".init_array")
461
1
    return ELF::SHT_INIT_ARRAY;
462
203k
463
203k
  if (Name == ".fini_array")
464
1
    return ELF::SHT_FINI_ARRAY;
465
203k
466
203k
  if (Name == ".preinit_array")
467
1
    return ELF::SHT_PREINIT_ARRAY;
468
203k
469
203k
  if (K.isBSS() || 
K.isThreadBSS()199k
)
470
3.43k
    return ELF::SHT_NOBITS;
471
199k
472
199k
  return ELF::SHT_PROGBITS;
473
199k
}
474
475
203k
static unsigned getELFSectionFlags(SectionKind K) {
476
203k
  unsigned Flags = 0;
477
203k
478
203k
  if (!K.isMetadata())
479
203k
    Flags |= ELF::SHF_ALLOC;
480
203k
481
203k
  if (K.isText())
482
194k
    Flags |= ELF::SHF_EXECINSTR;
483
203k
484
203k
  if (K.isExecuteOnly())
485
97
    Flags |= ELF::SHF_ARM_PURECODE;
486
203k
487
203k
  if (K.isWriteable())
488
7.22k
    Flags |= ELF::SHF_WRITE;
489
203k
490
203k
  if (K.isThreadLocal())
491
251
    Flags |= ELF::SHF_TLS;
492
203k
493
203k
  if (K.isMergeableCString() || 
K.isMergeableConst()202k
)
494
732
    Flags |= ELF::SHF_MERGE;
495
203k
496
203k
  if (K.isMergeableCString())
497
597
    Flags |= ELF::SHF_STRINGS;
498
203k
499
203k
  return Flags;
500
203k
}
501
502
203k
static const Comdat *getELFComdat(const GlobalValue *GV) {
503
203k
  const Comdat *C = GV->getComdat();
504
203k
  if (!C)
505
202k
    return nullptr;
506
182
507
182
  if (C->getSelectionKind() != Comdat::Any)
508
0
    report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
509
0
                       C->getName() + "' cannot be lowered.");
510
182
511
182
  return C;
512
182
}
513
514
static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
515
203k
                                              const TargetMachine &TM) {
516
203k
  MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
517
203k
  if (!MD)
518
203k
    return nullptr;
519
28
520
28
  const MDOperand &Op = MD->getOperand(0);
521
28
  if (!Op.get())
522
2
    return nullptr;
523
26
524
26
  auto *VM = dyn_cast<ValueAsMetadata>(Op);
525
26
  if (!VM)
526
0
    report_fatal_error("MD_associated operand is not ValueAsMetadata");
527
26
528
26
  auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
529
26
  return OtherGV ? 
dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV))20
:
nullptr6
;
530
26
}
531
532
203k
static unsigned getEntrySizeForKind(SectionKind Kind) {
533
203k
  if (Kind.isMergeable1ByteCString())
534
587
    return 1;
535
202k
  else if (Kind.isMergeable2ByteCString())
536
6
    return 2;
537
202k
  else if (Kind.isMergeable4ByteCString())
538
4
    return 4;
539
202k
  else if (Kind.isMergeableConst4())
540
60
    return 4;
541
202k
  else if (Kind.isMergeableConst8())
542
39
    return 8;
543
202k
  else if (Kind.isMergeableConst16())
544
29
    return 16;
545
202k
  else if (Kind.isMergeableConst32())
546
7
    return 32;
547
202k
  else {
548
202k
    // We shouldn't have mergeable C strings or mergeable constants that we
549
202k
    // didn't handle above.
550
202k
    assert(!Kind.isMergeableCString() && "unknown string width");
551
202k
    assert(!Kind.isMergeableConst() && "unknown data width");
552
202k
    return 0;
553
202k
  }
554
203k
}
555
556
MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
557
336
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
558
336
  StringRef SectionName = GO->getSection();
559
336
560
336
  // Check if '#pragma clang section' name is applicable.
561
336
  // Note that pragma directive overrides -ffunction-section, -fdata-section
562
336
  // and so section name is exactly as user specified and not uniqued.
563
336
  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
564
336
  if (GV && 
GV->hasImplicitSection()179
) {
565
13
    auto Attrs = GV->getAttributes();
566
13
    if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
567
7
      SectionName = Attrs.getAttribute("bss-section").getValueAsString();
568
7
    } else 
if (6
Attrs.hasAttribute("rodata-section")6
&&
Kind.isReadOnly()6
) {
569
3
      SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
570
3
    } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
571
3
      SectionName = Attrs.getAttribute("data-section").getValueAsString();
572
3
    }
573
13
  }
574
336
  const Function *F = dyn_cast<Function>(GO);
575
336
  if (F && 
F->hasFnAttribute("implicit-section-name")157
) {
576
2
    SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
577
2
  }
578
336
579
336
  // Infer section flags from the section name if we can.
580
336
  Kind = getELFKindForNamedSection(SectionName, Kind);
581
336
582
336
  StringRef Group = "";
583
336
  unsigned Flags = getELFSectionFlags(Kind);
584
336
  if (const Comdat *C = getELFComdat(GO)) {
585
2
    Group = C->getName();
586
2
    Flags |= ELF::SHF_GROUP;
587
2
  }
588
336
589
336
  // A section can have at most one associated section. Put each global with
590
336
  // MD_associated in a unique section.
591
336
  unsigned UniqueID = MCContext::GenericSectionID;
592
336
  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
593
336
  if (AssociatedSymbol) {
594
8
    UniqueID = NextUniqueID++;
595
8
    Flags |= ELF::SHF_LINK_ORDER;
596
8
  }
597
336
598
336
  MCSectionELF *Section = getContext().getELFSection(
599
336
      SectionName, getELFSectionType(SectionName, Kind), Flags,
600
336
      getEntrySizeForKind(Kind), Group, UniqueID, AssociatedSymbol);
601
336
  // Make sure that we did not get some other section with incompatible sh_link.
602
336
  // This should not be possible due to UniqueID code above.
603
336
  assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
604
336
         "Associated symbol mismatch between sections");
605
336
  return Section;
606
336
}
607
608
/// Return the section prefix name used by options FunctionsSections and
609
/// DataSections.
610
206k
static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
611
206k
  if (Kind.isText())
612
198k
    return ".text";
613
7.85k
  if (Kind.isReadOnly())
614
562
    return ".rodata";
615
7.29k
  if (Kind.isBSS())
616
3.36k
    return ".bss";
617
3.93k
  if (Kind.isThreadData())
618
132
    return ".tdata";
619
3.79k
  if (Kind.isThreadBSS())
620
128
    return ".tbss";
621
3.67k
  if (Kind.isData())
622
3.62k
    return ".data";
623
46
  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
624
46
  return ".data.rel.ro";
625
46
}
626
627
static MCSectionELF *selectELFSectionForGlobal(
628
    MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
629
    const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
630
202k
    unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
631
202k
632
202k
  StringRef Group = "";
633
202k
  if (const Comdat *C = getELFComdat(GO)) {
634
179
    Flags |= ELF::SHF_GROUP;
635
179
    Group = C->getName();
636
179
  }
637
202k
638
202k
  // Get the section entry size based on the kind.
639
202k
  unsigned EntrySize = getEntrySizeForKind(Kind);
640
202k
641
202k
  SmallString<128> Name;
642
202k
  if (Kind.isMergeableCString()) {
643
592
    // We also need alignment here.
644
592
    // FIXME: this is getting the alignment of the character, not the
645
592
    // alignment of the global!
646
592
    unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
647
592
        cast<GlobalVariable>(GO));
648
592
649
592
    std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
650
592
    Name = SizeSpec + utostr(Align);
651
202k
  } else if (Kind.isMergeableConst()) {
652
134
    Name = ".rodata.cst";
653
134
    Name += utostr(EntrySize);
654
202k
  } else {
655
202k
    Name = getSectionPrefixForGlobal(Kind);
656
202k
  }
657
202k
658
202k
  if (const auto *F = dyn_cast<Function>(GO)) {
659
194k
    const auto &OptionalPrefix = F->getSectionPrefix();
660
194k
    if (OptionalPrefix)
661
21
      Name += *OptionalPrefix;
662
194k
  }
663
202k
664
202k
  unsigned UniqueID = MCContext::GenericSectionID;
665
202k
  if (EmitUniqueSection) {
666
503
    if (TM.getUniqueSectionNames()) {
667
497
      Name.push_back('.');
668
497
      TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
669
497
    } else {
670
6
      UniqueID = *NextUniqueID;
671
6
      (*NextUniqueID)++;
672
6
    }
673
503
  }
674
202k
  // Use 0 as the unique ID for execute-only text.
675
202k
  if (Kind.isExecuteOnly())
676
93
    UniqueID = 0;
677
202k
  return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
678
202k
                           EntrySize, Group, UniqueID, AssociatedSymbol);
679
202k
}
680
681
MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
682
202k
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
683
202k
  unsigned Flags = getELFSectionFlags(Kind);
684
202k
685
202k
  // If we have -ffunction-section or -fdata-section then we should emit the
686
202k
  // global value to a uniqued section specifically for it.
687
202k
  bool EmitUniqueSection = false;
688
202k
  if (!(Flags & ELF::SHF_MERGE) && 
!Kind.isCommon()202k
) {
689
202k
    if (Kind.isText())
690
194k
      EmitUniqueSection = TM.getFunctionSections();
691
7.58k
    else
692
7.58k
      EmitUniqueSection = TM.getDataSections();
693
202k
  }
694
202k
  EmitUniqueSection |= GO->hasComdat();
695
202k
696
202k
  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
697
202k
  if (AssociatedSymbol) {
698
12
    EmitUniqueSection = true;
699
12
    Flags |= ELF::SHF_LINK_ORDER;
700
12
  }
701
202k
702
202k
  MCSectionELF *Section = selectELFSectionForGlobal(
703
202k
      getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
704
202k
      &NextUniqueID, AssociatedSymbol);
705
202k
  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
706
202k
  return Section;
707
202k
}
708
709
MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
710
157
    const Function &F, const TargetMachine &TM) const {
711
157
  // If the function can be removed, produce a unique section so that
712
157
  // the table doesn't prevent the removal.
713
157
  const Comdat *C = F.getComdat();
714
157
  bool EmitUniqueSection = TM.getFunctionSections() || 
C149
;
715
157
  if (!EmitUniqueSection)
716
148
    return ReadOnlySection;
717
9
718
9
  return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
719
9
                                   getMangler(), TM, EmitUniqueSection,
720
9
                                   ELF::SHF_ALLOC, &NextUniqueID,
721
9
                                   /* AssociatedSymbol */ nullptr);
722
9
}
723
724
bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
725
98
    bool UsesLabelDifference, const Function &F) const {
726
98
  // We can always create relative relocations, so use another section
727
98
  // that can be marked non-executable.
728
98
  return false;
729
98
}
730
731
/// Given a mergeable constant with the specified size and relocation
732
/// information, return a section that it should be placed in.
733
MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
734
    const DataLayout &DL, SectionKind Kind, const Constant *C,
735
31.5k
    unsigned &Align) const {
736
31.5k
  if (Kind.isMergeableConst4() && 
MergeableConst4Section3.72k
)
737
3.72k
    return MergeableConst4Section;
738
27.8k
  if (Kind.isMergeableConst8() && 
MergeableConst8Section2.68k
)
739
2.68k
    return MergeableConst8Section;
740
25.1k
  if (Kind.isMergeableConst16() && 
MergeableConst16Section18.1k
)
741
18.1k
    return MergeableConst16Section;
742
7.09k
  if (Kind.isMergeableConst32() && 
MergeableConst32Section5.58k
)
743
5.58k
    return MergeableConst32Section;
744
1.51k
  if (Kind.isReadOnly())
745
1.49k
    return ReadOnlySection;
746
17
747
17
  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
748
17
  return DataRelROSection;
749
17
}
750
751
static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
752
                                              bool IsCtor, unsigned Priority,
753
75
                                              const MCSymbol *KeySym) {
754
75
  std::string Name;
755
75
  unsigned Type;
756
75
  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
757
75
  StringRef COMDAT = KeySym ? 
KeySym->getName()22
:
""53
;
758
75
759
75
  if (KeySym)
760
22
    Flags |= ELF::SHF_GROUP;
761
75
762
75
  if (UseInitArray) {
763
44
    if (IsCtor) {
764
42
      Type = ELF::SHT_INIT_ARRAY;
765
42
      Name = ".init_array";
766
42
    } else {
767
2
      Type = ELF::SHT_FINI_ARRAY;
768
2
      Name = ".fini_array";
769
2
    }
770
44
    if (Priority != 65535) {
771
17
      Name += '.';
772
17
      Name += utostr(Priority);
773
17
    }
774
44
  } else {
775
31
    // The default scheme is .ctor / .dtor, so we have to invert the priority
776
31
    // numbering.
777
31
    if (IsCtor)
778
27
      Name = ".ctors";
779
4
    else
780
4
      Name = ".dtors";
781
31
    if (Priority != 65535)
782
18
      raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
783
31
    Type = ELF::SHT_PROGBITS;
784
31
  }
785
75
786
75
  return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
787
75
}
788
789
MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
790
69
    unsigned Priority, const MCSymbol *KeySym) const {
791
69
  return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
792
69
                                  KeySym);
793
69
}
794
795
MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
796
6
    unsigned Priority, const MCSymbol *KeySym) const {
797
6
  return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
798
6
                                  KeySym);
799
6
}
800
801
const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
802
    const GlobalValue *LHS, const GlobalValue *RHS,
803
14
    const TargetMachine &TM) const {
804
14
  // We may only use a PLT-relative relocation to refer to unnamed_addr
805
14
  // functions.
806
14
  if (!LHS->hasGlobalUnnamedAddr() || 
!LHS->getValueType()->isFunctionTy()7
)
807
8
    return nullptr;
808
6
809
6
  // Basic sanity checks.
810
6
  if (LHS->getType()->getPointerAddressSpace() != 0 ||
811
6
      RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
812
6
      RHS->isThreadLocal())
813
0
    return nullptr;
814
6
815
6
  return MCBinaryExpr::createSub(
816
6
      MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
817
6
                              getContext()),
818
6
      MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
819
6
}
820
821
19.0k
MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
822
19.0k
  // Use ".GCC.command.line" since this feature is to support clang's
823
19.0k
  // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
824
19.0k
  // same name.
825
19.0k
  return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
826
19.0k
                                    ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
827
19.0k
}
828
829
void
830
10.8k
TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
831
10.8k
  UseInitArray = UseInitArray_;
832
10.8k
  MCContext &Ctx = getContext();
833
10.8k
  if (!UseInitArray) {
834
82
    StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
835
82
                                          ELF::SHF_ALLOC | ELF::SHF_WRITE);
836
82
837
82
    StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
838
82
                                          ELF::SHF_ALLOC | ELF::SHF_WRITE);
839
82
    return;
840
82
  }
841
10.8k
842
10.8k
  StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
843
10.8k
                                        ELF::SHF_WRITE | ELF::SHF_ALLOC);
844
10.8k
  StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
845
10.8k
                                        ELF::SHF_WRITE | ELF::SHF_ALLOC);
846
10.8k
}
847
848
//===----------------------------------------------------------------------===//
849
//                                 MachO
850
//===----------------------------------------------------------------------===//
851
852
TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
853
20.1k
  : TargetLoweringObjectFile() {
854
20.1k
  SupportIndirectSymViaGOTPCRel = true;
855
20.1k
}
856
857
void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
858
15.3k
                                               const TargetMachine &TM) {
859
15.3k
  TargetLoweringObjectFile::Initialize(Ctx, TM);
860
15.3k
  if (TM.getRelocationModel() == Reloc::Static) {
861
865
    StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
862
865
                                            SectionKind::getData());
863
865
    StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
864
865
                                            SectionKind::getData());
865
14.4k
  } else {
866
14.4k
    StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
867
14.4k
                                            MachO::S_MOD_INIT_FUNC_POINTERS,
868
14.4k
                                            SectionKind::getData());
869
14.4k
    StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
870
14.4k
                                            MachO::S_MOD_TERM_FUNC_POINTERS,
871
14.4k
                                            SectionKind::getData());
872
14.4k
  }
873
15.3k
874
15.3k
  PersonalityEncoding =
875
15.3k
      dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
876
15.3k
  LSDAEncoding = dwarf::DW_EH_PE_pcrel;
877
15.3k
  TTypeEncoding =
878
15.3k
      dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
879
15.3k
}
880
881
void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
882
15.2k
                                                       Module &M) const {
883
15.2k
  // Emit the linker options if present.
884
15.2k
  if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
885
32
    for (const auto &Option : LinkerOptions->operands()) {
886
6
      SmallVector<std::string, 4> StrOptions;
887
6
      for (const auto &Piece : cast<MDNode>(Option)->operands())
888
8
        StrOptions.push_back(cast<MDString>(Piece)->getString());
889
6
      Streamer.EmitLinkerOptions(StrOptions);
890
6
    }
891
32
  }
892
15.2k
893
15.2k
  unsigned VersionVal = 0;
894
15.2k
  unsigned ImageInfoFlags = 0;
895
15.2k
  StringRef SectionVal;
896
15.2k
897
15.2k
  GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
898
15.2k
899
15.2k
  // The section is mandatory. If we don't have it, then we don't have GC info.
900
15.2k
  if (SectionVal.empty())
901
15.1k
    return;
902
76
903
76
  StringRef Segment, Section;
904
76
  unsigned TAA = 0, StubSize = 0;
905
76
  bool TAAParsed;
906
76
  std::string ErrorCode =
907
76
    MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
908
76
                                          TAA, TAAParsed, StubSize);
909
76
  if (!ErrorCode.empty())
910
0
    // If invalid, report the error with report_fatal_error.
911
0
    report_fatal_error("Invalid section specifier '" + Section + "': " +
912
0
                       ErrorCode + ".");
913
76
914
76
  // Get the section.
915
76
  MCSectionMachO *S = getContext().getMachOSection(
916
76
      Segment, Section, TAA, StubSize, SectionKind::getData());
917
76
  Streamer.SwitchSection(S);
918
76
  Streamer.EmitLabel(getContext().
919
76
                     getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
920
76
  Streamer.EmitIntValue(VersionVal, 4);
921
76
  Streamer.EmitIntValue(ImageInfoFlags, 4);
922
76
  Streamer.AddBlankLine();
923
76
}
924
925
837k
static void checkMachOComdat(const GlobalValue *GV) {
926
837k
  const Comdat *C = GV->getComdat();
927
837k
  if (!C)
928
837k
    return;
929
18.4E
930
18.4E
  report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
931
18.4E
                     "' cannot be lowered.");
932
18.4E
}
933
934
MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
935
8.21k
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
936
8.21k
  // Parse the section specifier and create it if valid.
937
8.21k
  StringRef Segment, Section;
938
8.21k
  unsigned TAA = 0, StubSize = 0;
939
8.21k
  bool TAAParsed;
940
8.21k
941
8.21k
  checkMachOComdat(GO);
942
8.21k
943
8.21k
  std::string ErrorCode =
944
8.21k
    MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
945
8.21k
                                          TAA, TAAParsed, StubSize);
946
8.21k
  if (!ErrorCode.empty()) {
947
2
    // If invalid, report the error with report_fatal_error.
948
2
    report_fatal_error("Global variable '" + GO->getName() +
949
2
                       "' has an invalid section specifier '" +
950
2
                       GO->getSection() + "': " + ErrorCode + ".");
951
2
  }
952
8.21k
953
8.21k
  // Get the section.
954
8.21k
  MCSectionMachO *S =
955
8.21k
      getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
956
8.21k
957
8.21k
  // If TAA wasn't set by ParseSectionSpecifier() above,
958
8.21k
  // use the value returned by getMachOSection() as a default.
959
8.21k
  if (!TAAParsed)
960
6.29k
    TAA = S->getTypeAndAttributes();
961
8.21k
962
8.21k
  // Okay, now that we got the section, verify that the TAA & StubSize agree.
963
8.21k
  // If the user declared multiple globals with different section flags, we need
964
8.21k
  // to reject it here.
965
8.21k
  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
966
0
    // If invalid, report the error with report_fatal_error.
967
0
    report_fatal_error("Global variable '" + GO->getName() +
968
0
                       "' section type or attributes does not match previous"
969
0
                       " section specifier");
970
0
  }
971
8.21k
972
8.21k
  return S;
973
8.21k
}
974
975
MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
976
829k
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
977
829k
  checkMachOComdat(GO);
978
829k
979
829k
  // Handle thread local data.
980
829k
  if (Kind.isThreadBSS()) 
return TLSBSSSection114
;
981
829k
  if (Kind.isThreadData()) 
return TLSDataSection12
;
982
829k
983
829k
  if (Kind.isText())
984
294k
    return GO->isWeakForLinker() ? 
TextCoalSection204k
:
TextSection89.8k
;
985
535k
986
535k
  // If this is weak/linkonce, put this in a coalescable section, either in text
987
535k
  // or data depending on if it is writable.
988
535k
  if (GO->isWeakForLinker()) {
989
42.1k
    if (Kind.isReadOnly())
990
1.50k
      return ConstTextCoalSection;
991
40.6k
    if (Kind.isReadOnlyWithRel())
992
2.90k
      return ConstDataCoalSection;
993
37.7k
    return DataCoalSection;
994
37.7k
  }
995
492k
996
492k
  // FIXME: Alignment check should be handled by section classifier.
997
492k
  if (Kind.isMergeable1ByteCString() &&
998
492k
      GO->getParent()->getDataLayout().getPreferredAlignment(
999
397k
          cast<GlobalVariable>(GO)) < 32)
1000
397k
    return CStringSection;
1001
95.6k
1002
95.6k
  // Do not put 16-bit arrays in the UString section if they have an
1003
95.6k
  // externally visible label, this runs into issues with certain linker
1004
95.6k
  // versions.
1005
95.6k
  if (Kind.isMergeable2ByteCString() && 
!GO->hasExternalLinkage()7
&&
1006
95.6k
      GO->getParent()->getDataLayout().getPreferredAlignment(
1007
4
          cast<GlobalVariable>(GO)) < 32)
1008
4
    return UStringSection;
1009
95.6k
1010
95.6k
  // With MachO only variables whose corresponding symbol starts with 'l' or
1011
95.6k
  // 'L' can be merged, so we only try merging GVs with private linkage.
1012
95.6k
  if (GO->hasPrivateLinkage() && 
Kind.isMergeableConst()72.7k
) {
1013
408
    if (Kind.isMergeableConst4())
1014
4
      return FourByteConstantSection;
1015
404
    if (Kind.isMergeableConst8())
1016
7
      return EightByteConstantSection;
1017
397
    if (Kind.isMergeableConst16())
1018
343
      return SixteenByteConstantSection;
1019
95.2k
  }
1020
95.2k
1021
95.2k
  // Otherwise, if it is readonly, but not something we can specially optimize,
1022
95.2k
  // just drop it in .const.
1023
95.2k
  if (Kind.isReadOnly())
1024
67.0k
    return ReadOnlySection;
1025
28.2k
1026
28.2k
  // If this is marked const, put it into a const section.  But if the dynamic
1027
28.2k
  // linker needs to write to it, put it in the data segment.
1028
28.2k
  if (Kind.isReadOnlyWithRel())
1029
9.90k
    return ConstDataSection;
1030
18.3k
1031
18.3k
  // Put zero initialized globals with strong external linkage in the
1032
18.3k
  // DATA, __common section with the .zerofill directive.
1033
18.3k
  if (Kind.isBSSExtern())
1034
1.96k
    return DataCommonSection;
1035
16.3k
1036
16.3k
  // Put zero initialized globals with local linkage in __DATA,__bss directive
1037
16.3k
  // with the .zerofill directive (aka .lcomm).
1038
16.3k
  if (Kind.isBSSLocal())
1039
4.76k
    return DataBSSSection;
1040
11.6k
1041
11.6k
  // Otherwise, just drop the variable in the normal data section.
1042
11.6k
  return DataSection;
1043
11.6k
}
1044
1045
MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1046
    const DataLayout &DL, SectionKind Kind, const Constant *C,
1047
17.4k
    unsigned &Align) const {
1048
17.4k
  // If this constant requires a relocation, we have to put it in the data
1049
17.4k
  // segment, not in the text segment.
1050
17.4k
  if (Kind.isData() || Kind.isReadOnlyWithRel())
1051
0
    return ConstDataSection;
1052
17.4k
1053
17.4k
  if (Kind.isMergeableConst4())
1054
494
    return FourByteConstantSection;
1055
16.9k
  if (Kind.isMergeableConst8())
1056
3.22k
    return EightByteConstantSection;
1057
13.7k
  if (Kind.isMergeableConst16())
1058
11.2k
    return SixteenByteConstantSection;
1059
2.44k
  return ReadOnlySection;  // .const
1060
2.44k
}
1061
1062
const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1063
    const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1064
8
    MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1065
8
  // The mach-o version of this method defaults to returning a stub reference.
1066
8
1067
8
  if (Encoding & DW_EH_PE_indirect) {
1068
8
    MachineModuleInfoMachO &MachOMMI =
1069
8
      MMI->getObjFileInfo<MachineModuleInfoMachO>();
1070
8
1071
8
    MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1072
8
1073
8
    // Add information about the stub reference to MachOMMI so that the stub
1074
8
    // gets emitted by the asmprinter.
1075
8
    MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1076
8
    if (!StubSym.getPointer()) {
1077
7
      MCSymbol *Sym = TM.getSymbol(GV);
1078
7
      StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1079
7
    }
1080
8
1081
8
    return TargetLoweringObjectFile::
1082
8
      getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1083
8
                        Encoding & ~DW_EH_PE_indirect, Streamer);
1084
8
  }
1085
0
1086
0
  return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1087
0
                                                           MMI, Streamer);
1088
0
}
1089
1090
MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1091
    const GlobalValue *GV, const TargetMachine &TM,
1092
23
    MachineModuleInfo *MMI) const {
1093
23
  // The mach-o version of this method defaults to returning a stub reference.
1094
23
  MachineModuleInfoMachO &MachOMMI =
1095
23
    MMI->getObjFileInfo<MachineModuleInfoMachO>();
1096
23
1097
23
  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1098
23
1099
23
  // Add information about the stub reference to MachOMMI so that the stub
1100
23
  // gets emitted by the asmprinter.
1101
23
  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1102
23
  if (!StubSym.getPointer()) {
1103
14
    MCSymbol *Sym = TM.getSymbol(GV);
1104
14
    StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1105
14
  }
1106
23
1107
23
  return SSym;
1108
23
}
1109
1110
const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1111
    const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
1112
11
    MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1113
11
  // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1114
11
  // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1115
11
  // through a non_lazy_ptr stub instead. One advantage is that it allows the
1116
11
  // computation of deltas to final external symbols. Example:
1117
11
  //
1118
11
  //    _extgotequiv:
1119
11
  //       .long   _extfoo
1120
11
  //
1121
11
  //    _delta:
1122
11
  //       .long   _extgotequiv-_delta
1123
11
  //
1124
11
  // is transformed to:
1125
11
  //
1126
11
  //    _delta:
1127
11
  //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1128
11
  //
1129
11
  //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1130
11
  //    L_extfoo$non_lazy_ptr:
1131
11
  //       .indirect_symbol        _extfoo
1132
11
  //       .long   0
1133
11
  //
1134
11
  // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1135
11
  // may point to both local (same translation unit) and global (other
1136
11
  // translation units) symbols. Example:
1137
11
  //
1138
11
  // .section __DATA,__pointers,non_lazy_symbol_pointers
1139
11
  // L1:
1140
11
  //    .indirect_symbol _myGlobal
1141
11
  //    .long 0
1142
11
  // L2:
1143
11
  //    .indirect_symbol _myLocal
1144
11
  //    .long _myLocal
1145
11
  //
1146
11
  // If the symbol is local, instead of the symbol's index, the assembler
1147
11
  // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1148
11
  // Then the linker will notice the constant in the table and will look at the
1149
11
  // content of the symbol.
1150
11
  MachineModuleInfoMachO &MachOMMI =
1151
11
    MMI->getObjFileInfo<MachineModuleInfoMachO>();
1152
11
  MCContext &Ctx = getContext();
1153
11
1154
11
  // The offset must consider the original displacement from the base symbol
1155
11
  // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1156
11
  Offset = -MV.getConstant();
1157
11
  const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1158
11
1159
11
  // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1160
11
  // non_lazy_ptr stubs.
1161
11
  SmallString<128> Name;
1162
11
  StringRef Suffix = "$non_lazy_ptr";
1163
11
  Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1164
11
  Name += Sym->getName();
1165
11
  Name += Suffix;
1166
11
  MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1167
11
1168
11
  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1169
11
  if (!StubSym.getPointer()) {
1170
5
    bool IsIndirectLocal = Sym->isDefined() && 
!Sym->isExternal()3
;
1171
5
    // With the assumption that IsIndirectLocal == GV->hasLocalLinkage().
1172
5
    StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1173
5
                                                 !IsIndirectLocal);
1174
5
  }
1175
11
1176
11
  const MCExpr *BSymExpr =
1177
11
    MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1178
11
  const MCExpr *LHS =
1179
11
    MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1180
11
1181
11
  if (!Offset)
1182
3
    return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1183
8
1184
8
  const MCExpr *RHS =
1185
8
    MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1186
8
  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1187
8
}
1188
1189
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1190
138k
                               const MCSection &Section) {
1191
138k
  if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1192
137k
    return true;
1193
1.03k
1194
1.03k
  // If it is not dead stripped, it is safe to use private labels.
1195
1.03k
  const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1196
1.03k
  if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1197
100
    return true;
1198
931
1199
931
  return false;
1200
931
}
1201
1202
void TargetLoweringObjectFileMachO::getNameWithPrefix(
1203
    SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1204
138k
    const TargetMachine &TM) const {
1205
138k
  bool CannotUsePrivateLabel = true;
1206
138k
  if (auto *GO = GV->getBaseObject()) {
1207
138k
    SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1208
138k
    const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1209
138k
    CannotUsePrivateLabel =
1210
138k
        !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1211
138k
  }
1212
138k
  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1213
138k
}
1214
1215
//===----------------------------------------------------------------------===//
1216
//                                  COFF
1217
//===----------------------------------------------------------------------===//
1218
1219
static unsigned
1220
453
getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1221
453
  unsigned Flags = 0;
1222
453
  bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1223
453
1224
453
  if (K.isMetadata())
1225
0
    Flags |=
1226
0
      COFF::IMAGE_SCN_MEM_DISCARDABLE;
1227
453
  else if (K.isText())
1228
177
    Flags |=
1229
177
      COFF::IMAGE_SCN_MEM_EXECUTE |
1230
177
      COFF::IMAGE_SCN_MEM_READ |
1231
177
      COFF::IMAGE_SCN_CNT_CODE |
1232
177
      (isThumb ? 
COFF::IMAGE_SCN_MEM_16BIT0
: (COFF::SectionCharacteristics)0);
1233
276
  else if (K.isBSS())
1234
19
    Flags |=
1235
19
      COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1236
19
      COFF::IMAGE_SCN_MEM_READ |
1237
19
      COFF::IMAGE_SCN_MEM_WRITE;
1238
257
  else if (K.isThreadLocal())
1239
1
    Flags |=
1240
1
      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1241
1
      COFF::IMAGE_SCN_MEM_READ |
1242
1
      COFF::IMAGE_SCN_MEM_WRITE;
1243
256
  else if (K.isReadOnly() || 
K.isReadOnlyWithRel()174
)
1244
195
    Flags |=
1245
195
      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1246
195
      COFF::IMAGE_SCN_MEM_READ;
1247
61
  else if (K.isWriteable())
1248
62
    Flags |=
1249
62
      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1250
62
      COFF::IMAGE_SCN_MEM_READ |
1251
62
      COFF::IMAGE_SCN_MEM_WRITE;
1252
453
1253
453
  return Flags;
1254
453
}
1255
1256
647
static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1257
647
  const Comdat *C = GV->getComdat();
1258
647
  assert(C && "expected GV to have a Comdat!");
1259
647
1260
647
  StringRef ComdatGVName = C->getName();
1261
647
  const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1262
647
  if (!ComdatGV)
1263
1
    report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1264
1
                       "' does not exist.");
1265
646
1266
646
  if (ComdatGV->getComdat() != C)
1267
1
    report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1268
1
                       "' is not a key for its COMDAT.");
1269
645
1270
645
  return ComdatGV;
1271
645
}
1272
1273
428
static int getSelectionForCOFF(const GlobalValue *GV) {
1274
428
  if (const Comdat *C = GV->getComdat()) {
1275
329
    const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1276
329
    if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1277
30
      ComdatKey = GA->getBaseObject();
1278
329
    if (ComdatKey == GV) {
1279
318
      switch (C->getSelectionKind()) {
1280
318
      case Comdat::Any:
1281
283
        return COFF::IMAGE_COMDAT_SELECT_ANY;
1282
318
      case Comdat::ExactMatch:
1283
1
        return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1284
318
      case Comdat::Largest:
1285
31
        return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1286
318
      case Comdat::NoDuplicates:
1287
1
        return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1288
318
      case Comdat::SameSize:
1289
2
        return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1290
11
      }
1291
11
    } else {
1292
11
      return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1293
11
    }
1294
99
  }
1295
99
  return 0;
1296
99
}
1297
1298
MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1299
29
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1300
29
  int Selection = 0;
1301
29
  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1302
29
  StringRef Name = GO->getSection();
1303
29
  StringRef COMDATSymName = "";
1304
29
  if (GO->hasComdat()) {
1305
9
    Selection = getSelectionForCOFF(GO);
1306
9
    const GlobalValue *ComdatGV;
1307
9
    if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1308
0
      ComdatGV = getComdatGVForCOFF(GO);
1309
9
    else
1310
9
      ComdatGV = GO;
1311
9
1312
9
    if (!ComdatGV->hasPrivateLinkage()) {
1313
9
      MCSymbol *Sym = TM.getSymbol(ComdatGV);
1314
9
      COMDATSymName = Sym->getName();
1315
9
      Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1316
9
    } else {
1317
0
      Selection = 0;
1318
0
    }
1319
9
  }
1320
29
1321
29
  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1322
29
                                     Selection);
1323
29
}
1324
1325
422
static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1326
422
  if (Kind.isText())
1327
171
    return ".text";
1328
251
  if (Kind.isBSS())
1329
19
    return ".bss";
1330
232
  if (Kind.isThreadLocal())
1331
1
    return ".tls$";
1332
231
  if (Kind.isReadOnly() || 
Kind.isReadOnlyWithRel()154
)
1333
183
    return ".rdata";
1334
48
  return ".data";
1335
48
}
1336
1337
MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1338
3.88k
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1339
3.88k
  // If we have -ffunction-sections then we should emit the global value to a
1340
3.88k
  // uniqued section specifically for it.
1341
3.88k
  bool EmitUniquedSection;
1342
3.88k
  if (Kind.isText())
1343
3.22k
    EmitUniquedSection = TM.getFunctionSections();
1344
664
  else
1345
664
    EmitUniquedSection = TM.getDataSections();
1346
3.88k
1347
3.88k
  if ((EmitUniquedSection && 
!Kind.isCommon()115
) ||
GO->hasComdat()3.77k
) {
1348
420
    SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1349
420
1350
420
    unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1351
420
1352
420
    Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1353
420
    int Selection = getSelectionForCOFF(GO);
1354
420
    if (!Selection)
1355
101
      Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1356
420
    const GlobalValue *ComdatGV;
1357
420
    if (GO->hasComdat())
1358
318
      ComdatGV = getComdatGVForCOFF(GO);
1359
102
    else
1360
102
      ComdatGV = GO;
1361
420
1362
420
    unsigned UniqueID = MCContext::GenericSectionID;
1363
420
    if (EmitUniquedSection)
1364
114
      UniqueID = NextUniqueID++;
1365
420
1366
420
    if (!ComdatGV->hasPrivateLinkage()) {
1367
417
      MCSymbol *Sym = TM.getSymbol(ComdatGV);
1368
417
      StringRef COMDATSymName = Sym->getName();
1369
417
1370
417
      // Append "$symbol" to the section name *before* IR-level mangling is
1371
417
      // applied when targetting mingw. This is what GCC does, and the ld.bfd
1372
417
      // COFF linker will not properly handle comdats otherwise.
1373
417
      if (getTargetTriple().isWindowsGNUEnvironment())
1374
16
        raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1375
417
1376
417
      return getContext().getCOFFSection(Name, Characteristics, Kind,
1377
417
                                         COMDATSymName, Selection, UniqueID);
1378
417
    } else {
1379
3
      SmallString<256> TmpData;
1380
3
      getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1381
3
      return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1382
3
                                         Selection, UniqueID);
1383
3
    }
1384
3.46k
  }
1385
3.46k
1386
3.46k
  if (Kind.isText())
1387
3.05k
    return TextSection;
1388
414
1389
414
  if (Kind.isThreadLocal())
1390
38
    return TLSDataSection;
1391
376
1392
376
  if (Kind.isReadOnly() || 
Kind.isReadOnlyWithRel()256
)
1393
125
    return ReadOnlySection;
1394
251
1395
251
  // Note: we claim that common symbols are put in BSSSection, but they are
1396
251
  // really emitted with the magic .comm directive, which creates a symbol table
1397
251
  // entry but not a section.
1398
251
  if (Kind.isBSS() || 
Kind.isCommon()97
)
1399
156
    return BSSSection;
1400
95
1401
95
  return DataSection;
1402
95
}
1403
1404
void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1405
    SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1406
389
    const TargetMachine &TM) const {
1407
389
  bool CannotUsePrivateLabel = false;
1408
389
  if (GV->hasPrivateLinkage() &&
1409
389
      ((isa<Function>(GV) && 
TM.getFunctionSections()16
) ||
1410
389
       (isa<GlobalVariable>(GV) && 
TM.getDataSections()373
)))
1411
7
    CannotUsePrivateLabel = true;
1412
389
1413
389
  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1414
389
}
1415
1416
MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1417
9
    const Function &F, const TargetMachine &TM) const {
1418
9
  // If the function can be removed, produce a unique section so that
1419
9
  // the table doesn't prevent the removal.
1420
9
  const Comdat *C = F.getComdat();
1421
9
  bool EmitUniqueSection = TM.getFunctionSections() || 
C5
;
1422
9
  if (!EmitUniqueSection)
1423
5
    return ReadOnlySection;
1424
4
1425
4
  // FIXME: we should produce a symbol for F instead.
1426
4
  if (F.hasPrivateLinkage())
1427
0
    return ReadOnlySection;
1428
4
1429
4
  MCSymbol *Sym = TM.getSymbol(&F);
1430
4
  StringRef COMDATSymName = Sym->getName();
1431
4
1432
4
  SectionKind Kind = SectionKind::getReadOnly();
1433
4
  StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1434
4
  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1435
4
  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1436
4
  unsigned UniqueID = NextUniqueID++;
1437
4
1438
4
  return getContext().getCOFFSection(
1439
4
      SecName, Characteristics, Kind, COMDATSymName,
1440
4
      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1441
4
}
1442
1443
void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1444
907
                                                      Module &M) const {
1445
907
  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1446
35
    // Emit the linker options to the linker .drectve section.  According to the
1447
35
    // spec, this section is a space-separated string containing flags for
1448
35
    // linker.
1449
35
    MCSection *Sec = getDrectveSection();
1450
35
    Streamer.SwitchSection(Sec);
1451
63
    for (const auto &Option : LinkerOptions->operands()) {
1452
64
      for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1453
64
        // Lead with a space for consistency with our dllexport implementation.
1454
64
        std::string Directive(" ");
1455
64
        Directive.append(cast<MDString>(Piece)->getString());
1456
64
        Streamer.EmitBytes(Directive);
1457
64
      }
1458
63
    }
1459
35
  }
1460
907
1461
907
  unsigned Version = 0;
1462
907
  unsigned Flags = 0;
1463
907
  StringRef Section;
1464
907
1465
907
  GetObjCImageInfo(M, Version, Flags, Section);
1466
907
  if (Section.empty())
1467
904
    return;
1468
3
1469
3
  auto &C = getContext();
1470
3
  auto *S = C.getCOFFSection(
1471
3
      Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1472
3
      SectionKind::getReadOnly());
1473
3
  Streamer.SwitchSection(S);
1474
3
  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1475
3
  Streamer.EmitIntValue(Version, 4);
1476
3
  Streamer.EmitIntValue(Flags, 4);
1477
3
  Streamer.AddBlankLine();
1478
3
}
1479
1480
void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1481
913
                                              const TargetMachine &TM) {
1482
913
  TargetLoweringObjectFile::Initialize(Ctx, TM);
1483
913
  const Triple &T = TM.getTargetTriple();
1484
913
  if (T.isWindowsMSVCEnvironment() || 
T.isWindowsItaniumEnvironment()170
) {
1485
790
    StaticCtorSection =
1486
790
        Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1487
790
                                           COFF::IMAGE_SCN_MEM_READ,
1488
790
                           SectionKind::getReadOnly());
1489
790
    StaticDtorSection =
1490
790
        Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1491
790
                                           COFF::IMAGE_SCN_MEM_READ,
1492
790
                           SectionKind::getReadOnly());
1493
790
  } else {
1494
123
    StaticCtorSection = Ctx.getCOFFSection(
1495
123
        ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1496
123
                      COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1497
123
        SectionKind::getData());
1498
123
    StaticDtorSection = Ctx.getCOFFSection(
1499
123
        ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1500
123
                      COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1501
123
        SectionKind::getData());
1502
123
  }
1503
913
}
1504
1505
static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1506
                                                   const Triple &T, bool IsCtor,
1507
                                                   unsigned Priority,
1508
                                                   const MCSymbol *KeySym,
1509
34
                                                   MCSectionCOFF *Default) {
1510
34
  if (T.isWindowsMSVCEnvironment() || 
T.isWindowsItaniumEnvironment()12
) {
1511
23
    // If the priority is the default, use .CRT$XCU, possibly associative.
1512
23
    if (Priority == 65535)
1513
17
      return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1514
6
1515
6
    // Otherwise, we need to compute a new section name. Low priorities should
1516
6
    // run earlier. The linker will sort sections ASCII-betically, and we need a
1517
6
    // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1518
6
    // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1519
6
    // low priorities need to sort before 'L', since the CRT uses that
1520
6
    // internally, so we use ".CRT$XCA00001" for them.
1521
6
    SmallString<24> Name;
1522
6
    raw_svector_ostream OS(Name);
1523
6
    OS << ".CRT$XC" << (Priority < 200 ? 
'A'4
:
'T'2
) << format("%05u", Priority);
1524
6
    MCSectionCOFF *Sec = Ctx.getCOFFSection(
1525
6
        Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1526
6
        SectionKind::getReadOnly());
1527
6
    return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1528
6
  }
1529
11
1530
11
  std::string Name = IsCtor ? 
".ctors"9
:
".dtors"2
;
1531
11
  if (Priority != 65535)
1532
2
    raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1533
11
1534
11
  return Ctx.getAssociativeCOFFSection(
1535
11
      Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1536
11
                                   COFF::IMAGE_SCN_MEM_READ |
1537
11
                                   COFF::IMAGE_SCN_MEM_WRITE,
1538
11
                         SectionKind::getData()),
1539
11
      KeySym, 0);
1540
11
}
1541
1542
MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1543
29
    unsigned Priority, const MCSymbol *KeySym) const {
1544
29
  return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1545
29
                                      Priority, KeySym,
1546
29
                                      cast<MCSectionCOFF>(StaticCtorSection));
1547
29
}
1548
1549
MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1550
5
    unsigned Priority, const MCSymbol *KeySym) const {
1551
5
  return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1552
5
                                      Priority, KeySym,
1553
5
                                      cast<MCSectionCOFF>(StaticDtorSection));
1554
5
}
1555
1556
void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1557
6.59k
    raw_ostream &OS, const GlobalValue *GV) const {
1558
6.59k
  emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1559
6.59k
}
1560
1561
void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1562
9
    raw_ostream &OS, const GlobalValue *GV) const {
1563
9
  emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1564
9
}
1565
1566
const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1567
    const GlobalValue *LHS, const GlobalValue *RHS,
1568
169
    const TargetMachine &TM) const {
1569
169
  const Triple &T = TM.getTargetTriple();
1570
169
  if (T.isOSCygMing())
1571
0
    return nullptr;
1572
169
1573
169
  // Our symbols should exist in address space zero, cowardly no-op if
1574
169
  // otherwise.
1575
169
  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1576
169
      RHS->getType()->getPointerAddressSpace() != 0)
1577
0
    return nullptr;
1578
169
1579
169
  // Both ptrtoint instructions must wrap global objects:
1580
169
  // - Only global variables are eligible for image relative relocations.
1581
169
  // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1582
169
  // We expect __ImageBase to be a global variable without a section, externally
1583
169
  // defined.
1584
169
  //
1585
169
  // It should look something like this: @__ImageBase = external constant i8
1586
169
  if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1587
169
      LHS->isThreadLocal() || RHS->isThreadLocal() ||
1588
169
      RHS->getName() != "__ImageBase" || 
!RHS->hasExternalLinkage()164
||
1589
169
      
cast<GlobalVariable>(RHS)->hasInitializer()164
||
RHS->hasSection()164
)
1590
5
    return nullptr;
1591
164
1592
164
  return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1593
164
                                 MCSymbolRefExpr::VK_COFF_IMGREL32,
1594
164
                                 getContext());
1595
164
}
1596
1597
619
static std::string APIntToHexString(const APInt &AI) {
1598
619
  unsigned Width = (AI.getBitWidth() / 8) * 2;
1599
619
  std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1600
619
  unsigned Size = HexString.size();
1601
619
  assert(Width >= Size && "hex string is too large!");
1602
619
  HexString.insert(HexString.begin(), Width - Size, '0');
1603
619
1604
619
  return HexString;
1605
619
}
1606
1607
703
static std::string scalarConstantToHexString(const Constant *C) {
1608
703
  Type *Ty = C->getType();
1609
703
  if (isa<UndefValue>(C)) {
1610
18
    return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1611
685
  } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1612
289
    return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1613
396
  } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1614
312
    return APIntToHexString(CI->getValue());
1615
312
  } else {
1616
84
    unsigned NumElements;
1617
84
    if (isa<VectorType>(Ty))
1618
75
      NumElements = Ty->getVectorNumElements();
1619
9
    else
1620
9
      NumElements = Ty->getArrayNumElements();
1621
84
    std::string HexString;
1622
498
    for (int I = NumElements - 1, E = -1; I != E; 
--I414
)
1623
414
      HexString += scalarConstantToHexString(C->getAggregateElement(I));
1624
84
    return HexString;
1625
84
  }
1626
703
}
1627
1628
MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1629
    const DataLayout &DL, SectionKind Kind, const Constant *C,
1630
310
    unsigned &Align) const {
1631
310
  if (Kind.isMergeableConst() && 
C307
&&
1632
310
      
getContext().getAsmInfo()->hasCOFFComdatConstants()307
) {
1633
289
    // This creates comdat sections with the given symbol name, but unless
1634
289
    // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1635
289
    // will be created with a null storage class, which makes GNU binutils
1636
289
    // error out.
1637
289
    const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1638
289
                                     COFF::IMAGE_SCN_MEM_READ |
1639
289
                                     COFF::IMAGE_SCN_LNK_COMDAT;
1640
289
    std::string COMDATSymName;
1641
289
    if (Kind.isMergeableConst4()) {
1642
102
      if (Align <= 4) {
1643
102
        COMDATSymName = "__real@" + scalarConstantToHexString(C);
1644
102
        Align = 4;
1645
102
      }
1646
187
    } else if (Kind.isMergeableConst8()) {
1647
112
      if (Align <= 8) {
1648
112
        COMDATSymName = "__real@" + scalarConstantToHexString(C);
1649
112
        Align = 8;
1650
112
      }
1651
112
    } else 
if (75
Kind.isMergeableConst16()75
) {
1652
60
      // FIXME: These may not be appropriate for non-x86 architectures.
1653
60
      if (Align <= 16) {
1654
60
        COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1655
60
        Align = 16;
1656
60
      }
1657
60
    } else 
if (15
Kind.isMergeableConst32()15
) {
1658
15
      if (Align <= 32) {
1659
15
        COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1660
15
        Align = 32;
1661
15
      }
1662
15
    }
1663
289
1664
289
    if (!COMDATSymName.empty())
1665
289
      return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1666
289
                                         COMDATSymName,
1667
289
                                         COFF::IMAGE_COMDAT_SELECT_ANY);
1668
21
  }
1669
21
1670
21
  return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1671
21
}
1672
1673
1674
//===----------------------------------------------------------------------===//
1675
//                                  Wasm
1676
//===----------------------------------------------------------------------===//
1677
1678
4.71k
static const Comdat *getWasmComdat(const GlobalValue *GV) {
1679
4.71k
  const Comdat *C = GV->getComdat();
1680
4.71k
  if (!C)
1681
4.70k
    return nullptr;
1682
14
1683
14
  if (C->getSelectionKind() != Comdat::Any)
1684
0
    report_fatal_error("WebAssembly COMDATs only support "
1685
0
                       "SelectionKind::Any, '" + C->getName() + "' cannot be "
1686
0
                       "lowered.");
1687
14
1688
14
  return C;
1689
14
}
1690
1691
7
static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1692
7
  // If we're told we have function data, then use that.
1693
7
  if (K.isText())
1694
0
    return SectionKind::getText();
1695
7
1696
7
  // Otherwise, ignore whatever section type the generic impl detected and use
1697
7
  // a plain data section.
1698
7
  return SectionKind::getData();
1699
7
}
1700
1701
MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1702
10
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1703
10
  // We don't support explict section names for functions in the wasm object
1704
10
  // format.  Each function has to be in its own unique section.
1705
10
  if (isa<Function>(GO)) {
1706
3
    return SelectSectionForGlobal(GO, Kind, TM);
1707
3
  }
1708
7
1709
7
  StringRef Name = GO->getSection();
1710
7
1711
7
  Kind = getWasmKindForNamedSection(Name, Kind);
1712
7
1713
7
  StringRef Group = "";
1714
7
  if (const Comdat *C = getWasmComdat(GO)) {
1715
0
    Group = C->getName();
1716
0
  }
1717
7
1718
7
  MCSectionWasm* Section =
1719
7
      getContext().getWasmSection(Name, Kind, Group,
1720
7
                                  MCContext::GenericSectionID);
1721
7
1722
7
  return Section;
1723
7
}
1724
1725
static MCSectionWasm *selectWasmSectionForGlobal(
1726
    MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1727
4.71k
    const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1728
4.71k
  StringRef Group = "";
1729
4.71k
  if (const Comdat *C = getWasmComdat(GO)) {
1730
13
    Group = C->getName();
1731
13
  }
1732
4.71k
1733
4.71k
  bool UniqueSectionNames = TM.getUniqueSectionNames();
1734
4.71k
  SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1735
4.71k
1736
4.71k
  if (const auto *F = dyn_cast<Function>(GO)) {
1737
4.45k
    const auto &OptionalPrefix = F->getSectionPrefix();
1738
4.45k
    if (OptionalPrefix)
1739
0
      Name += *OptionalPrefix;
1740
4.45k
  }
1741
4.71k
1742
4.71k
  if (EmitUniqueSection && UniqueSectionNames) {
1743
4.71k
    Name.push_back('.');
1744
4.71k
    TM.getNameWithPrefix(Name, GO, Mang, true);
1745
4.71k
  }
1746
4.71k
  unsigned UniqueID = MCContext::GenericSectionID;
1747
4.71k
  if (EmitUniqueSection && 
!UniqueSectionNames4.71k
) {
1748
0
    UniqueID = *NextUniqueID;
1749
0
    (*NextUniqueID)++;
1750
0
  }
1751
4.71k
1752
4.71k
  return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1753
4.71k
}
1754
1755
MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1756
4.71k
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1757
4.71k
1758
4.71k
  if (Kind.isCommon())
1759
0
    report_fatal_error("mergable sections not supported yet on wasm");
1760
4.71k
1761
4.71k
  // If we have -ffunction-section or -fdata-section then we should emit the
1762
4.71k
  // global value to a uniqued section specifically for it.
1763
4.71k
  bool EmitUniqueSection = false;
1764
4.71k
  if (Kind.isText())
1765
4.45k
    EmitUniqueSection = TM.getFunctionSections();
1766
261
  else
1767
261
    EmitUniqueSection = TM.getDataSections();
1768
4.71k
  EmitUniqueSection |= GO->hasComdat();
1769
4.71k
1770
4.71k
  return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1771
4.71k
                                    EmitUniqueSection, &NextUniqueID);
1772
4.71k
}
1773
1774
bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1775
0
    bool UsesLabelDifference, const Function &F) const {
1776
0
  // We can always create relative relocations, so use another section
1777
0
  // that can be marked non-executable.
1778
0
  return false;
1779
0
}
1780
1781
const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1782
    const GlobalValue *LHS, const GlobalValue *RHS,
1783
0
    const TargetMachine &TM) const {
1784
0
  // We may only use a PLT-relative relocation to refer to unnamed_addr
1785
0
  // functions.
1786
0
  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1787
0
    return nullptr;
1788
0
1789
0
  // Basic sanity checks.
1790
0
  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1791
0
      RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1792
0
      RHS->isThreadLocal())
1793
0
    return nullptr;
1794
0
1795
0
  return MCBinaryExpr::createSub(
1796
0
      MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1797
0
                              getContext()),
1798
0
      MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1799
0
}
1800
1801
426
void TargetLoweringObjectFileWasm::InitializeWasm() {
1802
426
  StaticCtorSection =
1803
426
      getContext().getWasmSection(".init_array", SectionKind::getData());
1804
426
1805
426
  // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
1806
426
  // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
1807
426
  TTypeEncoding = dwarf::DW_EH_PE_absptr;
1808
426
}
1809
1810
MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1811
25
    unsigned Priority, const MCSymbol *KeySym) const {
1812
25
  return Priority == UINT16_MAX ?
1813
5
         StaticCtorSection :
1814
25
         getContext().getWasmSection(".init_array." + utostr(Priority),
1815
20
                                     SectionKind::getData());
1816
25
}
1817
1818
MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1819
0
    unsigned Priority, const MCSymbol *KeySym) const {
1820
0
  llvm_unreachable("@llvm.global_dtors should have been lowered already");
1821
0
  return nullptr;
1822
0
}
1823
1824
//===----------------------------------------------------------------------===//
1825
//                                  XCOFF
1826
//===----------------------------------------------------------------------===//
1827
MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
1828
0
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1829
0
  llvm_unreachable("XCOFF explicit sections not yet implemented.");
1830
0
}
1831
1832
MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
1833
8
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1834
8
  assert(!TM.getFunctionSections() && !TM.getDataSections() &&
1835
8
         "XCOFF unique sections not yet implemented.");
1836
8
1837
8
  // Common symbols go into a csect with matching name which will get mapped
1838
8
  // into the .bss section.
1839
8
  if (Kind.isCommon()) {
1840
8
    SmallString<128> Name;
1841
8
    getNameWithPrefix(Name, GO, TM);
1842
8
    return getContext().getXCOFFSection(Name, XCOFF::XMC_RW, XCOFF::XTY_CM,
1843
8
                                        Kind, /* BeginSymbolName */ nullptr);
1844
8
  }
1845
0
1846
0
  report_fatal_error("XCOFF other section types not yet implemented.");
1847
0
}
1848
1849
bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
1850
0
    bool UsesLabelDifference, const Function &F) const {
1851
0
  llvm_unreachable("TLOF XCOFF not yet implemented.");
1852
0
}
1853
1854
void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
1855
9
                                               const TargetMachine &TgtM) {
1856
9
  TargetLoweringObjectFile::Initialize(Ctx, TgtM);
1857
9
  TTypeEncoding = 0;
1858
9
  PersonalityEncoding = 0;
1859
9
  LSDAEncoding = 0;
1860
9
}
1861
1862
MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
1863
0
    unsigned Priority, const MCSymbol *KeySym) const {
1864
0
  llvm_unreachable("XCOFF ctor section not yet implemented.");
1865
0
}
1866
1867
MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
1868
0
    unsigned Priority, const MCSymbol *KeySym) const {
1869
0
  llvm_unreachable("XCOFF dtor section not yet implemented.");
1870
0
}
1871
1872
const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
1873
    const GlobalValue *LHS, const GlobalValue *RHS,
1874
0
    const TargetMachine &TM) const {
1875
0
  llvm_unreachable("XCOFF not yet implemented.");
1876
0
}