Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/X86/X86FloatingPoint.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- X86FloatingPoint.cpp - Floating point Reg -> Stack converter ------===//
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 defines the pass which converts floating point instructions from
10
// pseudo registers into register stack instructions.  This pass uses live
11
// variable information to indicate where the FPn registers are used and their
12
// lifetimes.
13
//
14
// The x87 hardware tracks liveness of the stack registers, so it is necessary
15
// to implement exact liveness tracking between basic blocks. The CFG edges are
16
// partitioned into bundles where the same FP registers must be live in
17
// identical stack positions. Instructions are inserted at the end of each basic
18
// block to rearrange the live registers to match the outgoing bundle.
19
//
20
// This approach avoids splitting critical edges at the potential cost of more
21
// live register shuffling instructions when critical edges are present.
22
//
23
//===----------------------------------------------------------------------===//
24
25
#include "X86.h"
26
#include "X86InstrInfo.h"
27
#include "llvm/ADT/DepthFirstIterator.h"
28
#include "llvm/ADT/STLExtras.h"
29
#include "llvm/ADT/SmallPtrSet.h"
30
#include "llvm/ADT/SmallSet.h"
31
#include "llvm/ADT/SmallVector.h"
32
#include "llvm/ADT/Statistic.h"
33
#include "llvm/CodeGen/EdgeBundles.h"
34
#include "llvm/CodeGen/LivePhysRegs.h"
35
#include "llvm/CodeGen/MachineFunctionPass.h"
36
#include "llvm/CodeGen/MachineInstrBuilder.h"
37
#include "llvm/CodeGen/MachineRegisterInfo.h"
38
#include "llvm/CodeGen/Passes.h"
39
#include "llvm/CodeGen/TargetInstrInfo.h"
40
#include "llvm/CodeGen/TargetSubtargetInfo.h"
41
#include "llvm/Config/llvm-config.h"
42
#include "llvm/IR/InlineAsm.h"
43
#include "llvm/Support/Debug.h"
44
#include "llvm/Support/ErrorHandling.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include "llvm/Target/TargetMachine.h"
47
#include <algorithm>
48
#include <bitset>
49
using namespace llvm;
50
51
#define DEBUG_TYPE "x86-codegen"
52
53
STATISTIC(NumFXCH, "Number of fxch instructions inserted");
54
STATISTIC(NumFP  , "Number of floating point instructions");
55
56
namespace {
57
  const unsigned ScratchFPReg = 7;
58
59
  struct FPS : public MachineFunctionPass {
60
    static char ID;
61
12.2k
    FPS() : MachineFunctionPass(ID) {
62
12.2k
      // This is really only to keep valgrind quiet.
63
12.2k
      // The logic in isLive() is too much for it.
64
12.2k
      memset(Stack, 0, sizeof(Stack));
65
12.2k
      memset(RegMap, 0, sizeof(RegMap));
66
12.2k
    }
67
68
12.1k
    void getAnalysisUsage(AnalysisUsage &AU) const override {
69
12.1k
      AU.setPreservesCFG();
70
12.1k
      AU.addRequired<EdgeBundles>();
71
12.1k
      AU.addPreservedID(MachineLoopInfoID);
72
12.1k
      AU.addPreservedID(MachineDominatorsID);
73
12.1k
      MachineFunctionPass::getAnalysisUsage(AU);
74
12.1k
    }
75
76
    bool runOnMachineFunction(MachineFunction &MF) override;
77
78
12.1k
    MachineFunctionProperties getRequiredProperties() const override {
79
12.1k
      return MachineFunctionProperties().set(
80
12.1k
          MachineFunctionProperties::Property::NoVRegs);
81
12.1k
    }
82
83
150k
    StringRef getPassName() const override { return "X86 FP Stackifier"; }
84
85
  private:
86
    const TargetInstrInfo *TII; // Machine instruction info.
87
88
    // Two CFG edges are related if they leave the same block, or enter the same
89
    // block. The transitive closure of an edge under this relation is a
90
    // LiveBundle. It represents a set of CFG edges where the live FP stack
91
    // registers must be allocated identically in the x87 stack.
92
    //
93
    // A LiveBundle is usually all the edges leaving a block, or all the edges
94
    // entering a block, but it can contain more edges if critical edges are
95
    // present.
96
    //
97
    // The set of live FP registers in a LiveBundle is calculated by bundleCFG,
98
    // but the exact mapping of FP registers to stack slots is fixed later.
99
    struct LiveBundle {
100
      // Bit mask of live FP registers. Bit 0 = FP0, bit 1 = FP1, &c.
101
      unsigned Mask;
102
103
      // Number of pre-assigned live registers in FixStack. This is 0 when the
104
      // stack order has not yet been fixed.
105
      unsigned FixCount;
106
107
      // Assigned stack order for live-in registers.
108
      // FixStack[i] == getStackEntry(i) for all i < FixCount.
109
      unsigned char FixStack[8];
110
111
6.20k
      LiveBundle() : Mask(0), FixCount(0) {}
112
113
      // Have the live registers been assigned a stack order yet?
114
1.95k
      bool isFixed() const { return !Mask || FixCount; }
115
    };
116
117
    // Numbered LiveBundle structs. LiveBundles[0] is used for all CFG edges
118
    // with no live FP registers.
119
    SmallVector<LiveBundle, 8> LiveBundles;
120
121
    // The edge bundle analysis provides indices into the LiveBundles vector.
122
    EdgeBundles *Bundles;
123
124
    // Return a bitmask of FP registers in block's live-in list.
125
8.12k
    static unsigned calcLiveInMask(MachineBasicBlock *MBB, bool RemoveFPs) {
126
8.12k
      unsigned Mask = 0;
127
8.12k
      for (MachineBasicBlock::livein_iterator I = MBB->livein_begin();
128
27.5k
           I != MBB->livein_end(); ) {
129
19.4k
        MCPhysReg Reg = I->PhysReg;
130
19.4k
        static_assert(X86::FP6 - X86::FP0 == 6, "sequential regnums");
131
19.4k
        if (Reg >= X86::FP0 && 
Reg <= X86::FP611.0k
) {
132
9.76k
          Mask |= 1 << (Reg - X86::FP0);
133
9.76k
          if (RemoveFPs) {
134
4.88k
            I = MBB->removeLiveIn(I);
135
4.88k
            continue;
136
4.88k
          }
137
14.5k
        }
138
14.5k
        ++I;
139
14.5k
      }
140
8.12k
      return Mask;
141
8.12k
    }
142
143
    // Partition all the CFG edges into LiveBundles.
144
    void bundleCFGRecomputeKillFlags(MachineFunction &MF);
145
146
    MachineBasicBlock *MBB;     // Current basic block
147
148
    // The hardware keeps track of how many FP registers are live, so we have
149
    // to model that exactly. Usually, each live register corresponds to an
150
    // FP<n> register, but when dealing with calls, returns, and inline
151
    // assembly, it is sometimes necessary to have live scratch registers.
152
    unsigned Stack[8];          // FP<n> Registers in each stack slot...
153
    unsigned StackTop;          // The current top of the FP stack.
154
155
    enum {
156
      NumFPRegs = 8             // Including scratch pseudo-registers.
157
    };
158
159
    // For each live FP<n> register, point to its Stack[] entry.
160
    // The first entries correspond to FP0-FP6, the rest are scratch registers
161
    // used when we need slightly different live registers than what the
162
    // register allocator thinks.
163
    unsigned RegMap[NumFPRegs];
164
165
    // Set up our stack model to match the incoming registers to MBB.
166
    void setupBlockStack();
167
168
    // Shuffle live registers to match the expectations of successor blocks.
169
    void finishBlockStack();
170
171
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
172
    void dumpStack() const {
173
      dbgs() << "Stack contents:";
174
      for (unsigned i = 0; i != StackTop; ++i) {
175
        dbgs() << " FP" << Stack[i];
176
        assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
177
      }
178
    }
179
#endif
180
181
    /// getSlot - Return the stack slot number a particular register number is
182
    /// in.
183
18.3k
    unsigned getSlot(unsigned RegNo) const {
184
18.3k
      assert(RegNo < NumFPRegs && "Regno out of range!");
185
18.3k
      return RegMap[RegNo];
186
18.3k
    }
187
188
    /// isLive - Is RegNo currently live in the stack?
189
70
    bool isLive(unsigned RegNo) const {
190
70
      unsigned Slot = getSlot(RegNo);
191
70
      return Slot < StackTop && 
Stack[Slot] == RegNo56
;
192
70
    }
193
194
    /// getStackEntry - Return the X86::FP<n> register in register ST(i).
195
11.0k
    unsigned getStackEntry(unsigned STi) const {
196
11.0k
      if (STi >= StackTop)
197
0
        report_fatal_error("Access past stack top!");
198
11.0k
      return Stack[StackTop-1-STi];
199
11.0k
    }
200
201
    /// getSTReg - Return the X86::ST(i) register which contains the specified
202
    /// FP<RegNo> register.
203
7.56k
    unsigned getSTReg(unsigned RegNo) const {
204
7.56k
      return StackTop - 1 - getSlot(RegNo) + X86::ST0;
205
7.56k
    }
206
207
    // pushReg - Push the specified FP<n> register onto the stack.
208
15.9k
    void pushReg(unsigned Reg) {
209
15.9k
      assert(Reg < NumFPRegs && "Register number out of range!");
210
15.9k
      if (StackTop >= 8)
211
0
        report_fatal_error("Stack overflow!");
212
15.9k
      Stack[StackTop] = Reg;
213
15.9k
      RegMap[Reg] = StackTop++;
214
15.9k
    }
215
216
    // popReg - Pop a register from the stack.
217
3.49k
    void popReg() {
218
3.49k
      if (StackTop == 0)
219
0
        report_fatal_error("Cannot pop empty stack!");
220
3.49k
      RegMap[Stack[--StackTop]] = ~0;     // Update state
221
3.49k
    }
222
223
7.43k
    bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
224
7.43k
    void moveToTop(unsigned RegNo, MachineBasicBlock::iterator I) {
225
7.43k
      DebugLoc dl = I == MBB->end() ? 
DebugLoc()534
:
I->getDebugLoc()6.90k
;
226
7.43k
      if (isAtTop(RegNo)) 
return5.32k
;
227
2.11k
228
2.11k
      unsigned STReg = getSTReg(RegNo);
229
2.11k
      unsigned RegOnTop = getStackEntry(0);
230
2.11k
231
2.11k
      // Swap the slots the regs are in.
232
2.11k
      std::swap(RegMap[RegNo], RegMap[RegOnTop]);
233
2.11k
234
2.11k
      // Swap stack slot contents.
235
2.11k
      if (RegMap[RegOnTop] >= StackTop)
236
0
        report_fatal_error("Access past stack top!");
237
2.11k
      std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
238
2.11k
239
2.11k
      // Emit an fxch to update the runtime processors version of the state.
240
2.11k
      BuildMI(*MBB, I, dl, TII->get(X86::XCH_F)).addReg(STReg);
241
2.11k
      ++NumFXCH;
242
2.11k
    }
243
244
    void duplicateToTop(unsigned RegNo, unsigned AsReg,
245
1.16k
                        MachineBasicBlock::iterator I) {
246
1.16k
      DebugLoc dl = I == MBB->end() ? 
DebugLoc()0
: I->getDebugLoc();
247
1.16k
      unsigned STReg = getSTReg(RegNo);
248
1.16k
      pushReg(AsReg);   // New register on top of stack
249
1.16k
250
1.16k
      BuildMI(*MBB, I, dl, TII->get(X86::LD_Frr)).addReg(STReg);
251
1.16k
    }
252
253
    /// popStackAfter - Pop the current value off of the top of the FP stack
254
    /// after the specified instruction.
255
    void popStackAfter(MachineBasicBlock::iterator &I);
256
257
    /// freeStackSlotAfter - Free the specified register from the register
258
    /// stack, so that it is no longer in a register.  If the register is
259
    /// currently at the top of the stack, we just pop the current instruction,
260
    /// otherwise we store the current top-of-stack into the specified slot,
261
    /// then pop the top of stack.
262
    void freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned Reg);
263
264
    /// freeStackSlotBefore - Just the pop, no folding. Return the inserted
265
    /// instruction.
266
    MachineBasicBlock::iterator
267
    freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo);
