Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
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 contains a printer that converts from our internal representation
10
// of machine-dependent LLVM code to PowerPC assembly language. This printer is
11
// the output mechanism used by `llc'.
12
//
13
// Documentation at http://developer.apple.com/documentation/DeveloperTools/
14
// Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "MCTargetDesc/PPCInstPrinter.h"
19
#include "MCTargetDesc/PPCMCExpr.h"
20
#include "MCTargetDesc/PPCMCTargetDesc.h"
21
#include "MCTargetDesc/PPCPredicates.h"
22
#include "PPC.h"
23
#include "PPCInstrInfo.h"
24
#include "PPCMachineFunctionInfo.h"
25
#include "PPCSubtarget.h"
26
#include "PPCTargetMachine.h"
27
#include "PPCTargetStreamer.h"
28
#include "TargetInfo/PowerPCTargetInfo.h"
29
#include "llvm/ADT/MapVector.h"
30
#include "llvm/ADT/StringRef.h"
31
#include "llvm/ADT/Triple.h"
32
#include "llvm/ADT/Twine.h"
33
#include "llvm/BinaryFormat/ELF.h"
34
#include "llvm/BinaryFormat/MachO.h"
35
#include "llvm/CodeGen/AsmPrinter.h"
36
#include "llvm/CodeGen/MachineBasicBlock.h"
37
#include "llvm/CodeGen/MachineFunction.h"
38
#include "llvm/CodeGen/MachineInstr.h"
39
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
40
#include "llvm/CodeGen/MachineOperand.h"
41
#include "llvm/CodeGen/MachineRegisterInfo.h"
42
#include "llvm/CodeGen/StackMaps.h"
43
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
44
#include "llvm/IR/DataLayout.h"
45
#include "llvm/IR/GlobalValue.h"
46
#include "llvm/IR/Module.h"
47
#include "llvm/MC/MCAsmInfo.h"
48
#include "llvm/MC/MCContext.h"
49
#include "llvm/MC/MCExpr.h"
50
#include "llvm/MC/MCInst.h"
51
#include "llvm/MC/MCInstBuilder.h"
52
#include "llvm/MC/MCSectionELF.h"
53
#include "llvm/MC/MCSectionMachO.h"
54
#include "llvm/MC/MCSectionXCOFF.h"
55
#include "llvm/MC/MCStreamer.h"
56
#include "llvm/MC/MCSymbol.h"
57
#include "llvm/MC/MCSymbolELF.h"
58
#include "llvm/MC/MCSymbolXCOFF.h"
59
#include "llvm/MC/SectionKind.h"
60
#include "llvm/Support/Casting.h"
61
#include "llvm/Support/CodeGen.h"
62
#include "llvm/Support/Debug.h"
63
#include "llvm/Support/ErrorHandling.h"
64
#include "llvm/Support/TargetRegistry.h"
65
#include "llvm/Support/raw_ostream.h"
66
#include "llvm/Target/TargetMachine.h"
67
#include <algorithm>
68
#include <cassert>
69
#include <cstdint>
70
#include <memory>
71
#include <new>
72
73
using namespace llvm;
74
75
#define DEBUG_TYPE "asmprinter"
76
77
namespace {
78
79
class PPCAsmPrinter : public AsmPrinter {
80
protected:
81
  MapVector<MCSymbol *, MCSymbol *> TOC;
82
  const PPCSubtarget *Subtarget;
83
  StackMaps SM;
84
85
public:
86
  explicit PPCAsmPrinter(TargetMachine &TM,
87
                         std::unique_ptr<MCStreamer> Streamer)
88
1.76k
      : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
89
90
0
  StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
91
92
  MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
93
94
1.76k
  bool doInitialization(Module &M) override {
95
1.76k
    if (!TOC.empty())
96
0
      TOC.clear();
97
1.76k
    return AsmPrinter::doInitialization(M);
98
1.76k
  }
99
100
  void EmitInstruction(const MachineInstr *MI) override;
101
102
  /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
103
  /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
104
  /// The \p MI would be INLINEASM ONLY.
105
  void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
106
107
  void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
108
  bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
109
                       const char *ExtraCode, raw_ostream &O) override;
110
  bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
111
                             const char *ExtraCode, raw_ostream &O) override;
112
113
  void EmitEndOfAsmFile(Module &M) override;
114
115
  void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
116
  void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
117
  void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
118
11.2k
  bool runOnMachineFunction(MachineFunction &MF) override {
119
11.2k
    Subtarget = &MF.getSubtarget<PPCSubtarget>();
120
11.2k
    bool Changed = AsmPrinter::runOnMachineFunction(MF);
121
11.2k
    emitXRayTable();
122
11.2k
    return Changed;
123
11.2k
  }
124
};
125
126
/// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
127
class PPCLinuxAsmPrinter : public PPCAsmPrinter {
128
public:
129
  explicit PPCLinuxAsmPrinter(TargetMachine &TM,
130
                              std::unique_ptr<MCStreamer> Streamer)
131
1.76k
      : PPCAsmPrinter(TM, std::move(Streamer)) {}
132
133
11.2k
  StringRef getPassName() const override {
134
11.2k
    return "Linux PPC Assembly Printer";
135
11.2k
  }
136
137
  bool doFinalization(Module &M) override;
138
  void EmitStartOfAsmFile(Module &M) override;
139
140
  void EmitFunctionEntryLabel() override;
141
142
  void EmitFunctionBodyStart() override;
143
  void EmitFunctionBodyEnd() override;
144
  void EmitInstruction(const MachineInstr *MI) override;
145
};
146
147
/// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
148
/// OS X
149
class PPCDarwinAsmPrinter : public PPCAsmPrinter {
150
public:
151
  explicit PPCDarwinAsmPrinter(TargetMachine &TM,
152
                               std::unique_ptr<MCStreamer> Streamer)
153
0
      : PPCAsmPrinter(TM, std::move(Streamer)) {}
154
155
0
  StringRef getPassName() const override {
156
0
    return "Darwin PPC Assembly Printer";
157
0
  }
158
159
  bool doFinalization(Module &M) override;
160
  void EmitStartOfAsmFile(Module &M) override;
161
};
162
163
class PPCAIXAsmPrinter : public PPCAsmPrinter {
164
public:
165
  PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
166
5
      : PPCAsmPrinter(TM, std::move(Streamer)) {}
167
168
0
  StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
169
170
  void EmitGlobalVariable(const GlobalVariable *GV) override;
171
};
172
173
} // end anonymous namespace
174
175
void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
176
4
                                       raw_ostream &O) {
177
4
  // Computing the address of a global symbol, not calling it.
178
4
  const GlobalValue *GV = MO.getGlobal();
179
4
  MCSymbol *SymToPrint;
180
4
181
4
  // External or weakly linked global variables need non-lazily-resolved stubs
182
4
  if (Subtarget->hasLazyResolverStub(GV)) {
183
0
    SymToPrint = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
184
0
    MachineModuleInfoImpl::StubValueTy &StubSym =
185
0
        MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(
186
0
            SymToPrint);
187
0
    if (!StubSym.getPointer())
188
0
      StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
189
0
                                                   !GV->hasInternalLinkage());
190
4
  } else {
191
4
    SymToPrint = getSymbol(GV);
192
4
  }
193
4
194
4
  SymToPrint->print(O, MAI);
195
4
196
4
  printOffset(MO.getOffset(), O);
197
4
}
198
199
void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
200
518
                                 raw_ostream &O) {
201
518
  const DataLayout &DL = getDataLayout();
202
518
  const MachineOperand &MO = MI->getOperand(OpNo);
203
518
204
518
  switch (MO.getType()) {
205
518
  case MachineOperand::MO_Register: {
206
487
    // The MI is INLINEASM ONLY and UseVSXReg is always false.
207
487
    const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
208
487
209
487
    // Linux assembler (Others?) does not take register mnemonics.
210
487
    // FIXME - What about special registers used in mfspr/mtspr?
211
487
    if (!Subtarget->isDarwin())
212
487
      RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
213
487
    O << RegName;
214
487
    return;
215
518
  }
216
518
  case MachineOperand::MO_Immediate:
217
29
    O << MO.getImm();
218
29
    return;
219
518
220
518
  case MachineOperand::MO_MachineBasicBlock:
221
0
    MO.getMBB()->getSymbol()->print(O, MAI);
222
0
    return;
223
518
  case MachineOperand::MO_ConstantPoolIndex:
224
0
    O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
225
0
      << MO.getIndex();
226
0
    return;
227
518
  case MachineOperand::MO_BlockAddress:
228
0
    GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
229
0
    return;
230
518
  case MachineOperand::MO_GlobalAddress: {
231
2
    PrintSymbolOperand(MO, O);
232
2
    return;
233
518
  }
234
518
235
518
  default:
236
0
    O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
237
0
    return;
238
518
  }
239
518
}
240
241
/// PrintAsmOperand - Print out an operand for an inline asm expression.
242
///
243
bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
244
505
                                    const char *ExtraCode, raw_ostream &O) {
245
505
  // Does this asm operand have a single letter operand modifier?
246
505
  if (ExtraCode && 
ExtraCode[0]27
) {
247
27
    if (ExtraCode[1] != 0) 
return true0
; // Unknown modifier.
248
27
249
27
    switch (ExtraCode[0]) {
250
27
    default:
251
6
      // See if this is a generic print operand
252
6
      return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
253
27
    case 'L': // Write second word of DImode reference.
254
0
      // Verify that this operand has two consecutive registers.
255
0
      if (!MI->getOperand(OpNo).isReg() ||
256
0
          OpNo+1 == MI->getNumOperands() ||
257
0
          !MI->getOperand(OpNo+1).isReg())
258
0
        return true;
259
0
      ++OpNo;   // Return the high-part.
260
0
      break;
261
5
    case 'I':
262
5
      // Write 'i' if an integer constant, otherwise nothing.  Used to print
263
5
      // addi vs add, etc.
264
5
      if (MI->getOperand(OpNo).isImm())
265
2
        O << "i";
266
5
      return false;
267
16
    case 'x':
268
16
      if(!MI->getOperand(OpNo).isReg())
269
0
        return true;
270
16
      // This operand uses VSX numbering.
271
16
      // If the operand is a VMX register, convert it to a VSX register.
272
16
      unsigned Reg = MI->getOperand(OpNo).getReg();
273
16
      if (PPCInstrInfo::isVRRegister(Reg))
274
4
        Reg = PPC::VSX32 + (Reg - PPC::V0);
275
12
      else if (PPCInstrInfo::isVFRegister(Reg))
276
1
        Reg = PPC::VSX32 + (Reg - PPC::VF0);
277
16
      const char *RegName;
278
16
      RegName = PPCInstPrinter::getRegisterName(Reg);
279
16
      RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
280
16
      O << RegName;
281
16
      return false;
282
27
    }
283
27
  }
284
478
285
478
  printOperand(MI, OpNo, O);
286
478
  return false;
287
478
}
288
289
// At the moment, all inline asm memory operands are a single register.
290
// In any case, the output of this routine should always be just one
291
// assembler operand.
292
293
bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
294
                                          const char *ExtraCode,
