Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MipsConstantIslandPass.cpp - Emit Pc Relative loads ----------------===//
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 pass is used to make Pc relative loads of constants.
10
// For now, only Mips16 will use this.
11
//
12
// Loading constants inline is expensive on Mips16 and it's in general better
13
// to place the constant nearby in code space and then it can be loaded with a
14
// simple 16 bit load instruction.
15
//
16
// The constants can be not just numbers but addresses of functions and labels.
17
// This can be particularly helpful in static relocation mode for embedded
18
// non-linux targets.
19
//
20
//===----------------------------------------------------------------------===//
21
22
#include "Mips.h"
23
#include "Mips16InstrInfo.h"
24
#include "MipsMachineFunction.h"
25
#include "MipsSubtarget.h"
26
#include "llvm/ADT/STLExtras.h"
27
#include "llvm/ADT/SmallSet.h"
28
#include "llvm/ADT/SmallVector.h"
29
#include "llvm/ADT/Statistic.h"
30
#include "llvm/ADT/StringRef.h"
31
#include "llvm/CodeGen/MachineBasicBlock.h"
32
#include "llvm/CodeGen/MachineConstantPool.h"
33
#include "llvm/CodeGen/MachineFunction.h"
34
#include "llvm/CodeGen/MachineFunctionPass.h"
35
#include "llvm/CodeGen/MachineInstr.h"
36
#include "llvm/CodeGen/MachineInstrBuilder.h"
37
#include "llvm/CodeGen/MachineOperand.h"
38
#include "llvm/CodeGen/MachineRegisterInfo.h"
39
#include "llvm/Config/llvm-config.h"
40
#include "llvm/IR/Constants.h"
41
#include "llvm/IR/DataLayout.h"
42
#include "llvm/IR/DebugLoc.h"
43
#include "llvm/IR/Function.h"
44
#include "llvm/IR/Type.h"
45
#include "llvm/Support/CommandLine.h"
46
#include "llvm/Support/Compiler.h"
47
#include "llvm/Support/Debug.h"
48
#include "llvm/Support/ErrorHandling.h"
49
#include "llvm/Support/Format.h"
50
#include "llvm/Support/MathExtras.h"
51
#include "llvm/Support/raw_ostream.h"
52
#include <algorithm>
53
#include <cassert>
54
#include <cstdint>
55
#include <iterator>
56
#include <vector>
57
58
using namespace llvm;
59
60
#define DEBUG_TYPE "mips-constant-islands"
61
62
STATISTIC(NumCPEs,       "Number of constpool entries");
63
STATISTIC(NumSplit,      "Number of uncond branches inserted");
64
STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
65
STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
66
67
// FIXME: This option should be removed once it has received sufficient testing.
68
static cl::opt<bool>
69
AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
70
          cl::desc("Align constant islands in code"));
71
72
// Rather than do make check tests with huge amounts of code, we force
73
// the test to use this amount.
74
static cl::opt<int> ConstantIslandsSmallOffset(
75
  "mips-constant-islands-small-offset",
76
  cl::init(0),
77
  cl::desc("Make small offsets be this amount for testing purposes"),
78
  cl::Hidden);
79
80
// For testing purposes we tell it to not use relaxed load forms so that it
81
// will split blocks.
82
static cl::opt<bool> NoLoadRelaxation(
83
  "mips-constant-islands-no-load-relaxation",
84
  cl::init(false),
85
  cl::desc("Don't relax loads to long loads - for testing purposes"),
86
  cl::Hidden);