268
269
    /// Adjust the live registers to be the set in Mask.
270
    void adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I);
271
272
    /// Shuffle the top FixCount stack entries such that FP reg FixStack[0] is
273
    /// st(0), FP reg FixStack[1] is st(1) etc.
274
    void shuffleStackTop(const unsigned char *FixStack, unsigned FixCount,
275
                         MachineBasicBlock::iterator I);
276
277
    bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
278
279
    void handleCall(MachineBasicBlock::iterator &I);
280
    void handleReturn(MachineBasicBlock::iterator &I);
281
    void handleZeroArgFP(MachineBasicBlock::iterator &I);
282
    void handleOneArgFP(MachineBasicBlock::iterator &I);
283
    void handleOneArgFPRW(MachineBasicBlock::iterator &I);
284
    void handleTwoArgFP(MachineBasicBlock::iterator &I);
285
    void handleCompareFP(MachineBasicBlock::iterator &I);
286
    void handleCondMovFP(MachineBasicBlock::iterator &I);
287
    void handleSpecialFP(MachineBasicBlock::iterator &I);
288
289
    // Check if a COPY instruction is using FP registers.
290
2.66k
    static bool isFPCopy(MachineInstr &MI) {
291
2.66k
      unsigned DstReg = MI.getOperand(0).getReg();
292
2.66k
      unsigned SrcReg = MI.getOperand(1).getReg();
293
2.66k
294
2.66k
      return X86::RFP80RegClass.contains(DstReg) ||
295
2.66k
        
X86::RFP80RegClass.contains(SrcReg)2.09k
;
296
2.66k
    }
297
298
    void setKillFlags(MachineBasicBlock &MBB) const;
299
  };
300
}
301
302
char FPS::ID = 0;
303
304
102k
INITIALIZE_PASS_BEGIN(FPS, DEBUG_TYPE, "X86 FP Stackifier",
305
102k
                      false, false)
306
102k
INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
307
102k
INITIALIZE_PASS_END(FPS, DEBUG_TYPE, "X86 FP Stackifier",
308
                    false, false)
309
310
12.2k
FunctionPass *llvm::createX86FloatingPointStackifierPass() { return new FPS(); }
311
312
/// getFPReg - Return the X86::FPx register number for the specified operand.
313
/// For example, this returns 3 for X86::FP3.
314
33.7k
static unsigned getFPReg(const MachineOperand &MO) {
315
33.7k
  assert(MO.isReg() && "Expected an FP register!");
316
33.7k
  unsigned Reg = MO.getReg();
317
33.7k
  assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
318
33.7k
  return Reg - X86::FP0;
319
33.7k
}
320
321
/// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
322
/// register references into FP stack references.
323
///
324
137k
bool FPS::runOnMachineFunction(MachineFunction &MF) {
325
137k
  // We only need to run this pass if there are any FP registers used in this
326
137k
  // function.  If it is all integer, there is nothing for us to do!
327
137k
  bool FPIsUsed = false;
328
137k
329
137k
  static_assert(X86::FP6 == X86::FP0+6, "Register enums aren't sorted right!");
330
137k
  const MachineRegisterInfo &MRI = MF.getRegInfo();
331
1.08M
  for (unsigned i = 0; i <= 6; 
++i950k
)
332
952k
    if (!MRI.reg_nodbg_empty(X86::FP0 + i)) {
333
2.08k
      FPIsUsed = true;
334
2.08k
      break;
335
2.08k
    }
336
137k
337
137k
  // Early exit.
338
137k
  if (!FPIsUsed) 
return false135k
;
339
2.08k
340
2.08k
  Bundles = &getAnalysis<EdgeBundles>();
341
2.08k
  TII = MF.getSubtarget().getInstrInfo();
342
2.08k
343
2.08k
  // Prepare cross-MBB liveness.
344
2.08k
  bundleCFGRecomputeKillFlags(MF);
345
2.08k
346
2.08k
  StackTop = 0;
347
2.08k
348
2.08k
  // Process the function in depth first order so that we process at least one
349
2.08k
  // of the predecessors for every reachable block in the function.
350
2.08k
  df_iterator_default_set<MachineBasicBlock*> Processed;
351
2.08k
  MachineBasicBlock *Entry = &MF.front();
352
2.08k
353
2.08k
  LiveBundle &Bundle =
354
2.08k
    LiveBundles[Bundles->getBundle(Entry->getNumber(), false)];
355
2.08k
356
2.08k
  // In regcall convention, some FP registers may not be passed through
357
2.08k
  // the stack, so they will need to be assigned to the stack first
358
2.08k
  if ((Entry->getParent()->getFunction().getCallingConv() ==
359
2.08k
    CallingConv::X86_RegCall) && 
(6
Bundle.Mask6
&&
!Bundle.FixCount6
)) {
360
6
    // In the register calling convention, up to one FP argument could be
361
6
    // saved in the first FP register.
362
6
    // If bundle.mask is non-zero and Bundle.FixCount is zero, it means
363
6
    // that the FP registers contain arguments.
364
6
    // The actual value is passed in FP0.
365
6
    // Here we fix the stack and mark FP0 as pre-assigned register.
366
6
    assert((Bundle.Mask & 0xFE) == 0 &&
367
6
      "Only FP0 could be passed as an argument");
368
6
    Bundle.FixCount = 1;
369
6
    Bundle.FixStack[0] = 0;
370
6
  }
371
2.08k
372
2.08k
  bool Changed = false;
373
2.08k
  for (MachineBasicBlock *BB : depth_first_ext(Entry, Processed))
374
6.21k
    Changed |= processBasicBlock(MF, *BB);
375
2.08k
376
2.08k
  // Process any unreachable blocks in arbitrary order now.
377
2.08k
  if (MF.size() != Processed.size())
378
0
    for (MachineBasicBlock &BB : MF)
379
0
      if (Processed.insert(&BB).second)
380
0
        Changed |= processBasicBlock(MF, BB);
381
2.08k
382
2.08k
  LiveBundles.clear();
383
2.08k
384
2.08k
  return Changed;
385
2.08k
}
386
387
/// bundleCFG - Scan all the basic blocks to determine consistent live-in and
388
/// live-out sets for the FP registers. Consistent means that the set of
389
/// registers live-out from a block is identical to the live-in set of all
390
/// successors. This is not enforced by the normal live-in lists since
391
/// registers may be implicitly defined, or not used by all successors.
392
2.08k
void FPS::bundleCFGRecomputeKillFlags(MachineFunction &MF) {
393
2.08k
  assert(LiveBundles.empty() && "Stale data in LiveBundles");
394
2.08k
  LiveBundles.resize(Bundles->getNumBundles());
395
2.08k
396
2.08k
  // Gather the actual live-in masks for all MBBs.
397
6.21k
  for (MachineBasicBlock &MBB : MF) {
398
6.21k
    setKillFlags(MBB);
399
6.21k
400
6.21k
    const unsigned Mask = calcLiveInMask(&MBB, false);
401
6.21k
    if (!Mask)
402
4.48k
      continue;
403
1.72k
    // Update MBB ingoing bundle mask.
404
1.72k
    LiveBundles[Bundles->getBundle(MBB.getNumber(), false)].Mask |= Mask;
405
1.72k
  }
406
2.08k
}
407
408
/// processBasicBlock - Loop over all of the instructions in the basic block,
409
/// transforming FP instructions into their stack form.
410
///
411
6.21k
bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
412
6.21k
  bool Changed = false;
413
6.21k
  MBB = &BB;
414
6.21k
415
6.21k
  setupBlockStack();
416
6.21k
417
62.7k
  for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); 
++I56.5k
) {
418
56.5k
    MachineInstr &MI = *I;
419
56.5k
    uint64_t Flags = MI.getDesc().TSFlags;
420
56.5k
421
56.5k
    unsigned FPInstClass = Flags & X86II::FPTypeMask;
422
56.5k
    if (MI.isInlineAsm())
423
50
      FPInstClass = X86II::SpecialFP;
424
56.5k
425
56.5k
    if (MI.isCopy() && 
isFPCopy(MI)2.66k
)
426
567
      FPInstClass = X86II::SpecialFP;
427
56.5k
428
56.5k
    if (MI.isImplicitDef() &&
429
56.5k
        
X86::RFP80RegClass.contains(MI.getOperand(0).getReg())5
)
430
0
      FPInstClass = X86II::SpecialFP;
431
56.5k
432
56.5k
    if (MI.isCall())
433
1.35k
      FPInstClass = X86II::SpecialFP;
434
56.5k
435
56.5k
    if (FPInstClass == X86II::NotFP)
436
38.9k
      continue;  // Efficiently ignore non-fp insts!
437
17.5k
438
17.5k
    MachineInstr *PrevMI = nullptr;
439
17.5k
    if (I != BB.begin())
440
16.2k
      PrevMI = &*std::prev(I);
441
17.5k
442
17.5k
    ++NumFP;  // Keep track of # of pseudo instrs
443
17.5k
    LLVM_DEBUG(dbgs() << "\nFPInst:\t" << MI);
444
17.5k
445
17.5k
    // Get dead variables list now because the MI pointer may be deleted as part
446
17.5k
    // of processing!
447
17.5k
    SmallVector<unsigned, 8> DeadRegs;
448
131k
    for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i113k
) {
449
113k
      const MachineOperand &MO = MI.getOperand(i);
450
113k
      if (MO.isReg() && 
MO.isDead()80.3k
)
451
11.2k
        DeadRegs.push_back(MO.getReg());
452
113k
    }
453
17.5k
454
17.5k
    switch (FPInstClass) {
455
17.5k
    
case X86II::ZeroArgFP: handleZeroArgFP(I); break5.89k
;
456
17.5k
    
case X86II::OneArgFP: handleOneArgFP(I); break4.12k
; // fstp ST(0)
457
17.5k
    
case X86II::OneArgFPRW: handleOneArgFPRW(I); break1.14k
; // ST(0) = fsqrt(ST(0))
458
17.5k
    
case X86II::TwoArgFP: handleTwoArgFP(I); break981
;
459
17.5k
    
case X86II::CompareFP: handleCompareFP(I); break873
;
460
17.5k
    
case X86II::CondMovFP: handleCondMovFP(I); break479
;
461
17.5k
    
case X86II::SpecialFP: handleSpecialFP(I); break4.07k
;
462
17.5k
    
default: 0
llvm_unreachable0
("Unknown FP Type!");
463
17.5k
    }
464
17.5k
465
17.5k
    // Check to see if any of the values defined by this instruction are dead
466
17.5k
    // after definition.  If so, pop them.
467
28.8k
    
for (unsigned i = 0, e = DeadRegs.size(); 17.5k
i != e;
++i11.2k
) {
468
11.2k
      unsigned Reg = DeadRegs[i];
469
11.2k
      // Check if Reg is live on the stack. An inline-asm register operand that
470
11.2k
      // is in the clobber list and marked dead might not be live on the stack.
471
11.2k
      static_assert(X86::FP7 - X86::FP0 == 7, "sequential FP regnumbers");
472
11.2k
      if (Reg >= X86::FP0 && 
Reg <= X86::FP664
&&
isLive(Reg-X86::FP0)56
) {
473
41
        LLVM_DEBUG(dbgs() << "Register FP#" << Reg - X86::FP0 << " is dead!\n");
474
41
        freeStackSlotAfter(I, Reg-X86::FP0);
475
41
      }
476
11.2k
    }