295
44
                                          raw_ostream &O) {
296
44
  if (ExtraCode && 
ExtraCode[0]5
) {
297
5
    if (ExtraCode[1] != 0) 
return true0
; // Unknown modifier.
298
5
299
5
    switch (ExtraCode[0]) {
300
5
    
default: return true0
; // Unknown modifier.
301
5
    case 'y': // A memory reference for an X-form instruction
302
1
      {
303
1
        const char *RegName = "r0";
304
1
        if (!Subtarget->isDarwin())
305
1
          RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
306
1
        O << RegName << ", ";
307
1
        printOperand(MI, OpNo, O);
308
1
        return false;
309
5
      }
310
5
    case 'U': // Print 'u' for update form.
311
4
    case 'X': // Print 'x' for indexed form.
312
4
    {
313
4
      // FIXME: Currently for PowerPC memory operands are always loaded
314
4
      // into a register, so we never get an update or indexed form.
315
4
      // This is bad even for offset forms, since even if we know we
316
4
      // have a value in -16(r1), we will generate a load into r<n>
317
4
      // and then load from 0(r<n>).  Until that issue is fixed,
318
4
      // tolerate 'U' and 'X' but don't output anything.
319
4
      assert(MI->getOperand(OpNo).isReg());
320
4
      return false;
321
39
    }
322
5
    }
323
5
  }
324
39
325
39
  assert(MI->getOperand(OpNo).isReg());
326
39
  O << "0(";
327
39
  printOperand(MI, OpNo, O);
328
39
  O << ")";
329
39
  return false;
330
39
}
331
332
/// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
333
/// exists for it.  If not, create one.  Then return a symbol that references
334
/// the TOC entry.
335
2.04k
MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
336
2.04k
  MCSymbol *&TOCEntry = TOC[Sym];
337
2.04k
  if (!TOCEntry)
338
591
    TOCEntry = createTempSymbol("C");
339
2.04k
  return TOCEntry;
340
2.04k
}
341
342
1.75k
void PPCAsmPrinter::EmitEndOfAsmFile(Module &M) {
343
1.75k
  emitStackMaps(SM);
344
1.75k
}
345
346
17
void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
347
17
  unsigned NumNOPBytes = MI.getOperand(1).getImm();
348
17
349
17
  SM.recordStackMap(MI);
350
17
  assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
351
17
352
17
  // Scan ahead to trim the shadow.
353
17
  const MachineBasicBlock &MBB = *MI.getParent();
354
17
  MachineBasicBlock::const_iterator MII(MI);
355
17
  ++MII;
356
39
  while (NumNOPBytes > 0) {
357
29
    if (MII == MBB.end() || 
MII->isCall()28
||
358
29
        
MII->getOpcode() == PPC::DBG_VALUE22
||
359
29
        
MII->getOpcode() == TargetOpcode::PATCHPOINT22
||
360
29
        
MII->getOpcode() == TargetOpcode::STACKMAP22
)
361
7
      break;
362
22
    ++MII;
363
22
    NumNOPBytes -= 4;
364
22
  }
365
17
366
17
  // Emit nops.
367
30
  for (unsigned i = 0; i < NumNOPBytes; 
i += 413
)
368
13
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
369
17
}
370
371
// Lower a patchpoint of the form:
372
// [<def>], <id>, <numBytes>, <target>, <numArgs>
373
40
void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
374
40
  SM.recordPatchPoint(MI);
375
40
  PatchPointOpers Opers(&MI);
376
40
377
40
  unsigned EncodedBytes = 0;
378
40
  const MachineOperand &CalleeMO = Opers.getCallTarget();
379
40
380
40
  if (CalleeMO.isImm()) {
381
36
    int64_t CallTarget = CalleeMO.getImm();
382
36
    if (CallTarget) {
383
19
      assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
384
19
             "High 16 bits of call target should be zero.");
385
19
      unsigned ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
386
19
      EncodedBytes = 0;
387
19
      // Materialize the jump address:
388
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
389
19
                                      .addReg(ScratchReg)
390
19
                                      .addImm((CallTarget >> 32) & 0xFFFF));
391
19
      ++EncodedBytes;
392
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
393
19
                                      .addReg(ScratchReg)
394
19
                                      .addReg(ScratchReg)
395
19
                                      .addImm(32).addImm(16));
396
19
      ++EncodedBytes;
397
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
398
19
                                      .addReg(ScratchReg)
399
19
                                      .addReg(ScratchReg)
400
19
                                      .addImm((CallTarget >> 16) & 0xFFFF));
401
19
      ++EncodedBytes;
402
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
403
19
                                      .addReg(ScratchReg)
404
19
                                      .addReg(ScratchReg)
405
19
                                      .addImm(CallTarget & 0xFFFF));
406
19
407
19
      // Save the current TOC pointer before the remote call.
408
19
      int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
409
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
410
19
                                      .addReg(PPC::X2)
411
19
                                      .addImm(TOCSaveOffset)
412
19
                                      .addReg(PPC::X1));
413
19
      ++EncodedBytes;
414
19
415
19
      // If we're on ELFv1, then we need to load the actual function pointer
416
19
      // from the function descriptor.
417
19
      if (!Subtarget->isELFv2ABI()) {
418
15
        // Load the new TOC pointer and the function address, but not r11
419
15
        // (needing this is rare, and loading it here would prevent passing it
420
15
        // via a 'nest' parameter.
421
15
        EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
422
15
                                        .addReg(PPC::X2)
423
15
                                        .addImm(8)
424
15
                                        .addReg(ScratchReg));
425
15
        ++EncodedBytes;
426
15
        EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
427
15
                                        .addReg(ScratchReg)
428
15
                                        .addImm(0)
429
15
                                        .addReg(ScratchReg));
430
15
        ++EncodedBytes;
431
15
      }
432
19
433
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
434
19
                                      .addReg(ScratchReg));
435
19
      ++EncodedBytes;
436
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
437
19
      ++EncodedBytes;
438
19
439
19
      // Restore the TOC pointer after the call.
440
19
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
441
19
                                      .addReg(PPC::X2)
442
19
                                      .addImm(TOCSaveOffset)
443
19
                                      .addReg(PPC::X1));
444
19
      ++EncodedBytes;
445
19
    }
446
36
  } else 
if (4
CalleeMO.isGlobal()4
) {
447
4
    const GlobalValue *GValue = CalleeMO.getGlobal();
448
4
    MCSymbol *MOSymbol = getSymbol(GValue);
449
4
    const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
450
4
451
4
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
452
4
                                    .addExpr(SymVar));
453
4
    EncodedBytes += 2;
454
4
  }
455
40
456
40
  // Each instruction is 4 bytes.
457
40
  EncodedBytes *= 4;
458
40
459
40
  // Emit padding.
460
40
  unsigned NumBytes = Opers.getNumPatchBytes();
461
40
  assert(NumBytes >= EncodedBytes &&
462
40
         "Patchpoint can't request size less than the length of a call.");
463
40
  assert((NumBytes - EncodedBytes) % 4 == 0 &&
464
40
         "Invalid number of NOP bytes requested!");