87
88
344
static unsigned int branchTargetOperand(MachineInstr *MI) {
89
344
  switch (MI->getOpcode()) {
90
344
  case Mips::Bimm16:
91
261
  case Mips::BimmX16:
92
261
  case Mips::Bteqz16:
93
261
  case Mips::BteqzX16:
94
261
  case Mips::Btnez16:
95
261
  case Mips::BtnezX16:
96
261
  case Mips::JalB16:
97
261
    return 0;
98
261
  case Mips::BeqzRxImm16:
99
83
  case Mips::BeqzRxImmX16:
100
83
  case Mips::BnezRxImm16:
101
83
  case Mips::BnezRxImmX16:
102
83
    return 1;
103
0
  }
104
0
  llvm_unreachable("Unknown branch type");
105
0
}
106
107
24
static unsigned int longformBranchOpcode(unsigned int Opcode) {
108
24
  switch (Opcode) {
109
24
  case Mips::Bimm16:
110
0
  case Mips::BimmX16:
111
0
    return Mips::BimmX16;
112
4
  case Mips::Bteqz16:
113
4
  case Mips::BteqzX16:
114
4
    return Mips::BteqzX16;
115
8
  case Mips::Btnez16:
116
8
  case Mips::BtnezX16:
117
8
    return Mips::BtnezX16;
118
8
  case Mips::JalB16:
119
0
    return Mips::JalB16;
120
8
  case Mips::BeqzRxImm16:
121
8
  case Mips::BeqzRxImmX16:
122
8
    return Mips::BeqzRxImmX16;
123
8
  case Mips::BnezRxImm16:
124
4
  case Mips::BnezRxImmX16:
125
4
    return Mips::BnezRxImmX16;
126
0
  }
127
0
  llvm_unreachable("Unknown branch type");
128
0
}
129
130
// FIXME: need to go through this whole constant islands port and check the math
131
// for branch ranges and clean this up and make some functions to calculate things
132
// that are done many times identically.
133
// Need to refactor some of the code to call this routine.
134
24
static unsigned int branchMaxOffsets(unsigned int Opcode) {
135
24
  unsigned Bits, Scale;
136
24
  switch (Opcode) {
137
24
    case Mips::Bimm16:
138
0
      Bits = 11;
139
0
      Scale = 2;
140
0
      break;
141
24
    case Mips::BimmX16:
142
0
      Bits = 16;
143
0
      Scale = 2;
144
0
      break;
145
24
    case Mips::BeqzRxImm16:
146
0
      Bits = 8;
147
0
      Scale = 2;
148
0
      break;
149
24
    case Mips::BeqzRxImmX16:
150
8
      Bits = 16;
151
8
      Scale = 2;
152
8
      break;
153
24
    case Mips::BnezRxImm16:
154
0
      Bits = 8;
155
0
      Scale = 2;
156
0
      break;
157
24
    case Mips::BnezRxImmX16:
158
4
      Bits = 16;
159
4
      Scale = 2;
160
4
      break;
161
24
    case Mips::Bteqz16:
162
0
      Bits = 8;
163
0
      Scale = 2;
164
0
      break;
165
24
    case Mips::BteqzX16:
166
4
      Bits = 16;
167
4
      Scale = 2;
168
4
      break;
169
24
    case Mips::Btnez16:
170
0
      Bits = 8;
171
0
      Scale = 2;
172
0
      break;
173
24
    case Mips::BtnezX16:
174
8
      Bits = 16;
175
8
      Scale = 2;
176
8
      break;
177
24
    default:
178
0
      llvm_unreachable("Unknown branch type");
179
24
  }
180
24
  unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
181
24
  return MaxOffs;
182
24
}
183
184
namespace {
185
186
  using Iter = MachineBasicBlock::iterator;
187
  using ReverseIter = MachineBasicBlock::reverse_iterator;
188
189
  /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
190
  /// requires constant pool entries to be scattered among the instructions
191
  /// inside a function.  To do this, it completely ignores the normal LLVM
192
  /// constant pool; instead, it places constants wherever it feels like with
193
  /// special instructions.
194
  ///
195
  /// The terminology used in this pass includes:
196
  ///   Islands - Clumps of constants placed in the function.
197
  ///   Water   - Potential places where an island could be formed.
198
  ///   CPE     - A constant pool entry that has been placed somewhere, which
199
  ///             tracks a list of users.
200
201
  class MipsConstantIslands : public MachineFunctionPass {
202
    /// BasicBlockInfo - Information about the offset and size of a single
203
    /// basic block.
204
    struct BasicBlockInfo {
205
      /// Offset - Distance from the beginning of the function to the beginning
206
      /// of this basic block.
207
      ///
208
      /// Offsets are computed assuming worst case padding before an aligned
209
      /// block. This means that subtracting basic block offsets always gives a
210
      /// conservative estimate of the real distance which may be smaller.
211
      ///
212
      /// Because worst case padding is used, the computed offset of an aligned
213
      /// block may not actually be aligned.
214
      unsigned Offset = 0;
215
216
      /// Size - Size of the basic block in bytes.  If the block contains
217
      /// inline assembly, this is a worst case estimate.
218
      ///
219
      /// The size does not include any alignment padding whether from the
220
      /// beginning of the block, or from an aligned jump table at the end.
221
      unsigned Size = 0;
222
223
782
      BasicBlockInfo() = default;
224
225
      // FIXME: ignore LogAlign for this patch
226
      //
227
21
      unsigned postOffset(unsigned LogAlign = 0) const {
228
21
        unsigned PO = Offset + Size;
229
21
        return PO;
230
21
      }
231
    };
232
233
    std::vector<BasicBlockInfo> BBInfo;
234
235
    /// WaterList - A sorted list of basic blocks where islands could be placed
236
    /// (i.e. blocks that don't fall through to the following block, due
237
    /// to a return, unreachable, or unconditional branch).
238
    std::vector<MachineBasicBlock*> WaterList;
239
240
    /// NewWaterList - The subset of WaterList that was created since the
241
    /// previous iteration by inserting unconditional branches.
242
    SmallSet<MachineBasicBlock*, 4> NewWaterList;
243
244
    using water_iterator = std::vector<MachineBasicBlock *>::iterator;
245
246
    /// CPUser - One user of a constant pool, keeping the machine instruction
247
    /// pointer, the constant pool being referenced, and the max displacement
248
    /// allowed from the instruction to the CP.  The HighWaterMark records the
249
    /// highest basic block where a new CPEntry can be placed.  To ensure this
250
    /// pass terminates, the CP entries are initially placed at the end of the
251
    /// function and then move monotonically to lower addresses.  The
252
    /// exception to this rule is when the current CP entry for a particular
253
    /// CPUser is out of range, but there is another CP entry for the same
254
    /// constant value in range.  We want to use the existing in-range CP
255
    /// entry, but if it later moves out of range, the search for new water
256
    /// should resume where it left off.  The HighWaterMark is used to record
257
    /// that point.
258
    struct CPUser {
259
      MachineInstr *MI;
260
      MachineInstr *CPEMI;
261
      MachineBasicBlock *HighWaterMark;
262
263
    private:
264
      unsigned MaxDisp;
265
      unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
266
                                // with different displacements
267
      unsigned LongFormOpcode;
268
269
    public:
270
      bool NegOk;
271
272
      CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
273
             bool neg,
274
             unsigned longformmaxdisp, unsigned longformopcode)
275
        : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
276
          LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
277
34
          NegOk(neg){
278
34
        HighWaterMark = CPEMI->getParent();
279
34
      }
280
281
      /// getMaxDisp - Returns the maximum displacement supported by MI.
282
55
      unsigned getMaxDisp() const {
283
55
        unsigned xMaxDisp = ConstantIslandsSmallOffset?
284
55
                            
ConstantIslandsSmallOffset0
: MaxDisp;
285
55
        return xMaxDisp;
286
55
      }
287
288
3
      void setMaxDisp(unsigned val) {
289
3
        MaxDisp = val;
290
3
      }
291
292
6
      unsigned getLongFormMaxDisp() const {
293
6
        return LongFormMaxDisp;
294
6
      }
295
296
3
      unsigned getLongFormOpcode() const {
297
3
          return LongFormOpcode;
298
3
      }
299
    };
300
301
    /// CPUsers - Keep track of all of the machine instructions that use various
302
    /// constant pools and their max displacement.
303
    std::vector<CPUser> CPUsers;
304
305
  /// CPEntry - One per constant pool entry, keeping the machine instruction
306
  /// pointer, the constpool index, and the number of CPUser's which
307
  /// reference this entry.
308
  struct CPEntry {
309
    MachineInstr *CPEMI;
310
    unsigned CPI;
311
    unsigned RefCount;
312
313
    CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
314
37
      : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
315
  };
316
317
  /// CPEntries - Keep track of all of the constant pool entry machine
318
  /// instructions. For each original constpool index (i.e. those that
319
  /// existed upon entry to this pass), it keeps a vector of entries.
320
  /// Original elements are cloned as we go along; the clones are
321
  /// put in the vector of the original element, but have distinct CPIs.
322
  std::vector<std::vector<CPEntry>> CPEntries;
323
324
  /// ImmBranch - One per immediate branch, keeping the machine instruction
325
  /// pointer, conditional or unconditional, the max displacement,
326
  /// and (if isCond is true) the corresponding unconditional branch
327
  /// opcode.
328
  struct ImmBranch {
329
    MachineInstr *MI;
330
    unsigned MaxDisp : 31;
331
    bool isCond : 1;
332
    int UncondBr;
333
334
    ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
335
259
      : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
336
  };
337
338
  /// ImmBranches - Keep track of all the immediate branch instructions.
339
  ///
340
  std::vector<ImmBranch> ImmBranches;
341
342
  /// HasFarJump - True if any far jump instruction has been emitted during
343
  /// the branch fix up pass.
344
  bool HasFarJump;
345
346
  const MipsSubtarget *STI = nullptr;
347
  const Mips16InstrInfo *TII;
348
  MipsFunctionInfo *MFI;
349
  MachineFunction *MF = nullptr;
350
  MachineConstantPool *MCP = nullptr;
351
352
  unsigned PICLabelUId;
353
  bool PrescannedForConstants = false;
354
355
379
  void initPICLabelUId(unsigned UId) {
356
379
    PICLabelUId = UId;
357
379
  }
358
359
3
  unsigned createPICLabelUId() {
360
3
    return PICLabelUId++;
361
3
  }
362
363
  public:
364
    static char ID;
365
366
2.09k
    MipsConstantIslands() : MachineFunctionPass(ID) {}
367
368
15.2k
    StringRef getPassName() const override { return "Mips Constant Islands"; }
369
370
    bool runOnMachineFunction(MachineFunction &F) override;
371
372
2.01k
    MachineFunctionProperties getRequiredProperties() const override {
373
2.01k
      return MachineFunctionProperties().set(
374
2.01k
          MachineFunctionProperties::Property::NoVRegs);
375
2.01k
    }
376
377
    void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
378
    CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
379
    unsigned getCPELogAlign(const MachineInstr &CPEMI);
380
    void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
381
    unsigned getOffsetOf(MachineInstr *MI) const;
382
    unsigned getUserOffset(CPUser&) const;
383
    void dumpBBs();
384
385
    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
386
                         unsigned Disp, bool NegativeOK);
387
    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
388
                         const CPUser &U);
389
390
    void computeBlockSize(MachineBasicBlock *MBB);
391
    MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
392
    void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
393
    void adjustBBOffsetsAfter(MachineBasicBlock *BB);
394
    bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
395
    int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
396
    int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
397
    bool findAvailableWater(CPUser&U, unsigned UserOffset,
398
                            water_iterator &WaterIter);
399
    void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
400
                        MachineBasicBlock *&NewMBB);
401
    bool handleConstantPoolUser(unsigned CPUserIndex);
402
    void removeDeadCPEMI(MachineInstr *CPEMI);
403
    bool removeUnusedCPEntries();
404
    bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
405
                          MachineInstr *CPEMI, unsigned Disp, bool NegOk,
406
                          bool DoDump = false);
407
    bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
408
                        CPUser &U, unsigned &Growth);
409
    bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
410
    bool fixupImmediateBr(ImmBranch &Br);
411
    bool fixupConditionalBr(ImmBranch &Br);
412
    bool fixupUnconditionalBr(ImmBranch &Br);
413
414
    void prescanForConstants();
415
  };
416
417
} // end anonymous namespace
418
419
char MipsConstantIslands::ID = 0;
420
421
bool MipsConstantIslands::isOffsetInRange
422
  (unsigned UserOffset, unsigned TrialOffset,
423
14
   const CPUser &U) {
424
14
  return isOffsetInRange(UserOffset, TrialOffset,
425
14
                         U.getMaxDisp(), U.NegOk);
426
14
}
427
428
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
429
/// print block size and offset information - debugging
430
LLVM_DUMP_METHOD void MipsConstantIslands::dumpBBs() {
431
  for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
432
    const BasicBlockInfo &BBI = BBInfo[J];
433
    dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
434
           << format(" size=%#x\n", BBInfo[J].Size);
435
  }
436
}
437
#endif
438
439
13.2k
bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
440
13.2k
  // The intention is for this to be a mips16 only pass for now
441
13.2k
  // FIXME:
442
13.2k
  MF = &mf;
443
13.2k
  MCP = mf.getConstantPool();
444
13.2k
  STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
445
13.2k
  LLVM_DEBUG(dbgs() << "constant island machine function "
446
13.2k
                    << "\n");
447
13.2k
  if (!STI->inMips16Mode() || 
!MipsSubtarget::useConstantIslands()380
) {
448
12.8k
    return false;
449
12.8k
  }
450
379
  TII = (const Mips16InstrInfo *)STI->getInstrInfo();
451
379
  MFI = MF->getInfo<MipsFunctionInfo>();
452
379
  LLVM_DEBUG(dbgs() << "constant island processing "
453
379
                    << "\n");
454
379
  //
455
379
  // will need to make predermination if there is any constants we need to
456
379
  // put in constant islands. TBD.
457
379
  //
458
379
  if (!PrescannedForConstants) 
prescanForConstants()337
;
459
379
460
379
  HasFarJump = false;
461
379
  // This pass invalidates liveness information when it splits basic blocks.
462
379
  MF->getRegInfo().invalidateLiveness();