477
17.5k
478
17.5k
    // Print out all of the instructions expanded to if -debug
479
17.5k
    LLVM_DEBUG({
480
17.5k
      MachineBasicBlock::iterator PrevI = PrevMI;
481
17.5k
      if (I == PrevI) {
482
17.5k
        dbgs() << "Just deleted pseudo instruction\n";
483
17.5k
      } else {
484
17.5k
        MachineBasicBlock::iterator Start = I;
485
17.5k
        // Rewind to first instruction newly inserted.
486
17.5k
        while (Start != BB.begin() && std::prev(Start) != PrevI)
487
17.5k
          --Start;
488
17.5k
        dbgs() << "Inserted instructions:\n\t";
489
17.5k
        Start->print(dbgs());
490
17.5k
        while (++Start != std::next(I)) {
491
17.5k
        }
492
17.5k
      }
493
17.5k
      dumpStack();
494
17.5k
    });
495
17.5k
    (void)PrevMI;
496
17.5k
497
17.5k
    Changed = true;
498
17.5k
  }
499
6.21k
500
6.21k
  finishBlockStack();
501
6.21k
502
6.21k
  return Changed;
503
6.21k
}
504
505
/// setupBlockStack - Use the live bundles to set up our model of the stack
506
/// to match predecessors' live out stack.
507
6.21k
void FPS::setupBlockStack() {
508
6.21k
  LLVM_DEBUG(dbgs() << "\nSetting up live-ins for " << printMBBReference(*MBB)
509
6.21k
                    << " derived from " << MBB->getName() << ".\n");
510
6.21k
  StackTop = 0;
511
6.21k
  // Get the live-in bundle for MBB.
512
6.21k
  const LiveBundle &Bundle =
513
6.21k
    LiveBundles[Bundles->getBundle(MBB->getNumber(), false)];
514
6.21k
515
6.21k
  if (!Bundle.Mask) {
516
4.30k
    LLVM_DEBUG(dbgs() << "Block has no FP live-ins.\n");
517
4.30k
    return;
518
4.30k
  }
519
1.91k
520
1.91k
  // Depth-first iteration should ensure that we always have an assigned stack.
521
1.91k
  assert(Bundle.isFixed() && "Reached block before any predecessors");
522
1.91k
523
1.91k
  // Push the fixed live-in registers.
524
8.25k
  for (unsigned i = Bundle.FixCount; i > 0; 
--i6.34k
) {
525
6.34k
    LLVM_DEBUG(dbgs() << "Live-in st(" << (i - 1) << "): %fp"
526
6.34k
                      << unsigned(Bundle.FixStack[i - 1]) << '\n');
527
6.34k
    pushReg(Bundle.FixStack[i-1]);
528
6.34k
  }
529
1.91k
530
1.91k
  // Kill off unwanted live-ins. This can happen with a critical edge.
531
1.91k
  // FIXME: We could keep these live registers around as zombies. They may need
532
1.91k
  // to be revived at the end of a short block. It might save a few instrs.
533
1.91k
  unsigned Mask = calcLiveInMask(MBB, /*RemoveFPs=*/true);
534
1.91k
  adjustLiveRegs(Mask, MBB->begin());
535
1.91k
  LLVM_DEBUG(MBB->dump());
536
1.91k
}
537
538
/// finishBlockStack - Revive live-outs that are implicitly defined out of
539
/// MBB. Shuffle live registers to match the expected fixed stack of any
540
/// predecessors, and ensure that all predecessors are expecting the same
541
/// stack.
542
6.21k
void FPS::finishBlockStack() {
543
6.21k
  // The RET handling below takes care of return blocks for us.
544
6.21k
  if (MBB->succ_empty())
545
2.17k
    return;
546
4.03k
547
4.03k
  LLVM_DEBUG(dbgs() << "Setting up live-outs for " << printMBBReference(*MBB)
548
4.03k
                    << " derived from " << MBB->getName() << ".\n");
549
4.03k
550
4.03k
  // Get MBB's live-out bundle.
551
4.03k
  unsigned BundleIdx = Bundles->getBundle(MBB->getNumber(), true);
552
4.03k
  LiveBundle &Bundle = LiveBundles[BundleIdx];
553
4.03k
554
4.03k
  // We may need to kill and define some registers to match successors.
555
4.03k
  // FIXME: This can probably be combined with the shuffle below.
556
4.03k
  MachineBasicBlock::iterator Term = MBB->getFirstTerminator();
557
4.03k
  adjustLiveRegs(Bundle.Mask, Term);
558
4.03k
559
4.03k
  if (!Bundle.Mask) {
560
2.08k
    LLVM_DEBUG(dbgs() << "No live-outs.\n");
561
2.08k
    return;
562
2.08k
  }
563
1.95k
564
1.95k
  // Has the stack order been fixed yet?
565
1.95k
  LLVM_DEBUG(dbgs() << "LB#" << BundleIdx << ": ");
566
1.95k
  if (Bundle.isFixed()) {
567
1.04k
    LLVM_DEBUG(dbgs() << "Shuffling stack to match.\n");
568
1.04k
    shuffleStackTop(Bundle.FixStack, Bundle.FixCount, Term);
569
1.04k
  } else {
570
902
    // Not fixed yet, we get to choose.
571
902
    LLVM_DEBUG(dbgs() << "Fixing stack order now.\n");
572
902
    Bundle.FixCount = StackTop;
573
3.77k
    for (unsigned i = 0; i < StackTop; 
++i2.87k
)
574
2.87k
      Bundle.FixStack[i] = getStackEntry(i);
575
902
  }
576
1.95k
}
577
578
579
//===----------------------------------------------------------------------===//
580
// Efficient Lookup Table Support
581
//===----------------------------------------------------------------------===//
582
583
namespace {
584
  struct TableEntry {
585
    uint16_t from;
586
    uint16_t to;
587
0
    bool operator<(const TableEntry &TE) const { return from < TE.from; }
588
108k
    friend bool operator<(const TableEntry &TE, unsigned V) {
589
108k
      return TE.from < V;
590
108k
    }
591
    friend bool LLVM_ATTRIBUTE_UNUSED operator<(unsigned V,
592
0
                                                const TableEntry &TE) {
593
0
      return V < TE.from;
594
0
    }
595
  };
596
}
597
598
16.9k
static int Lookup(ArrayRef<TableEntry> Table, unsigned Opcode) {
599
16.9k
  const TableEntry *I = llvm::lower_bound(Table, Opcode);
600
16.9k
  if (I != Table.end() && I->from == Opcode)
601
16.8k
    return I->to;
602
94
  return -1;
603
94
}
604
605
#ifdef NDEBUG
606
#define ASSERT_SORTED(TABLE)
607
#else
608
#define ASSERT_SORTED(TABLE)                                                   \
609
  {                                                                            \
610
    static std::atomic<bool> TABLE##Checked(false);                            \
611
    if (!TABLE##Checked.load(std::memory_order_relaxed)) {                     \
612
      assert(std::is_sorted(std::begin(TABLE), std::end(TABLE)) &&             \
613
             "All lookup tables must be sorted for efficient access!");        \
614
      TABLE##Checked.store(true, std::memory_order_relaxed);                   \
615
    }                                                                          \
616
  }