465
231
  for (unsigned i = EncodedBytes; i < NumBytes; 
i += 4191
)
466
191
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
467
40
}
468
469
/// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
470
/// call to __tls_get_addr to the current output stream.
471
void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
472
29
                                MCSymbolRefExpr::VariantKind VK) {
473
29
  StringRef Name = "__tls_get_addr";
474
29
  MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
475
29
  MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
476
29
  const Module *M = MF->getFunction().getParent();
477
29
478
29
  assert(MI->getOperand(0).isReg() &&
479
29
         ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
480
29
          (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
481
29
         "GETtls[ld]ADDR[32] must define GPR3");
482
29
  assert(MI->getOperand(1).isReg() &&
483
29
         ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
484
29
          (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
485
29
         "GETtls[ld]ADDR[32] must read GPR3");
486
29
487
29
  if (!Subtarget->isPPC64() && 
!Subtarget->isDarwin()10
&&
488
29
      
isPositionIndependent()10
)
489
10
    Kind = MCSymbolRefExpr::VK_PLT;
490
29
  const MCExpr *TlsRef =
491
29
    MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
492
29
493
29
  // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
494
29
  if (Kind == MCSymbolRefExpr::VK_PLT && 
Subtarget->isSecurePlt()10
&&
495
29
      
M->getPICLevel() == PICLevel::BigPIC2
)
496
1
    TlsRef = MCBinaryExpr::createAdd(
497
1
        TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
498
29
  const MachineOperand &MO = MI->getOperand(2);
499
29
  const GlobalValue *GValue = MO.getGlobal();
500
29
  MCSymbol *MOSymbol = getSymbol(GValue);
501
29
  const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
502
29
  EmitToStreamer(*OutStreamer,
503
29
                 MCInstBuilder(Subtarget->isPPC64() ?
504
19
                               PPC::BL8_NOP_TLS : 
PPC::BL_TLS10
)
505
29
                 .addExpr(TlsRef)
506
29
                 .addExpr(SymVar));
507
29
}
508
509
/// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
510
/// the current output stream.
511
///
512
99.6k
void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
513
99.6k
  MCInst TmpInst;
514
99.6k
  bool isPPC64 = Subtarget->isPPC64();
515
99.6k
  bool isDarwin = TM.getTargetTriple().isOSDarwin();
516
99.6k
  const Module *M = MF->getFunction().getParent();
517
99.6k
  PICLevel::Level PL = M->getPICLevel();
518
99.6k
519
#ifndef NDEBUG
520
  // Validate that SPE and FPU are mutually exclusive in codegen
521
  if (!MI->isInlineAsm()) {
522
    for (const MachineOperand &MO: MI->operands()) {
523
      if (MO.isReg()) {
524
        unsigned Reg = MO.getReg();
525
        if (Subtarget->hasSPE()) {
526
          if (PPC::F4RCRegClass.contains(Reg) ||
527
              PPC::F8RCRegClass.contains(Reg) ||
528
              PPC::QBRCRegClass.contains(Reg) ||
529
              PPC::QFRCRegClass.contains(Reg) ||
530
              PPC::QSRCRegClass.contains(Reg) ||
531
              PPC::VFRCRegClass.contains(Reg) ||
532
              PPC::VRRCRegClass.contains(Reg) ||
533
              PPC::VSFRCRegClass.contains(Reg) ||
534
              PPC::VSSRCRegClass.contains(Reg)
535
              )
536
            llvm_unreachable("SPE targets cannot have FPRegs!");
537
        } else {
538
          if (PPC::SPERCRegClass.contains(Reg))
539
            llvm_unreachable("SPE register found in FPU-targeted code!");
540
        }
541
      }
542
    }
543
  }
544
#endif
545
  // Lower multi-instruction pseudo operations.
546
99.6k
  switch (MI->getOpcode()) {
547
99.6k
  
default: break86.1k
;
548
99.6k
  case TargetOpcode::DBG_VALUE:
549
0
    llvm_unreachable("Should be handled target independently");
550
99.6k
  case TargetOpcode::STACKMAP:
551
17
    return LowerSTACKMAP(SM, *MI);
552
99.6k
  case TargetOpcode::PATCHPOINT:
553
40
    return LowerPATCHPOINT(SM, *MI);
554
99.6k
555
99.6k
  case PPC::MoveGOTtoLR: {
556
1
    // Transform %lr = MoveGOTtoLR
557
1
    // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
558
1
    // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
559
1
    // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
560
1
    //      blrl
561
1
    // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
562
1
    MCSymbol *GOTSymbol =
563
1
      OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
564
1
    const MCExpr *OffsExpr =
565
1
      MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
566
1
                                                      MCSymbolRefExpr::VK_PPC_LOCAL,
567
1
                                                      OutContext),
568
1
                              MCConstantExpr::create(4, OutContext),
569
1
                              OutContext);
570
1
571
1
    // Emit the 'bl'.
572
1
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
573
1
    return;
574
99.6k
  }
575
99.6k
  case PPC::MovePCtoLR:
576
26
  case PPC::MovePCtoLR8: {
577
26
    // Transform %lr = MovePCtoLR
578
26
    // Into this, where the label is the PIC base:
579
26
    //     bl L1$pb
580
26
    // L1$pb:
581
26
    MCSymbol *PICBase = MF->getPICBaseSymbol();
582
26
583
26
    // Emit the 'bl'.
584
26
    EmitToStreamer(*OutStreamer,
585
26
                   MCInstBuilder(PPC::BL)
586
26
                       // FIXME: We would like an efficient form for this, so we
587
26
                       // don't have to do a lot of extra uniquing.
588
26
                       .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
589
26
590
26
    // Emit the label.
591
26
    OutStreamer->EmitLabel(PICBase);
592
26
    return;
593
26
  }
594
26
  case PPC::UpdateGBR: {
595
22
    // Transform %rd = UpdateGBR(%rt, %ri)
596
22
    // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
597
22
    //       add %rd, %rt, %ri
598
22
    // or into (if secure plt mode is on):
599
22
    //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
600
22
    //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
601
22
    // Get the offset from the GOT Base Register to the GOT
602
22
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
603
22
    if (Subtarget->isSecurePlt() && 
isPositionIndependent()10
) {
604
10
      unsigned PICR = TmpInst.getOperand(0).getReg();
605
10
      MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
606
10
          M->getPICLevel() == PICLevel::SmallPIC ? 
"_GLOBAL_OFFSET_TABLE_"2
607
10
                                                 : 
".LTOC"8
);
608
10
      const MCExpr *PB =
609
10
          MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
610
10
611
10
      const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
612
10
          MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
613
10
614
10
      const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, false, OutContext);
615
10
      EmitToStreamer(
616
10
          *OutStreamer,
617
10
          MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
618
10
619
10
      const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, false, OutContext);
620
10
      EmitToStreamer(
621
10
          *OutStreamer,
622
10
          MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
623
10
      return;
624
12
    } else {
625
12
      MCSymbol *PICOffset =
626
12
        MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol();
627
12
      TmpInst.setOpcode(PPC::LWZ);
628
12
      const MCExpr *Exp =
629
12
        MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
630
12
      const MCExpr *PB =
631
12
        MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
632
12
                                MCSymbolRefExpr::VK_None,
633
12
                                OutContext);
634
12
      const MCOperand TR = TmpInst.getOperand(1);
635
12
      const MCOperand PICR = TmpInst.getOperand(0);
636
12
637
12
      // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
638
12
      TmpInst.getOperand(1) =
639
12
          MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
640
12
      TmpInst.getOperand(0) = TR;
641
12
      TmpInst.getOperand(2) = PICR;
642
12
      EmitToStreamer(*OutStreamer, TmpInst);
643
12
644
12
      TmpInst.setOpcode(PPC::ADD4);
645
12
      TmpInst.getOperand(0) = PICR;
646
12
      TmpInst.getOperand(1) = TR;
647
12
      TmpInst.getOperand(2) = PICR;
648
12
      EmitToStreamer(*OutStreamer, TmpInst);
649
12
      return;
650
12
    }
651
0
  }
652
32
  case PPC::LWZtoc: {
653
32
    // Transform %r3 = LWZtoc @min1, %r2
654
32
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
655
32
656
32
    // Change the opcode to LWZ, and the global address operand to be a
657
32
    // reference to the GOT entry we will synthesize later.
658
32
    TmpInst.setOpcode(PPC::LWZ);
659
32
    const MachineOperand &MO = MI->getOperand(1);
660
32
661
32
    // Map symbol -> label of TOC entry
662
32
    assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
663
32
    MCSymbol *MOSymbol = nullptr;
664
32
    if (MO.isGlobal())
665
18
      MOSymbol = getSymbol(MO.getGlobal());
666
14
    else if (MO.isCPI())
667
11
      MOSymbol = GetCPISymbol(MO.getIndex());
668
3
    else if (MO.isJTI())
669
0
      MOSymbol = GetJTISymbol(MO.getIndex());
670
3
    else if (MO.isBlockAddress())
671
3
      MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
672
32
673
32
    if (PL == PICLevel::SmallPIC) {
674
2
      const MCExpr *Exp =
675
2
        MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
676
2
                                OutContext);
677
2
      TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
678
30
    } else {
679
30
      MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
680
30
681
30
      const MCExpr *Exp =
682
30
        MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None,
683
30
                                OutContext);
684
30
      const MCExpr *PB =
685
30
        MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
686
30
                                                             OutContext);
687
30
      Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
688
30
      TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
689
30
    }
690
32
    EmitToStreamer(*OutStreamer, TmpInst);
691
32
    return;
692
0
  }
693
12
  case PPC::LDtocJTI:
694
12
  case PPC::LDtocCPT:
695
12
  case PPC::LDtocBA:
696
12
  case PPC::LDtoc: {
697
12
    // Transform %x3 = LDtoc @min1, %x2
698
12
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
699
12
700
12
    // Change the opcode to LD, and the global address operand to be a
701
12
    // reference to the TOC entry we will synthesize later.
702
12
    TmpInst.setOpcode(PPC::LD);
703
12
    const MachineOperand &MO = MI->getOperand(1);
704
12
705
12
    // Map symbol -> label of TOC entry
706
12
    assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
707
12
    MCSymbol *MOSymbol = nullptr;
708
12
    if (MO.isGlobal())
709
6
      MOSymbol = getSymbol(MO.getGlobal());
710
6
    else if (MO.isCPI())
711
4
      MOSymbol = GetCPISymbol(MO.getIndex());
712
2
    else if (MO.isJTI())
713
0
      MOSymbol = GetJTISymbol(MO.getIndex());
714
2
    else if (MO.isBlockAddress())
715
2
      MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
716
12
717
12
    MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
718
12
719
12
    const MCExpr *Exp =
720
12
      MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC,
721
12
                              OutContext);
722
12
    TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
723
12
    EmitToStreamer(*OutStreamer, TmpInst);
724
12
    return;
725
12
  }
726
12
727
3.47k
  case PPC::ADDIStocHA8: {
728
3.47k
    // Transform %xd = ADDIStocHA8 %x2, @sym
729
3.47k
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
730
3.47k
731
3.47k
    // Change the opcode to ADDIS8.  If the global address is external, has
732
3.47k
    // common linkage, is a non-local function address, or is a jump table
733
3.47k
    // address, then generate a TOC entry and reference that.  Otherwise
734
3.47k
    // reference the symbol directly.
735
3.47k
    TmpInst.setOpcode(PPC::ADDIS8);
736
3.47k
    const MachineOperand &MO = MI->getOperand(2);
737
3.47k
    assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
738
3.47k
            MO.isBlockAddress()) &&
739
3.47k
           "Invalid operand for ADDIStocHA8!");
740
3.47k
    MCSymbol *MOSymbol = nullptr;
741
3.47k
    bool GlobalToc = false;
742
3.47k
743
3.47k
    if (MO.isGlobal()) {
744
1.76k
      const GlobalValue *GV = MO.getGlobal();
745
1.76k
      MOSymbol = getSymbol(GV);
746
1.76k
      unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
747
1.76k
      GlobalToc = (GVFlags & PPCII::MO_NLP_FLAG);
748
1.76k
    } else 
if (1.71k
MO.isCPI()1.71k
) {
749
1.70k
      MOSymbol = GetCPISymbol(MO.getIndex());
750
1.70k
    } else 
if (17
MO.isJTI()17
) {
751
10
      MOSymbol = GetJTISymbol(MO.getIndex());
752
10
    } else 
if (7
MO.isBlockAddress()7
) {
753
7
      MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
754
7
    }
755
3.47k
756
3.47k
    if (GlobalToc || 
MO.isJTI()2.50k
||
MO.isBlockAddress()2.49k
||
757
3.47k
        
TM.getCodeModel() == CodeModel::Large2.48k
)
758
999
      MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
759
3.47k
760
3.47k
    const MCExpr *Exp =
761
3.47k
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_HA,
762
3.47k
                              OutContext);
763
3.47k
764
3.47k
    if (!MO.isJTI() && 
MO.getOffset()3.46k
)
765
5
      Exp = MCBinaryExpr::createAdd(Exp,
766
5
                                    MCConstantExpr::create(MO.getOffset(),
767
5
                                                           OutContext),
768
5
                                    OutContext);
769
3.47k
770
3.47k
    TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
771
3.47k
    EmitToStreamer(*OutStreamer, TmpInst);
772
3.47k
    return;
773
12
  }
774
999
  case PPC::LDtocL: {
775
999
    // Transform %xd = LDtocL @sym, %xs
776
999
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
777
999
778
999
    // Change the opcode to LD.  If the global address is external, has
779
999
    // common linkage, or is a jump table address, then reference the
780
999
    // associated TOC entry.  Otherwise reference the symbol directly.
781
999
    TmpInst.setOpcode(PPC::LD);
782
999
    const MachineOperand &MO = MI->getOperand(1);
783
999
    assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
784
999
            MO.isBlockAddress()) &&
785
999
           "Invalid operand for LDtocL!");
786
999
    MCSymbol *MOSymbol = nullptr;
787
999
788
999
    if (MO.isJTI())
789
10
      MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
790
989
    else if (MO.isBlockAddress()) {
791
7
      MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
792
7
      MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
793
7
    }
794
982
    else if (MO.isCPI()) {
795
5
      MOSymbol = GetCPISymbol(MO.getIndex());
796
5
      if (TM.getCodeModel() == CodeModel::Large)
797
5
        MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
798
5
    }
799
977
    else if (MO.isGlobal()) {
800
977
      const GlobalValue *GV = MO.getGlobal();
801
977
      MOSymbol = getSymbol(GV);
802
977
      LLVM_DEBUG(
803
977
          unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
804
977
          assert((GVFlags & PPCII::MO_NLP_FLAG) &&
805
977
                 "LDtocL used on symbol that could be accessed directly is "
806
977
                 "invalid. Must match ADDIStocHA8."));
807
977
      MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
808
977
    }
809
999
810
999
    const MCExpr *Exp =
811
999
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
812
999
                              OutContext);
813
999
    TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
814
999
    EmitToStreamer(*OutStreamer, TmpInst);
815
999
    return;
816
12
  }
817
1.34k
  case PPC::ADDItocL: {
818
1.34k
    // Transform %xd = ADDItocL %xs, @sym
819
1.34k
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
820
1.34k
821
1.34k
    // Change the opcode to ADDI8.  If the global address is external, then
822
1.34k
    // generate a TOC entry and reference that.  Otherwise reference the
823
1.34k
    // symbol directly.
824
1.34k
    TmpInst.setOpcode(PPC::ADDI8);
825
1.34k
    const MachineOperand &MO = MI->getOperand(2);
826
1.34k
    assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
827
1.34k
    MCSymbol *MOSymbol = nullptr;
828
1.34k
829
1.34k
    if (MO.isGlobal()) {
830
398
      const GlobalValue *GV = MO.getGlobal();
831
398
      LLVM_DEBUG(unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
832
398
                 assert(!(GVFlags & PPCII::MO_NLP_FLAG) &&
833
398
                        "Interposable definitions must use indirect access."));
834
398
      MOSymbol = getSymbol(GV);
835
944
    } else if (MO.isCPI()) {
836
944
      MOSymbol = GetCPISymbol(MO.getIndex());
837
944
    }
838
1.34k
839
1.34k
    const MCExpr *Exp =
840
1.34k
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
841
1.34k
                              OutContext);
842
1.34k
    TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
843
1.34k
    EmitToStreamer(*OutStreamer, TmpInst);
844
1.34k
    return;
845
12
  }
846
15
  case PPC::ADDISgotTprelHA: {
847
15
    // Transform: %xd = ADDISgotTprelHA %x2, @sym
848
15
    // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
849
15
    assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
850
15
    const MachineOperand &MO = MI->getOperand(2);
851
15
    const GlobalValue *GValue = MO.getGlobal();
852
15
    MCSymbol *MOSymbol = getSymbol(GValue);
853
15
    const MCExpr *SymGotTprel =
854
15
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
855
15
                              OutContext);
856
15
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
857
15
                                 .addReg(MI->getOperand(0).getReg())
858
15
                                 .addReg(MI->getOperand(1).getReg())
859
15
                                 .addExpr(SymGotTprel));
860
15
    return;
861
12
  }
862
17
  case PPC::LDgotTprelL:
863
17
  case PPC::LDgotTprelL32: {
864
17
    // Transform %xd = LDgotTprelL @sym, %xs
865
17
    LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
866
17
867
17
    // Change the opcode to LD.
868
17
    TmpInst.setOpcode(isPPC64 ? 
PPC::LD15
:
PPC::LWZ2
);
869
17
    const MachineOperand &MO = MI->getOperand(1);
870
17
    const GlobalValue *GValue = MO.getGlobal();
871
17
    MCSymbol *MOSymbol = getSymbol(GValue);
872
17
    const MCExpr *Exp =
873
17
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO,
874
17
                              OutContext);
875
17
    TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
876
17
    EmitToStreamer(*OutStreamer, TmpInst);
877
17
    return;
878
17
  }
879
17
880
17
  case PPC::PPC32PICGOT: {
881
10
    MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
882
10
    MCSymbol *GOTRef = OutContext.createTempSymbol();
883
10
    MCSymbol *NextInstr = OutContext.createTempSymbol();
884
10
885
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
886
10
      // FIXME: We would like an efficient form for this, so we don't have to do
887
10
      // a lot of extra uniquing.
888
10
      .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
889
10
    const MCExpr *OffsExpr =
890
10
      MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
891
10
                                MCSymbolRefExpr::create(GOTRef, OutContext),
892
10
        OutContext);
893
10
    OutStreamer->EmitLabel(GOTRef);
894
10
    OutStreamer->EmitValue(OffsExpr, 4);
895
10
    OutStreamer->EmitLabel(NextInstr);
896
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
897
10
                                 .addReg(MI->getOperand(0).getReg()));
898
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
899
10
                                 .addReg(MI->getOperand(1).getReg())
900
10
                                 .addImm(0)
901
10
                                 .addReg(MI->getOperand(0).getReg()));
902
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
903
10
                                 .addReg(MI->getOperand(0).getReg())
904
10
                                 .addReg(MI->getOperand(1).getReg())
905
10
                                 .addReg(MI->getOperand(0).getReg()));
906
10
    return;
907
17
  }
908
17
  case PPC::PPC32GOT: {
909
1
    MCSymbol *GOTSymbol =
910
1
        OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
911
1
    const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
912
1
        GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
913
1
    const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
914
1
        GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
915
1
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
916
1
                                 .addReg(MI->getOperand(0).getReg())
917
1
                                 .addExpr(SymGotTlsL));