463
379
464
379
  // Renumber all of the machine basic blocks in the function, guaranteeing that
465
379
  // the numbers agree with the position of the block in the function.
466
379
  MF->RenumberBlocks();
467
379
468
379
  bool MadeChange = false;
469
379
470
379
  // Perform the initial placement of the constant pool entries.  To start with,
471
379
  // we put them all at the end of the function.
472
379
  std::vector<MachineInstr*> CPEMIs;
473
379
  if (!MCP->isEmpty())
474
20
    doInitialPlacement(CPEMIs);
475
379
476
379
  /// The next UID to take is the first unused one.
477
379
  initPICLabelUId(CPEMIs.size());
478
379
479
379
  // Do the initial scan of the function, building up information about the
480
379
  // sizes of each block, the location of all the water, and finding all of the
481
379
  // constant pool users.
482
379
  initializeFunctionInfo(CPEMIs);
483
379
  CPEMIs.clear();
484
379
  LLVM_DEBUG(dumpBBs());
485
379
486
379
  /// Remove dead constant pool entries.
487
379
  MadeChange |= removeUnusedCPEntries();
488
379
489
379
  // Iteratively place constant pool entries and fix up branches until there
490
379
  // is no change.
491
379
  unsigned NoCPIters = 0, NoBRIters = 0;
492
379
  (void)NoBRIters;
493
413
  while (true) {
494
413
    LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
495
413
    bool CPChange = false;
496
453
    for (unsigned i = 0, e = CPUsers.size(); i != e; 
++i40
)
497
40
      CPChange |= handleConstantPoolUser(i);
498
413
    if (CPChange && 
++NoCPIters > 306
)
499
0
      report_fatal_error("Constant Island pass failed to converge!");
500
413
    LLVM_DEBUG(dumpBBs());
501
413
502
413
    // Clear NewWaterList now.  If we split a block for branches, it should
503
413
    // appear as "new water" for the next iteration of constant pool placement.
504
413
    NewWaterList.clear();
505
413
506
413
    LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
507
413
    bool BRChange = false;
508
732
    for (unsigned i = 0, e = ImmBranches.size(); i != e; 
++i319
)
509
319
      BRChange |= fixupImmediateBr(ImmBranches[i]);
510
413
    if (BRChange && 
++NoBRIters > 3028
)
511
0
      report_fatal_error("Branch Fix Up pass failed to converge!");
512
413
    LLVM_DEBUG(dumpBBs());
513
413
    if (!CPChange && 
!BRChange407
)
514
379
      break;
515
34
    MadeChange = true;
516
34
  }
517
379
518
379
  LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
519
379
520
379
  BBInfo.clear();
521
379
  WaterList.clear();
522
379
  CPUsers.clear();
523
379
  CPEntries.clear();
524
379
  ImmBranches.clear();
525
379
  return MadeChange;
526
379
}
527
528
/// doInitialPlacement - Perform the initial placement of the constant pool
529
/// entries.  To start with, we put them all at the end of the function.
530
void
531
20
MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
532
20
  // Create the basic block to hold the CPE's.
533
20
  MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
534
20
  MF->push_back(BB);
535
20
536
20
  // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
537
20
  unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
538
20
539
20
  // Mark the basic block as required by the const-pool.
540
20
  // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
541
20
  BB->setAlignment(AlignConstantIslands ? MaxAlign : 
20
);
542
20
543
20
  // The function needs to be as aligned as the basic blocks. The linker may
544
20
  // move functions around based on their alignment.
545
20
  MF->ensureAlignment(BB->getAlignment());
546
20
547
20
  // Order the entries in BB by descending alignment.  That ensures correct
548
20
  // alignment of all entries as long as BB is sufficiently aligned.  Keep
549
20
  // track of the insertion point for each alignment.  We are going to bucket
550
20
  // sort the entries as they are created.
551
20
  SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
552
20
553
20
  // Add all of the constants from the constant pool to the end block, use an
554
20
  // identity mapping of CPI's to CPE's.
555
20
  const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
556
20
557
20
  const DataLayout &TD = MF->getDataLayout();
558
54
  for (unsigned i = 0, e = CPs.size(); i != e; 
++i34
) {
559
34
    unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
560
34
    assert(Size >= 4 && "Too small constant pool entry");
561
34
    unsigned Align = CPs[i].getAlignment();
562
34
    assert(isPowerOf2_32(Align) && "Invalid alignment");
563
34
    // Verify that all constant pool entries are a multiple of their alignment.
564
34
    // If not, we would have to pad them out so that instructions stay aligned.
565
34
    assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
566
34
567
34
    // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
568
34
    unsigned LogAlign = Log2_32(Align);
569
34
    MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
570
34
571
34
    MachineInstr *CPEMI =
572
34
      BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
573
34
        .addImm(i).addConstantPoolIndex(i).addImm(Size);
574
34
575
34
    CPEMIs.push_back(CPEMI);
576
34
577
34
    // Ensure that future entries with higher alignment get inserted before
578
34
    // CPEMI. This is bucket sort with iterators.
579
34
    for (unsigned a = LogAlign + 1; a <= MaxAlign; 
++a0
)
580
0
      if (InsPoint[a] == InsAt)
581
0
        InsPoint[a] = CPEMI;
582
34
    // Add a new CPEntry, but no corresponding CPUser yet.
583
34
    CPEntries.emplace_back(1, CPEntry(CPEMI, i));
584
34
    ++NumCPEs;
585
34
    LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
586
34
                      << Size << ", align = " << Align << '\n');
587
34
  }
588
20
  LLVM_DEBUG(BB->dump());
589
20
}
590
591
/// BBHasFallthrough - Return true if the specified basic block can fallthrough
592
/// into the block immediately after it.
593
785
static bool BBHasFallthrough(MachineBasicBlock *MBB) {
594
785
  // Get the next machine basic block in the function.
595
785
  MachineFunction::iterator MBBI = MBB->getIterator();
596
785
  // Can't fall off end of function.
597
785
  if (std::next(MBBI) == MBB->getParent()->end())
598
379
    return false;
599
406
600
406
  MachineBasicBlock *NextBB = &*std::next(MBBI);
601
406
  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
602
515
       E = MBB->succ_end(); I != E; 
++I109
)
603
413
    if (*I == NextBB)
604
304
      return true;
605
406
606
406
  
return false102
;
607
406
}
608
609
/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
610
/// look up the corresponding CPEntry.
611
MipsConstantIslands::CPEntry
612
*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
613
37
                                        const MachineInstr *CPEMI) {
614
37
  std::vector<CPEntry> &CPEs = CPEntries[CPI];
615
37
  // Number of entries per constpool index should be small, just do a
616
37
  // linear search.
617
37
  for (unsigned i = 0, e = CPEs.size(); i != e; 
++i0
) {
618
37
    if (CPEs[i].CPEMI == CPEMI)
619
37
      return &CPEs[i];
620
37
  }
621
37
  
return nullptr0
;
622
37
}
623
624
/// getCPELogAlign - Returns the required alignment of the constant pool entry
625
/// represented by CPEMI.  Alignment is measured in log2(bytes) units.
626
18
unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr &CPEMI) {
627
18
  assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
628
18
629
18
  // Everything is 4-byte aligned unless AlignConstantIslands is set.
630
18
  if (!AlignConstantIslands)
631
0
    return 2;
632
18
633
18
  unsigned CPI = CPEMI.getOperand(1).getIndex();
634
18
  assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
635
18
  unsigned Align = MCP->getConstants()[CPI].getAlignment();
636
18
  assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
637
18
  return Log2_32(Align);
638
18
}
639
640
/// initializeFunctionInfo - Do the initial scan of the function, building up
641
/// information about the sizes of each block, the location of all the water,
642
/// and finding all of the constant pool users.
643
void MipsConstantIslands::
644
379
initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
645
379
  BBInfo.clear();
646
379
  BBInfo.resize(MF->getNumBlockIDs());
647
379
648
379
  // First thing, compute the size of all basic blocks, and see if the function
649
379
  // has any inline assembly in it. If so, we have to be conservative about
650
379
  // alignment assumptions, as we don't know for sure the size of any
651
379
  // instructions in the inline assembly.
652
1.15k
  for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; 
++I778
)
653
778
    computeBlockSize(&*I);
654
379
655
379
  // Compute block offsets.
656
379
  adjustBBOffsetsAfter(&MF->front());
657
379
658
379
  // Now go back through the instructions and build up our data structures.