617
#endif
618
619
//===----------------------------------------------------------------------===//
620
// Register File -> Register Stack Mapping Methods
621
//===----------------------------------------------------------------------===//
622
623
// OpcodeTable - Sorted map of register instructions to their stack version.
624
// The first element is an register file pseudo instruction, the second is the
625
// concrete X86 instruction which uses the register stack.
626
//
627
static const TableEntry OpcodeTable[] = {
628
  { X86::ABS_Fp32     , X86::ABS_F     },
629
  { X86::ABS_Fp64     , X86::ABS_F     },
630
  { X86::ABS_Fp80     , X86::ABS_F     },
631
  { X86::ADD_Fp32m    , X86::ADD_F32m  },
632
  { X86::ADD_Fp64m    , X86::ADD_F64m  },
633
  { X86::ADD_Fp64m32  , X86::ADD_F32m  },
634
  { X86::ADD_Fp80m32  , X86::ADD_F32m  },
635
  { X86::ADD_Fp80m64  , X86::ADD_F64m  },
636
  { X86::ADD_FpI16m32 , X86::ADD_FI16m },
637
  { X86::ADD_FpI16m64 , X86::ADD_FI16m },
638
  { X86::ADD_FpI16m80 , X86::ADD_FI16m },
639
  { X86::ADD_FpI32m32 , X86::ADD_FI32m },
640
  { X86::ADD_FpI32m64 , X86::ADD_FI32m },
641
  { X86::ADD_FpI32m80 , X86::ADD_FI32m },
642
  { X86::CHS_Fp32     , X86::CHS_F     },
643
  { X86::CHS_Fp64     , X86::CHS_F     },
644
  { X86::CHS_Fp80     , X86::CHS_F     },
645
  { X86::CMOVBE_Fp32  , X86::CMOVBE_F  },
646
  { X86::CMOVBE_Fp64  , X86::CMOVBE_F  },
647
  { X86::CMOVBE_Fp80  , X86::CMOVBE_F  },
648
  { X86::CMOVB_Fp32   , X86::CMOVB_F   },
649
  { X86::CMOVB_Fp64   , X86::CMOVB_F  },
650
  { X86::CMOVB_Fp80   , X86::CMOVB_F  },
651
  { X86::CMOVE_Fp32   , X86::CMOVE_F  },
652
  { X86::CMOVE_Fp64   , X86::CMOVE_F   },
653
  { X86::CMOVE_Fp80   , X86::CMOVE_F   },
654
  { X86::CMOVNBE_Fp32 , X86::CMOVNBE_F },
655
  { X86::CMOVNBE_Fp64 , X86::CMOVNBE_F },
656
  { X86::CMOVNBE_Fp80 , X86::CMOVNBE_F },
657
  { X86::CMOVNB_Fp32  , X86::CMOVNB_F  },
658
  { X86::CMOVNB_Fp64  , X86::CMOVNB_F  },
659
  { X86::CMOVNB_Fp80  , X86::CMOVNB_F  },
660
  { X86::CMOVNE_Fp32  , X86::CMOVNE_F  },
661
  { X86::CMOVNE_Fp64  , X86::CMOVNE_F  },
662
  { X86::CMOVNE_Fp80  , X86::CMOVNE_F  },
663
  { X86::CMOVNP_Fp32  , X86::CMOVNP_F  },
664
  { X86::CMOVNP_Fp64  , X86::CMOVNP_F  },
665
  { X86::CMOVNP_Fp80  , X86::CMOVNP_F  },
666
  { X86::CMOVP_Fp32   , X86::CMOVP_F   },
667
  { X86::CMOVP_Fp64   , X86::CMOVP_F   },
668
  { X86::CMOVP_Fp80   , X86::CMOVP_F   },
669
  { X86::COS_Fp32     , X86::COS_F     },
670
  { X86::COS_Fp64     , X86::COS_F     },
671
  { X86::COS_Fp80     , X86::COS_F     },
672
  { X86::DIVR_Fp32m   , X86::DIVR_F32m },
673
  { X86::DIVR_Fp64m   , X86::DIVR_F64m },
674
  { X86::DIVR_Fp64m32 , X86::DIVR_F32m },
675
  { X86::DIVR_Fp80m32 , X86::DIVR_F32m },
676
  { X86::DIVR_Fp80m64 , X86::DIVR_F64m },
677
  { X86::DIVR_FpI16m32, X86::DIVR_FI16m},
678
  { X86::DIVR_FpI16m64, X86::DIVR_FI16m},
679
  { X86::DIVR_FpI16m80, X86::DIVR_FI16m},
680
  { X86::DIVR_FpI32m32, X86::DIVR_FI32m},
681
  { X86::DIVR_FpI32m64, X86::DIVR_FI32m},
682
  { X86::DIVR_FpI32m80, X86::DIVR_FI32m},
683
  { X86::DIV_Fp32m    , X86::DIV_F32m  },
684
  { X86::DIV_Fp64m    , X86::DIV_F64m  },
685
  { X86::DIV_Fp64m32  , X86::DIV_F32m  },
686
  { X86::DIV_Fp80m32  , X86::DIV_F32m  },
687
  { X86::DIV_Fp80m64  , X86::DIV_F64m  },
688
  { X86::DIV_FpI16m32 , X86::DIV_FI16m },
689
  { X86::DIV_FpI16m64 , X86::DIV_FI16m },
690
  { X86::DIV_FpI16m80 , X86::DIV_FI16m },
691
  { X86::DIV_FpI32m32 , X86::DIV_FI32m },
692
  { X86::DIV_FpI32m64 , X86::DIV_FI32m },
693
  { X86::DIV_FpI32m80 , X86::DIV_FI32m },
694
  { X86::ILD_Fp16m32  , X86::ILD_F16m  },
695
  { X86::ILD_Fp16m64  , X86::ILD_F16m  },
696
  { X86::ILD_Fp16m80  , X86::ILD_F16m  },
697
  { X86::ILD_Fp32m32  , X86::ILD_F32m  },
698
  { X86::ILD_Fp32m64  , X86::ILD_F32m  },
699
  { X86::ILD_Fp32m80  , X86::ILD_F32m  },
700
  { X86::ILD_Fp64m32  , X86::ILD_F64m  },
701
  { X86::ILD_Fp64m64  , X86::ILD_F64m  },
702
  { X86::ILD_Fp64m80  , X86::ILD_F64m  },
703
  { X86::ISTT_Fp16m32 , X86::ISTT_FP16m},
704
  { X86::ISTT_Fp16m64 , X86::ISTT_FP16m},
705
  { X86::ISTT_Fp16m80 , X86::ISTT_FP16m},
706
  { X86::ISTT_Fp32m32 , X86::ISTT_FP32m},
707
  { X86::ISTT_Fp32m64 , X86::ISTT_FP32m},
708
  { X86::ISTT_Fp32m80 , X86::ISTT_FP32m},
709
  { X86::ISTT_Fp64m32 , X86::ISTT_FP64m},
710
  { X86::ISTT_Fp64m64 , X86::ISTT_FP64m},
711
  { X86::ISTT_Fp64m80 , X86::ISTT_FP64m},
712
  { X86::IST_Fp16m32  , X86::IST_F16m  },
713
  { X86::IST_Fp16m64  , X86::IST_F16m  },
714
  { X86::IST_Fp16m80  , X86::IST_F16m  },
715
  { X86::IST_Fp32m32  , X86::IST_F32m  },
716
  { X86::IST_Fp32m64  , X86::IST_F32m  },
717
  { X86::IST_Fp32m80  , X86::IST_F32m  },
718
  { X86::IST_Fp64m32  , X86::IST_FP64m },
719
  { X86::IST_Fp64m64  , X86::IST_FP64m },
720
  { X86::IST_Fp64m80  , X86::IST_FP64m },
721
  { X86::LD_Fp032     , X86::LD_F0     },
722
  { X86::LD_Fp064     , X86::LD_F0     },
723
  { X86::LD_Fp080     , X86::LD_F0     },
724
  { X86::LD_Fp132     , X86::LD_F1     },
725
  { X86::LD_Fp164     , X86::LD_F1     },
726
  { X86::LD_Fp180     , X86::LD_F1     },
727
  { X86::LD_Fp32m     , X86::LD_F32m   },
728
  { X86::LD_Fp32m64   , X86::LD_F32m   },
729
  { X86::LD_Fp32m80   , X86::LD_F32m   },
730
  { X86::LD_Fp64m     , X86::LD_F64m   },
731
  { X86::LD_Fp64m80   , X86::LD_F64m   },
732
  { X86::LD_Fp80m     , X86::LD_F80m   },
733
  { X86::MUL_Fp32m    , X86::MUL_F32m  },
734
  { X86::MUL_Fp64m    , X86::MUL_F64m  },
735
  { X86::MUL_Fp64m32  , X86::MUL_F32m  },
736
  { X86::MUL_Fp80m32  , X86::MUL_F32m  },
737
  { X86::MUL_Fp80m64  , X86::MUL_F64m  },
738
  { X86::MUL_FpI16m32 , X86::MUL_FI16m },
739
  { X86::MUL_FpI16m64 , X86::MUL_FI16m },
740
  { X86::MUL_FpI16m80 , X86::MUL_FI16m },
741
  { X86::MUL_FpI32m32 , X86::MUL_FI32m },
742
  { X86::MUL_FpI32m64 , X86::MUL_FI32m },
743
  { X86::MUL_FpI32m80 , X86::MUL_FI32m },
744
  { X86::SIN_Fp32     , X86::SIN_F     },
745
  { X86::SIN_Fp64     , X86::SIN_F     },
746
  { X86::SIN_Fp80     , X86::SIN_F     },
747
  { X86::SQRT_Fp32    , X86::SQRT_F    },
748
  { X86::SQRT_Fp64    , X86::SQRT_F    },
749
  { X86::SQRT_Fp80    , X86::SQRT_F    },
750
  { X86::ST_Fp32m     , X86::ST_F32m   },
751
  { X86::ST_Fp64m     , X86::ST_F64m   },
752
  { X86::ST_Fp64m32   , X86::ST_F32m   },
753
  { X86::ST_Fp80m32   , X86::ST_F32m   },
754
  { X86::ST_Fp80m64   , X86::ST_F64m   },
755
  { X86::ST_FpP80m    , X86::ST_FP80m  },
756
  { X86::SUBR_Fp32m   , X86::SUBR_F32m },
757
  { X86::SUBR_Fp64m   , X86::SUBR_F64m },
758
  { X86::SUBR_Fp64m32 , X86::SUBR_F32m },
759
  { X86::SUBR_Fp80m32 , X86::SUBR_F32m },
760
  { X86::SUBR_Fp80m64 , X86::SUBR_F64m },
761
  { X86::SUBR_FpI16m32, X86::SUBR_FI16m},
762
  { X86::SUBR_FpI16m64, X86::SUBR_FI16m},
763
  { X86::SUBR_FpI16m80, X86::SUBR_FI16m},
764
  { X86::SUBR_FpI32m32, X86::SUBR_FI32m},
765
  { X86::SUBR_FpI32m64, X86::SUBR_FI32m},
766
  { X86::SUBR_FpI32m80, X86::SUBR_FI32m},
767
  { X86::SUB_Fp32m    , X86::SUB_F32m  },
768
  { X86::SUB_Fp64m    , X86::SUB_F64m  },
769
  { X86::SUB_Fp64m32  , X86::SUB_F32m  },
770
  { X86::SUB_Fp80m32  , X86::SUB_F32m  },
771
  { X86::SUB_Fp80m64  , X86::SUB_F64m  },
772
  { X86::SUB_FpI16m32 , X86::SUB_FI16m },
773
  { X86::SUB_FpI16m64 , X86::SUB_FI16m },
774
  { X86::SUB_FpI16m80 , X86::SUB_FI16m },
775
  { X86::SUB_FpI32m32 , X86::SUB_FI32m },
776
  { X86::SUB_FpI32m64 , X86::SUB_FI32m },
777
  { X86::SUB_FpI32m80 , X86::SUB_FI32m },
778
  { X86::TST_Fp32     , X86::TST_F     },
779
  { X86::TST_Fp64     , X86::TST_F     },
780
  { X86::TST_Fp80     , X86::TST_F     },
781
  { X86::UCOM_FpIr32  , X86::UCOM_FIr  },
782
  { X86::UCOM_FpIr64  , X86::UCOM_FIr  },
783
  { X86::UCOM_FpIr80  , X86::UCOM_FIr  },
784
  { X86::UCOM_Fpr32   , X86::UCOM_Fr   },
785
  { X86::UCOM_Fpr64   , X86::UCOM_Fr   },
786
  { X86::UCOM_Fpr80   , X86::UCOM_Fr   },
787
};
788
789
12.5k
static unsigned getConcreteOpcode(unsigned Opcode) {
790
12.5k
  ASSERT_SORTED(OpcodeTable);
791
12.5k
  int Opc = Lookup(OpcodeTable, Opcode);
792
12.5k
  assert(Opc != -1 && "FP Stack instruction not in OpcodeTable!");
793
12.5k
  return Opc;
794
12.5k
}
795
796
//===----------------------------------------------------------------------===//
797
// Helper Methods
798
//===----------------------------------------------------------------------===//
799
800
// PopTable - Sorted map of instructions to their popping version.  The first
801
// element is an instruction, the second is the version which pops.
802
//
803
static const TableEntry PopTable[] = {
804
  { X86::ADD_FrST0 , X86::ADD_FPrST0  },
805
806
  { X86::DIVR_FrST0, X86::DIVR_FPrST0 },
807
  { X86::DIV_FrST0 , X86::DIV_FPrST0  },
808
809
  { X86::IST_F16m  , X86::IST_FP16m   },
810
  { X86::IST_F32m  , X86::IST_FP32m   },
811
812
  { X86::MUL_FrST0 , X86::MUL_FPrST0  },
813
814
  { X86::ST_F32m   , X86::ST_FP32m    },
815
  { X86::ST_F64m   , X86::ST_FP64m    },
816
  { X86::ST_Frr    , X86::ST_FPrr     },
817
818
  { X86::SUBR_FrST0, X86::SUBR_FPrST0 },
819
  { X86::SUB_FrST0 , X86::SUB_FPrST0  },
820
821
  { X86::UCOM_FIr  , X86::UCOM_FIPr   },
822
823
  { X86::UCOM_FPr  , X86::UCOM_FPPr   },
824
  { X86::UCOM_Fr   , X86::UCOM_FPr    },
825
};
826
827
/// popStackAfter - Pop the current value off of the top of the FP stack after
828
/// the specified instruction.  This attempts to be sneaky and combine the pop
829
/// into the instruction itself if possible.  The iterator is left pointing to
830
/// the last instruction, be it a new pop instruction inserted, or the old
831
/// instruction if it was modified in place.
832
///
833
3.49k
void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
834
3.49k
  MachineInstr &MI = *I;
835
3.49k
  const DebugLoc &dl = MI.getDebugLoc();
836
3.49k
  ASSERT_SORTED(PopTable);
837
3.49k
838
3.49k
  popReg();
839
3.49k
840
3.49k
  // Check to see if there is a popping version of this instruction...
841
3.49k
  int Opcode = Lookup(PopTable, I->getOpcode());
842
3.49k
  if (Opcode != -1) {
843
3.40k
    I->setDesc(TII->get(Opcode));
844
3.40k
    if (Opcode == X86::UCOM_FPPr)
845
60
      I->RemoveOperand(0);
846
3.40k
  } else {    // Insert an explicit pop
847
94
    I = BuildMI(*MBB, ++I, dl, TII->get(X86::ST_FPrr)).addReg(X86::ST0);
848
94
  }