918
1
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
919
1
                                 .addReg(MI->getOperand(0).getReg())
920
1
                                 .addReg(MI->getOperand(0).getReg())
921
1
                                 .addExpr(SymGotTlsHA));
922
1
    return;
923
17
  }
924
17
  case PPC::ADDIStlsgdHA: {
925
13
    // Transform: %xd = ADDIStlsgdHA %x2, @sym
926
13
    // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
927
13
    assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
928
13
    const MachineOperand &MO = MI->getOperand(2);
929
13
    const GlobalValue *GValue = MO.getGlobal();
930
13
    MCSymbol *MOSymbol = getSymbol(GValue);
931
13
    const MCExpr *SymGotTlsGD =
932
13
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
933
13
                              OutContext);
934
13
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
935
13
                                 .addReg(MI->getOperand(0).getReg())
936
13
                                 .addReg(MI->getOperand(1).getReg())
937
13
                                 .addExpr(SymGotTlsGD));
938
13
    return;
939
17
  }
940
20
  case PPC::ADDItlsgdL:
941
20
    // Transform: %xd = ADDItlsgdL %xs, @sym
942
20
    // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
943
20
  case PPC::ADDItlsgdL32: {
944
20
    // Transform: %rd = ADDItlsgdL32 %rs, @sym
945
20
    // Into:      %rd = ADDI %rs, sym@got@tlsgd
946
20
    const MachineOperand &MO = MI->getOperand(2);
947
20
    const GlobalValue *GValue = MO.getGlobal();
948
20
    MCSymbol *MOSymbol = getSymbol(GValue);
949
20
    const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
950
20
        MOSymbol, Subtarget->isPPC64() ? 
MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO13
951
20
                                       : 
MCSymbolRefExpr::VK_PPC_GOT_TLSGD7
,
952
20
        OutContext);
953
20
    EmitToStreamer(*OutStreamer,
954
20
                   MCInstBuilder(Subtarget->isPPC64() ? 
PPC::ADDI813
:
PPC::ADDI7
)
955
20
                   .addReg(MI->getOperand(0).getReg())
956
20
                   .addReg(MI->getOperand(1).getReg())
957
20
                   .addExpr(SymGotTlsGD));
958
20
    return;
959
20
  }
960
20
  case PPC::GETtlsADDR:
961
20
    // Transform: %x3 = GETtlsADDR %x3, @sym
962
20
    // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
963
20
  case PPC::GETtlsADDR32: {
964
20
    // Transform: %r3 = GETtlsADDR32 %r3, @sym
965
20
    // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
966
20
    EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
967
20
    return;
968
20
  }
969
20
  case PPC::ADDIStlsldHA: {
970
6
    // Transform: %xd = ADDIStlsldHA %x2, @sym
971
6
    // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
972
6
    assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
973
6
    const MachineOperand &MO = MI->getOperand(2);
974
6
    const GlobalValue *GValue = MO.getGlobal();
975
6
    MCSymbol *MOSymbol = getSymbol(GValue);
976
6
    const MCExpr *SymGotTlsLD =
977
6
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
978
6
                              OutContext);
979
6
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
980
6
                                 .addReg(MI->getOperand(0).getReg())
981
6
                                 .addReg(MI->getOperand(1).getReg())
982
6
                                 .addExpr(SymGotTlsLD));
983
6
    return;
984
20
  }
985
20
  case PPC::ADDItlsldL:
986
9
    // Transform: %xd = ADDItlsldL %xs, @sym
987
9
    // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
988
9
  case PPC::ADDItlsldL32: {
989
9
    // Transform: %rd = ADDItlsldL32 %rs, @sym
990
9
    // Into:      %rd = ADDI %rs, sym@got@tlsld
991
9
    const MachineOperand &MO = MI->getOperand(2);
992
9
    const GlobalValue *GValue = MO.getGlobal();
993
9
    MCSymbol *MOSymbol = getSymbol(GValue);
994
9
    const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
995
9
        MOSymbol, Subtarget->isPPC64() ? 
MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO6
996
9
                                       : 
MCSymbolRefExpr::VK_PPC_GOT_TLSLD3
,
997
9
        OutContext);
998
9
    EmitToStreamer(*OutStreamer,
999
9
                   MCInstBuilder(Subtarget->isPPC64() ? 
PPC::ADDI86
:
PPC::ADDI3
)
1000
9
                       .addReg(MI->getOperand(0).getReg())
1001
9
                       .addReg(MI->getOperand(1).getReg())
1002
9
                       .addExpr(SymGotTlsLD));
1003
9
    return;
1004
9
  }
1005
9
  case PPC::GETtlsldADDR:
1006
9
    // Transform: %x3 = GETtlsldADDR %x3, @sym
1007
9
    // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1008
9
  case PPC::GETtlsldADDR32: {
1009
9
    // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1010
9
    // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1011
9
    EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1012
9
    return;
1013
9
  }
1014
9
  case PPC::ADDISdtprelHA:
1015
9
    // Transform: %xd = ADDISdtprelHA %xs, @sym
1016
9
    // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1017
9
  case PPC::ADDISdtprelHA32: {
1018
9
    // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1019
9
    // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1020
9
    const MachineOperand &MO = MI->getOperand(2);
1021
9
    const GlobalValue *GValue = MO.getGlobal();
1022
9
    MCSymbol *MOSymbol = getSymbol(GValue);
1023
9
    const MCExpr *SymDtprel =
1024
9
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1025
9
                              OutContext);
1026
9
    EmitToStreamer(
1027
9
        *OutStreamer,
1028
9
        MCInstBuilder(Subtarget->isPPC64() ? 
PPC::ADDIS86
:
PPC::ADDIS3
)
1029
9
            .addReg(MI->getOperand(0).getReg())
1030
9
            .addReg(MI->getOperand(1).getReg())
1031
9
            .addExpr(SymDtprel));
1032
9
    return;
1033
9
  }
1034
9
  case PPC::ADDIdtprelL:
1035
5
    // Transform: %xd = ADDIdtprelL %xs, @sym
1036
5
    // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1037
5
  case PPC::ADDIdtprelL32: {
1038
5
    // Transform: %rd = ADDIdtprelL32 %rs, @sym
1039
5
    // Into:      %rd = ADDI %rs, sym@dtprel@l
1040
5
    const MachineOperand &MO = MI->getOperand(2);
1041
5
    const GlobalValue *GValue = MO.getGlobal();
1042
5
    MCSymbol *MOSymbol = getSymbol(GValue);
1043
5
    const MCExpr *SymDtprel =
1044
5
      MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1045
5
                              OutContext);
1046
5
    EmitToStreamer(*OutStreamer,
1047
5
                   MCInstBuilder(Subtarget->isPPC64() ? 
PPC::ADDI82
:
PPC::ADDI3
)
1048
5
                       .addReg(MI->getOperand(0).getReg())
1049
5
                       .addReg(MI->getOperand(1).getReg())
1050
5
                       .addExpr(SymDtprel));
1051
5
    return;
1052
5
  }
1053
68
  case PPC::MFOCRF:
1054
68
  case PPC::MFOCRF8:
1055
68
    if (!Subtarget->hasMFOCRF()) {
1056
16
      // Transform: %r3 = MFOCRF %cr7
1057
16
      // Into:      %r3 = MFCR   ;; cr7
1058
16
      unsigned NewOpcode =
1059
16
        MI->getOpcode() == PPC::MFOCRF ? 
PPC::MFCR8
:
PPC::MFCR88
;
1060
16
      OutStreamer->AddComment(PPCInstPrinter::
1061
16
                              getRegisterName(MI->getOperand(1).getReg()));
1062
16
      EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1063
16
                                  .addReg(MI->getOperand(0).getReg()));
1064
16
      return;
1065
16
    }
1066
52
    break;
1067
122
  case PPC::MTOCRF:
1068
122
  case PPC::MTOCRF8:
1069
122
    if (!Subtarget->hasMFOCRF()) {
1070
37
      // Transform: %cr7 = MTOCRF %r3
1071
37
      // Into:      MTCRF mask, %r3 ;; cr7
1072
37
      unsigned NewOpcode =
1073
37
        MI->getOpcode() == PPC::MTOCRF ? 
PPC::MTCRF19
:
PPC::MTCRF818
;
1074
37
      unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1075
37
                              ->getEncodingValue(MI->getOperand(0).getReg());
1076
37
      OutStreamer->AddComment(PPCInstPrinter::
1077
37
                              getRegisterName(MI->getOperand(0).getReg()));
1078
37
      EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1079
37
                                     .addImm(Mask)
1080
37
                                     .addReg(MI->getOperand(1).getReg()));
1081
37
      return;
1082
37
    }
1083
85
    break;
1084
7.20k
  case PPC::LD:
1085
7.20k
  case PPC::STD:
1086
7.20k
  case PPC::LWA_32:
1087
7.20k
  case PPC::LWA: {
1088
7.20k
    // Verify alignment is legal, so we don't create relocations
1089
7.20k
    // that can't be supported.
1090
7.20k
    // FIXME:  This test is currently disabled for Darwin.  The test
1091
7.20k
    // suite shows a handful of test cases that fail this check for
1092
7.20k
    // Darwin.  Those need to be investigated before this sanity test
1093
7.20k
    // can be enabled for those subtargets.
1094
7.20k
    if (!Subtarget->isDarwin()) {
1095
7.20k
      unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 
23.72k
:
13.48k
;
1096
7.20k
      const MachineOperand &MO = MI->getOperand(OpNum);
1097
7.20k
      if (MO.isGlobal() && 
MO.getGlobal()->getAlignment() < 442
)
1098
7.20k
        
llvm_unreachable0
("Global must be word-aligned for LD, STD, LWA!");
1099
7.20k
    }
1100
7.20k
    // Now process the instruction normally.
1101
7.20k
    break;
1102
93.5k
  }