659
778
  for (MachineBasicBlock &MBB : *MF) {
660
778
    // If this block doesn't fall through into the next MBB, then this is
661
778
    // 'water' that a constant pool island could be placed.
662
778
    if (!BBHasFallthrough(&MBB))
663
480
      WaterList.push_back(&MBB);
664
12.8k
    for (MachineInstr &MI : MBB) {
665
12.8k
      if (MI.isDebugInstr())
666
0
        continue;
667
12.8k
668
12.8k
      int Opc = MI.getOpcode();
669
12.8k
      if (MI.isBranch()) {
670
642
        bool isCond = false;
671
642
        unsigned Bits = 0;
672
642
        unsigned Scale = 1;
673
642
        int UOpc = Opc;
674
642
        switch (Opc) {
675
642
        default:
676
389
          continue;  // Ignore other branches for now
677
642
        case Mips::Bimm16:
678
75
          Bits = 11;
679
75
          Scale = 2;
680
75
          isCond = false;
681
75
          break;
682
642
        case Mips::BimmX16:
683
0
          Bits = 16;
684
0
          Scale = 2;
685
0
          isCond = false;
686
0
          break;
687
642
        case Mips::BeqzRxImm16:
688
18
          UOpc=Mips::Bimm16;
689
18
          Bits = 8;
690
18
          Scale = 2;
691
18
          isCond = true;
692
18
          break;
693
642
        case Mips::BeqzRxImmX16:
694
0
          UOpc=Mips::Bimm16;
695
0
          Bits = 16;
696
0
          Scale = 2;
697
0
          isCond = true;
698
0
          break;
699
642
        case Mips::BnezRxImm16:
700
36
          UOpc=Mips::Bimm16;
701
36
          Bits = 8;
702
36
          Scale = 2;
703
36
          isCond = true;
704
36
          break;
705
642
        case Mips::BnezRxImmX16:
706
0
          UOpc=Mips::Bimm16;
707
0
          Bits = 16;
708
0
          Scale = 2;
709
0
          isCond = true;
710
0
          break;
711
642
        case Mips::Bteqz16:
712
55
          UOpc=Mips::Bimm16;
713
55
          Bits = 8;
714
55
          Scale = 2;
715
55
          isCond = true;
716
55
          break;
717
642
        case Mips::BteqzX16:
718
0
          UOpc=Mips::Bimm16;
719
0
          Bits = 16;
720
0
          Scale = 2;
721
0
          isCond = true;
722
0
          break;
723
642
        case Mips::Btnez16:
724
69
          UOpc=Mips::Bimm16;
725
69
          Bits = 8;
726
69
          Scale = 2;
727
69
          isCond = true;
728
69
          break;
729
642
        case Mips::BtnezX16:
730
0
          UOpc=Mips::Bimm16;
731
0
          Bits = 16;
732
0
          Scale = 2;
733
0
          isCond = true;
734
0
          break;
735
253
        }
736
253
        // Record this immediate branch.
737
253
        unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
738
253
        ImmBranches.push_back(ImmBranch(&MI, MaxOffs, isCond, UOpc));
739
253
      }
740
12.8k
741
12.8k
      
if (12.4k
Opc == Mips::CONSTPOOL_ENTRY12.4k
)
742
34
        continue;
743
12.4k
744
12.4k
      // Scan the instructions for constant pool operands.
745
49.6k
      
for (unsigned op = 0, e = MI.getNumOperands(); 12.4k
op != e;
++op37.2k
)
746
37.2k
        if (MI.getOperand(op).isCPI()) {
747
34
          // We found one.  The addressing mode tells us the max displacement
748
34
          // from the PC that this instruction permits.
749
34
750
34
          // Basic size info comes from the TSFlags field.
751
34
          unsigned Bits = 0;
752
34
          unsigned Scale = 1;
753
34
          bool NegOk = false;
754
34
          unsigned LongFormBits = 0;
755
34
          unsigned LongFormScale = 0;
756
34
          unsigned LongFormOpcode = 0;
757
34
          switch (Opc) {
758
34
          default:
759
0
            llvm_unreachable("Unknown addressing mode for CP reference!");
760
34
          case Mips::LwRxPcTcp16:
761
34
            Bits = 8;
762
34
            Scale = 4;
763
34
            LongFormOpcode = Mips::LwRxPcTcpX16;
764
34
            LongFormBits = 14;
765
34
            LongFormScale = 1;
766
34
            break;
767
34
          case Mips::LwRxPcTcpX16:
768
0
            Bits = 14;
769
0
            Scale = 1;
770
0
            NegOk = true;
771
0
            break;
772
34
          }
773
34
          // Remember that this is a user of a CP entry.
774
34
          unsigned CPI = MI.getOperand(op).getIndex();
775
34
          MachineInstr *CPEMI = CPEMIs[CPI];
776
34
          unsigned MaxOffs = ((1 << Bits)-1) * Scale;
777
34
          unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
778
34
          CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs,
779
34
                                   LongFormOpcode));
780
34
781
34
          // Increment corresponding CPEntry reference count.
782
34
          CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
783
34
          assert(CPE && "Cannot find a corresponding CPEntry!");
784
34
          CPE->RefCount++;
785
34
786
34
          // Instructions can only use one CP entry, don't bother scanning the
787
34
          // rest of the operands.
788
34
          break;
789
34
        }
790
12.4k
    }
791
778
  }
792
379
}
793
794
/// computeBlockSize - Compute the size and some alignment information for MBB.
795
/// This function updates BBInfo directly.
796
780
void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
797
780
  BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
798
780
  BBI.Size = 0;
799
780
800
780
  for (const MachineInstr &MI : *MBB)
801
13.3k
    BBI.Size += TII->getInstSizeInBytes(MI);
802
780
}
803
804
/// getOffsetOf - Return the current offset of the specified machine instruction
805
/// from the start of the function.  This offset changes as stuff is moved
806
/// around inside the function.
807
442
unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
808
442
  MachineBasicBlock *MBB = MI->getParent();
809
442
810
442
  // The offset is composed of two things: the sum of the sizes of all MBB's
811
442
  // before this instruction's block, and the offset from the start of the block
812
442
  // it is in.
813
442
  unsigned Offset = BBInfo[MBB->getNumber()].Offset;
814
442
815
442
  // Sum instructions before MI in MBB.
816
4.40k
  for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; 
++I3.95k
) {
817
3.95k
    assert(I != MBB->end() && "Didn't find MI in its own basic block?");
818
3.95k
    Offset += TII->getInstSizeInBytes(*I);
819
3.95k
  }
820
442
  return Offset;
821
442
}
822
823
/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
824
/// ID.
825
static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
826
8
                              const MachineBasicBlock *RHS) {
827
8
  return LHS->getNumber() < RHS->getNumber();
828
8
}
829
830
/// updateForInsertedWaterBlock - When a block is newly inserted into the
831
/// machine function, it upsets all of the block numbers.  Renumber the blocks
832
/// and update the arrays that parallel this numbering.
833
void MipsConstantIslands::updateForInsertedWaterBlock
834
3
  (MachineBasicBlock *NewBB) {
835
3
  // Renumber the MBB's to keep them consecutive.
836
3
  NewBB->getParent()->RenumberBlocks(NewBB);
837
3
838
3
  // Insert an entry into BBInfo to align it properly with the (newly
839
3
  // renumbered) block numbers.
840
3
  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
841
3
842
3
  // Next, update WaterList.  Specifically, we need to add NewMBB as having
843
3
  // available water after it.
844
3
  water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
845
3
  WaterList.insert(IP, NewBB);
846
3
}
847
848
40
unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
849
40
  return getOffsetOf(U.MI);
850
40
}
851
852
/// Split the basic block containing MI into two blocks, which are joined by
853
/// an unconditional branch.  Update data structures and renumber blocks to
854
/// account for this change and returns the newly created block.
855
MachineBasicBlock *
856
1
MipsConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
857
1
  MachineBasicBlock *OrigBB = MI.getParent();
858
1
859
1
  // Create a new MBB for the code after the OrigBB.
860
1
  MachineBasicBlock *NewBB =
861
1
    MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
862
1
  MachineFunction::iterator MBBI = ++OrigBB->getIterator();
863
1
  MF->insert(MBBI, NewBB);
864
1
865
1
  // Splice the instructions starting with MI over to NewBB.
866
1
  NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
867
1
868
1
  // Add an unconditional branch from OrigBB to NewBB.
869
1
  // Note the new unconditional branch is not being recorded.
870
1
  // There doesn't seem to be meaningful DebugInfo available; this doesn't
871
1
  // correspond to anything in the source.
872
1
  BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
873
1
  ++NumSplit;
874
1
875
1
  // Update the CFG.  All succs of OrigBB are now succs of NewBB.
876
1
  NewBB->transferSuccessors(OrigBB);
877
1
878
1
  // OrigBB branches to NewBB.
879
1
  OrigBB->addSuccessor(NewBB);
880
1
881
1
  // Update internal data structures to account for the newly inserted MBB.
882
1
  // This is almost the same as updateForInsertedWaterBlock, except that
883
1
  // the Water goes after OrigBB, not NewBB.
884
1
  MF->RenumberBlocks(NewBB);
885
1
886
1
  // Insert an entry into BBInfo to align it properly with the (newly
887
1
  // renumbered) block numbers.
888
1
  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
889
1
890
1
  // Next, update WaterList.  Specifically, we need to add OrigMBB as having
891
1
  // available water after it (but not if it's already there, which happens