849
3.49k
}
850
851
/// freeStackSlotAfter - Free the specified register from the register stack, so
852
/// that it is no longer in a register.  If the register is currently at the top
853
/// of the stack, we just pop the current instruction, otherwise we store the
854
/// current top-of-stack into the specified slot, then pop the top of stack.
855
1.16k
void FPS::freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned FPRegNo) {
856
1.16k
  if (getStackEntry(0) == FPRegNo) {  // already at the top of stack? easy.
857
676
    popStackAfter(I);
858
676
    return;
859
676
  }
860
485
861
485
  // Otherwise, store the top of stack into the dead slot, killing the operand
862
485
  // without having to add in an explicit xchg then pop.
863
485
  //
864
485
  I = freeStackSlotBefore(++I, FPRegNo);
865
485
}
866
867
/// freeStackSlotBefore - Free the specified register without trying any
868
/// folding.
869
MachineBasicBlock::iterator
870
1.95k
FPS::freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo) {
871
1.95k
  unsigned STReg    = getSTReg(FPRegNo);
872
1.95k
  unsigned OldSlot  = getSlot(FPRegNo);
873
1.95k
  unsigned TopReg   = Stack[StackTop-1];
874
1.95k
  Stack[OldSlot]    = TopReg;
875
1.95k
  RegMap[TopReg]    = OldSlot;
876
1.95k
  RegMap[FPRegNo]   = ~0;
877
1.95k
  Stack[--StackTop] = ~0;
878
1.95k
  return BuildMI(*MBB, I, DebugLoc(), TII->get(X86::ST_FPrr))
879
1.95k
      .addReg(STReg)
880
1.95k
      .getInstr();
881
1.95k
}
882
883
/// adjustLiveRegs - Kill and revive registers such that exactly the FP
884
/// registers with a bit in Mask are live.
885
8.04k
void FPS::adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I) {
886
8.04k
  unsigned Defs = Mask;
887
8.04k
  unsigned Kills = 0;
888
21.2k
  for (unsigned i = 0; i < StackTop; 
++i13.1k
) {
889
13.1k
    unsigned RegNo = Stack[i];
890
13.1k
    if (!(Defs & (1 << RegNo)))
891
1.46k
      // This register is live, but we don't want it.
892
1.46k
      Kills |= (1 << RegNo);
893
11.7k
    else
894
11.7k
      // We don't need to imp-def this live register.
895
11.7k
      Defs &= ~(1 << RegNo);
896
13.1k
  }
897
8.04k
  assert((Kills & Defs) == 0 && "Register needs killing and def'ing?");
898
8.04k
899
8.04k
  // Produce implicit-defs for free by using killed registers.
900
8.04k
  while (Kills && 
Defs925
) {
901
0
    unsigned KReg = countTrailingZeros(Kills);
902
0
    unsigned DReg = countTrailingZeros(Defs);
903
0
    LLVM_DEBUG(dbgs() << "Renaming %fp" << KReg << " as imp %fp" << DReg
904
0
                      << "\n");
905
0
    std::swap(Stack[getSlot(KReg)], Stack[getSlot(DReg)]);
906
0
    std::swap(RegMap[KReg], RegMap[DReg]);
907
0
    Kills &= ~(1 << KReg);
908
0
    Defs &= ~(1 << DReg);
909
0
  }
910
8.04k
911
8.04k
  // Kill registers by popping.
912
8.04k
  if (Kills && 
I != MBB->begin()925
) {
913
0
    MachineBasicBlock::iterator I2 = std::prev(I);
914
0
    while (StackTop) {
915
0
      unsigned KReg = getStackEntry(0);
916
0
      if (!(Kills & (1 << KReg)))
917
0
        break;
918
0
      LLVM_DEBUG(dbgs() << "Popping %fp" << KReg << "\n");
919
0
      popStackAfter(I2);
920
0
      Kills &= ~(1 << KReg);
921
0
    }
922
0
  }
923
8.04k
924
8.04k
  // Manually kill the rest.
925
9.51k
  while (Kills) {
926
1.46k
    unsigned KReg = countTrailingZeros(Kills);
927
1.46k
    LLVM_DEBUG(dbgs() << "Killing %fp" << KReg << "\n");
928
1.46k
    freeStackSlotBefore(I, KReg);
929
1.46k
    Kills &= ~(1 << KReg);
930
1.46k
  }
931
8.04k
932
8.04k
  // Load zeros for all the imp-defs.
933
9.12k
  while(Defs) {
934
1.08k
    unsigned DReg = countTrailingZeros(Defs);
935
1.08k
    LLVM_DEBUG(dbgs() << "Defining %fp" << DReg << " as 0\n");
936
1.08k
    BuildMI(*MBB, I, DebugLoc(), TII->get(X86::LD_F0));
937
1.08k
    pushReg(DReg);
938
1.08k
    Defs &= ~(1 << DReg);
939
1.08k
  }
940
8.04k
941
8.04k
  // Now we should have the correct registers live.
942
8.04k
  LLVM_DEBUG(dumpStack());
943
8.04k
  assert(StackTop == countPopulation(Mask) && "Live count mismatch");
944
8.04k
}
945
946
/// shuffleStackTop - emit fxch instructions before I to shuffle the top
947
/// FixCount entries into the order given by FixStack.
948
/// FIXME: Is there a better algorithm than insertion sort?
949
void FPS::shuffleStackTop(const unsigned char *FixStack,
950
                          unsigned FixCount,
951
1.09k
                          MachineBasicBlock::iterator I) {
952
1.09k
  // Move items into place, starting from the desired stack bottom.
953
4.85k
  while (FixCount--) {
954
3.75k
    // Old register at position FixCount.
955
3.75k
    unsigned OldReg = getStackEntry(FixCount);
956
3.75k
    // Desired register at position FixCount.
957
3.75k
    unsigned Reg = FixStack[FixCount];
958
3.75k
    if (Reg == OldReg)
959
3.13k
      continue;
960
619
    // (Reg st0) (OldReg st0) = (Reg OldReg st0)
961
619
    moveToTop(Reg, I);
962
619
    if (FixCount > 0)
963
615
      moveToTop(OldReg, I);
964
619
  }
965
1.09k
  LLVM_DEBUG(dumpStack());
966
1.09k
}
967
968
969
//===----------------------------------------------------------------------===//
970
// Instruction transformation implementation
971
//===----------------------------------------------------------------------===//
972
973
1.35k
void FPS::handleCall(MachineBasicBlock::iterator &I) {
974
1.35k
  unsigned STReturns = 0;
975
1.35k
  const MachineFunction* MF = I->getParent()->getParent();
976
1.35k
977
10.3k
  for (const auto &MO : I->operands()) {
978
10.3k
    if (!MO.isReg())
979
2.72k
      continue;
980
7.60k
981
7.60k
    unsigned R = MO.getReg() - X86::FP0;
982
7.60k
983
7.60k
    if (R < 8) {
984
543
      if (MF->getFunction().getCallingConv() != CallingConv::X86_RegCall) {
985
537
        assert(MO.isDef() && MO.isImplicit());
986
537
      }
987
543
988
543
      STReturns |= 1 << R;
989
543
    }
990
7.60k
  }
991
1.35k
992
1.35k
  unsigned N = countTrailingOnes(STReturns);
993
1.35k
994
1.35k
  // FP registers used for function return must be consecutive starting at
995
1.35k
  // FP0
996
1.35k
  assert(STReturns == 0 || (isMask_32(STReturns) && N <= 2));
997
1.35k
998
1.35k
  // Reset the FP Stack - It is required because of possible leftovers from
999
1.35k
  // passed arguments. The caller should assume that the FP stack is
1000
1.35k
  // returned empty (unless the callee returns values on FP stack).
1001
1.36k
  while (StackTop > 0)
1002
3
    popReg();
1003
1.35k
1004
1.89k
  for (unsigned I = 0; I < N; 
++I540
)
1005
540
    pushReg(N - I - 1);
1006
1.35k
}
1007
1008
/// If RET has an FP register use operand, pass the first one in ST(0) and
1009
/// the second one in ST(1).
1010
2.10k
void FPS::handleReturn(MachineBasicBlock::iterator &I) {
1011
2.10k
  MachineInstr &MI = *I;
1012
2.10k
1013
2.10k
  // Find the register operands.
1014
2.10k
  unsigned FirstFPRegOp = ~0U, SecondFPRegOp = ~0U;
1015
2.10k
  unsigned LiveMask = 0;
1016
2.10k
1017
6.50k
  for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i4.40k
) {
1018
4.40k
    MachineOperand &Op = MI.getOperand(i);
1019
4.40k
    if (!Op.isReg() || 
Op.getReg() < X86::FP02.31k
||
Op.getReg() > X86::FP61.58k
)
1020
3.08k
      continue;
1021
1.32k
    // FP Register uses must be kills unless there are two uses of the same
1022
1.32k
    // register, in which case only one will be a kill.
1023
1.32k
    assert(Op.isUse() &&
1024
1.32k
           (Op.isKill() ||                    // Marked kill.
1025
1.32k
            getFPReg(Op) == FirstFPRegOp ||   // Second instance.
1026
1.32k
            MI.killsRegister(Op.getReg())) && // Later use is marked kill.
1027
1.32k
           "Ret only defs operands, and values aren't live beyond it");
1028
1.32k
1029
1.32k
    if (FirstFPRegOp == ~0U)
1030
1.15k
      FirstFPRegOp = getFPReg(Op);
1031
161
    else {
1032
161
      assert(SecondFPRegOp == ~0U && "More than two fp operands!");
1033
161
      SecondFPRegOp = getFPReg(Op);
1034
161
    }
1035
1.32k
    LiveMask |= (1 << getFPReg(Op));
1036
1.32k
1037
1.32k
    // Remove the operand so that later passes don't see it.
1038
1.32k
    MI.RemoveOperand(i);
1039
1.32k
    --i;
1040
1.32k
    --e;
1041
1.32k
  }
1042
2.10k
1043
2.10k
  // We may have been carrying spurious live-ins, so make sure only the
1044
2.10k
  // returned registers are left live.
1045
2.10k
  adjustLiveRegs(LiveMask, MI);
1046
2.10k
  if (!LiveMask) 
return945
; // Quick check to see if any are possible.
1047
1.15k
1048
1.15k
  // There are only four possibilities here:
1049
1.15k
  // 1) we are returning a single FP value.  In this case, it has to be in
1050
1.15k
  //    ST(0) already, so just declare success by removing the value from the
1051
1.15k
  //    FP Stack.
1052
1.15k
  if (SecondFPRegOp == ~0U) {
1053
998
    // Assert that the top of stack contains the right FP register.
1054
998
    assert(StackTop == 1 && FirstFPRegOp == getStackEntry(0) &&
1055
998
           "Top of stack not the right register for RET!");
1056
998
1057
998
    // Ok, everything is good, mark the value as not being on the stack
1058
998
    // anymore so that our assertion about the stack being empty at end of
1059
998
    // block doesn't fire.
1060
998
    StackTop = 0;
1061
998
    return;
1062
998
  }
1063
161
1064
161
  // Otherwise, we are returning two values:
1065
161
  // 2) If returning the same value for both, we only have one thing in the FP
1066
161
  //    stack.  Consider:  RET FP1, FP1
1067
161
  if (StackTop == 1) {
1068
2
    assert(FirstFPRegOp == SecondFPRegOp && FirstFPRegOp == getStackEntry(0)&&
1069
2
           "Stack misconfiguration for RET!");
1070
2
1071
2
    // Duplicate the TOS so that we return it twice.  Just pick some other FPx
1072
2
    // register to hold it.
1073
2
    unsigned NewReg = ScratchFPReg;
1074
2
    duplicateToTop(FirstFPRegOp, NewReg, MI);
1075
2
    FirstFPRegOp = NewReg;
1076
2
  }
1077
161
1078
161
  /// Okay we know we have two different FPx operands now:
1079
161
  assert(StackTop == 2 && "Must have two values live!");