1103
93.5k
  }
1104
93.5k
1105
93.5k
  LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
1106
93.5k
  EmitToStreamer(*OutStreamer, TmpInst);
1107
93.5k
}
1108
1109
99.7k
void PPCLinuxAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1110
99.7k
  if (!Subtarget->isPPC64())
1111
11.7k
    return PPCAsmPrinter::EmitInstruction(MI);
1112
87.9k
1113
87.9k
  switch (MI->getOpcode()) {
1114
87.9k
  default:
1115
87.9k
    return PPCAsmPrinter::EmitInstruction(MI);
1116
87.9k
  case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1117
8
    // .begin:
1118
8
    //   b .end # lis 0, FuncId[16..32]
1119
8
    //   nop    # li  0, FuncId[0..15]
1120
8
    //   std 0, -8(1)
1121
8
    //   mflr 0
1122
8
    //   bl __xray_FunctionEntry
1123
8
    //   mtlr 0
1124
8
    // .end:
1125
8
    //
1126
8
    // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1127
8
    // of instructions change.
1128
8
    MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1129
8
    MCSymbol *EndOfSled = OutContext.createTempSymbol();
1130
8
    OutStreamer->EmitLabel(BeginOfSled);
1131
8
    EmitToStreamer(*OutStreamer,
1132
8
                   MCInstBuilder(PPC::B).addExpr(
1133
8
                       MCSymbolRefExpr::create(EndOfSled, OutContext)));
1134
8
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1135
8
    EmitToStreamer(
1136
8
        *OutStreamer,
1137
8
        MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1138
8
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1139
8
    EmitToStreamer(*OutStreamer,
1140
8
                   MCInstBuilder(PPC::BL8_NOP)
1141
8
                       .addExpr(MCSymbolRefExpr::create(
1142
8
                           OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1143
8
                           OutContext)));
1144
8
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1145
8
    OutStreamer->EmitLabel(EndOfSled);
1146
8
    recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER);
1147
8
    break;
1148
87.9k
  }
1149
87.9k
  case TargetOpcode::PATCHABLE_RET: {
1150
11
    unsigned RetOpcode = MI->getOperand(0).getImm();
1151
11
    MCInst RetInst;
1152
11
    RetInst.setOpcode(RetOpcode);
1153
11
    for (const auto &MO :
1154
33
         make_range(std::next(MI->operands_begin()), MI->operands_end())) {
1155
33
      MCOperand MCOp;
1156
33
      if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this, false))
1157
32
        RetInst.addOperand(MCOp);
1158
33
    }
1159
11
1160
11
    bool IsConditional;
1161
11
    if (RetOpcode == PPC::BCCLR) {
1162
2
      IsConditional = true;
1163
9
    } else if (RetOpcode == PPC::TCRETURNdi8 || 
RetOpcode == PPC::TCRETURNri88
||
1164
9
               
RetOpcode == PPC::TCRETURNai88
) {
1165
1
      break;
1166
8
    } else if (RetOpcode == PPC::BLR8 || 
RetOpcode == PPC::TAILB81
) {
1167
8
      IsConditional = false;
1168
8
    } else {
1169
0
      EmitToStreamer(*OutStreamer, RetInst);
1170
0
      break;
1171
0
    }
1172
10
1173
10
    MCSymbol *FallthroughLabel;
1174
10
    if (IsConditional) {
1175
2
      // Before:
1176
2
      //   bgtlr cr0
1177
2
      //
1178
2
      // After:
1179
2
      //   ble cr0, .end
1180
2
      // .p2align 3
1181
2
      // .begin:
1182
2
      //   blr    # lis 0, FuncId[16..32]
1183
2
      //   nop    # li  0, FuncId[0..15]
1184
2
      //   std 0, -8(1)
1185
2
      //   mflr 0
1186
2
      //   bl __xray_FunctionExit
1187
2
      //   mtlr 0
1188
2
      //   blr
1189
2
      // .end:
1190
2
      //
1191
2
      // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1192
2
      // of instructions change.
1193
2
      FallthroughLabel = OutContext.createTempSymbol();
1194
2
      EmitToStreamer(
1195
2
          *OutStreamer,
1196
2
          MCInstBuilder(PPC::BCC)
1197
2
              .addImm(PPC::InvertPredicate(
1198
2
                  static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1199
2
              .addReg(MI->getOperand(2).getReg())
1200
2
              .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1201
2
      RetInst = MCInst();
1202
2
      RetInst.setOpcode(PPC::BLR8);
1203
2
    }
1204
10
    // .p2align 3
1205
10
    // .begin:
1206
10
    //   b(lr)? # lis 0, FuncId[16..32]
1207
10
    //   nop    # li  0, FuncId[0..15]
1208
10
    //   std 0, -8(1)
1209
10
    //   mflr 0
1210
10
    //   bl __xray_FunctionExit
1211
10
    //   mtlr 0
1212
10
    //   b(lr)?
1213
10
    //
1214
10
    // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1215
10
    // of instructions change.
1216
10
    OutStreamer->EmitCodeAlignment(8);
1217
10
    MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1218
10
    OutStreamer->EmitLabel(BeginOfSled);
1219
10
    EmitToStreamer(*OutStreamer, RetInst);
1220
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1221
10
    EmitToStreamer(
1222
10
        *OutStreamer,
1223
10
        MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1224
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1225
10
    EmitToStreamer(*OutStreamer,
1226
10
                   MCInstBuilder(PPC::BL8_NOP)
1227
10
                       .addExpr(MCSymbolRefExpr::create(
1228
10
                           OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1229
10
                           OutContext)));
1230
10
    EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1231
10
    EmitToStreamer(*OutStreamer, RetInst);
1232
10
    if (IsConditional)
1233
2
      OutStreamer->EmitLabel(FallthroughLabel);
1234
10
    recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT);
1235
10
    break;
1236
10
  }
1237
10
  case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1238
0
    llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1239
10
  case TargetOpcode::PATCHABLE_TAIL_CALL:
1240
0
    // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1241
0
    // normal function exit from a tail exit.
1242
0
    llvm_unreachable("Tail call is handled in the normal case. See comments "
1243
87.9k
                     "around this assert.");
1244
87.9k
  }
1245
87.9k
}
1246
1247
1.76k
void PPCLinuxAsmPrinter::EmitStartOfAsmFile(Module &M) {
1248
1.76k
  if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1249
565
    PPCTargetStreamer *TS =
1250
565
      static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1251
565
1252
565
    if (TS)
1253
565
      TS->emitAbiVersion(2);
1254
565
  }
1255
1.76k
1256
1.76k
  if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1257
1.76k
      
!isPositionIndependent()388
)
1258
1.72k
    return AsmPrinter::EmitStartOfAsmFile(M);
1259
32
1260
32
  if (M.getPICLevel() == PICLevel::SmallPIC)
1261
3
    return AsmPrinter::EmitStartOfAsmFile(M);
1262
29
1263
29
  OutStreamer->SwitchSection(OutContext.getELFSection(
1264
29
      ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1265
29
1266
29
  MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1267
29
  MCSymbol *CurrentPos = OutContext.createTempSymbol();
1268
29
1269
29
  OutStreamer->EmitLabel(CurrentPos);
1270
29
1271
29
  // The GOT pointer points to the middle of the GOT, in order to reference the
1272
29
  // entire 64kB range.  0x8000 is the midpoint.
1273
29
  const MCExpr *tocExpr =
1274
29
    MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1275
29
                            MCConstantExpr::create(0x8000, OutContext),
1276
29
                            OutContext);
1277
29
1278
29
  OutStreamer->EmitAssignment(TOCSym, tocExpr);
1279
29
1280
29
  OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1281
29
}
1282
1283
11.2k
void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
1284
11.2k
  // linux/ppc32 - Normal entry label.
1285
11.2k
  if (!Subtarget->isPPC64() &&
1286
11.2k
      
(1.04k
!isPositionIndependent()1.04k
||
1287
1.04k
       
MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC50
))
1288
994
    return AsmPrinter::EmitFunctionEntryLabel();
1289
10.2k
1290
10.2k
  if (!Subtarget->isPPC64()) {
1291
47
    const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1292
47
    if (PPCFI->usesPICBase() && 
!Subtarget->isSecurePlt()20
) {
1293
12
      MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol();
1294
12
      MCSymbol *PICBase = MF->getPICBaseSymbol();
1295
12
      OutStreamer->EmitLabel(RelocSymbol);
1296
12
1297
12
      const MCExpr *OffsExpr =
1298
12
        MCBinaryExpr::createSub(
1299
12
          MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1300
12
                                                               OutContext),
1301
12
                                  MCSymbolRefExpr::create(PICBase, OutContext),
1302
12
          OutContext);
1303
12
      OutStreamer->EmitValue(OffsExpr, 4);
1304
12
      OutStreamer->EmitLabel(CurrentFnSym);
1305
12
      return;
1306
12
    } else
1307
35
      return AsmPrinter::EmitFunctionEntryLabel();
1308
10.2k
  }