892
1
  // when splitting before a conditional branch that is followed by an
893
1
  // unconditional branch - in that case we want to insert NewBB).
894
1
  water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
895
1
  MachineBasicBlock* WaterBB = *IP;
896
1
  if (WaterBB == OrigBB)
897
1
    WaterList.insert(std::next(IP), NewBB);
898
0
  else
899
0
    WaterList.insert(IP, OrigBB);
900
1
  NewWaterList.insert(OrigBB);
901
1
902
1
  // Figure out how large the OrigBB is.  As the first half of the original
903
1
  // block, it cannot contain a tablejump.  The size includes
904
1
  // the new jump we added.  (It should be possible to do this without
905
1
  // recounting everything, but it's very confusing, and this is rarely
906
1
  // executed.)
907
1
  computeBlockSize(OrigBB);
908
1
909
1
  // Figure out how large the NewMBB is.  As the second half of the original
910
1
  // block, it may contain a tablejump.
911
1
  computeBlockSize(NewBB);
912
1
913
1
  // All BBOffsets following these blocks must be modified.
914
1
  adjustBBOffsetsAfter(OrigBB);
915
1
916
1
  return NewBB;
917
1
}
918
919
/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
920
/// reference) is within MaxDisp of TrialOffset (a proposed location of a
921
/// constant pool entry).
922
bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
923
                                         unsigned TrialOffset, unsigned MaxDisp,
924
57
                                         bool NegativeOK) {
925
57
  if (UserOffset <= TrialOffset) {
926
57
    // User before the Trial.
927
57
    if (TrialOffset - UserOffset <= MaxDisp)
928
39
      return true;
929
0
  } else if (NegativeOK) {
930
0
    if (UserOffset - TrialOffset <= MaxDisp)
931
0
      return true;
932
18
  }
933
18
  return false;
934
18
}
935
936
/// isWaterInRange - Returns true if a CPE placed after the specified
937
/// Water (a basic block) will be in range for the specific MI.
938
///
939
/// Compute how much the function will grow by inserting a CPE after Water.
940
bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
941
                                        MachineBasicBlock* Water, CPUser &U,
942
14
                                        unsigned &Growth) {
943
14
  unsigned CPELogAlign = getCPELogAlign(*U.CPEMI);
944
14
  unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
945
14
  unsigned NextBlockOffset, NextBlockAlignment;
946
14
  MachineFunction::const_iterator NextBlock = ++Water->getIterator();
947
14
  if (NextBlock == MF->end()) {
948
6
    NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
949
6
    NextBlockAlignment = 0;
950
8
  } else {
951
8
    NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
952
8
    NextBlockAlignment = NextBlock->getAlignment();
953
8
  }
954
14
  unsigned Size = U.CPEMI->getOperand(2).getImm();
955
14
  unsigned CPEEnd = CPEOffset + Size;
956
14
957
14
  // The CPE may be able to hide in the alignment padding before the next
958
14
  // block. It may also cause more padding to be required if it is more aligned
959
14
  // that the next block.
960
14
  if (CPEEnd > NextBlockOffset) {
961
14
    Growth = CPEEnd - NextBlockOffset;
962
14
    // Compute the padding that would go at the end of the CPE to align the next
963
14
    // block.
964
14
    Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
965
14
966
14
    // If the CPE is to be inserted before the instruction, that will raise
967
14
    // the offset of the instruction. Also account for unknown alignment padding
968
14
    // in blocks between CPE and the user.
969
14
    if (CPEOffset < UserOffset)
970
0
      UserOffset += Growth;
971
14
  } else
972
0
    // CPE fits in existing padding.
973
0
    Growth = 0;
974
14
975
14
  return isOffsetInRange(UserOffset, CPEOffset, U);
976
14
}
977
978
/// isCPEntryInRange - Returns true if the distance between specific MI and
979
/// specific ConstPool entry instruction can fit in MI's displacement field.
980
bool MipsConstantIslands::isCPEntryInRange
981
  (MachineInstr *MI, unsigned UserOffset,
982
   MachineInstr *CPEMI, unsigned MaxDisp,
983
43
   bool NegOk, bool DoDump) {
984
43
  unsigned CPEOffset  = getOffsetOf(CPEMI);
985
43
986
43
  if (DoDump) {
987
43
    LLVM_DEBUG({
988
43
      unsigned Block = MI->getParent()->getNumber();
989
43
      const BasicBlockInfo &BBI = BBInfo[Block];
990
43
      dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
991
43
             << " max delta=" << MaxDisp
992
43
             << format(" insn address=%#x", UserOffset) << " in "
993
43
             << printMBBReference(*MI->getParent()) << ": "
994
43
             << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
995
43
             << format("CPE address=%#x offset=%+d: ", CPEOffset,
996
43
                       int(CPEOffset - UserOffset));
997
43
    });
998
43
  }
999
43
1000
43
  return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1001
43
}
1002
1003
#ifndef NDEBUG
1004
/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1005
/// unconditionally branches to its only successor.
1006
static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1007
  if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1008
    return false;
1009
  MachineBasicBlock *Succ = *MBB->succ_begin();
1010
  MachineBasicBlock *Pred = *MBB->pred_begin();
1011
  MachineInstr *PredMI = &Pred->back();
1012
  if (PredMI->getOpcode() == Mips::Bimm16)
1013
    return PredMI->getOperand(0).getMBB() == Succ;
1014
  return false;
1015
}
1016
#endif
1017
1018
407
void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1019
407
  unsigned BBNum = BB->getNumber();
1020
860
  for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; 
++i453
) {
1021
453
    // Get the offset and known bits at the end of the layout predecessor.
1022
453
    // Include the alignment of the current block.
1023
453
    unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
1024
453
    BBInfo[i].Offset = Offset;
1025
453
  }
1026
407
}
1027
1028
/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1029
/// and instruction CPEMI, and decrement its refcount.  If the refcount
1030
/// becomes 0 remove the entry and instruction.  Returns true if we removed
1031
/// the entry, false if we didn't.
1032
bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1033
3
                                                    MachineInstr *CPEMI) {
1034
3
  // Find the old entry. Eliminate it if it is no longer used.
1035
3
  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1036
3
  assert(CPE && "Unexpected!");
1037
3
  if (--CPE->RefCount == 0) {
1038
3
    removeDeadCPEMI(CPEMI);
1039
3
    CPE->CPEMI = nullptr;
1040
3
    --NumCPEs;
1041
3
    return true;
1042
3
  }
1043
0
  return false;
1044
0
}
1045
1046
/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1047
/// if not, see if an in-range clone of the CPE is in range, and if so,
1048
/// change the data structures so the user references the clone.  Returns:
1049
/// 0 = no existing entry found
1050
/// 1 = entry found, and there were no code insertions or deletions
1051
/// 2 = entry found, and there were code insertions or deletions
1052
int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1053
40
{
1054
40
  MachineInstr *UserMI = U.MI;
1055
40
  MachineInstr *CPEMI  = U.CPEMI;
1056
40
1057
40
  // Check to see if the CPE is already in-range.
1058
40
  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1059
40
                       true)) {
1060
34
    LLVM_DEBUG(dbgs() << "In range\n");
1061
34
    return 1;
1062
34
  }
1063
6
1064
6
  // No.  Look for previously created clones of the CPE that are in range.
1065
6
  unsigned CPI = CPEMI->getOperand(1).getIndex();
1066
6
  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1067
12
  for (unsigned i = 0, e = CPEs.size(); i != e; 
++i6
) {
1068
6
    // We already tried this one
1069
6
    if (CPEs[i].CPEMI == CPEMI)
1070
6
      continue;
1071
0
    // Removing CPEs can leave empty entries, skip
1072
0
    if (CPEs[i].CPEMI == nullptr)
1073
0
      continue;
1074
0
    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1075
0
                     U.NegOk)) {
1076
0
      LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1077
0
                        << CPEs[i].CPI << "\n");
1078
0
      // Point the CPUser node to the replacement
1079
0
      U.CPEMI = CPEs[i].CPEMI;
1080
0
      // Change the CPI in the instruction operand to refer to the clone.
1081
0
      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1082
0
        if (UserMI->getOperand(j).isCPI()) {
1083
0
          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1084
0
          break;
1085
0
        }
1086
0
      // Adjust the refcount of the clone...
1087
0
      CPEs[i].RefCount++;
1088
0
      // ...and the original.  If we didn't remove the old entry, none of the
1089
0
      // addresses changed, so we don't need another pass.
1090
0
      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1091
0
    }
1092
0
  }
1093
6
  return 0;
1094
6
}
1095
1096
/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1097
/// This version checks if the longer form of the instruction can be used to
1098
/// to satisfy things.
1099
/// if not, see if an in-range clone of the CPE is in range, and if so,
1100
/// change the data structures so the user references the clone.  Returns:
1101
/// 0 = no existing entry found
1102
/// 1 = entry found, and there were no code insertions or deletions
1103
/// 2 = entry found, and there were code insertions or deletions
1104
int MipsConstantIslands::findLongFormInRangeCPEntry
1105
  (CPUser& U, unsigned UserOffset)