1080
161
1081
161
  /// 3) If SecondFPRegOp is currently in ST(0) and FirstFPRegOp is currently
1082
161
  ///    in ST(1).  In this case, emit an fxch.
1083
161
  if (getStackEntry(0) == SecondFPRegOp) {
1084
11
    assert(getStackEntry(1) == FirstFPRegOp && "Unknown regs live");
1085
11
    moveToTop(FirstFPRegOp, MI);
1086
11
  }
1087
161
1088
161
  /// 4) Finally, FirstFPRegOp must be in ST(0) and SecondFPRegOp must be in
1089
161
  /// ST(1).  Just remove both from our understanding of the stack and return.
1090
161
  assert(getStackEntry(0) == FirstFPRegOp && "Unknown regs live");
1091
161
  assert(getStackEntry(1) == SecondFPRegOp && "Unknown regs live");
1092
161
  StackTop = 0;
1093
161
}
1094
1095
/// handleZeroArgFP - ST(0) = fld0    ST(0) = flds <mem>
1096
///
1097
5.89k
void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
1098
5.89k
  MachineInstr &MI = *I;
1099
5.89k
  unsigned DestReg = getFPReg(MI.getOperand(0));
1100
5.89k
1101
5.89k
  // Change from the pseudo instruction to the concrete instruction.
1102
5.89k
  MI.RemoveOperand(0); // Remove the explicit ST(0) operand
1103
5.89k
  MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));
1104
5.89k
  MI.addOperand(
1105
5.89k
      MachineOperand::CreateReg(X86::ST0, /*isDef*/ true, /*isImp*/ true));
1106
5.89k
1107
5.89k
  // Result gets pushed on the stack.
1108
5.89k
  pushReg(DestReg);
1109
5.89k
}
1110
1111
/// handleOneArgFP - fst <mem>, ST(0)
1112
///
1113
4.12k
void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
1114
4.12k
  MachineInstr &MI = *I;
1115
4.12k
  unsigned NumOps = MI.getDesc().getNumOperands();
1116
4.12k
  assert((NumOps == X86::AddrNumOperands + 1 || NumOps == 1) &&
1117
4.12k
         "Can only handle fst* & ftst instructions!");
1118
4.12k
1119
4.12k
  // Is this the last use of the source register?
1120
4.12k
  unsigned Reg = getFPReg(MI.getOperand(NumOps - 1));
1121
4.12k
  bool KillsSrc = MI.killsRegister(X86::FP0 + Reg);
1122
4.12k
1123
4.12k
  // FISTP64m is strange because there isn't a non-popping versions.
1124
4.12k
  // If we have one _and_ we don't want to pop the operand, duplicate the value
1125
4.12k
  // on the stack instead of moving it.  This ensure that popping the value is
1126
4.12k
  // always ok.
1127
4.12k
  // Ditto FISTTP16m, FISTTP32m, FISTTP64m, ST_FpP80m.
1128
4.12k
  //
1129
4.12k
  if (!KillsSrc && 
(508
MI.getOpcode() == X86::IST_Fp64m32508
||
1130
508
                    MI.getOpcode() == X86::ISTT_Fp16m32 ||
1131
508
                    MI.getOpcode() == X86::ISTT_Fp32m32 ||
1132
508
                    MI.getOpcode() == X86::ISTT_Fp64m32 ||
1133
508
                    MI.getOpcode() == X86::IST_Fp64m64 ||
1134
508
                    MI.getOpcode() == X86::ISTT_Fp16m64 ||
1135
508
                    MI.getOpcode() == X86::ISTT_Fp32m64 ||
1136
508
                    MI.getOpcode() == X86::ISTT_Fp64m64 ||
1137
508
                    MI.getOpcode() == X86::IST_Fp64m80 ||
1138
508
                    MI.getOpcode() == X86::ISTT_Fp16m80 ||
1139
508
                    MI.getOpcode() == X86::ISTT_Fp32m80 ||
1140
508
                    
MI.getOpcode() == X86::ISTT_Fp64m80500
||
1141
508
                    
MI.getOpcode() == X86::ST_FpP80m500
)) {
1142
345
    duplicateToTop(Reg, ScratchFPReg, I);
1143
3.78k
  } else {
1144
3.78k
    moveToTop(Reg, I);            // Move to the top of the stack...
1145
3.78k
  }
1146
4.12k
1147
4.12k
  // Convert from the pseudo instruction to the concrete instruction.
1148
4.12k
  MI.RemoveOperand(NumOps - 1); // Remove explicit ST(0) operand
1149
4.12k
  MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));
1150
4.12k
  MI.addOperand(
1151
4.12k
      MachineOperand::CreateReg(X86::ST0, /*isDef*/ false, /*isImp*/ true));
1152
4.12k
1153
4.12k
  if (MI.getOpcode() == X86::IST_FP64m || 
MI.getOpcode() == X86::ISTT_FP16m3.74k
||
1154
4.12k
      
MI.getOpcode() == X86::ISTT_FP32m3.74k
||
MI.getOpcode() == X86::ISTT_FP64m3.70k
||
1155
4.12k
      
MI.getOpcode() == X86::ST_FP80m3.63k
) {
1156
1.65k
    if (StackTop == 0)
1157
0
      report_fatal_error("Stack empty??");
1158
1.65k
    --StackTop;
1159
2.47k
  } else if (KillsSrc) { // Last use of operand?
1160
2.31k
    popStackAfter(I);
1161
2.31k
  }
1162
4.12k
}
1163
1164
1165
/// handleOneArgFPRW: Handle instructions that read from the top of stack and
1166
/// replace the value with a newly computed value.  These instructions may have
1167
/// non-fp operands after their FP operands.
1168
///
1169
///  Examples:
1170
///     R1 = fchs R2
1171
///     R1 = fadd R2, [mem]
1172
///
1173
1.14k
void FPS::handleOneArgFPRW(MachineBasicBlock::iterator &I) {
1174
1.14k
  MachineInstr &MI = *I;
1175
#ifndef NDEBUG
1176
  unsigned NumOps = MI.getDesc().getNumOperands();
1177
  assert(NumOps >= 2 && "FPRW instructions must have 2 ops!!");
1178
#endif
1179
1180
1.14k
  // Is this the last use of the source register?
1181
1.14k
  unsigned Reg = getFPReg(MI.getOperand(1));
1182
1.14k
  bool KillsSrc = MI.killsRegister(X86::FP0 + Reg);
1183
1.14k
1184
1.14k
  if (KillsSrc) {
1185
871
    // If this is the last use of the source register, just make sure it's on
1186
871
    // the top of the stack.
1187
871
    moveToTop(Reg, I);
1188
871
    if (StackTop == 0)
1189
0
      report_fatal_error("Stack cannot be empty!");
1190
871
    --StackTop;
1191
871
    pushReg(getFPReg(MI.getOperand(0)));
1192
871
  } else {
1193
273
    // If this is not the last use of the source register, _copy_ it to the top
1194
273
    // of the stack.
1195
273
    duplicateToTop(Reg, getFPReg(MI.getOperand(0)), I);
1196
273
  }
1197
1.14k
1198
1.14k
  // Change from the pseudo instruction to the concrete instruction.
1199
1.14k
  MI.RemoveOperand(1); // Drop the source operand.
1200
1.14k
  MI.RemoveOperand(0); // Drop the destination operand.
1201
1.14k
  MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));
1202
1.14k
}
1203
1204
1205
//===----------------------------------------------------------------------===//
1206
// Define tables of various ways to map pseudo instructions
1207
//
1208
1209
// ForwardST0Table - Map: A = B op C  into: ST(0) = ST(0) op ST(i)
1210
static const TableEntry ForwardST0Table[] = {
1211
  { X86::ADD_Fp32  , X86::ADD_FST0r },
1212
  { X86::ADD_Fp64  , X86::ADD_FST0r },
1213
  { X86::ADD_Fp80  , X86::ADD_FST0r },
1214
  { X86::DIV_Fp32  , X86::DIV_FST0r },
1215
  { X86::DIV_Fp64  , X86::DIV_FST0r },
1216
  { X86::DIV_Fp80  , X86::DIV_FST0r },
1217
  { X86::MUL_Fp32  , X86::MUL_FST0r },
1218
  { X86::MUL_Fp64  , X86::MUL_FST0r },
1219
  { X86::MUL_Fp80  , X86::MUL_FST0r },
1220
  { X86::SUB_Fp32  , X86::SUB_FST0r },
1221
  { X86::SUB_Fp64  , X86::SUB_FST0r },
1222
  { X86::SUB_Fp80  , X86::SUB_FST0r },
1223
};
1224
1225
// ReverseST0Table - Map: A = B op C  into: ST(0) = ST(i) op ST(0)
1226
static const TableEntry ReverseST0Table[] = {
1227
  { X86::ADD_Fp32  , X86::ADD_FST0r  },   // commutative
1228
  { X86::ADD_Fp64  , X86::ADD_FST0r  },   // commutative
1229
  { X86::ADD_Fp80  , X86::ADD_FST0r  },   // commutative
1230
  { X86::DIV_Fp32  , X86::DIVR_FST0r },
1231
  { X86::DIV_Fp64  , X86::DIVR_FST0r },
1232
  { X86::DIV_Fp80  , X86::DIVR_FST0r },
1233
  { X86::MUL_Fp32  , X86::MUL_FST0r  },   // commutative
1234
  { X86::MUL_Fp64  , X86::MUL_FST0r  },   // commutative
1235
  { X86::MUL_Fp80  , X86::MUL_FST0r  },   // commutative
1236
  { X86::SUB_Fp32  , X86::SUBR_FST0r },
1237
  { X86::SUB_Fp64  , X86::SUBR_FST0r },
1238
  { X86::SUB_Fp80  , X86::SUBR_FST0r },
1239
};
1240
1241
// ForwardSTiTable - Map: A = B op C  into: ST(i) = ST(0) op ST(i)
1242
static const TableEntry ForwardSTiTable[] = {
1243
  { X86::ADD_Fp32  , X86::ADD_FrST0  },   // commutative
1244
  { X86::ADD_Fp64  , X86::ADD_FrST0  },   // commutative
1245
  { X86::ADD_Fp80  , X86::ADD_FrST0  },   // commutative
1246
  { X86::DIV_Fp32  , X86::DIVR_FrST0 },
1247
  { X86::DIV_Fp64  , X86::DIVR_FrST0 },
1248
  { X86::DIV_Fp80  , X86::DIVR_FrST0 },
1249
  { X86::MUL_Fp32  , X86::MUL_FrST0  },   // commutative
1250
  { X86::MUL_Fp64  , X86::MUL_FrST0  },   // commutative
1251
  { X86::MUL_Fp80  , X86::MUL_FrST0  },   // commutative
1252
  { X86::SUB_Fp32  , X86::SUBR_FrST0 },
1253
  { X86::SUB_Fp64  , X86::SUBR_FrST0 },
1254
  { X86::SUB_Fp80  , X86::SUBR_FrST0 },
1255
};
1256
1257
// ReverseSTiTable - Map: A = B op C  into: ST(i) = ST(i) op ST(0)
1258
static const TableEntry ReverseSTiTable[] = {
1259
  { X86::ADD_Fp32  , X86::ADD_FrST0 },
1260
  { X86::ADD_Fp64  , X86::ADD_FrST0 },
1261
  { X86::ADD_Fp80  , X86::ADD_FrST0 },
1262
  { X86::DIV_Fp32  , X86::DIV_FrST0 },
1263
  { X86::DIV_Fp64  , X86::DIV_FrST0 },
1264
  { X86::DIV_Fp80  , X86::DIV_FrST0 },
1265
  { X86::MUL_Fp32  , X86::MUL_FrST0 },
1266
  { X86::MUL_Fp64  , X86::MUL_FrST0 },
1267
  { X86::MUL_Fp80  , X86::MUL_FrST0 },
1268
  { X86::SUB_Fp32  , X86::SUB_FrST0 },
1269
  { X86::SUB_Fp64  , X86::SUB_FrST0 },
1270
  { X86::SUB_Fp80  , X86::SUB_FrST0 },
1271
};
1272
1273
1274
/// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
1275
/// instructions which need to be simplified and possibly transformed.
1276
///
1277
/// Result: ST(0) = fsub  ST(0), ST(i)
1278
///         ST(i) = fsub  ST(0), ST(i)
1279
///         ST(0) = fsubr ST(0), ST(i)
1280
///         ST(i) = fsubr ST(0), ST(i)
1281
///
1282
981
void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
1283
981
  ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