1309
10.2k
1310
10.2k
  // ELFv2 ABI - Normal entry label.
1311
10.2k
  if (Subtarget->isELFv2ABI()) {
1312
5.31k
    // In the Large code model, we allow arbitrary displacements between
1313
5.31k
    // the text section and its associated TOC section.  We place the
1314
5.31k
    // full 8-byte offset to the TOC in memory immediately preceding
1315
5.31k
    // the function global entry point.
1316
5.31k
    if (TM.getCodeModel() == CodeModel::Large
1317
5.31k
        && 
!MF->getRegInfo().use_empty(PPC::X2)5
) {
1318
4
      const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1319
4
1320
4
      MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1321
4
      MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol();
1322
4
      const MCExpr *TOCDeltaExpr =
1323
4
        MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1324
4
                                MCSymbolRefExpr::create(GlobalEPSymbol,
1325
4
                                                        OutContext),
1326
4
                                OutContext);
1327
4
1328
4
      OutStreamer->EmitLabel(PPCFI->getTOCOffsetSymbol());
1329
4
      OutStreamer->EmitValue(TOCDeltaExpr, 8);
1330
4
    }
1331
5.31k
    return AsmPrinter::EmitFunctionEntryLabel();
1332
5.31k
  }
1333
4.91k
1334
4.91k
  // Emit an official procedure descriptor.
1335
4.91k
  MCSectionSubPair Current = OutStreamer->getCurrentSection();
1336
4.91k
  MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1337
4.91k
      ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1338
4.91k
  OutStreamer->SwitchSection(Section);
1339
4.91k
  OutStreamer->EmitLabel(CurrentFnSym);
1340
4.91k
  OutStreamer->EmitValueToAlignment(8);
1341
4.91k
  MCSymbol *Symbol1 = CurrentFnSymForSize;
1342
4.91k
  // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1343
4.91k
  // entry point.
1344
4.91k
  OutStreamer->EmitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1345
4.91k
                         8 /*size*/);
1346
4.91k
  MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1347
4.91k
  // Generates a R_PPC64_TOC relocation for TOC base insertion.
1348
4.91k
  OutStreamer->EmitValue(
1349
4.91k
    MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1350
4.91k
    8/*size*/);
1351
4.91k
  // Emit a null environment pointer.
1352
4.91k
  OutStreamer->EmitIntValue(0, 8 /* size */);
1353
4.91k
  OutStreamer->SwitchSection(Current.first, Current.second);
1354
4.91k
}
1355
1356
1.75k
bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
1357
1.75k
  const DataLayout &DL = getDataLayout();
1358
1.75k
1359
1.75k
  bool isPPC64 = DL.getPointerSizeInBits() == 64;
1360
1.75k
1361
1.75k
  PPCTargetStreamer &TS =
1362
1.75k
      static_cast<PPCTargetStreamer &>(*OutStreamer->getTargetStreamer());
1363
1.75k
1364
1.75k
  if (!TOC.empty()) {
1365
296
    MCSectionELF *Section;
1366
296
1367
296
    if (isPPC64)
1368
279
      Section = OutStreamer->getContext().getELFSection(
1369
279
          ".toc", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1370
17
        else
1371
17
          Section = OutStreamer->getContext().getELFSection(
1372
17
              ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1373
296
    OutStreamer->SwitchSection(Section);
1374
296
1375
296
    for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
1376
887
         E = TOC.end(); I != E; 
++I591
) {
1377
591
      OutStreamer->EmitLabel(I->second);
1378
591
      MCSymbol *S = I->first;
1379
591
      if (isPPC64) {
1380
562
        TS.emitTCEntry(*S);
1381
562
      } else {
1382
29
        OutStreamer->EmitValueToAlignment(4);
1383
29
        OutStreamer->EmitSymbolValue(S, 4);
1384
29
      }
1385
591
    }
1386
296
  }
1387
1.75k
1388
1.75k
  return AsmPrinter::doFinalization(M);
1389
1.75k
}
1390
1391
/// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1392
11.2k
void PPCLinuxAsmPrinter::EmitFunctionBodyStart() {
1393
11.2k
  // In the ELFv2 ABI, in functions that use the TOC register, we need to
1394
11.2k
  // provide two entry points.  The ABI guarantees that when calling the
1395
11.2k
  // local entry point, r2 is set up by the caller to contain the TOC base
1396
11.2k
  // for this function, and when calling the global entry point, r12 is set
1397
11.2k
  // up by the caller to hold the address of the global entry point.  We
1398
11.2k
  // thus emit a prefix sequence along the following lines:
1399
11.2k
  //
1400
11.2k
  // func:
1401
11.2k
  // .Lfunc_gepNN:
1402
11.2k
  //         # global entry point
1403
11.2k
  //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1404
11.2k
  //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1405
11.2k
  // .Lfunc_lepNN:
1406
11.2k
  //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1407
11.2k
  //         # local entry point, followed by function body
1408
11.2k
  //
1409
11.2k
  // For the Large code model, we create
1410
11.2k
  //
1411
11.2k
  // .Lfunc_tocNN:
1412
11.2k
  //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1413
11.2k
  // func:
1414
11.2k
  // .Lfunc_gepNN:
1415
11.2k
  //         # global entry point
1416
11.2k
  //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1417
11.2k
  //         add   r2,r2,r12
1418
11.2k
  // .Lfunc_lepNN:
1419
11.2k
  //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1420
11.2k
  //         # local entry point, followed by function body
1421
11.2k
  //
1422
11.2k
  // This ensures we have r2 set up correctly while executing the function
1423
11.2k
  // body, no matter which entry point is called.
1424
11.2k
  if (Subtarget->isELFv2ABI()
1425
11.2k
      // Only do all that if the function uses r2 in the first place.
1426
11.2k
      && 
!MF->getRegInfo().use_empty(PPC::X2)5.31k
) {
1427
1.54k
    // Note: The logic here must be synchronized with the code in the
1428
1.54k
    // branch-selection pass which sets the offset of the first block in the
1429
1.54k
    // function. This matters because it affects the alignment.
1430
1.54k
    const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1431
1.54k
1432
1.54k
    MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol();
1433
1.54k
    OutStreamer->EmitLabel(GlobalEntryLabel);
1434
1.54k
    const MCSymbolRefExpr *GlobalEntryLabelExp =
1435
1.54k
      MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1436
1.54k
1437
1.54k
    if (TM.getCodeModel() != CodeModel::Large) {
1438
1.54k
      MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1439
1.54k
      const MCExpr *TOCDeltaExpr =
1440
1.54k
        MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1441
1.54k
                                GlobalEntryLabelExp, OutContext);
1442
1.54k
1443
1.54k
      const MCExpr *TOCDeltaHi =
1444
1.54k
        PPCMCExpr::createHa(TOCDeltaExpr, false, OutContext);
1445
1.54k
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1446
1.54k
                                   .addReg(PPC::X2)
1447
1.54k
                                   .addReg(PPC::X12)
1448
1.54k
                                   .addExpr(TOCDeltaHi));
1449
1.54k
1450
1.54k
      const MCExpr *TOCDeltaLo =
1451
1.54k
        PPCMCExpr::createLo(TOCDeltaExpr, false, OutContext);
1452
1.54k
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1453
1.54k
                                   .addReg(PPC::X2)
1454
1.54k
                                   .addReg(PPC::X2)
1455
1.54k
                                   .addExpr(TOCDeltaLo));
1456
1.54k
    } else {
1457
4
      MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol();
1458
4
      const MCExpr *TOCOffsetDeltaExpr =
1459
4
        MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1460
4
                                GlobalEntryLabelExp, OutContext);
1461
4
1462
4
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1463
4
                                   .addReg(PPC::X2)
1464
4
                                   .addExpr(TOCOffsetDeltaExpr)
1465
4
                                   .addReg(PPC::X12));
1466
4
      EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1467
4
                                   .addReg(PPC::X2)
1468
4
                                   .addReg(PPC::X2)
1469
4
                                   .addReg(PPC::X12));
1470
4
    }
1471
1.54k
1472
1.54k
    MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol();
1473
1.54k
    OutStreamer->EmitLabel(LocalEntryLabel);
1474
1.54k
    const MCSymbolRefExpr *LocalEntryLabelExp =
1475
1.54k
       MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1476
1.54k
    const MCExpr *LocalOffsetExp =
1477
1.54k
      MCBinaryExpr::createSub(LocalEntryLabelExp,
1478
1.54k
                              GlobalEntryLabelExp, OutContext);
1479
1.54k
1480
1.54k
    PPCTargetStreamer *TS =
1481
1.54k
      static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1482
1.54k
1483
1.54k
    if (TS)
1484
1.54k
      TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1485
1.54k
  }
1486
11.2k
}
1487
1488
/// EmitFunctionBodyEnd - Print the traceback table before the .size
1489
/// directive.
1490
///
1491
11.2k
void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
1492
11.2k
  // Only the 64-bit target requires a traceback table.  For now,
1493
11.2k
  // we only emit the word of zeroes that GDB requires to find
1494
11.2k
  // the end of the function, and zeroes for the eight-byte
1495
11.2k
  // mandatory fields.
1496
11.2k
  // FIXME: We should fill in the eight-byte mandatory fields as described in
1497
11.2k
  // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1498
11.2k
  // currently make use of these fields).
1499
11.2k
  if (Subtarget->isPPC64()) {
1500
10.2k
    OutStreamer->EmitIntValue(0, 4/*size*/);
1501
10.2k
    OutStreamer->EmitIntValue(0, 8/*size*/);
1502
10.2k
  }