1106
3
{
1107
3
  MachineInstr *UserMI = U.MI;
1108
3
  MachineInstr *CPEMI  = U.CPEMI;
1109
3
1110
3
  // Check to see if the CPE is already in-range.
1111
3
  if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1112
3
                       U.getLongFormMaxDisp(), U.NegOk,
1113
3
                       true)) {
1114
3
    LLVM_DEBUG(dbgs() << "In range\n");
1115
3
    UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1116
3
    U.setMaxDisp(U.getLongFormMaxDisp());
1117
3
    return 2;  // instruction is longer length now
1118
3
  }
1119
0
1120
0
  // No.  Look for previously created clones of the CPE that are in range.
1121
0
  unsigned CPI = CPEMI->getOperand(1).getIndex();
1122
0
  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1123
0
  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1124
0
    // We already tried this one
1125
0
    if (CPEs[i].CPEMI == CPEMI)
1126
0
      continue;
1127
0
    // Removing CPEs can leave empty entries, skip
1128
0
    if (CPEs[i].CPEMI == nullptr)
1129
0
      continue;
1130
0
    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1131
0
                         U.getLongFormMaxDisp(), U.NegOk)) {
1132
0
      LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1133
0
                        << CPEs[i].CPI << "\n");
1134
0
      // Point the CPUser node to the replacement
1135
0
      U.CPEMI = CPEs[i].CPEMI;
1136
0
      // Change the CPI in the instruction operand to refer to the clone.
1137
0
      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1138
0
        if (UserMI->getOperand(j).isCPI()) {
1139
0
          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1140
0
          break;
1141
0
        }
1142
0
      // Adjust the refcount of the clone...
1143
0
      CPEs[i].RefCount++;
1144
0
      // ...and the original.  If we didn't remove the old entry, none of the
1145
0
      // addresses changed, so we don't need another pass.
1146
0
      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1147
0
    }
1148
0
  }
1149
0
  return 0;
1150
0
}
1151
1152
/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1153
/// the specific unconditional branch instruction.
1154
6
static inline unsigned getUnconditionalBrDisp(int Opc) {
1155
6
  switch (Opc) {
1156
6
  case Mips::Bimm16:
1157
6
    return ((1<<10)-1)*2;
1158
6
  case Mips::BimmX16:
1159
0
    return ((1<<16)-1)*2;
1160
6
  default:
1161
0
    break;
1162
0
  }
1163
0
  return ((1<<16)-1)*2;
1164
0
}
1165
1166
/// findAvailableWater - Look for an existing entry in the WaterList in which
1167
/// we can place the CPE referenced from U so it's within range of U's MI.
1168
/// Returns true if found, false if not.  If it returns true, WaterIter
1169
/// is set to the WaterList entry.
1170
/// To ensure that this pass
1171
/// terminates, the CPE location for a particular CPUser is only allowed to
1172
/// move to a lower address, so search backward from the end of the list and
1173
/// prefer the first water that is in range.
1174
bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1175
6
                                      water_iterator &WaterIter) {
1176
6
  if (WaterList.empty())
1177
0
    return false;
1178
6
1179
6
  unsigned BestGrowth = ~0u;
1180
6
  for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1181
14
       
--IP8
) {
1182
14
    MachineBasicBlock* WaterBB = *IP;
1183
14
    // Check if water is in range and is either at a lower address than the
1184
14
    // current "high water mark" or a new water block that was created since
1185
14
    // the previous iteration by inserting an unconditional branch.  In the
1186
14
    // latter case, we want to allow resetting the high water mark back to
1187
14
    // this new water since we haven't seen it before.  Inserting branches
1188
14
    // should be relatively uncommon and when it does happen, we want to be
1189
14
    // sure to take advantage of it for all the CPEs near that block, so that
1190
14
    // we don't insert more branches than necessary.
1191
14
    unsigned Growth;
1192
14
    if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1193
14
        
(2
WaterBB->getNumber() < U.HighWaterMark->getNumber()2
||
1194
2
         
NewWaterList.count(WaterBB)0
) && Growth < BestGrowth) {
1195
2
      // This is the least amount of required padding seen so far.
1196
2
      BestGrowth = Growth;
1197
2
      WaterIter = IP;
1198
2
      LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1199
2
                        << " Growth=" << Growth << '\n');
1200
2
1201
2
      // Keep looking unless it is perfect.
1202
2
      if (BestGrowth == 0)
1203
0
        return true;
1204
14
    }
1205
14
    if (IP == B)
1206
6
      break;
1207
14
  }
1208
6
  return BestGrowth != ~0u;
1209
6
}
1210
1211
/// createNewWater - No existing WaterList entry will work for
1212
/// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1213
/// block is used if in range, and the conditional branch munged so control
1214
/// flow is correct.  Otherwise the block is split to create a hole with an
1215
/// unconditional branch around it.  In either case NewMBB is set to a
1216
/// block following which the new island can be inserted (the WaterList
1217
/// is not adjusted).
1218
void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1219
                                        unsigned UserOffset,
1220
1
                                        MachineBasicBlock *&NewMBB) {
1221
1
  CPUser &U = CPUsers[CPUserIndex];
1222
1
  MachineInstr *UserMI = U.MI;
1223
1
  MachineInstr *CPEMI  = U.CPEMI;
1224
1
  unsigned CPELogAlign = getCPELogAlign(*CPEMI);
1225
1
  MachineBasicBlock *UserMBB = UserMI->getParent();
1226
1
  const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1227
1
1228
1
  // If the block does not end in an unconditional branch already, and if the
1229
1
  // end of the block is within range, make new water there.
1230
1
  if (BBHasFallthrough(UserMBB)) {
1231
0
    // Size of branch to insert.
1232
0
    unsigned Delta = 2;
1233
0
    // Compute the offset where the CPE will begin.
1234
0
    unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1235
0
1236
0
    if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1237
0
      LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1238
0
                        << format(", expected CPE offset %#x\n", CPEOffset));
1239
0
      NewMBB = &*++UserMBB->getIterator();
1240
0
      // Add an unconditional branch from UserMBB to fallthrough block.  Record
1241
0
      // it for branch lengthening; this new branch will not get out of range,
1242
0
      // but if the preceding conditional branch is out of range, the targets
1243
0
      // will be exchanged, and the altered branch may be out of range, so the
1244
0
      // machinery has to know about it.
1245
0
      int UncondBr = Mips::Bimm16;
1246
0
      BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1247
0
      unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1248
0
      ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1249
0
                                      MaxDisp, false, UncondBr));
1250
0
      BBInfo[UserMBB->getNumber()].Size += Delta;
1251
0
      adjustBBOffsetsAfter(UserMBB);
1252
0
      return;
1253
0
    }
1254
1
  }
1255
1
1256
1
  // What a big block.  Find a place within the block to split it.
1257
1
1258
1
  // Try to split the block so it's fully aligned.  Compute the latest split
1259
1
  // point where we can add a 4-byte branch instruction, and then align to
1260
1
  // LogAlign which is the largest possible alignment in the function.
1261
1
  unsigned LogAlign = MF->getAlignment();
1262
1
  assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1263
1
  unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1264
1
  LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1265
1
                              BaseInsertOffset));
1266
1
1267
1
  // The 4 in the following is for the unconditional branch we'll be inserting
1268
1
  // Alignment of the island is handled
1269
1
  // inside isOffsetInRange.
1270
1
  BaseInsertOffset -= 4;
1271
1
1272
1
  LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1273
1
                    << " la=" << LogAlign << '\n');
1274
1
1275
1
  // This could point off the end of the block if we've already got constant
1276
1
  // pool entries following this block; only the last one is in the water list.
1277
1
  // Back past any possible branches (allow for a conditional and a maximally
1278
1
  // long unconditional).
1279
1
  if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1280
0
    BaseInsertOffset = UserBBI.postOffset() - 8;
1281
0
    LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1282
0
  }
1283
1
  unsigned EndInsertOffset = BaseInsertOffset + 4 +
1284
1
    CPEMI->getOperand(2).getImm();
1285
1
  MachineBasicBlock::iterator MI = UserMI;
1286
1
  ++MI;
1287
1
  unsigned CPUIndex = CPUserIndex+1;
1288
1
  unsigned NumCPUsers = CPUsers.size();
1289
1
  //MachineInstr *LastIT = 0;
1290
1
  for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1291
406
       Offset < BaseInsertOffset;
1292
405
       Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1293
405
    assert(MI != UserMBB->end() && "Fell off end of block");
1294
405
    if (CPUIndex < NumCPUsers && 
CPUsers[CPUIndex].MI == MI0
) {
1295
0
      CPUser &U = CPUsers[CPUIndex];
1296
0
      if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1297
0
        // Shift intertion point by one unit of alignment so it is within reach.
1298
0
        BaseInsertOffset -= 1u << LogAlign;
1299
0
        EndInsertOffset  -= 1u << LogAlign;
1300
0
      }