1284
981
  ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
1285
981
  MachineInstr &MI = *I;
1286
981
1287
981
  unsigned NumOperands = MI.getDesc().getNumOperands();
1288
981
  assert(NumOperands == 3 && "Illegal TwoArgFP instruction!");
1289
981
  unsigned Dest = getFPReg(MI.getOperand(0));
1290
981
  unsigned Op0 = getFPReg(MI.getOperand(NumOperands - 2));
1291
981
  unsigned Op1 = getFPReg(MI.getOperand(NumOperands - 1));
1292
981
  bool KillsOp0 = MI.killsRegister(X86::FP0 + Op0);
1293
981
  bool KillsOp1 = MI.killsRegister(X86::FP0 + Op1);
1294
981
  DebugLoc dl = MI.getDebugLoc();
1295
981
1296
981
  unsigned TOS = getStackEntry(0);
1297
981
1298
981
  // One of our operands must be on the top of the stack.  If neither is yet, we
1299
981
  // need to move one.
1300
981
  if (Op0 != TOS && 
Op1 != TOS684
) { // No operand at TOS?
1301
280
    // We can choose to move either operand to the top of the stack.  If one of
1302
280
    // the operands is killed by this instruction, we want that one so that we
1303
280
    // can update right on top of the old version.
1304
280
    if (KillsOp0) {
1305
178
      moveToTop(Op0, I);         // Move dead operand to TOS.
1306
178
      TOS = Op0;
1307
178
    } else 
if (102
KillsOp1102
) {
1308
11
      moveToTop(Op1, I);
1309
11
      TOS = Op1;
1310
91
    } else {
1311
91
      // All of the operands are live after this instruction executes, so we
1312
91
      // cannot update on top of any operand.  Because of this, we must
1313
91
      // duplicate one of the stack elements to the top.  It doesn't matter
1314
91
      // which one we pick.
1315
91
      //
1316
91
      duplicateToTop(Op0, Dest, I);
1317
91
      Op0 = TOS = Dest;
1318
91
      KillsOp0 = true;
1319
91
    }
1320
701
  } else if (!KillsOp0 && 
!KillsOp1225
) {
1321
193
    // If we DO have one of our operands at the top of the stack, but we don't
1322
193
    // have a dead operand, we must duplicate one of the operands to a new slot
1323
193
    // on the stack.
1324
193
    duplicateToTop(Op0, Dest, I);
1325
193
    Op0 = TOS = Dest;
1326
193
    KillsOp0 = true;
1327
193
  }
1328
981
1329
981
  // Now we know that one of our operands is on the top of the stack, and at
1330
981
  // least one of our operands is killed by this instruction.
1331
981
  assert((TOS == Op0 || TOS == Op1) && (KillsOp0 || KillsOp1) &&
1332
981
         "Stack conditions not set up right!");
1333
981
1334
981
  // We decide which form to use based on what is on the top of the stack, and
1335
981
  // which operand is killed by this instruction.
1336
981
  ArrayRef<TableEntry> InstTable;
1337
981
  bool isForward = TOS == Op0;
1338
981
  bool updateST0 = (TOS == Op0 && 
!KillsOp1720
) ||
(610
TOS == Op1610
&&
!KillsOp0303
);
1339
981
  if (updateST0) {
1340
413
    if (isForward)
1341
371
      InstTable = ForwardST0Table;
1342
42
    else
1343
42
      InstTable = ReverseST0Table;
1344
568
  } else {
1345
568
    if (isForward)
1346
349
      InstTable = ForwardSTiTable;
1347
219
    else
1348
219
      InstTable = ReverseSTiTable;
1349
568
  }
1350
981
1351
981
  int Opcode = Lookup(InstTable, MI.getOpcode());
1352
981
  assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
1353
981
1354
981
  // NotTOS - The register which is not on the top of stack...
1355
981
  unsigned NotTOS = (TOS == Op0) ? 
Op1720
:
Op0261
;
1356
981
1357
981
  // Replace the old instruction with a new instruction
1358
981
  MBB->remove(&*I++);
1359
981
  I = BuildMI(*MBB, I, dl, TII->get(Opcode)).addReg(getSTReg(NotTOS));
1360
981
1361
981
  // If both operands are killed, pop one off of the stack in addition to
1362
981
  // overwriting the other one.
1363
981
  if (KillsOp0 && 
KillsOp1938
&&
Op0 != Op1549
) {
1364
507
    assert(!updateST0 && "Should have updated other operand!");
1365
507
    popStackAfter(I);   // Pop the top of stack
1366
507
  }
1367
981
1368
981
  // Update stack information so that we know the destination register is now on
1369
981
  // the stack.
1370
981
  unsigned UpdatedSlot = getSlot(updateST0 ? 
TOS413
:
NotTOS568
);
1371
981
  assert(UpdatedSlot < StackTop && Dest < 7);
1372
981
  Stack[UpdatedSlot]   = Dest;
1373
981
  RegMap[Dest]         = UpdatedSlot;
1374
981
  MBB->getParent()->DeleteMachineInstr(&MI); // Remove the old instruction
1375
981
}
1376
1377
/// handleCompareFP - Handle FUCOM and FUCOMI instructions, which have two FP
1378
/// register arguments and no explicit destinations.
1379
///
1380
873
void FPS::handleCompareFP(MachineBasicBlock::iterator &I) {
1381
873
  MachineInstr &MI = *I;
1382
873
1383
873
  unsigned NumOperands = MI.getDesc().getNumOperands();
1384
873
  assert(NumOperands == 2 && "Illegal FUCOM* instruction!");
1385
873
  unsigned Op0 = getFPReg(MI.getOperand(NumOperands - 2));
1386
873
  unsigned Op1 = getFPReg(MI.getOperand(NumOperands - 1));
1387
873
  bool KillsOp0 = MI.killsRegister(X86::FP0 + Op0);
1388
873
  bool KillsOp1 = MI.killsRegister(X86::FP0 + Op1);
1389
873
1390
873
  // Make sure the first operand is on the top of stack, the other one can be
1391
873
  // anywhere.
1392
873
  moveToTop(Op0, I);
1393
873
1394
873
  // Change from the pseudo instruction to the concrete instruction.
1395
873
  MI.getOperand(0).setReg(getSTReg(Op1));
1396
873
  MI.RemoveOperand(1);
1397
873
  MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));
1398
873
1399
873
  // If any of the operands are killed by this instruction, free them.
1400
873
  if (KillsOp0) 
freeStackSlotAfter(I, Op0)522
;
1401
873
  if (KillsOp1 && 
Op0 != Op1258
)
freeStackSlotAfter(I, Op1)202
;
1402
873
}
1403
1404
/// handleCondMovFP - Handle two address conditional move instructions.  These
1405
/// instructions move a st(i) register to st(0) iff a condition is true.  These
1406
/// instructions require that the first operand is at the top of the stack, but
1407
/// otherwise don't modify the stack at all.
1408
479
void FPS::handleCondMovFP(MachineBasicBlock::iterator &I) {
1409
479
  MachineInstr &MI = *I;
1410
479
1411
479
  unsigned Op0 = getFPReg(MI.getOperand(0));
1412
479
  unsigned Op1 = getFPReg(MI.getOperand(2));
1413
479
  bool KillsOp1 = MI.killsRegister(X86::FP0 + Op1);
1414
479
1415
479
  // The first operand *must* be on the top of the stack.
1416
479
  moveToTop(Op0, I);
1417
479
1418
479
  // Change the second operand to the stack register that the operand is in.
1419
479
  // Change from the pseudo instruction to the concrete instruction.
1420
479
  MI.RemoveOperand(0);
1421
479
  MI.RemoveOperand(1);
1422
479
  MI.getOperand(0).setReg(getSTReg(Op1));
1423
479
  MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));
1424
479
1425
479
  // If we kill the second operand, make sure to pop it from the stack.
1426
479
  if (Op0 != Op1 && KillsOp1) {
1427
382
    // Get this value off of the register stack.
1428
382
    freeStackSlotAfter(I, Op1);
1429
382
  }