1503
11.2k
}
1504
1505
0
void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
1506
0
  static const char *const CPUDirectives[] = {
1507
0
    "",
1508
0
    "ppc",
1509
0
    "ppc440",
1510
0
    "ppc601",
1511
0
    "ppc602",
1512
0
    "ppc603",
1513
0
    "ppc7400",
1514
0
    "ppc750",
1515
0
    "ppc970",
1516
0
    "ppcA2",
1517
0
    "ppce500",
1518
0
    "ppce500mc",
1519
0
    "ppce5500",
1520
0
    "power3",
1521
0
    "power4",
1522
0
    "power5",
1523
0
    "power5x",
1524
0
    "power6",
1525
0
    "power6x",
1526
0
    "power7",
1527
0
    // FIXME: why is power8 missing here?
1528
0
    "ppc64",
1529
0
    "ppc64le",
1530
0
    "power9"
1531
0
  };
1532
0
1533
0
  // Get the numerically largest directive.
1534
0
  // FIXME: How should we merge darwin directives?
1535
0
  unsigned Directive = PPC::DIR_NONE;
1536
0
  for (const Function &F : M) {
1537
0
    const PPCSubtarget &STI = TM.getSubtarget<PPCSubtarget>(F);
1538
0
    unsigned FDir = STI.getDarwinDirective();
1539
0
    Directive = Directive > FDir ? FDir : STI.getDarwinDirective();
1540
0
    if (STI.hasMFOCRF() && Directive < PPC::DIR_970)
1541
0
      Directive = PPC::DIR_970;
1542
0
    if (STI.hasAltivec() && Directive < PPC::DIR_7400)
1543
0
      Directive = PPC::DIR_7400;
1544
0
    if (STI.isPPC64() && Directive < PPC::DIR_64)
1545
0
      Directive = PPC::DIR_64;
1546
0
  }
1547
0
1548
0
  assert(Directive <= PPC::DIR_64 && "Directive out of range.");
1549
0
1550
0
  assert(Directive < array_lengthof(CPUDirectives) &&
1551
0
         "CPUDirectives[] might not be up-to-date!");
1552
0
  PPCTargetStreamer &TStreamer =
1553
0
      *static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1554
0
  TStreamer.emitMachine(CPUDirectives[Directive]);
1555
0
1556
0
  // Prime text sections so they are adjacent.  This reduces the likelihood a
1557
0
  // large data or debug section causes a branch to exceed 16M limit.
1558
0
  const TargetLoweringObjectFileMachO &TLOFMacho =
1559
0
      static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1560
0
  OutStreamer->SwitchSection(TLOFMacho.getTextCoalSection());
1561
0
  if (TM.getRelocationModel() == Reloc::PIC_) {
1562
0
    OutStreamer->SwitchSection(
1563
0
           OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
1564
0
                                      MachO::S_SYMBOL_STUBS |
1565
0
                                      MachO::S_ATTR_PURE_INSTRUCTIONS,
1566
0
                                      32, SectionKind::getText()));
1567
0
  } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
1568
0
    OutStreamer->SwitchSection(
1569
0
           OutContext.getMachOSection("__TEXT","__symbol_stub1",
1570
0
                                      MachO::S_SYMBOL_STUBS |
1571
0
                                      MachO::S_ATTR_PURE_INSTRUCTIONS,
1572
0
                                      16, SectionKind::getText()));
1573
0
  }
1574
0
  OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1575
0
}
1576
1577
0
bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1578
0
  bool isPPC64 = getDataLayout().getPointerSizeInBits() == 64;
1579
0
1580
0
  // Darwin/PPC always uses mach-o.
1581
0
  const TargetLoweringObjectFileMachO &TLOFMacho =
1582
0
      static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1583
0
  if (MMI) {
1584
0
    MachineModuleInfoMachO &MMIMacho =
1585
0
        MMI->getObjFileInfo<MachineModuleInfoMachO>();
1586
0
1587
0
    if (MAI->doesSupportExceptionHandling()) {
1588
0
      // Add the (possibly multiple) personalities to the set of global values.
1589
0
      // Only referenced functions get into the Personalities list.
1590
0
      for (const Function *Personality : MMI->getPersonalities()) {
1591
0
        if (Personality) {
1592
0
          MCSymbol *NLPSym =
1593
0
              getSymbolWithGlobalValueBase(Personality, "$non_lazy_ptr");
1594
0
          MachineModuleInfoImpl::StubValueTy &StubSym =
1595
0
              MMIMacho.getGVStubEntry(NLPSym);
1596
0
          StubSym =
1597
0
              MachineModuleInfoImpl::StubValueTy(getSymbol(Personality), true);
1598
0
        }
1599
0
      }
1600
0
    }
1601
0
1602
0
    // Output stubs for dynamically-linked functions.
1603
0
    MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
1604
0
1605
0
    // Output macho stubs for external and common global variables.
1606
0
    if (!Stubs.empty()) {
1607
0
      // Switch with ".non_lazy_symbol_pointer" directive.
1608
0
      OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1609
0
      EmitAlignment(isPPC64 ? 3 : 2);
1610
0
1611
0
      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1612
0
        // L_foo$stub:
1613
0
        OutStreamer->EmitLabel(Stubs[i].first);
1614
0
        //   .indirect_symbol _foo
1615
0
        MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1616
0
        OutStreamer->EmitSymbolAttribute(MCSym.getPointer(),
1617
0
                                         MCSA_IndirectSymbol);
1618
0
1619
0
        if (MCSym.getInt())
1620
0
          // External to current translation unit.
1621
0
          OutStreamer->EmitIntValue(0, isPPC64 ? 8 : 4 /*size*/);
1622
0
        else
1623
0
          // Internal to current translation unit.
1624
0
          //
1625
0
          // When we place the LSDA into the TEXT section, the type info
1626
0
          // pointers
1627
0
          // need to be indirect and pc-rel. We accomplish this by using NLPs.
1628
0
          // However, sometimes the types are local to the file. So we need to
1629
0
          // fill in the value for the NLP in those cases.
1630
0
          OutStreamer->EmitValue(
1631
0
              MCSymbolRefExpr::create(MCSym.getPointer(), OutContext),
1632
0
              isPPC64 ? 8 : 4 /*size*/);
1633
0
      }
1634
0
1635
0
      Stubs.clear();
1636
0
      OutStreamer->AddBlankLine();
1637
0
    }
1638
0
  }
1639
0
1640
0
  // Funny Darwin hack: This flag tells the linker that no global symbols
1641
0
  // contain code that falls through to other global symbols (e.g. the obvious
1642
0
  // implementation of multiple entry points).  If this doesn't occur, the
1643
0
  // linker can safely perform dead code stripping.  Since LLVM never generates
1644
0
  // code that does this, it is always safe to set.
1645
0
  OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1646
0
1647
0
  return AsmPrinter::doFinalization(M);
1648
0
}
1649
1650
8
void PPCAIXAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
1651
8
  // Early error checking limiting what is supported.
1652
8
  if (GV->isThreadLocal())
1653
0
    report_fatal_error("Thread local not yet supported on AIX.");
1654
8
1655
8
  if (GV->hasSection())
1656
0
    report_fatal_error("Custom section for Data not yet supported.");
1657
8
1658
8
  if (GV->hasComdat())
1659
0
    report_fatal_error("COMDAT not yet supported on AIX.");
1660
8
1661
8
  SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
1662
8
  if (!GVKind.isCommon())
1663
0
    report_fatal_error("Only common variables are supported on AIX.");
1664
8
1665
8
  // Create the containing csect and switch to it.
1666
8
  MCSectionXCOFF *CSect = dyn_cast<MCSectionXCOFF>(
1667
8
      getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
1668
8
  OutStreamer->SwitchSection(CSect);
1669
8
1670
8
  // Create the symbol and emit it.
1671
8
  MCSymbolXCOFF *XSym = dyn_cast<MCSymbolXCOFF>(getSymbol(GV));
1672
8
  auto DL = GV->getParent()->getDataLayout();
1673
8
  unsigned Align =
1674
8
      GV->getAlignment() ? GV->getAlignment() : 
DL.getPreferredAlignment(GV)0
;
1675
8
  uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
1676
8
  OutStreamer->EmitCommonSymbol(XSym, Size, Align);
1677
8
}
1678
1679
/// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1680
/// for a MachineFunction to the given output stream, in a format that the
1681
/// Darwin assembler can deal with.
1682
///
1683
static AsmPrinter *
1684
createPPCAsmPrinterPass(TargetMachine &tm,
1685
1.76k
                        std::unique_ptr<MCStreamer> &&Streamer) {
1686
1.76k
  if (tm.getTargetTriple().isMacOSX())
1687
0
    return new PPCDarwinAsmPrinter(tm, std::move(Streamer));
1688
1.76k
  if (tm.getTargetTriple().isOSAIX())
1689
5
    return new PPCAIXAsmPrinter(tm, std::move(Streamer));
1690
1.76k
1691
1.76k
  return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
1692
1.76k
}
1693
1694
// Force static initialization.
1695
78.9k
extern "C" void LLVMInitializePowerPCAsmPrinter() {
1696
78.9k
  TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
1697
78.9k
                                     createPPCAsmPrinterPass);
1698
78.9k
  TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
1699
78.9k
                                     createPPCAsmPrinterPass);
1700
78.9k
  TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
1701
78.9k
                                     createPPCAsmPrinterPass);
1702
78.9k
}