1301
0
      // This is overly conservative, as we don't account for CPEMIs being
1302
0
      // reused within the block, but it doesn't matter much.  Also assume CPEs
1303
0
      // are added in order with alignment padding.  We may eventually be able
1304
0
      // to pack the aligned CPEs better.
1305
0
      EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1306
0
      CPUIndex++;
1307
0
    }
1308
405
  }
1309
1
1310
1
  NewMBB = splitBlockBeforeInstr(*--MI);
1311
1
}
1312
1313
/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1314
/// is out-of-range.  If so, pick up the constant pool value and move it some
1315
/// place in-range.  Return true if we changed any addresses (thus must run
1316
/// another pass of branch lengthening), false otherwise.
1317
40
bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1318
40
  CPUser &U = CPUsers[CPUserIndex];
1319
40
  MachineInstr *UserMI = U.MI;
1320
40
  MachineInstr *CPEMI  = U.CPEMI;
1321
40
  unsigned CPI = CPEMI->getOperand(1).getIndex();
1322
40
  unsigned Size = CPEMI->getOperand(2).getImm();
1323
40
  // Compute this only once, it's expensive.
1324
40
  unsigned UserOffset = getUserOffset(U);
1325
40
1326
40
  // See if the current entry is within range, or there is a clone of it
1327
40
  // in range.
1328
40
  int result = findInRangeCPEntry(U, UserOffset);
1329
40
  if (result==1) 
return false34
;
1330
6
  else if (result==2) 
return true0
;
1331
6
1332
6
  // Look for water where we can place this CPE.
1333
6
  MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1334
6
  MachineBasicBlock *NewMBB;
1335
6
  water_iterator IP;
1336
6
  if (findAvailableWater(U, UserOffset, IP)) {
1337
2
    LLVM_DEBUG(dbgs() << "Found water in range\n");
1338
2
    MachineBasicBlock *WaterBB = *IP;
1339
2
1340
2
    // If the original WaterList entry was "new water" on this iteration,
1341
2
    // propagate that to the new island.  This is just keeping NewWaterList
1342
2
    // updated to match the WaterList, which will be updated below.
1343
2
    if (NewWaterList.erase(WaterBB))
1344
0
      NewWaterList.insert(NewIsland);
1345
2
1346
2
    // The new CPE goes before the following block (NewMBB).
1347
2
    NewMBB = &*++WaterBB->getIterator();
1348
4
  } else {
1349
4
    // No water found.
1350
4
    // we first see if a longer form of the instrucion could have reached
1351
4
    // the constant. in that case we won't bother to split
1352
4
    if (!NoLoadRelaxation) {
1353
3
      result = findLongFormInRangeCPEntry(U, UserOffset);
1354
3
      if (result != 0) return true;
1355
1
    }
1356
1
    LLVM_DEBUG(dbgs() << "No water found\n");
1357
1
    createNewWater(CPUserIndex, UserOffset, NewMBB);
1358
1
1359
1
    // splitBlockBeforeInstr adds to WaterList, which is important when it is
1360
1
    // called while handling branches so that the water will be seen on the
1361
1
    // next iteration for constant pools, but in this context, we don't want
1362
1
    // it.  Check for this so it will be removed from the WaterList.
1363
1
    // Also remove any entry from NewWaterList.
1364
1
    MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1365
1
    IP = llvm::find(WaterList, WaterBB);
1366
1
    if (IP != WaterList.end())
1367
1
      NewWaterList.erase(WaterBB);
1368
1
1369
1
    // We are adding new water.  Update NewWaterList.
1370
1
    NewWaterList.insert(NewIsland);
1371
1
  }
1372
6
1373
6
  // Remove the original WaterList entry; we want subsequent insertions in
1374
6
  // this vicinity to go after the one we're about to insert.  This
1375
6
  // considerably reduces the number of times we have to move the same CPE
1376
6
  // more than once and is also important to ensure the algorithm terminates.
1377
6
  
if (3
IP != WaterList.end()3
)
1378
3
    WaterList.erase(IP);
1379
3
1380
3
  // Okay, we know we can put an island before NewMBB now, do it!
1381
3
  MF->insert(NewMBB->getIterator(), NewIsland);
1382
3
1383
3
  // Update internal data structures to account for the newly inserted MBB.
1384
3
  updateForInsertedWaterBlock(NewIsland);
1385
3
1386
3
  // Decrement the old entry, and remove it if refcount becomes 0.
1387
3
  decrementCPEReferenceCount(CPI, CPEMI);
1388
3
1389
3
  // No existing clone of this CPE is within range.
1390
3
  // We will be generating a new clone.  Get a UID for it.
1391
3
  unsigned ID = createPICLabelUId();
1392
3
1393
3
  // Now that we have an island to add the CPE to, clone the original CPE and
1394
3
  // add it to the island.
1395
3
  U.HighWaterMark = NewIsland;
1396
3
  U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1397
3
                .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1398
3
  CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1399
3
  ++NumCPEs;
1400
3
1401
3
  // Mark the basic block as aligned as required by the const-pool entry.
1402
3
  NewIsland->setAlignment(getCPELogAlign(*U.CPEMI));
1403
3
1404
3
  // Increase the size of the island block to account for the new entry.
1405
3
  BBInfo[NewIsland->getNumber()].Size += Size;
1406
3
  adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1407
3
1408
3
  // Finally, change the CPI in the instruction operand to be ID.
1409
6
  for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; 
++i3
)
1410
6
    if (UserMI->getOperand(i).isCPI()) {
1411
3
      UserMI->getOperand(i).setIndex(ID);
1412
3
      break;
1413
3
    }
1414
3
1415
3
  LLVM_DEBUG(
1416
3
      dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1417
3
             << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1418
3
1419
3
  return true;
1420
6
}
1421
1422
/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1423
/// sizes and offsets of impacted basic blocks.
1424
3
void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1425
3
  MachineBasicBlock *CPEBB = CPEMI->getParent();
1426
3
  unsigned Size = CPEMI->getOperand(2).getImm();
1427
3
  CPEMI->eraseFromParent();
1428
3
  BBInfo[CPEBB->getNumber()].Size -= Size;
1429
3
  // All succeeding offsets have the current size value added in, fix this.
1430
3
  if (CPEBB->empty()) {
1431
3
    BBInfo[CPEBB->getNumber()].Size = 0;
1432
3
1433
3
    // This block no longer needs to be aligned.
1434
3
    CPEBB->setAlignment(0);
1435
3
  } else
1436
0
    // Entries are sorted by descending alignment, so realign from the front.
1437
0
    CPEBB->setAlignment(getCPELogAlign(*CPEBB->begin()));
1438
3
1439
3
  adjustBBOffsetsAfter(CPEBB);
1440
3
  // An island has only one predecessor BB and one successor BB. Check if
1441
3
  // this BB's predecessor jumps directly to this BB's successor. This
1442
3
  // shouldn't happen currently.
1443
3
  assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1444
3
  // FIXME: remove the empty blocks after all the work is done?
1445
3
}
1446
1447
/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1448
/// are zero.
1449
379
bool MipsConstantIslands::removeUnusedCPEntries() {
1450
379
  unsigned MadeChange = false;
1451
413
  for (unsigned i = 0, e = CPEntries.size(); i != e; 
++i34
) {
1452
34
      std::vector<CPEntry> &CPEs = CPEntries[i];
1453
68
      for (unsigned j = 0, ee = CPEs.size(); j != ee; 
++j34
) {
1454
34
        if (CPEs[j].RefCount == 0 && 
CPEs[j].CPEMI0
) {
1455
0
          removeDeadCPEMI(CPEs[j].CPEMI);
1456
0
          CPEs[j].CPEMI = nullptr;
1457
0
          MadeChange = true;
1458
0
        }
1459
34
      }
1460
34
  }
1461
379
  return MadeChange;
1462
379
}
1463
1464
/// isBBInRange - Returns true if the distance between specific MI and
1465
/// specific BB can fit in MI's displacement field.
1466
bool MipsConstantIslands::isBBInRange
1467
359
  (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1468
359
  unsigned PCAdj = 4;
1469
359
  unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1470
359
  unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1471
359
1472
359
  LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1473
359
                    << " from " << printMBBReference(*MI->getParent())
1474
359
                    << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1475
359
                    << " to " << DestOffset << " offset "
1476
359
                    << int(DestOffset - BrOffset) << "\t" << *MI);
1477
359
1478
359
  if (BrOffset <= DestOffset) {
1479
287
    // Branch before the Dest.
1480
287
    if (DestOffset-BrOffset <= MaxDisp)
1481
241
      return true;
1482
72
  } else {
1483
72
    if (BrOffset-DestOffset <= MaxDisp)
1484
61
      return true;
1485
57
  }
1486
57
  return false;