1430
479
}
1431
1432
1433
/// handleSpecialFP - Handle special instructions which behave unlike other
1434
/// floating point instructions.  This is primarily intended for use by pseudo
1435
/// instructions.
1436
///
1437
4.07k
void FPS::handleSpecialFP(MachineBasicBlock::iterator &Inst) {
1438
4.07k
  MachineInstr &MI = *Inst;
1439
4.07k
1440
4.07k
  if (MI.isCall()) {
1441
1.35k
    handleCall(Inst);
1442
1.35k
    return;
1443
1.35k
  }
1444
2.72k
1445
2.72k
  if (MI.isReturn()) {
1446
2.10k
    handleReturn(Inst);
1447
2.10k
    return;
1448
2.10k
  }
1449
617
1450
617
  switch (MI.getOpcode()) {
1451
617
  
default: 0
llvm_unreachable0
("Unknown SpecialFP instruction!");
1452
617
  case TargetOpcode::COPY: {
1453
567
    // We handle three kinds of copies: FP <- FP, FP <- ST, and ST <- FP.
1454
567
    const MachineOperand &MO1 = MI.getOperand(1);
1455
567
    const MachineOperand &MO0 = MI.getOperand(0);
1456
567
    bool KillsSrc = MI.killsRegister(MO1.getReg());
1457
567
1458
567
    // FP <- FP copy.
1459
567
    unsigned DstFP = getFPReg(MO0);
1460
567
    unsigned SrcFP = getFPReg(MO1);
1461
567
    assert(isLive(SrcFP) && "Cannot copy dead register");
1462
567
    if (KillsSrc) {
1463
311
      // If the input operand is killed, we can just change the owner of the
1464
311
      // incoming stack slot into the result.
1465
311
      unsigned Slot = getSlot(SrcFP);
1466
311
      Stack[Slot] = DstFP;
1467
311
      RegMap[DstFP] = Slot;
1468
311
    } else {
1469
256
      // For COPY we just duplicate the specified value to a new stack slot.
1470
256
      // This could be made better, but would require substantial changes.
1471
256
      duplicateToTop(SrcFP, DstFP, Inst);
1472
256
    }
1473
567
    break;
1474
617
  }
1475
617
1476
617
  case TargetOpcode::IMPLICIT_DEF: {
1477
0
    // All FP registers must be explicitly defined, so load a 0 instead.
1478
0
    unsigned Reg = MI.getOperand(0).getReg() - X86::FP0;
1479
0
    LLVM_DEBUG(dbgs() << "Emitting LD_F0 for implicit FP" << Reg << '\n');
1480
0
    BuildMI(*MBB, Inst, MI.getDebugLoc(), TII->get(X86::LD_F0));
1481
0
    pushReg(Reg);
1482
0
    break;
1483
617
  }
1484
617
1485
617
  case TargetOpcode::INLINEASM:
1486
50
  case TargetOpcode::INLINEASM_BR: {
1487
50
    // The inline asm MachineInstr currently only *uses* FP registers for the
1488
50
    // 'f' constraint.  These should be turned into the current ST(x) register
1489
50
    // in the machine instr.
1490
50
    //
1491
50
    // There are special rules for x87 inline assembly. The compiler must know
1492
50
    // exactly how many registers are popped and pushed implicitly by the asm.
1493
50
    // Otherwise it is not possible to restore the stack state after the inline
1494
50
    // asm.
1495
50
    //
1496
50
    // There are 3 kinds of input operands:
1497
50
    //
1498
50
    // 1. Popped inputs. These must appear at the stack top in ST0-STn. A
1499
50
    //    popped input operand must be in a fixed stack slot, and it is either
1500
50
    //    tied to an output operand, or in the clobber list. The MI has ST use
1501
50
    //    and def operands for these inputs.
1502
50
    //
1503
50
    // 2. Fixed inputs. These inputs appear in fixed stack slots, but are
1504
50
    //    preserved by the inline asm. The fixed stack slots must be STn-STm
1505
50
    //    following the popped inputs. A fixed input operand cannot be tied to
1506
50
    //    an output or appear in the clobber list. The MI has ST use operands
1507
50
    //    and no defs for these inputs.
1508
50
    //
1509
50
    // 3. Preserved inputs. These inputs use the "f" constraint which is
1510
50
    //    represented as an FP register. The inline asm won't change these
1511
50
    //    stack slots.
1512
50
    //
1513
50
    // Outputs must be in ST registers, FP outputs are not allowed. Clobbered
1514
50
    // registers do not count as output operands. The inline asm changes the
1515
50
    // stack as if it popped all the popped inputs and then pushed all the
1516
50
    // output operands.
1517
50
1518
50
    // Scan the assembly for ST registers used, defined and clobbered. We can
1519
50
    // only tell clobbers from defs by looking at the asm descriptor.
1520
50
    unsigned STUses = 0, STDefs = 0, STClobbers = 0, STDeadDefs = 0;
1521
50
    unsigned NumOps = 0;
1522
50
    SmallSet<unsigned, 1> FRegIdx;
1523
50
    unsigned RCID;
1524
50
1525
50
    for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI.getNumOperands();
1526
274
         i != e && 
MI.getOperand(i).isImm()224
;
i += 1 + NumOps224
) {
1527
224
      unsigned Flags = MI.getOperand(i).getImm();
1528
224
1529
224
      NumOps = InlineAsm::getNumOperandRegisters(Flags);
1530
224
      if (NumOps != 1)
1531
3
        continue;
1532
221
      const MachineOperand &MO = MI.getOperand(i + 1);
1533
221
      if (!MO.isReg())
1534
1
        continue;
1535
220
      unsigned STReg = MO.getReg() - X86::FP0;
1536
220
      if (STReg >= 8)
1537
142
        continue;
1538
78
1539
78
      // If the flag has a register class constraint, this must be an operand
1540
78
      // with constraint "f". Record its index and continue.
1541
78
      if (InlineAsm::hasRegClassConstraint(Flags, RCID)) {
1542
12
        FRegIdx.insert(i + 1);
1543
12
        continue;
1544
12
      }
1545
66
1546
66
      switch (InlineAsm::getKind(Flags)) {
1547
66
      case InlineAsm::Kind_RegUse:
1548
30
        STUses |= (1u << STReg);
1549
30
        break;
1550
66
      case InlineAsm::Kind_RegDef:
1551
21
      case InlineAsm::Kind_RegDefEarlyClobber:
1552
21
        STDefs |= (1u << STReg);
1553
21
        if (MO.isDead())
1554
8
          STDeadDefs |= (1u << STReg);
1555
21
        break;
1556
21
      case InlineAsm::Kind_Clobber:
1557
15
        STClobbers |= (1u << STReg);
1558
15
        break;
1559
21
      default:
1560
0
        break;
1561
66
      }
1562
66
    }
1563
50
1564
50
    if (STUses && 
!isMask_32(STUses)26
)
1565
0
      MI.emitError("fixed input regs must be last on the x87 stack");
1566
50
    unsigned NumSTUses = countTrailingOnes(STUses);
1567
50
1568
50
    // Defs must be contiguous from the stack top. ST0-STn.
1569
50
    if (STDefs && 
!isMask_32(STDefs)15
) {
1570
0
      MI.emitError("output regs must be last on the x87 stack");
1571
0
      STDefs = NextPowerOf2(STDefs) - 1;
1572
0
    }
1573
50
    unsigned NumSTDefs = countTrailingOnes(STDefs);
1574
50
1575
50
    // So must the clobbered stack slots. ST0-STm, m >= n.
1576
50
    if (STClobbers && 
!isMask_32(STDefs | STClobbers)14
)
1577
0
      MI.emitError("clobbers must be last on the x87 stack");
1578
50
1579
50
    // Popped inputs are the ones that are also clobbered or defined.
1580
50
    unsigned STPopped = STUses & (STDefs | STClobbers);
1581
50
    if (STPopped && 
!isMask_32(STPopped)23
)
1582
0
      MI.emitError("implicitly popped regs must be last on the x87 stack");
1583
50
    unsigned NumSTPopped = countTrailingOnes(STPopped);
1584
50
1585
50
    LLVM_DEBUG(dbgs() << "Asm uses " << NumSTUses << " fixed regs, pops "
1586
50
                      << NumSTPopped << ", and defines " << NumSTDefs
1587
50
                      << " regs.\n");
1588
50
1589
#ifndef NDEBUG
1590
    // If any input operand uses constraint "f", all output register
1591
    // constraints must be early-clobber defs.
1592
    for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I)
1593
      if (FRegIdx.count(I)) {
1594
        assert((1 << getFPReg(MI.getOperand(I)) & STDefs) == 0 &&
1595
               "Operands with constraint \"f\" cannot overlap with defs");
1596
      }
1597
#endif
1598
1599
50
    // Collect all FP registers (register operands with constraints "t", "u",
1600
50
    // and "f") to kill afer the instruction.
1601
50
    unsigned FPKills = ((1u << NumFPRegs) - 1) & ~0xff;
1602
610
    for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i560
) {
1603
560
      MachineOperand &Op = MI.getOperand(i);
1604
560
      if (!Op.isReg() || 
Op.getReg() < X86::FP0229
||
Op.getReg() > X86::FP686
)
1605
482
        continue;
1606
78
      unsigned FPReg = getFPReg(Op);
1607
78
1608
78
      // If we kill this operand, make sure to pop it from the stack after the
1609
78
      // asm.  We just remember it for now, and pop them all off at the end in
1610
78
      // a batch.
1611
78
      if (Op.isUse() && 
Op.isKill()42
)
1612
40
        FPKills |= 1U << FPReg;
1613
78
    }
1614
50
1615
50
    // Do not include registers that are implicitly popped by defs/clobbers.
1616
50
    FPKills &= ~(STDefs | STClobbers);
1617
50
1618
50
    // Now we can rearrange the live registers to match what was requested.
1619
50
    unsigned char STUsesArray[8];
1620
50
1621
80
    for (unsigned I = 0; I < NumSTUses; 
++I30
)
1622
30
      STUsesArray[I] = I;
1623
50
1624
50
    shuffleStackTop(STUsesArray, NumSTUses, Inst);
1625
50
    LLVM_DEBUG({
1626
50
      dbgs() << "Before asm: ";
1627
50
      dumpStack();
1628
50
    });
1629
50
1630
50
    // With the stack layout fixed, rewrite the FP registers.
1631
610
    for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i560
) {
1632
560
      MachineOperand &Op = MI.getOperand(i);
1633
560
      if (!Op.isReg() || 
Op.getReg() < X86::FP0229
||
Op.getReg() > X86::FP686
)
1634
482
        continue;
1635
78
1636
78
      unsigned FPReg = getFPReg(Op);
1637
78
1638
78
      if (FRegIdx.count(i))
1639
12
        // Operand with constraint "f".
1640
12
        Op.setReg(getSTReg(FPReg));
1641
66
      else
1642
66
        // Operand with a single register class constraint ("t" or "u").
1643
66
        Op.setReg(X86::ST0 + FPReg);
1644
78
    }
1645
50
1646
50
    // Simulate the inline asm popping its inputs and pushing its outputs.
1647
50
    StackTop -= NumSTPopped;
1648
50
1649
71
    for (unsigned i = 0; i < NumSTDefs; 
++i21
)
1650
21
      pushReg(NumSTDefs - i - 1);
1651
50
1652
50
    // If this asm kills any FP registers (is the last use of them) we must
1653
50
    // explicitly emit pop instructions for them.  Do this now after the asm has
1654
50
    // executed so that the ST(x) numbers are not off (which would happen if we
1655
50
    // did this inline with operand rewriting).
1656
50
    //
1657
50
    // Note: this might be a non-optimal pop sequence.  We might be able to do
1658
50
    // better by trying to pop in stack order or something.
1659
64
    while (FPKills) {
1660
14
      unsigned FPReg = countTrailingZeros(FPKills);
1661
14
      if (isLive(FPReg))
1662
14
        freeStackSlotAfter(Inst, FPReg);
1663
14
      FPKills &= ~(1U << FPReg);
1664
14
    }
1665
50
1666
50
    // Don't delete the inline asm!
1667
50
    return;
1668
567
  }
1669
567
  }
1670
567
1671
567
  Inst = MBB->erase(Inst);  // Remove the pseudo instruction
1672
567
1673
567
  // We want to leave I pointing to the previous instruction, but what if we
1674
567
  // just erased the first instruction?
1675
567
  if (Inst == MBB->begin()) {
1676
0
    LLVM_DEBUG(dbgs() << "Inserting dummy KILL\n");
1677
0
    Inst = BuildMI(*MBB, Inst, DebugLoc(), TII->get(TargetOpcode::KILL));
1678
0
  } else
1679
567
    --Inst;
1680
567
}
1681
1682
6.21k
void FPS::setKillFlags(MachineBasicBlock &MBB) const {
1683
6.21k
  const TargetRegisterInfo &TRI =
1684
6.21k
      *MBB.getParent()->getSubtarget().getRegisterInfo();
1685
6.21k
  LivePhysRegs LPR(TRI);
1686
6.21k
1687
6.21k
  LPR.addLiveOuts(MBB);
1688
6.21k
1689
6.21k
  for (MachineBasicBlock::reverse_iterator I = MBB.rbegin(), E = MBB.rend();
1690
61.3k
       I != E; 
++I55.0k
) {
1691
55.0k
    if (I->isDebugInstr())
1692
3
      continue;
1693
55.0k
1694
55.0k
    std::bitset<8> Defs;
1695
55.0k
    SmallVector<MachineOperand *, 2> Uses;
1696
55.0k
    MachineInstr &MI = *I;
1697
55.0k
1698
293k
    for (auto &MO : I->operands()) {
1699
293k
      if (!MO.isReg())
1700
100k
        continue;
1701
193k
1702
193k
      unsigned Reg = MO.getReg() - X86::FP0;
1703
193k
1704
193k
      if (Reg >= 8)
1705
171k
        continue;
1706
21.9k
1707
21.9k
      if (MO.isDef()) {
1708
10.1k
        Defs.set(Reg);
1709
10.1k
        if (!LPR.contains(MO.getReg()))
1710
520
          MO.setIsDead();
1711
10.1k
      } else
1712
11.8k
        Uses.push_back(&MO);
1713
21.9k
    }
1714
55.0k
1715
55.0k
    for (auto *MO : Uses)
1716
11.8k
      if (Defs.test(getFPReg(*MO)) || 
!LPR.contains(MO->getReg())10.0k
)
1717
9.05k
        MO->setIsKill();
1718
55.0k
1719
55.0k
    LPR.stepBackward(MI);
1720
55.0k
  }
1721
6.21k
}