1487
57
}
1488
1489
/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1490
/// away to fit in its displacement field.
1491
319
bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1492
319
  MachineInstr *MI = Br.MI;
1493
319
  unsigned TargetOperand = branchTargetOperand(MI);
1494
319
  MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1495
319
1496
319
  // Check to see if the DestBB is already in-range.
1497
319
  if (isBBInRange(MI, DestBB, Br.MaxDisp))
1498
280
    return false;
1499
39
1500
39
  if (!Br.isCond)
1501
15
    return fixupUnconditionalBr(Br);
1502
24
  return fixupConditionalBr(Br);
1503
24
}
1504
1505
/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1506
/// too far away to fit in its displacement field. If the LR register has been
1507
/// spilled in the epilogue, then we can use BL to implement a far jump.
1508
/// Otherwise, add an intermediate branch instruction to a branch.
1509
bool
1510
15
MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1511
15
  MachineInstr *MI = Br.MI;
1512
15
  MachineBasicBlock *MBB = MI->getParent();
1513
15
  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1514
15
  // Use BL to implement far jump.
1515
15
  unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1516
15
  if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1517
4
    Br.MaxDisp = BimmX16MaxDisp;
1518
4
    MI->setDesc(TII->get(Mips::BimmX16));
1519
4
  }
1520
11
  else {
1521
11
    // need to give the math a more careful look here
1522
11
    // this is really a segment address and not
1523
11
    // a PC relative address. FIXME. But I think that
1524
11
    // just reducing the bits by 1 as I've done is correct.
1525
11
    // The basic block we are branching too much be longword aligned.
1526
11
    // we know that RA is saved because we always save it right now.
1527
11
    // this requirement will be relaxed later but we also have an alternate
1528
11
    // way to implement this that I will implement that does not need jal.
1529
11
    // We should have a way to back out this alignment restriction if we "can" later.
1530
11
    // but it is not harmful.
1531
11
    //
1532
11
    DestBB->setAlignment(2);
1533
11
    Br.MaxDisp = ((1<<24)-1) * 2;
1534
11
    MI->setDesc(TII->get(Mips::JalB16));
1535
11
  }
1536
15
  BBInfo[MBB->getNumber()].Size += 2;
1537
15
  adjustBBOffsetsAfter(MBB);
1538
15
  HasFarJump = true;
1539
15
  ++NumUBrFixed;
1540
15
1541
15
  LLVM_DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1542
15
1543
15
  return true;
1544
15
}
1545
1546
/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1547
/// far away to fit in its displacement field. It is converted to an inverse
1548
/// conditional branch + an unconditional branch to the destination.
1549
bool
1550
24
MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1551
24
  MachineInstr *MI = Br.MI;
1552
24
  unsigned TargetOperand = branchTargetOperand(MI);
1553
24
  MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1554
24
  unsigned Opcode = MI->getOpcode();
1555
24
  unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1556
24
  unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1557
24
1558
24
  // Check to see if the DestBB is already in-range.
1559
24
  if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1560
17
    Br.MaxDisp = LongFormMaxOff;
1561
17
    MI->setDesc(TII->get(LongFormOpcode));
1562
17
    return true;
1563
17
  }
1564
7
1565
7
  // Add an unconditional branch to the destination and invert the branch
1566
7
  // condition to jump over it:
1567
7
  // bteqz L1
1568
7
  // =>
1569
7
  // bnez L2
1570
7
  // b   L1
1571
7
  // L2:
1572
7
1573
7
  // If the branch is at the end of its MBB and that has a fall-through block,
1574
7
  // direct the updated conditional branch to the fall-through block. Otherwise,
1575
7
  // split the MBB before the next instruction.
1576
7
  MachineBasicBlock *MBB = MI->getParent();
1577
7
  MachineInstr *BMI = &MBB->back();
1578
7
  bool NeedSplit = (BMI != MI) || 
!BBHasFallthrough(MBB)6
;
1579
7
  unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
1580
7
1581
7
  ++NumCBrFixed;
1582
7
  if (BMI != MI) {
1583
1
    if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1584
1
        BMI->isUnconditionalBranch()) {
1585
1
      // Last MI in the BB is an unconditional branch. Can we simply invert the
1586
1
      // condition and swap destinations:
1587
1
      // beqz L1
1588
1
      // b   L2
1589
1
      // =>
1590
1
      // bnez L2
1591
1
      // b   L1
1592
1
      unsigned BMITargetOperand = branchTargetOperand(BMI);
1593
1
      MachineBasicBlock *NewDest =
1594
1
        BMI->getOperand(BMITargetOperand).getMBB();
1595
1
      if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1596
1
        LLVM_DEBUG(
1597
1
            dbgs() << "  Invert Bcc condition and swap its destination with "
1598
1
                   << *BMI);
1599
1
        MI->setDesc(TII->get(OppositeBranchOpcode));
1600
1
        BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1601
1
        MI->getOperand(TargetOperand).setMBB(NewDest);
1602
1
        return true;
1603
1
      }
1604
6
    }
1605
1
  }
1606
6
1607
6
  if (NeedSplit) {
1608
0
    splitBlockBeforeInstr(*MI);
1609
0
    // No need for the branch to the next block. We're adding an unconditional
1610
0
    // branch to the destination.
1611
0
    int delta = TII->getInstSizeInBytes(MBB->back());
1612
0
    BBInfo[MBB->getNumber()].Size -= delta;
1613
0
    MBB->back().eraseFromParent();
1614
0
    // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1615
0
  }
1616
6
  MachineBasicBlock *NextBB = &*++MBB->getIterator();
1617
6
1618
6
  LLVM_DEBUG(dbgs() << "  Insert B to " << printMBBReference(*DestBB)
1619
6
                    << " also invert condition and change dest. to "
1620
6
                    << printMBBReference(*NextBB) << "\n");
1621
6
1622
6
  // Insert a new conditional branch and a new unconditional branch.
1623
6
  // Also update the ImmBranch as well as adding a new entry for the new branch.
1624
6
  if (MI->getNumExplicitOperands() == 2) {
1625
3
    BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1626
3
           .addReg(MI->getOperand(0).getReg())
1627
3
           .addMBB(NextBB);
1628
3
  } else {
1629
3
    BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1630
3
           .addMBB(NextBB);
1631
3
  }
1632
6
  Br.MI = &MBB->back();
1633
6
  BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1634
6
  BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1635
6
  BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1636
6
  unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1637
6
  ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1638
6
1639
6
  // Remove the old conditional branch.  It may or may not still be in MBB.
1640
6
  BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1641
6
  MI->eraseFromParent();
1642
6
  adjustBBOffsetsAfter(MBB);
1643
6
  return true;
1644
6
}
1645
1646
337
void MipsConstantIslands::prescanForConstants() {
1647
337
  unsigned J = 0;
1648
337
  (void)J;
1649
337
  for (MachineFunction::iterator B =
1650
1.02k
         MF->begin(), E = MF->end(); B != E; 
++B683
) {
1651
683
    for (MachineBasicBlock::instr_iterator I =
1652
10.6k
        B->instr_begin(), EB = B->instr_end(); I != EB; 
++I9.93k
) {
1653
9.93k
      switch(I->getDesc().getOpcode()) {
1654
9.93k
        case Mips::LwConstant32: {
1655
34
          PrescannedForConstants = true;
1656
34
          LLVM_DEBUG(dbgs() << "constant island constant " << *I << "\n");
1657
34
          J = I->getNumOperands();
1658
34
          LLVM_DEBUG(dbgs() << "num operands " << J << "\n");
1659
34
          MachineOperand& Literal = I->getOperand(1);
1660
34
          if (Literal.isImm()) {
1661
34
            int64_t V = Literal.getImm();
1662
34
            LLVM_DEBUG(dbgs() << "literal " << V << "\n");
1663
34
            Type *Int32Ty =
1664
34
              Type::getInt32Ty(MF->getFunction().getContext());
1665
34
            const Constant *C = ConstantInt::get(Int32Ty, V);
1666
34
            unsigned index = MCP->getConstantPoolIndex(C, 4);
1667
34
            I->getOperand(2).ChangeToImmediate(index);
1668
34
            LLVM_DEBUG(dbgs() << "constant island constant " << *I << "\n");
1669
34
            I->setDesc(TII->get(Mips::LwRxPcTcp16));
1670
34
            I->RemoveOperand(1);
1671
34
            I->RemoveOperand(1);
1672
34
            I->addOperand(MachineOperand::CreateCPI(index, 0));
1673
34
            I->addOperand(MachineOperand::CreateImm(4));
1674
34
          }
1675
34
          break;
1676
9.93k
        }
1677
9.93k
        default:
1678
9.90k
          break;
1679
9.93k
      }
1680
9.93k
    }
1681
683
  }
1682
337
}
1683
1684
/// Returns a pass that converts branches to long branches.
1685
2.09k
FunctionPass *llvm::createMipsConstantIslandPass() {
1686
2.09k
  return new MipsConstantIslands();
1687
2.09k
}