LLVM 24.0.0git
ARMConstantIslandPass.cpp
Go to the documentation of this file.
1//===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that splits the constant pool up into 'islands'
10// which are scattered through-out the function. This is required due to the
11// limited pc-relative displacements that ARM has.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ARM.h"
16#include "ARMBaseInstrInfo.h"
17#include "ARMBasicBlockInfo.h"
19#include "ARMSubtarget.h"
21#include "MVETailPredUtils.h"
22#include "Thumb2InstrInfo.h"
23#include "Utils/ARMBaseInfo.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/StringRef.h"
39#include "llvm/Config/llvm-config.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DebugLoc.h"
42#include "llvm/MC/MCInstrDesc.h"
43#include "llvm/Pass.h"
45#include "llvm/Support/Debug.h"
47#include "llvm/Support/Format.h"
49#include <algorithm>
50#include <cassert>
51#include <cstdint>
52#include <iterator>
53#include <vector>
54
55using namespace llvm;
56
57#define DEBUG_TYPE "arm-cp-islands"
58
59#define ARM_CP_ISLANDS_OPT_NAME \
60 "ARM constant island placement and branch shortening pass"
61STATISTIC(NumCPEs, "Number of constpool entries");
62STATISTIC(NumSplit, "Number of uncond branches inserted");
63STATISTIC(NumCBrFixed, "Number of cond branches fixed");
64STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
65STATISTIC(NumTBs, "Number of table branches generated");
66STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
67STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
68STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
69STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
70STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
71STATISTIC(NumLEInserted, "Number of LE backwards branches inserted");
72
73namespace {
74
75 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
76 /// requires constant pool entries to be scattered among the instructions
77 /// inside a function. To do this, it completely ignores the normal LLVM
78 /// constant pool; instead, it places constants wherever it feels like with
79 /// special instructions.
80 ///
81 /// The terminology used in this pass includes:
82 /// Islands - Clumps of constants placed in the function.
83 /// Water - Potential places where an island could be formed.
84 /// CPE - A constant pool entry that has been placed somewhere, which
85 /// tracks a list of users.
86 class ARMConstantIslands : public MachineFunctionPass {
87 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
88
89 /// WaterList - A sorted list of basic blocks where islands could be placed
90 /// (i.e. blocks that don't fall through to the following block, due
91 /// to a return, unreachable, or unconditional branch).
92 std::vector<MachineBasicBlock*> WaterList;
93
94 /// NewWaterList - The subset of WaterList that was created since the
95 /// previous iteration by inserting unconditional branches.
97
98 using water_iterator = std::vector<MachineBasicBlock *>::iterator;
99
100 /// CPUser - One user of a constant pool, keeping the machine instruction
101 /// pointer, the constant pool being referenced, and the max displacement
102 /// allowed from the instruction to the CP. The HighWaterMark records the
103 /// highest basic block where a new CPEntry can be placed. To ensure this
104 /// pass terminates, the CP entries are initially placed at the end of the
105 /// function and then move monotonically to lower addresses. The
106 /// exception to this rule is when the current CP entry for a particular
107 /// CPUser is out of range, but there is another CP entry for the same
108 /// constant value in range. We want to use the existing in-range CP
109 /// entry, but if it later moves out of range, the search for new water
110 /// should resume where it left off. The HighWaterMark is used to record
111 /// that point.
112 struct CPUser {
114 MachineInstr *CPEMI;
115 MachineBasicBlock *HighWaterMark;
116 unsigned MaxDisp;
117 bool NegOk;
118 bool IsSoImm;
119 bool KnownAlignment = false;
120
121 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
122 bool neg, bool soimm)
123 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
124 HighWaterMark = CPEMI->getParent();
125 }
126
127 /// getMaxDisp - Returns the maximum displacement supported by MI.
128 /// Correct for unknown alignment.
129 /// Conservatively subtract 2 bytes to handle weird alignment effects.
130 unsigned getMaxDisp() const {
131 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
132 }
133 };
134
135 /// CPUsers - Keep track of all of the machine instructions that use various
136 /// constant pools and their max displacement.
137 std::vector<CPUser> CPUsers;
138
139 /// CPEntry - One per constant pool entry, keeping the machine instruction
140 /// pointer, the constpool index, and the number of CPUser's which
141 /// reference this entry.
142 struct CPEntry {
143 MachineInstr *CPEMI;
144 unsigned CPI;
145 unsigned RefCount;
146
147 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
148 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
149 };
150
151 /// CPEntries - Keep track of all of the constant pool entry machine
152 /// instructions. For each original constpool index (i.e. those that existed
153 /// upon entry to this pass), it keeps a vector of entries. Original
154 /// elements are cloned as we go along; the clones are put in the vector of
155 /// the original element, but have distinct CPIs.
156 ///
157 /// The first half of CPEntries contains generic constants, the second half
158 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
159 /// which vector it will be in here.
160 std::vector<std::vector<CPEntry>> CPEntries;
161
162 /// Maps a JT index to the offset in CPEntries containing copies of that
163 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
164 DenseMap<int, int> JumpTableEntryIndices;
165
166 /// Maps a JT index to the LEA that actually uses the index to calculate its
167 /// base address.
168 DenseMap<int, int> JumpTableUserIndices;
169
170 /// ImmBranch - One per immediate branch, keeping the machine instruction
171 /// pointer, conditional or unconditional, the max displacement,
172 /// and (if isCond is true) the corresponding unconditional branch
173 /// opcode.
174 struct ImmBranch {
175 MachineInstr *MI;
176 unsigned MaxDisp : 31;
178 unsigned isCond : 1;
179 unsigned UncondBr;
180
181 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
182 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
183 };
184
185 /// ImmBranches - Keep track of all the immediate branch instructions.
186 std::vector<ImmBranch> ImmBranches;
187
188 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
189 SmallVector<MachineInstr*, 4> PushPopMIs;
190
191 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
192 SmallVector<MachineInstr*, 4> T2JumpTables;
193
194 MachineFunction *MF;
195 MachineConstantPool *MCP;
196 const ARMBaseInstrInfo *TII;
197 const ARMSubtarget *STI;
198 ARMFunctionInfo *AFI;
199 MachineDominatorTree *DT = nullptr;
200 bool isThumb;
201 bool isThumb1;
202 bool isThumb2;
203 bool isPositionIndependentOrROPI;
204
205 public:
206 static char ID;
207
208 ARMConstantIslands() : MachineFunctionPass(ID) {}
209
210 bool runOnMachineFunction(MachineFunction &MF) override;
211
212 void getAnalysisUsage(AnalysisUsage &AU) const override {
213 AU.addRequired<MachineDominatorTreeWrapperPass>();
215 }
216
217 MachineFunctionProperties getRequiredProperties() const override {
218 return MachineFunctionProperties().setNoVRegs();
219 }
220
221 StringRef getPassName() const override {
223 }
224
225 private:
226 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
227 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
228 bool BBHasFallthrough(MachineBasicBlock *MBB);
229 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
230 Align getCPEAlign(const MachineInstr *CPEMI);
231 void scanFunctionJumpTables();
232 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
233 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
234 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
235 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
236 unsigned getCombinedIndex(const MachineInstr *CPEMI);
237 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
238 bool findAvailableWater(CPUser&U, unsigned UserOffset,
239 water_iterator &WaterIter, bool CloserWater);
240 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
241 MachineBasicBlock *&NewMBB);
242 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
243 void removeDeadCPEMI(MachineInstr *CPEMI);
244 bool removeUnusedCPEntries();
245 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
246 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
247 bool DoDump = false);
248 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
249 CPUser &U, unsigned &Growth);
250 bool fixupImmediateBr(ImmBranch &Br);
251 bool fixupConditionalBr(ImmBranch &Br);
252 bool fixupUnconditionalBr(ImmBranch &Br);
253 bool optimizeThumb2Instructions();
254 bool optimizeThumb2Branches();
255 bool reorderThumb2JumpTables();
256 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
257 unsigned &DeadSize, bool &CanDeleteLEA,
258 bool &BaseRegKill);
259 bool optimizeThumb2JumpTables();
260 MachineBasicBlock *adjustJTTargetBlockForward(unsigned JTI,
261 MachineBasicBlock *BB,
262 MachineBasicBlock *JTBB);
263
264 unsigned getUserOffset(CPUser&) const;
265 void dumpBBs();
266 void verify();
267
268 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
269 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
270 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
271 const CPUser &U) {
272 return isOffsetInRange(UserOffset, TrialOffset,
273 U.getMaxDisp(), U.NegOk, U.IsSoImm);
274 }
275 };
276
277} // end anonymous namespace
278
279char ARMConstantIslands::ID = 0;
280
281/// verify - check BBOffsets, BBSizes, alignment of islands
282void ARMConstantIslands::verify() {
283#ifndef NDEBUG
284 BBInfoVector &BBInfo = BBUtils->getBBInfo();
285 assert(is_sorted(*MF, [&BBInfo](const MachineBasicBlock &LHS,
286 const MachineBasicBlock &RHS) {
287 return BBInfo[LHS.getNumber()].postOffset() <
288 BBInfo[RHS.getNumber()].postOffset();
289 }));
290 LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
291 for (CPUser &U : CPUsers) {
292 unsigned UserOffset = getUserOffset(U);
293 // Verify offset using the real max displacement without the safety
294 // adjustment.
295 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
296 /* DoDump = */ true)) {
297 LLVM_DEBUG(dbgs() << "OK\n");
298 continue;
299 }
300 LLVM_DEBUG(dbgs() << "Out of range.\n");
301 dumpBBs();
302 LLVM_DEBUG(MF->dump());
303 llvm_unreachable("Constant pool entry out of range!");
304 }
305#endif
306}
307
308#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
309/// print block size and offset information - debugging
310LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
311 LLVM_DEBUG({
312 BBInfoVector &BBInfo = BBUtils->getBBInfo();
313 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
314 const BasicBlockInfo &BBI = BBInfo[J];
315 dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
316 << " kb=" << unsigned(BBI.KnownBits)
317 << " ua=" << unsigned(BBI.Unalign) << " pa=" << Log2(BBI.PostAlign)
318 << format(" size=%#x\n", BBInfo[J].Size);
319 }
320 });
321}
322#endif
323
324// Align blocks where the previous block does not fall through. This may add
325// extra NOP's but they will not be executed. It uses the PrefLoopAlignment as a
326// measure of how much to align, and only runs at CodeGenOptLevel::Aggressive.
327static bool AlignBlocks(MachineFunction *MF, const ARMSubtarget *STI) {
329 MF->getFunction().hasOptSize())
330 return false;
331
332 auto *TLI = STI->getTargetLowering();
333 const Align Alignment = TLI->getPrefLoopAlignment();
334 if (Alignment < 4)
335 return false;
336
337 bool Changed = false;
338 bool PrevCanFallthrough = true;
339 for (auto &MBB : *MF) {
340 if (!PrevCanFallthrough) {
341 Changed = true;
342 MBB.setAlignment(Alignment);
343 }
344
345 PrevCanFallthrough = MBB.canFallThrough();
346
347 // For LOB's, the ARMLowOverheadLoops pass may remove the unconditional
348 // branch later in the pipeline.
349 if (STI->hasLOB()) {
350 for (const auto &MI : reverse(MBB.terminators())) {
351 if (MI.getOpcode() == ARM::t2B &&
352 MI.getOperand(0).getMBB() == MBB.getNextNode())
353 continue;
354 if (isLoopStart(MI) || MI.getOpcode() == ARM::t2LoopEnd ||
355 MI.getOpcode() == ARM::t2LoopEndDec) {
356 PrevCanFallthrough = true;
357 break;
358 }
359 // Any other terminator - nothing to do
360 break;
361 }
362 }
363 }
364
365 return Changed;
366}
367
368bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
369 MF = &mf;
370 MCP = mf.getConstantPool();
371 BBUtils = std::make_unique<ARMBasicBlockUtils>(mf);
372
373 LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
374 << MCP->getConstants().size() << " CP entries, aligned to "
375 << MCP->getConstantPoolAlign().value() << " bytes *****\n");
376
377 STI = &MF->getSubtarget<ARMSubtarget>();
378 TII = STI->getInstrInfo();
379 isPositionIndependentOrROPI =
381 AFI = MF->getInfo<ARMFunctionInfo>();
382 DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
383
384 isThumb = AFI->isThumbFunction();
385 isThumb1 = AFI->isThumb1OnlyFunction();
386 isThumb2 = AFI->isThumb2Function();
387
388 bool GenerateTBB =
389 isThumb2 || (isThumb1 && STI->getCLOpts().synthesize_thumb_1_tbb);
390 // TBB generation code in this constant island pass has not been adapted to
391 // deal with speculation barriers.
392 if (STI->hardenSlsRetBr())
393 GenerateTBB = false;
394
395 // Renumber all of the machine basic blocks in the function, guaranteeing that
396 // the numbers agree with the position of the block in the function.
397 MF->RenumberBlocks();
398
399 // Try to reorder and otherwise adjust the block layout to make good use
400 // of the TB[BH] instructions.
401 bool MadeChange = false;
402 if (GenerateTBB && STI->getCLOpts().adjust_jump_tables) {
403 scanFunctionJumpTables();
404 MadeChange |= reorderThumb2JumpTables();
405 // Data is out of date, so clear it. It'll be re-computed later.
406 T2JumpTables.clear();
407 // Blocks may have shifted around. Keep the numbering up to date.
408 MF->RenumberBlocks();
409 }
410
411 // Align any non-fallthrough blocks
412 MadeChange |= AlignBlocks(MF, STI);
413
414 // Perform the initial placement of the constant pool entries. To start with,
415 // we put them all at the end of the function.
416 std::vector<MachineInstr*> CPEMIs;
417 if (!MCP->isEmpty())
418 doInitialConstPlacement(CPEMIs);
419
420 if (MF->getJumpTableInfo())
421 doInitialJumpTablePlacement(CPEMIs);
422
423 /// The next UID to take is the first unused one.
424 AFI->initPICLabelUId(CPEMIs.size());
425
426 // Do the initial scan of the function, building up information about the
427 // sizes of each block, the location of all the water, and finding all of the
428 // constant pool users.
429 initializeFunctionInfo(CPEMIs);
430 CPEMIs.clear();
431 LLVM_DEBUG(dumpBBs());
432
433 // Functions with jump tables need an alignment of 4 because they use the ADR
434 // instruction, which aligns the PC to 4 bytes before adding an offset.
435 if (!T2JumpTables.empty())
436 MF->ensureAlignment(Align(4));
437
438 // Funclet entries are aligned to the function's preferred alignment when
439 // they are emitted (WinException::beginFunclet), so count that padding. The
440 // alignment is final only after the jump table check above.
441 if (MF->hasEHFunclets()) {
442 const Align FuncletAlign = MF->getPreferredAlignment();
443 for (MachineBasicBlock &MBB : *MF) {
444 if (MBB.isEHFuncletEntry() && MBB.getAlignment() < FuncletAlign) {
445 MBB.setAlignment(FuncletAlign);
446 BBUtils->adjustBBOffsetsAfter(MBB.getPrevNode());
447 }
448 }
449 }
450
451 /// Remove dead constant pool entries.
452 MadeChange |= removeUnusedCPEntries();
453
454 // Iteratively place constant pool entries and fix up branches until there
455 // is no change.
456 unsigned CPMaxIteration = STI->getCLOpts().constant_island_max_iteration;
457 unsigned NoCPIters = 0, NoBRIters = 0;
458 while (true) {
459 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
460 bool CPChange = false;
461 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
462 // For most inputs, it converges in no more than 5 iterations.
463 // If it doesn't end in 10, the input may have huge BB or many CPEs.
464 // In this case, we will try different heuristics.
465 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);
466 if (CPChange && ++NoCPIters > CPMaxIteration)
467 report_fatal_error("Constant Island pass failed to converge!");
468 LLVM_DEBUG(dumpBBs());
469
470 // Clear NewWaterList now. If we split a block for branches, it should
471 // appear as "new water" for the next iteration of constant pool placement.
472 NewWaterList.clear();
473
474 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
475 bool BRChange = false;
476 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
477 // Note: fixupImmediateBr can append to ImmBranches.
478 BRChange |= fixupImmediateBr(ImmBranches[i]);
479 }
480 if (BRChange && ++NoBRIters > 30)
481 report_fatal_error("Branch Fix Up pass failed to converge!");
482 LLVM_DEBUG(dumpBBs());
483
484 if (!CPChange && !BRChange)
485 break;
486 MadeChange = true;
487 }
488
489 // Shrink 32-bit Thumb2 load and store instructions.
490 if (isThumb2 && !STI->prefers32BitThumb())
491 MadeChange |= optimizeThumb2Instructions();
492
493 // Shrink 32-bit branch instructions.
494 if (isThumb && STI->hasV8MBaselineOps())
495 MadeChange |= optimizeThumb2Branches();
496
497 // Optimize jump tables using TBB / TBH.
498 if (GenerateTBB && !STI->genExecuteOnly())
499 MadeChange |= optimizeThumb2JumpTables();
500
501 // After a while, this might be made debug-only, but it is not expensive.
502 verify();
503
504 // Save the mapping between original and cloned constpool entries.
505 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
506 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
507 const CPEntry & CPE = CPEntries[i][j];
508 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())
509 AFI->recordCPEClone(i, CPE.CPI);
510 }
511 }
512
513 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
514
515 BBUtils->clear();
516 WaterList.clear();
517 CPUsers.clear();
518 CPEntries.clear();
519 JumpTableEntryIndices.clear();
520 JumpTableUserIndices.clear();
521 ImmBranches.clear();
522 PushPopMIs.clear();
523 T2JumpTables.clear();
524
525 return MadeChange;
526}
527
528/// Perform the initial placement of the regular constant pool entries.
529/// To start with, we put them all at the end of the function.
530void
531ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
532 // Create the basic block to hold the CPE's.
533 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
534 MF->push_back(BB);
535
536 // MachineConstantPool measures alignment in bytes.
537 const Align MaxAlign = MCP->getConstantPoolAlign();
538 const unsigned MaxLogAlign = Log2(MaxAlign);
539
540 // Mark the basic block as required by the const-pool.
541 BB->setAlignment(MaxAlign);
542
543 // The function needs to be as aligned as the basic blocks. The linker may
544 // move functions around based on their alignment.
545 // Special case: halfword literals still need word alignment on the function.
546 Align FuncAlign = MaxAlign;
547 if (MaxAlign == 2)
548 FuncAlign = Align(4);
549 MF->ensureAlignment(FuncAlign);
550
551 // Order the entries in BB by descending alignment. That ensures correct
552 // alignment of all entries as long as BB is sufficiently aligned. Keep
553 // track of the insertion point for each alignment. We are going to bucket
554 // sort the entries as they are created.
555 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,
556 BB->end());
557
558 // Add all of the constants from the constant pool to the end block, use an
559 // identity mapping of CPI's to CPE's.
560 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
561
562 const DataLayout &TD = MF->getDataLayout();
563 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
564 unsigned Size = CPs[i].getSizeInBytes(TD);
565 Align Alignment = CPs[i].getAlign();
566 // Verify that all constant pool entries are a multiple of their alignment.
567 // If not, we would have to pad them out so that instructions stay aligned.
568 assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");
569
570 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
571 unsigned LogAlign = Log2(Alignment);
572 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
573 MachineInstr *CPEMI =
574 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
576 CPEMIs.push_back(CPEMI);
577
578 // Ensure that future entries with higher alignment get inserted before
579 // CPEMI. This is bucket sort with iterators.
580 for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)
581 if (InsPoint[a] == InsAt)
582 InsPoint[a] = CPEMI;
583
584 // Add a new CPEntry, but no corresponding CPUser yet.
585 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
586 ++NumCPEs;
587 LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
588 << Size << ", align = " << Alignment.value() << '\n');
589 }
590 LLVM_DEBUG(BB->dump());
591}
592
593/// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
594/// instructions can be made more efficient if the jump table immediately
595/// follows the instruction, it's best to place them immediately next to their
596/// jumps to begin with. In almost all cases they'll never be moved from that
597/// position.
598void ARMConstantIslands::doInitialJumpTablePlacement(
599 std::vector<MachineInstr *> &CPEMIs) {
600 unsigned i = CPEntries.size();
601 auto MJTI = MF->getJumpTableInfo();
602 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
603
604 // Only inline jump tables are placed in the function.
605 if (MJTI->getEntryKind() != MachineJumpTableInfo::EK_Inline)
606 return;
607
608 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
609 for (MachineBasicBlock &MBB : *MF) {
610 auto MI = MBB.getLastNonDebugInstr();
611 // Look past potential SpeculationBarriers at end of BB.
612 while (MI != MBB.end() &&
613 (isSpeculationBarrierEndBBOpcode(MI->getOpcode()) ||
614 MI->isDebugInstr()))
615 --MI;
616
617 if (MI == MBB.end())
618 continue;
619
620 unsigned JTOpcode;
621 switch (MI->getOpcode()) {
622 default:
623 continue;
624 case ARM::BR_JTadd:
625 case ARM::BR_JTr:
626 case ARM::tBR_JTr:
627 case ARM::BR_JTm_i12:
628 case ARM::BR_JTm_rs:
629 // These instructions are emitted only in ARM or Thumb1 modes which do not
630 // support PACBTI. Hence we don't add BTI instructions in the destination
631 // blocks.
632 assert(!MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement() &&
633 "Branch protection must not be enabled for Arm or Thumb1 modes");
634 JTOpcode = ARM::JUMPTABLE_ADDRS;
635 break;
636 case ARM::t2BR_JT:
637 JTOpcode = ARM::JUMPTABLE_INSTS;
638 break;
639 case ARM::tTBB_JT:
640 case ARM::t2TBB_JT:
641 JTOpcode = ARM::JUMPTABLE_TBB;
642 break;
643 case ARM::tTBH_JT:
644 case ARM::t2TBH_JT:
645 JTOpcode = ARM::JUMPTABLE_TBH;
646 break;
647 }
648
649 unsigned NumOps = MI->getDesc().getNumOperands();
650 MachineOperand JTOp =
651 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));
652 unsigned JTI = JTOp.getIndex();
653 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);
654 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();
655 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);
656 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),
657 DebugLoc(), TII->get(JTOpcode))
658 .addImm(i++)
660 .addImm(Size);
661 CPEMIs.push_back(CPEMI);
662 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));
663 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));
664 if (!LastCorrectlyNumberedBB)
665 LastCorrectlyNumberedBB = &MBB;
666 }
667
668 // If we did anything then we need to renumber the subsequent blocks.
669 if (LastCorrectlyNumberedBB)
670 MF->RenumberBlocks(LastCorrectlyNumberedBB);
671}
672
673/// BBHasFallthrough - Return true if the specified basic block can fallthrough
674/// into the block immediately after it.
675bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
676 // Get the next machine basic block in the function.
678 // Can't fall off end of function.
679 if (std::next(MBBI) == MBB->getParent()->end())
680 return false;
681
682 MachineBasicBlock *NextBB = &*std::next(MBBI);
683 if (!MBB->isSuccessor(NextBB))
684 return false;
685
686 // Try to analyze the end of the block. A potential fallthrough may already
687 // have an unconditional branch for whatever reason.
688 MachineBasicBlock *TBB, *FBB;
689 SmallVector<MachineOperand, 4> Cond;
690 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
691 return TooDifficult || FBB == nullptr;
692}
693
694/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
695/// look up the corresponding CPEntry.
696ARMConstantIslands::CPEntry *
697ARMConstantIslands::findConstPoolEntry(unsigned CPI,
698 const MachineInstr *CPEMI) {
699 std::vector<CPEntry> &CPEs = CPEntries[CPI];
700 // Number of entries per constpool index should be small, just do a
701 // linear search.
702 for (CPEntry &CPE : CPEs)
703 if (CPE.CPEMI == CPEMI)
704 return &CPE;
705 return nullptr;
706}
707
708/// getCPEAlign - Returns the required alignment of the constant pool entry
709/// represented by CPEMI.
710Align ARMConstantIslands::getCPEAlign(const MachineInstr *CPEMI) {
711 switch (CPEMI->getOpcode()) {
712 case ARM::CONSTPOOL_ENTRY:
713 break;
714 case ARM::JUMPTABLE_TBB:
715 return isThumb1 ? Align(4) : Align(1);
716 case ARM::JUMPTABLE_TBH:
717 return isThumb1 ? Align(4) : Align(2);
718 case ARM::JUMPTABLE_INSTS:
719 return Align(2);
720 case ARM::JUMPTABLE_ADDRS:
721 return Align(4);
722 default:
723 llvm_unreachable("unknown constpool entry kind");
724 }
725
726 unsigned CPI = getCombinedIndex(CPEMI);
727 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
728 return MCP->getConstants()[CPI].getAlign();
729}
730
731/// scanFunctionJumpTables - Do a scan of the function, building up
732/// information about the sizes of each block and the locations of all
733/// the jump tables.
734void ARMConstantIslands::scanFunctionJumpTables() {
735 for (MachineBasicBlock &MBB : *MF) {
736 for (MachineInstr &I : MBB)
737 if (I.isBranch() &&
738 (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
739 T2JumpTables.push_back(&I);
740 }
741}
742
743/// initializeFunctionInfo - Do the initial scan of the function, building up
744/// information about the sizes of each block, the location of all the water,
745/// and finding all of the constant pool users.
746void ARMConstantIslands::
747initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
748
749 BBUtils->computeAllBlockSizes();
750 BBInfoVector &BBInfo = BBUtils->getBBInfo();
751 // The known bits of the entry block offset are determined by the function
752 // alignment.
753 BBInfo.front().KnownBits = Log2(MF->getAlignment());
754
755 // Compute block offsets and known bits.
756 BBUtils->adjustBBOffsetsAfter(&MF->front());
757
758 // We only care about jump table instructions when jump tables are inline.
759 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
760 bool InlineJumpTables =
762
763 // Now go back through the instructions and build up our data structures.
764 for (MachineBasicBlock &MBB : *MF) {
765 // If this block doesn't fall through into the next MBB, then this is
766 // 'water' that a constant pool island could be placed.
767 if (!BBHasFallthrough(&MBB))
768 WaterList.push_back(&MBB);
769
770 for (MachineInstr &I : MBB) {
771 if (I.isDebugInstr())
772 continue;
773
774 unsigned Opc = I.getOpcode();
775 if (I.isBranch()) {
776 bool isCond = false;
777 unsigned Bits = 0;
778 unsigned Scale = 1;
779 int UOpc = Opc;
780 switch (Opc) {
781 default:
782 continue; // Ignore other JT branches
783 case ARM::t2BR_JT:
784 case ARM::tBR_JTr:
785 if (InlineJumpTables)
786 T2JumpTables.push_back(&I);
787 continue; // Does not get an entry in ImmBranches
788 case ARM::Bcc:
789 isCond = true;
790 UOpc = ARM::B;
791 [[fallthrough]];
792 case ARM::B:
793 Bits = 24;
794 Scale = 4;
795 break;
796 case ARM::tBcc:
797 isCond = true;
798 UOpc = ARM::tB;
799 Bits = 8;
800 Scale = 2;
801 break;
802 case ARM::tB:
803 Bits = 11;
804 Scale = 2;
805 break;
806 case ARM::t2Bcc:
807 isCond = true;
808 UOpc = ARM::t2B;
809 Bits = 20;
810 Scale = 2;
811 break;
812 case ARM::t2B:
813 Bits = 24;
814 Scale = 2;
815 break;
816 }
817
818 // Record this immediate branch.
819 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
820 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
821 }
822
823 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
824 PushPopMIs.push_back(&I);
825
826 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
827 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
828 Opc == ARM::JUMPTABLE_TBH)
829 continue;
830
831 // Scan the instructions for constant pool operands.
832 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
833 if (I.getOperand(op).isCPI() ||
834 (I.getOperand(op).isJTI() && InlineJumpTables)) {
835 // We found one. The addressing mode tells us the max displacement
836 // from the PC that this instruction permits.
837
838 // Basic size info comes from the TSFlags field.
839 unsigned Bits = 0;
840 unsigned Scale = 1;
841 bool NegOk = false;
842 bool IsSoImm = false;
843
844 switch (Opc) {
845 default:
846 llvm_unreachable("Unknown addressing mode for CP reference!");
847
848 // Taking the address of a CP entry.
849 case ARM::LEApcrel:
850 case ARM::LEApcrelJT: {
851 // This takes a SoImm, which is 8 bit immediate rotated. We'll
852 // pretend the maximum offset is 255 * 4. Since each instruction
853 // 4 byte wide, this is always correct. We'll check for other
854 // displacements that fits in a SoImm as well.
855 Bits = 8;
856 NegOk = true;
857 IsSoImm = true;
858 unsigned CPI = I.getOperand(op).getIndex();
859 assert(CPI < CPEMIs.size());
860 MachineInstr *CPEMI = CPEMIs[CPI];
861 const Align CPEAlign = getCPEAlign(CPEMI);
862 const unsigned LogCPEAlign = Log2(CPEAlign);
863 if (LogCPEAlign >= 2)
864 Scale = 4;
865 else
866 // For constants with less than 4-byte alignment,
867 // we'll pretend the maximum offset is 255 * 1.
868 Scale = 1;
869 }
870 break;
871 case ARM::t2LEApcrel:
872 case ARM::t2LEApcrelJT:
873 Bits = 12;
874 NegOk = true;
875 break;
876 case ARM::tLEApcrel:
877 case ARM::tLEApcrelJT:
878 Bits = 8;
879 Scale = 4;
880 break;
881
882 case ARM::LDRBi12:
883 case ARM::LDRi12:
884 case ARM::LDRcp:
885 case ARM::t2LDRpci:
886 case ARM::t2LDRHpci:
887 case ARM::t2LDRSHpci:
888 case ARM::t2LDRBpci:
889 case ARM::t2LDRSBpci:
890 Bits = 12; // +-offset_12
891 NegOk = true;
892 break;
893
894 case ARM::tLDRpci:
895 Bits = 8;
896 Scale = 4; // +(offset_8*4)
897 break;
898
899 case ARM::VLDRD:
900 case ARM::VLDRS:
901 Bits = 8;
902 Scale = 4; // +-(offset_8*4)
903 NegOk = true;
904 break;
905 case ARM::VLDRH:
906 Bits = 8;
907 Scale = 2; // +-(offset_8*2)
908 NegOk = true;
909 break;
910 }
911
912 // Remember that this is a user of a CP entry.
913 unsigned CPI = I.getOperand(op).getIndex();
914 if (I.getOperand(op).isJTI()) {
915 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
916 CPI = JumpTableEntryIndices[CPI];
917 }
918
919 MachineInstr *CPEMI = CPEMIs[CPI];
920 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
921 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
922
923 // Increment corresponding CPEntry reference count.
924 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
925 assert(CPE && "Cannot find a corresponding CPEntry!");
926 CPE->RefCount++;
927
928 // Instructions can only use one CP entry, don't bother scanning the
929 // rest of the operands.
930 break;
931 }
932 }
933 }
934}
935
936/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
937/// ID.
939 const MachineBasicBlock *RHS) {
940 return LHS->getNumber() < RHS->getNumber();
941}
942
943/// updateForInsertedWaterBlock - When a block is newly inserted into the
944/// machine function, it upsets all of the block numbers. Renumber the blocks
945/// and update the arrays that parallel this numbering.
946void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
947 // Renumber the MBB's to keep them consecutive.
948 NewBB->getParent()->RenumberBlocks(NewBB);
949
950 // Insert an entry into BBInfo to align it properly with the (newly
951 // renumbered) block numbers.
952 BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
953
954 // Next, update WaterList. Specifically, we need to add NewMBB as having
955 // available water after it.
956 water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);
957 WaterList.insert(IP, NewBB);
958}
959
960/// Split the basic block containing MI into two blocks, which are joined by
961/// an unconditional branch. Update data structures and renumber blocks to
962/// account for this change and returns the newly created block.
963MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
964 MachineBasicBlock *OrigBB = MI->getParent();
965
966 // Collect liveness information at MI.
967 LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo());
968 LRs.addLiveOuts(*OrigBB);
969 auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse();
970 for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd))
971 LRs.stepBackward(LiveMI);
972
973 // Create a new MBB for the code after the OrigBB.
974 MachineBasicBlock *NewBB =
975 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
977 MF->insert(MBBI, NewBB);
978
979 // Splice the instructions starting with MI over to NewBB.
980 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
981
982 // Add an unconditional branch from OrigBB to NewBB.
983 // Note the new unconditional branch is not being recorded.
984 // There doesn't seem to be meaningful DebugInfo available; this doesn't
985 // correspond to anything in the source.
986 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
987 if (!isThumb)
988 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
989 else
990 BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
991 .addMBB(NewBB)
993 ++NumSplit;
994
995 // Update the CFG. All succs of OrigBB are now succs of NewBB.
996 NewBB->transferSuccessors(OrigBB);
997
998 // OrigBB branches to NewBB.
999 OrigBB->addSuccessor(NewBB);
1000
1001 // Update live-in information in the new block.
1002 MachineRegisterInfo &MRI = MF->getRegInfo();
1003 for (MCPhysReg L : LRs)
1004 if (!MRI.isReserved(L))
1005 NewBB->addLiveIn(L);
1006
1007 // Update internal data structures to account for the newly inserted MBB.
1008 // This is almost the same as updateForInsertedWaterBlock, except that
1009 // the Water goes after OrigBB, not NewBB.
1010 MF->RenumberBlocks(NewBB);
1011
1012 // Insert an entry into BBInfo to align it properly with the (newly
1013 // renumbered) block numbers.
1014 BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());
1015
1016 // Next, update WaterList. Specifically, we need to add OrigMBB as having
1017 // available water after it (but not if it's already there, which happens
1018 // when splitting before a conditional branch that is followed by an
1019 // unconditional branch - in that case we want to insert NewBB).
1020 water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);
1021 MachineBasicBlock* WaterBB = *IP;
1022 if (WaterBB == OrigBB)
1023 WaterList.insert(std::next(IP), NewBB);
1024 else
1025 WaterList.insert(IP, OrigBB);
1026 NewWaterList.insert(OrigBB);
1027
1028 // Figure out how large the OrigBB is. As the first half of the original
1029 // block, it cannot contain a tablejump. The size includes
1030 // the new jump we added. (It should be possible to do this without
1031 // recounting everything, but it's very confusing, and this is rarely
1032 // executed.)
1033 BBUtils->computeBlockSize(OrigBB);
1034
1035 // Figure out how large the NewMBB is. As the second half of the original
1036 // block, it may contain a tablejump.
1037 BBUtils->computeBlockSize(NewBB);
1038
1039 // All BBOffsets following these blocks must be modified.
1040 BBUtils->adjustBBOffsetsAfter(OrigBB);
1041
1042 return NewBB;
1043}
1044
1045/// getUserOffset - Compute the offset of U.MI as seen by the hardware
1046/// displacement computation. Update U.KnownAlignment to match its current
1047/// basic block location.
1048unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
1049 unsigned UserOffset = BBUtils->getOffsetOf(U.MI);
1050
1051 SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();
1052 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
1053 unsigned KnownBits = BBI.internalKnownBits();
1054
1055 // The value read from PC is offset from the actual instruction address.
1056 UserOffset += (isThumb ? 4 : 8);
1057
1058 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
1059 // Make sure U.getMaxDisp() returns a constrained range.
1060 U.KnownAlignment = (KnownBits >= 2);
1061
1062 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
1063 // purposes of the displacement computation; compensate for that here.
1064 // For unknown alignments, getMaxDisp() constrains the range instead.
1065 if (isThumb && U.KnownAlignment)
1066 UserOffset &= ~3u;
1067
1068 return UserOffset;
1069}
1070
1071/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
1072/// reference) is within MaxDisp of TrialOffset (a proposed location of a
1073/// constant pool entry).
1074/// UserOffset is computed by getUserOffset above to include PC adjustments. If
1075/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1076/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
1077bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
1078 unsigned TrialOffset, unsigned MaxDisp,
1079 bool NegativeOK, bool IsSoImm) {
1080 if (UserOffset <= TrialOffset) {
1081 // User before the Trial.
1082 if (TrialOffset - UserOffset <= MaxDisp)
1083 return true;
1084 // FIXME: Make use full range of soimm values.
1085 } else if (NegativeOK) {
1086 if (UserOffset - TrialOffset <= MaxDisp)
1087 return true;
1088 // FIXME: Make use full range of soimm values.
1089 }
1090 return false;
1091}
1092
1093/// isWaterInRange - Returns true if a CPE placed after the specified
1094/// Water (a basic block) will be in range for the specific MI.
1095///
1096/// Compute how much the function will grow by inserting a CPE after Water.
1097bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
1098 MachineBasicBlock* Water, CPUser &U,
1099 unsigned &Growth) {
1100 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1101 const Align CPEAlign = getCPEAlign(U.CPEMI);
1102 const unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPEAlign);
1103 unsigned NextBlockOffset;
1104 Align NextBlockAlignment;
1105 MachineFunction::const_iterator NextBlock = Water->getIterator();
1106 if (++NextBlock == MF->end()) {
1107 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1108 } else {
1109 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1110 NextBlockAlignment = NextBlock->getAlignment();
1111 }
1112 unsigned Size = U.CPEMI->getOperand(2).getImm();
1113 unsigned CPEEnd = CPEOffset + Size;
1114
1115 // The CPE may be able to hide in the alignment padding before the next
1116 // block. It may also cause more padding to be required if it is more aligned
1117 // that the next block.
1118 if (CPEEnd > NextBlockOffset) {
1119 Growth = CPEEnd - NextBlockOffset;
1120 // Compute the padding that would go at the end of the CPE to align the next
1121 // block.
1122 Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);
1123
1124 // If the CPE is to be inserted before the instruction, that will raise
1125 // the offset of the instruction. Also account for unknown alignment padding
1126 // in blocks between CPE and the user.
1127 if (CPEOffset < UserOffset)
1128 UserOffset += Growth + UnknownPadding(MF->getAlignment(), Log2(CPEAlign));
1129 } else
1130 // CPE fits in existing padding.
1131 Growth = 0;
1132
1133 return isOffsetInRange(UserOffset, CPEOffset, U);
1134}
1135
1136/// isCPEntryInRange - Returns true if the distance between specific MI and
1137/// specific ConstPool entry instruction can fit in MI's displacement field.
1138bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1139 MachineInstr *CPEMI, unsigned MaxDisp,
1140 bool NegOk, bool DoDump) {
1141 unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);
1142
1143 if (DoDump) {
1144 LLVM_DEBUG({
1145 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1146 unsigned Block = MI->getParent()->getNumber();
1147 const BasicBlockInfo &BBI = BBInfo[Block];
1148 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1149 << " max delta=" << MaxDisp
1150 << format(" insn address=%#x", UserOffset) << " in "
1151 << printMBBReference(*MI->getParent()) << ": "
1152 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1153 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1154 int(CPEOffset - UserOffset));
1155 });
1156 }
1157
1158 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1159}
1160
1161#ifndef NDEBUG
1162/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1163/// unconditionally branches to its only successor.
1165 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1166 return false;
1167
1168 MachineBasicBlock *Succ = *MBB->succ_begin();
1169 MachineBasicBlock *Pred = *MBB->pred_begin();
1170 MachineInstr *PredMI = &Pred->back();
1171 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1172 || PredMI->getOpcode() == ARM::t2B)
1173 return PredMI->getOperand(0).getMBB() == Succ;
1174 return false;
1175}
1176#endif // NDEBUG
1177
1178/// decrementCPEReferenceCount - find the constant pool entry with index CPI
1179/// and instruction CPEMI, and decrement its refcount. If the refcount
1180/// becomes 0 remove the entry and instruction. Returns true if we removed
1181/// the entry, false if we didn't.
1182bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1183 MachineInstr *CPEMI) {
1184 // Find the old entry. Eliminate it if it is no longer used.
1185 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1186 assert(CPE && "Unexpected!");
1187 if (--CPE->RefCount == 0) {
1188 removeDeadCPEMI(CPEMI);
1189 CPE->CPEMI = nullptr;
1190 --NumCPEs;
1191 return true;
1192 }
1193 return false;
1194}
1195
1196unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1197 if (CPEMI->getOperand(1).isCPI())
1198 return CPEMI->getOperand(1).getIndex();
1199
1200 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1201}
1202
1203/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1204/// if not, see if an in-range clone of the CPE is in range, and if so,
1205/// change the data structures so the user references the clone. Returns:
1206/// 0 = no existing entry found
1207/// 1 = entry found, and there were no code insertions or deletions
1208/// 2 = entry found, and there were code insertions or deletions
1209int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
1210 MachineInstr *UserMI = U.MI;
1211 MachineInstr *CPEMI = U.CPEMI;
1212
1213 // Check to see if the CPE is already in-range.
1214 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1215 true)) {
1216 LLVM_DEBUG(dbgs() << "In range\n");
1217 return 1;
1218 }
1219
1220 // No. Look for previously created clones of the CPE that are in range.
1221 unsigned CPI = getCombinedIndex(CPEMI);
1222 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1223 for (CPEntry &CPE : CPEs) {
1224 // We already tried this one
1225 if (CPE.CPEMI == CPEMI)
1226 continue;
1227 // Removing CPEs can leave empty entries, skip
1228 if (CPE.CPEMI == nullptr)
1229 continue;
1230 if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, U.getMaxDisp(),
1231 U.NegOk)) {
1232 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI
1233 << "\n");
1234 // Point the CPUser node to the replacement
1235 U.CPEMI = CPE.CPEMI;
1236 // Change the CPI in the instruction operand to refer to the clone.
1237 for (MachineOperand &MO : UserMI->operands())
1238 if (MO.isCPI()) {
1239 MO.setIndex(CPE.CPI);
1240 break;
1241 }
1242 // Adjust the refcount of the clone...
1243 CPE.RefCount++;
1244 // ...and the original. If we didn't remove the old entry, none of the
1245 // addresses changed, so we don't need another pass.
1246 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1247 }
1248 }
1249 return 0;
1250}
1251
1252/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1253/// the specific unconditional branch instruction.
1254static inline unsigned getUnconditionalBrDisp(int Opc) {
1255 switch (Opc) {
1256 case ARM::tB:
1257 return ((1<<10)-1)*2;
1258 case ARM::t2B:
1259 return ((1<<23)-1)*2;
1260 default:
1261 break;
1262 }
1263
1264 return ((1<<23)-1)*4;
1265}
1266
1267/// findAvailableWater - Look for an existing entry in the WaterList in which
1268/// we can place the CPE referenced from U so it's within range of U's MI.
1269/// Returns true if found, false if not. If it returns true, WaterIter
1270/// is set to the WaterList entry. For Thumb, prefer water that will not
1271/// introduce padding to water that will. To ensure that this pass
1272/// terminates, the CPE location for a particular CPUser is only allowed to
1273/// move to a lower address, so search backward from the end of the list and
1274/// prefer the first water that is in range.
1275bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1276 water_iterator &WaterIter,
1277 bool CloserWater) {
1278 if (WaterList.empty())
1279 return false;
1280
1281 unsigned BestGrowth = ~0u;
1282 // The nearest water without splitting the UserBB is right after it.
1283 // If the distance is still large (we have a big BB), then we need to split it
1284 // if we don't converge after certain iterations. This helps the following
1285 // situation to converge:
1286 // BB0:
1287 // Big BB
1288 // BB1:
1289 // Constant Pool
1290 // When a CP access is out of range, BB0 may be used as water. However,
1291 // inserting islands between BB0 and BB1 makes other accesses out of range.
1292 MachineBasicBlock *UserBB = U.MI->getParent();
1293 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1294 const Align CPEAlign = getCPEAlign(U.CPEMI);
1295 unsigned MinNoSplitDisp =
1296 BBInfo[UserBB->getNumber()].postOffset(CPEAlign) - UserOffset;
1297 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1298 return false;
1299 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1300 --IP) {
1301 MachineBasicBlock* WaterBB = *IP;
1302 // Check if water is in range and is either at a lower address than the
1303 // current "high water mark" or a new water block that was created since
1304 // the previous iteration by inserting an unconditional branch. In the
1305 // latter case, we want to allow resetting the high water mark back to
1306 // this new water since we haven't seen it before. Inserting branches
1307 // should be relatively uncommon and when it does happen, we want to be
1308 // sure to take advantage of it for all the CPEs near that block, so that
1309 // we don't insert more branches than necessary.
1310 // When CloserWater is true, we try to find the lowest address after (or
1311 // equal to) user MI's BB no matter of padding growth.
1312 unsigned Growth;
1313 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1314 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1315 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1316 (CloserWater || Growth < BestGrowth)) {
1317 // This is the least amount of required padding seen so far.
1318 BestGrowth = Growth;
1319 WaterIter = IP;
1320 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1321 << " Growth=" << Growth << '\n');
1322
1323 if (CloserWater && WaterBB == U.MI->getParent())
1324 return true;
1325 // Keep looking unless it is perfect and we're not looking for the lowest
1326 // possible address.
1327 if (!CloserWater && BestGrowth == 0)
1328 return true;
1329 }
1330 if (IP == B)
1331 break;
1332 }
1333 return BestGrowth != ~0u;
1334}
1335
1336/// createNewWater - No existing WaterList entry will work for
1337/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1338/// block is used if in range, and the conditional branch munged so control
1339/// flow is correct. Otherwise the block is split to create a hole with an
1340/// unconditional branch around it. In either case NewMBB is set to a
1341/// block following which the new island can be inserted (the WaterList
1342/// is not adjusted).
1343void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1344 unsigned UserOffset,
1345 MachineBasicBlock *&NewMBB) {
1346 CPUser &U = CPUsers[CPUserIndex];
1347 MachineInstr *UserMI = U.MI;
1348 MachineInstr *CPEMI = U.CPEMI;
1349 const Align CPEAlign = getCPEAlign(CPEMI);
1350 MachineBasicBlock *UserMBB = UserMI->getParent();
1351 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1352 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1353
1354 // If the block does not end in an unconditional branch already, and if the
1355 // end of the block is within range, make new water there. (The addition
1356 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1357 // Thumb2, 2 on Thumb1.
1358 if (BBHasFallthrough(UserMBB)) {
1359 // Size of branch to insert.
1360 unsigned Delta = isThumb1 ? 2 : 4;
1361 // Compute the offset where the CPE will begin.
1362 unsigned CPEOffset = UserBBI.postOffset(CPEAlign) + Delta;
1363
1364 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1365 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1366 << format(", expected CPE offset %#x\n", CPEOffset));
1367 NewMBB = &*++UserMBB->getIterator();
1368 // Add an unconditional branch from UserMBB to fallthrough block. Record
1369 // it for branch lengthening; this new branch will not get out of range,
1370 // but if the preceding conditional branch is out of range, the targets
1371 // will be exchanged, and the altered branch may be out of range, so the
1372 // machinery has to know about it.
1373 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1374 if (!isThumb)
1375 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1376 else
1377 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1378 .addMBB(NewMBB)
1380 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1381 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1382 MaxDisp, false, UncondBr));
1383 BBUtils->computeBlockSize(UserMBB);
1384 BBUtils->adjustBBOffsetsAfter(UserMBB);
1385 return;
1386 }
1387 }
1388
1389 // What a big block. Find a place within the block to split it. This is a
1390 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1391 // entries are 4 bytes: if instruction I references island CPE, and
1392 // instruction I+1 references CPE', it will not work well to put CPE as far
1393 // forward as possible, since then CPE' cannot immediately follow it (that
1394 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1395 // need to create a new island. So, we make a first guess, then walk through
1396 // the instructions between the one currently being looked at and the
1397 // possible insertion point, and make sure any other instructions that
1398 // reference CPEs will be able to use the same island area; if not, we back
1399 // up the insertion point.
1400
1401 // Try to split the block so it's fully aligned. Compute the latest split
1402 // point where we can add a 4-byte branch instruction, and then align to
1403 // Align which is the largest possible alignment in the function.
1404 const Align Align = MF->getAlignment();
1405 assert(Align >= CPEAlign && "Over-aligned constant pool entry");
1406 unsigned KnownBits = UserBBI.internalKnownBits();
1407 unsigned UPad = UnknownPadding(Align, KnownBits);
1408 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1409 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1410 BaseInsertOffset));
1411
1412 // The 4 in the following is for the unconditional branch we'll be inserting
1413 // (allows for long branch on Thumb1). Alignment of the island is handled
1414 // inside isOffsetInRange.
1415 BaseInsertOffset -= 4;
1416
1417 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1418 << " la=" << Log2(Align) << " kb=" << KnownBits
1419 << " up=" << UPad << '\n');
1420
1421 // This could point off the end of the block if we've already got constant
1422 // pool entries following this block; only the last one is in the water list.
1423 // Back past any possible branches (allow for a conditional and a maximally
1424 // long unconditional).
1425 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1426 // Ensure BaseInsertOffset is larger than the offset of the instruction
1427 // following UserMI so that the loop which searches for the split point
1428 // iterates at least once.
1429 BaseInsertOffset =
1430 std::max(UserBBI.postOffset() - UPad - 8,
1431 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
1432 // If the CP is referenced(ie, UserOffset) is in first four instructions
1433 // after IT, this recalculated BaseInsertOffset could be in the middle of
1434 // an IT block. If it is, change the BaseInsertOffset to just after the
1435 // IT block. This still make the CP Entry is in range because of the
1436 // following reasons.
1437 // 1. The initial BaseseInsertOffset calculated is (UserOffset +
1438 // U.getMaxDisp() - UPad).
1439 // 2. An IT block is only at most 4 instructions plus the "it" itself (18
1440 // bytes).
1441 // 3. All the relevant instructions support much larger Maximum
1442 // displacement.
1444 ++I;
1445 Register PredReg;
1446 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1447 I->getOpcode() != ARM::t2IT &&
1448 getITInstrPredicate(*I, PredReg) != ARMCC::AL;
1449 Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) {
1450 BaseInsertOffset =
1451 std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1);
1452 assert(I != UserMBB->end() && "Fell off end of block");
1453 }
1454 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1455 }
1456 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1457 CPEMI->getOperand(2).getImm();
1459 ++MI;
1460 unsigned CPUIndex = CPUserIndex+1;
1461 unsigned NumCPUsers = CPUsers.size();
1462 MachineInstr *LastIT = nullptr;
1463 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1464 Offset < BaseInsertOffset;
1465 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1466 assert(MI != UserMBB->end() && "Fell off end of block");
1467 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
1468 CPUser &U = CPUsers[CPUIndex];
1469 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1470 // Shift intertion point by one unit of alignment so it is within reach.
1471 BaseInsertOffset -= Align.value();
1472 EndInsertOffset -= Align.value();
1473 }
1474 // This is overly conservative, as we don't account for CPEMIs being
1475 // reused within the block, but it doesn't matter much. Also assume CPEs
1476 // are added in order with alignment padding. We may eventually be able
1477 // to pack the aligned CPEs better.
1478 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1479 CPUIndex++;
1480 }
1481
1482 // Remember the last IT instruction.
1483 if (MI->getOpcode() == ARM::t2IT)
1484 LastIT = &*MI;
1485 }
1486
1487 --MI;
1488
1489 // Avoid splitting an IT block.
1490 if (LastIT) {
1491 Register PredReg;
1493 if (CC != ARMCC::AL)
1494 MI = LastIT;
1495 }
1496
1497 // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1498 // On Windows, this instruction pair is covered by one single
1499 // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1500 // constant island is injected inbetween them, the relocation will clobber
1501 // the instruction and fail to update the MOVT instruction.
1502 // (These instructions are bundled up until right before the ConstantIslands
1503 // pass.)
1504 if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
1505 (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1507 --MI;
1508 assert(MI->getOpcode() == ARM::t2MOVi16 &&
1509 (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1511 }
1512
1513 // We really must not split an IT block.
1514#ifndef NDEBUG
1515 Register PredReg;
1516 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL);
1517#endif
1518 NewMBB = splitBlockBeforeInstr(&*MI);
1519}
1520
1521/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1522/// is out-of-range. If so, pick up the constant pool value and move it some
1523/// place in-range. Return true if we changed any addresses (thus must run
1524/// another pass of branch lengthening), false otherwise.
1525bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1526 bool CloserWater) {
1527 CPUser &U = CPUsers[CPUserIndex];
1528 MachineInstr *UserMI = U.MI;
1529 MachineInstr *CPEMI = U.CPEMI;
1530 unsigned CPI = getCombinedIndex(CPEMI);
1531 unsigned Size = CPEMI->getOperand(2).getImm();
1532 // Compute this only once, it's expensive.
1533 unsigned UserOffset = getUserOffset(U);
1534
1535 // See if the current entry is within range, or there is a clone of it
1536 // in range.
1537 int result = findInRangeCPEntry(U, UserOffset);
1538 if (result==1) return false;
1539 else if (result==2) return true;
1540
1541 // No existing clone of this CPE is within range.
1542 // We will be generating a new clone. Get a UID for it.
1543 unsigned ID = AFI->createPICLabelUId();
1544
1545 // Look for water where we can place this CPE.
1546 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1547 MachineBasicBlock *NewMBB;
1548 water_iterator IP;
1549 if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
1550 LLVM_DEBUG(dbgs() << "Found water in range\n");
1551 MachineBasicBlock *WaterBB = *IP;
1552
1553 // If the original WaterList entry was "new water" on this iteration,
1554 // propagate that to the new island. This is just keeping NewWaterList
1555 // updated to match the WaterList, which will be updated below.
1556 if (NewWaterList.erase(WaterBB))
1557 NewWaterList.insert(NewIsland);
1558
1559 // The new CPE goes before the following block (NewMBB).
1560 NewMBB = &*++WaterBB->getIterator();
1561 } else {
1562 // No water found.
1563 LLVM_DEBUG(dbgs() << "No water found\n");
1564 createNewWater(CPUserIndex, UserOffset, NewMBB);
1565
1566 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1567 // called while handling branches so that the water will be seen on the
1568 // next iteration for constant pools, but in this context, we don't want
1569 // it. Check for this so it will be removed from the WaterList.
1570 // Also remove any entry from NewWaterList.
1571 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1572 IP = find(WaterList, WaterBB);
1573 if (IP != WaterList.end())
1574 NewWaterList.erase(WaterBB);
1575
1576 // We are adding new water. Update NewWaterList.
1577 NewWaterList.insert(NewIsland);
1578 }
1579 // Always align the new block because CP entries can be smaller than 4
1580 // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1581 // be an already aligned constant pool block.
1582 const Align Alignment = isThumb ? Align(2) : Align(4);
1583 if (NewMBB->getAlignment() < Alignment)
1584 NewMBB->setAlignment(Alignment);
1585
1586 // Remove the original WaterList entry; we want subsequent insertions in
1587 // this vicinity to go after the one we're about to insert. This
1588 // considerably reduces the number of times we have to move the same CPE
1589 // more than once and is also important to ensure the algorithm terminates.
1590 if (IP != WaterList.end())
1591 WaterList.erase(IP);
1592
1593 // Okay, we know we can put an island before NewMBB now, do it!
1594 MF->insert(NewMBB->getIterator(), NewIsland);
1595
1596 // Update internal data structures to account for the newly inserted MBB.
1597 updateForInsertedWaterBlock(NewIsland);
1598
1599 // Now that we have an island to add the CPE to, clone the original CPE and
1600 // add it to the island.
1601 U.HighWaterMark = NewIsland;
1602 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1603 .addImm(ID)
1604 .add(CPEMI->getOperand(1))
1605 .addImm(Size);
1606 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1607 ++NumCPEs;
1608
1609 // Decrement the old entry, and remove it if refcount becomes 0.
1610 decrementCPEReferenceCount(CPI, CPEMI);
1611
1612 // Mark the basic block as aligned as required by the const-pool entry.
1613 NewIsland->setAlignment(getCPEAlign(U.CPEMI));
1614
1615 // Increase the size of the island block to account for the new entry.
1616 BBUtils->adjustBBSize(NewIsland, Size);
1617 BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1618
1619 // Finally, change the CPI in the instruction operand to be ID.
1620 for (MachineOperand &MO : UserMI->operands())
1621 if (MO.isCPI()) {
1622 MO.setIndex(ID);
1623 break;
1624 }
1625
1626 LLVM_DEBUG(
1627 dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1628 << format(" offset=%#x\n",
1629 BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));
1630
1631 return true;
1632}
1633
1634/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1635/// sizes and offsets of impacted basic blocks.
1636void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1637 MachineBasicBlock *CPEBB = CPEMI->getParent();
1638 unsigned Size = CPEMI->getOperand(2).getImm();
1639 CPEMI->eraseFromParent();
1640 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1641 BBUtils->adjustBBSize(CPEBB, -Size);
1642 // All succeeding offsets have the current size value added in, fix this.
1643 if (CPEBB->empty()) {
1644 BBInfo[CPEBB->getNumber()].Size = 0;
1645
1646 // This block no longer needs to be aligned.
1647 CPEBB->setAlignment(Align(1));
1648 } else {
1649 // Entries are sorted by descending alignment, so realign from the front.
1650 CPEBB->setAlignment(getCPEAlign(&*CPEBB->begin()));
1651 }
1652
1653 BBUtils->adjustBBOffsetsAfter(CPEBB);
1654 // An island has only one predecessor BB and one successor BB. Check if
1655 // this BB's predecessor jumps directly to this BB's successor. This
1656 // shouldn't happen currently.
1657 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1658 // FIXME: remove the empty blocks after all the work is done?
1659}
1660
1661/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1662/// are zero.
1663bool ARMConstantIslands::removeUnusedCPEntries() {
1664 unsigned MadeChange = false;
1665 for (std::vector<CPEntry> &CPEs : CPEntries) {
1666 for (CPEntry &CPE : CPEs) {
1667 if (CPE.RefCount == 0 && CPE.CPEMI) {
1668 removeDeadCPEMI(CPE.CPEMI);
1669 CPE.CPEMI = nullptr;
1670 MadeChange = true;
1671 }
1672 }
1673 }
1674 return MadeChange;
1675}
1676
1677
1678/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1679/// away to fit in its displacement field.
1680bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1681 MachineInstr *MI = Br.MI;
1682 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1683
1684 // Check to see if the DestBB is already in-range.
1685 if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))
1686 return false;
1687
1688 if (!Br.isCond)
1689 return fixupUnconditionalBr(Br);
1690 return fixupConditionalBr(Br);
1691}
1692
1693/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1694/// too far away to fit in its displacement field. If the LR register has been
1695/// spilled in the epilogue, then we can use BL to implement a far jump.
1696/// Otherwise, add an intermediate branch instruction to a branch.
1697bool
1698ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1699 MachineInstr *MI = Br.MI;
1700 MachineBasicBlock *MBB = MI->getParent();
1701 if (!isThumb1)
1702 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1703
1704 if (!AFI->isLRSpilled())
1705 report_fatal_error("underestimated function size");
1706
1707 // Use BL to implement far jump.
1708 Br.MaxDisp = (1 << 21) * 2;
1709 MI->setDesc(TII->get(ARM::tBfar));
1710 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1711 BBInfo[MBB->getNumber()].Size += 2;
1712 BBUtils->adjustBBOffsetsAfter(MBB);
1713 ++NumUBrFixed;
1714
1715 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
1716
1717 return true;
1718}
1719
1720/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1721/// far away to fit in its displacement field. It is converted to an inverse
1722/// conditional branch + an unconditional branch to the destination.
1723bool
1724ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1725 MachineInstr *MI = Br.MI;
1726 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1727
1728 // Add an unconditional branch to the destination and invert the branch
1729 // condition to jump over it:
1730 // blt L1
1731 // =>
1732 // bge L2
1733 // b L1
1734 // L2:
1735 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1737 Register CCReg = MI->getOperand(2).getReg();
1738
1739 // If the branch is at the end of its MBB and that has a fall-through block,
1740 // direct the updated conditional branch to the fall-through block. Otherwise,
1741 // split the MBB before the next instruction.
1742 MachineBasicBlock *MBB = MI->getParent();
1743 MachineInstr *BMI = &MBB->back();
1744 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1745
1746 ++NumCBrFixed;
1747 if (BMI != MI) {
1748 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1749 BMI->getOpcode() == Br.UncondBr) {
1750 // Last MI in the BB is an unconditional branch. Can we simply invert the
1751 // condition and swap destinations:
1752 // beq L1
1753 // b L2
1754 // =>
1755 // bne L2
1756 // b L1
1757 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1758 if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {
1759 LLVM_DEBUG(
1760 dbgs() << " Invert Bcc condition and swap its destination with "
1761 << *BMI);
1762 BMI->getOperand(0).setMBB(DestBB);
1763 MI->getOperand(0).setMBB(NewDest);
1764 MI->getOperand(1).setImm(CC);
1765 return true;
1766 }
1767 }
1768 }
1769
1770 if (NeedSplit) {
1771 splitBlockBeforeInstr(MI);
1772 // No need for the branch to the next block. We're adding an unconditional
1773 // branch to the destination.
1774 int delta = TII->getInstSizeInBytes(MBB->back());
1775 BBUtils->adjustBBSize(MBB, -delta);
1777
1778 // The conditional successor will be swapped between the BBs after this, so
1779 // update CFG.
1780 MBB->addSuccessor(DestBB);
1781 std::next(MBB->getIterator())->removeSuccessor(DestBB);
1782
1783 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1784 }
1785 MachineBasicBlock *NextBB = &*++MBB->getIterator();
1786
1787 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
1788 << " also invert condition and change dest. to "
1789 << printMBBReference(*NextBB) << "\n");
1790
1791 // Insert a new conditional branch and a new unconditional branch.
1792 // Also update the ImmBranch as well as adding a new entry for the new branch.
1793 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1794 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1795 Br.MI = &MBB->back();
1796 BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
1797 if (isThumb)
1798 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1799 .addMBB(DestBB)
1801 else
1802 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1803 BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));
1804 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1805 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1806
1807 // Remove the old conditional branch. It may or may not still be in MBB.
1808 BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));
1809 MI->eraseFromParent();
1810 BBUtils->adjustBBOffsetsAfter(MBB);
1811 return true;
1812}
1813
1814bool ARMConstantIslands::optimizeThumb2Instructions() {
1815 bool MadeChange = false;
1816
1817 // Shrink ADR and LDR from constantpool.
1818 for (CPUser &U : CPUsers) {
1819 unsigned Opcode = U.MI->getOpcode();
1820 unsigned NewOpc = 0;
1821 unsigned Scale = 1;
1822 unsigned Bits = 0;
1823 switch (Opcode) {
1824 default: break;
1825 case ARM::t2LEApcrel:
1826 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1827 NewOpc = ARM::tLEApcrel;
1828 Bits = 8;
1829 Scale = 4;
1830 }
1831 break;
1832 case ARM::t2LDRpci:
1833 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1834 NewOpc = ARM::tLDRpci;
1835 Bits = 8;
1836 Scale = 4;
1837 }
1838 break;
1839 }
1840
1841 if (!NewOpc)
1842 continue;
1843
1844 unsigned UserOffset = getUserOffset(U);
1845 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1846
1847 // Be conservative with inline asm.
1848 if (!U.KnownAlignment)
1849 MaxOffs -= 2;
1850
1851 // FIXME: Check if offset is multiple of scale if scale is not 4.
1852 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1853 LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
1854 U.MI->setDesc(TII->get(NewOpc));
1855 MachineBasicBlock *MBB = U.MI->getParent();
1856 BBUtils->adjustBBSize(MBB, -2);
1857 BBUtils->adjustBBOffsetsAfter(MBB);
1858 ++NumT2CPShrunk;
1859 MadeChange = true;
1860 }
1861 }
1862
1863 return MadeChange;
1864}
1865
1866
1867bool ARMConstantIslands::optimizeThumb2Branches() {
1868
1869 auto TryShrinkBranch = [this](ImmBranch &Br) {
1870 unsigned Opcode = Br.MI->getOpcode();
1871 unsigned NewOpc = 0;
1872 unsigned Scale = 1;
1873 unsigned Bits = 0;
1874 switch (Opcode) {
1875 default: break;
1876 case ARM::t2B:
1877 NewOpc = ARM::tB;
1878 Bits = 11;
1879 Scale = 2;
1880 break;
1881 case ARM::t2Bcc:
1882 NewOpc = ARM::tBcc;
1883 Bits = 8;
1884 Scale = 2;
1885 break;
1886 }
1887 if (NewOpc) {
1888 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1889 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1890 if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {
1891 LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1892 Br.MI->setDesc(TII->get(NewOpc));
1893 MachineBasicBlock *MBB = Br.MI->getParent();
1894 BBUtils->adjustBBSize(MBB, -2);
1895 BBUtils->adjustBBOffsetsAfter(MBB);
1896 ++NumT2BrShrunk;
1897 return true;
1898 }
1899 }
1900 return false;
1901 };
1902
1903 struct ImmCompare {
1904 MachineInstr* MI = nullptr;
1905 unsigned NewOpc = 0;
1906 };
1907
1908 auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp,
1909 MachineBasicBlock *DestBB) {
1910 ImmCmp.MI = nullptr;
1911 ImmCmp.NewOpc = 0;
1912
1913 // Folding the compare into a CBZ/CBNZ clobbers the comparison, so it is not
1914 // safe if CPSR is live past the branch.
1915 //
1916 for (const MachineBasicBlock *Succ : Br.MI->getParent()->successors()) {
1917 if (Succ->isLiveIn(ARM::CPSR))
1918 return false;
1919 }
1920
1921 Register PredReg;
1922 unsigned NewOpc = 0;
1923 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
1924 if (Pred == ARMCC::EQ)
1925 NewOpc = ARM::tCBZ;
1926 else if (Pred == ARMCC::NE)
1927 NewOpc = ARM::tCBNZ;
1928 else
1929 return false;
1930
1931 // Check if the distance is within 126. Subtract starting offset by 2
1932 // because the cmp will be eliminated.
1933 unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;
1934 BBInfoVector &BBInfo = BBUtils->getBBInfo();
1935 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1936 if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
1937 return false;
1938
1939 // Search backwards to find a tCMPi8
1940 auto *TRI = STI->getRegisterInfo();
1941 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
1942 if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
1943 return false;
1944
1945 ImmCmp.MI = CmpMI;
1946 ImmCmp.NewOpc = NewOpc;
1947 return true;
1948 };
1949
1950 auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) {
1951 if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasV8_1MMainlineOps() ||
1952 !STI->hasLOB() || STI->hasMinSize())
1953 return false;
1954
1955 MachineBasicBlock *MBB = Br.MI->getParent();
1956 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1957 if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) ||
1958 !BBUtils->isBBInRange(Br.MI, DestBB, 4094))
1959 return false;
1960
1961 if (!DT->dominates(DestBB, MBB))
1962 return false;
1963
1964 // We queried for the CBN?Z opcode based upon the 'ExitBB', the opposite
1965 // target of Br. So now we need to reverse the condition.
1966 Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ;
1967
1968 MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(),
1969 TII->get(ARM::t2LE));
1970 // Swapped a t2Bcc for a t2LE, so no need to update the size of the block.
1971 MIB.add(Br.MI->getOperand(0));
1972 Br.MI->eraseFromParent();
1973 Br.MI = MIB;
1974 ++NumLEInserted;
1975 return true;
1976 };
1977
1978 bool MadeChange = false;
1979
1980 // The order in which branches appear in ImmBranches is approximately their
1981 // order within the function body. By visiting later branches first, we reduce
1982 // the distance between earlier forward branches and their targets, making it
1983 // more likely that the cbn?z optimization, which can only apply to forward
1984 // branches, will succeed.
1985 for (ImmBranch &Br : reverse(ImmBranches)) {
1986 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1987 MachineBasicBlock *MBB = Br.MI->getParent();
1988 MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ?
1989 MBB->getFallThrough() :
1990 MBB->back().getOperand(0).getMBB();
1991
1992 ImmCompare Cmp;
1993 if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) {
1994 DestBB = ExitBB;
1995 MadeChange = true;
1996 } else {
1997 FindCmpForCBZ(Br, Cmp, DestBB);
1998 MadeChange |= TryShrinkBranch(Br);
1999 }
2000
2001 unsigned Opcode = Br.MI->getOpcode();
2002 if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc)
2003 continue;
2004
2005 Register Reg = Cmp.MI->getOperand(0).getReg();
2006
2007 // Check for Kill flags on Reg. If they are present remove them and set kill
2008 // on the new CBZ.
2009 auto *TRI = STI->getRegisterInfo();
2010 MachineBasicBlock::iterator KillMI = Br.MI;
2011 bool RegKilled = false;
2012 do {
2013 --KillMI;
2014 if (KillMI->killsRegister(Reg, TRI)) {
2015 KillMI->clearRegisterKills(Reg, TRI);
2016 RegKilled = true;
2017 break;
2018 }
2019 } while (KillMI != Cmp.MI);
2020
2021 // Create the new CBZ/CBNZ
2022 LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI);
2023 MachineInstr *NewBR =
2024 BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc))
2025 .addReg(Reg, getKillRegState(RegKilled) |
2026 getRegState(Cmp.MI->getOperand(0)))
2027 .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
2028
2029 Cmp.MI->eraseFromParent();
2030
2031 if (Br.MI->getOpcode() == ARM::tBcc) {
2032 Br.MI->eraseFromParent();
2033 Br.MI = NewBR;
2034 BBUtils->adjustBBSize(MBB, -2);
2035 } else if (MBB->back().getOpcode() != ARM::t2LE) {
2036 // An LE has been generated, but it's not the terminator - that is an
2037 // unconditional branch. However, the logic has now been reversed with the
2038 // CBN?Z being the conditional branch and the LE being the unconditional
2039 // branch. So this means we can remove the redundant unconditional branch
2040 // at the end of the block.
2041 MachineInstr *LastMI = &MBB->back();
2042 BBUtils->adjustBBSize(MBB, -LastMI->getDesc().getSize());
2043 LastMI->eraseFromParent();
2044 }
2045 BBUtils->adjustBBOffsetsAfter(MBB);
2046 ++NumCBZ;
2047 MadeChange = true;
2048 }
2049
2050 return MadeChange;
2051}
2052
2053static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
2054 unsigned BaseReg) {
2055 if (I.getOpcode() != ARM::t2ADDrs)
2056 return false;
2057
2058 if (I.getOperand(0).getReg() != EntryReg)
2059 return false;
2060
2061 if (I.getOperand(1).getReg() != BaseReg)
2062 return false;
2063
2064 // FIXME: what about CC and IdxReg?
2065 return true;
2066}
2067
2068/// While trying to form a TBB/TBH instruction, we may (if the table
2069/// doesn't immediately follow the BR_JT) need access to the start of the
2070/// jump-table. We know one instruction that produces such a register; this
2071/// function works out whether that definition can be preserved to the BR_JT,
2072/// possibly by removing an intervening addition (which is usually needed to
2073/// calculate the actual entry to jump to).
2074bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
2075 MachineInstr *LEAMI,
2076 unsigned &DeadSize,
2077 bool &CanDeleteLEA,
2078 bool &BaseRegKill) {
2079 if (JumpMI->getParent() != LEAMI->getParent())
2080 return false;
2081
2082 // Now we hope that we have at least these instructions in the basic block:
2083 // BaseReg = t2LEA ...
2084 // [...]
2085 // EntryReg = t2ADDrs BaseReg, ...
2086 // [...]
2087 // t2BR_JT EntryReg
2088 //
2089 // We have to be very conservative about what we recognise here though. The
2090 // main perturbing factors to watch out for are:
2091 // + Spills at any point in the chain: not direct problems but we would
2092 // expect a blocking Def of the spilled register so in practice what we
2093 // can do is limited.
2094 // + EntryReg == BaseReg: this is the one situation we should allow a Def
2095 // of BaseReg, but only if the t2ADDrs can be removed.
2096 // + Some instruction other than t2ADDrs computing the entry. Not seen in
2097 // the wild, but we should be careful.
2098 Register EntryReg = JumpMI->getOperand(0).getReg();
2099 Register BaseReg = LEAMI->getOperand(0).getReg();
2100
2101 CanDeleteLEA = true;
2102 BaseRegKill = false;
2103 MachineInstr *RemovableAdd = nullptr;
2105 for (++I; &*I != JumpMI; ++I) {
2106 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
2107 RemovableAdd = &*I;
2108 break;
2109 }
2110
2111 for (const MachineOperand &MO : I->operands()) {
2112 if (!MO.isReg() || !MO.getReg())
2113 continue;
2114 if (MO.isDef() && MO.getReg() == BaseReg)
2115 return false;
2116 if (MO.isUse() && MO.getReg() == BaseReg) {
2117 BaseRegKill = BaseRegKill || MO.isKill();
2118 CanDeleteLEA = false;
2119 }
2120 }
2121 }
2122
2123 if (!RemovableAdd)
2124 return true;
2125
2126 // Check the add really is removable, and that nothing else in the block
2127 // clobbers BaseReg.
2128 for (++I; &*I != JumpMI; ++I) {
2129 for (const MachineOperand &MO : I->operands()) {
2130 if (!MO.isReg() || !MO.getReg())
2131 continue;
2132 if (MO.isDef() && MO.getReg() == BaseReg)
2133 return false;
2134 if (MO.isUse() && MO.getReg() == EntryReg)
2135 RemovableAdd = nullptr;
2136 }
2137 }
2138
2139 if (RemovableAdd) {
2140 RemovableAdd->eraseFromParent();
2141 DeadSize += isThumb2 ? 4 : 2;
2142 } else if (BaseReg == EntryReg) {
2143 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2144 // preserve it.
2145 return false;
2146 }
2147
2148 // We reached the end of the block without seeing another definition of
2149 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2150 // used in the TBB/TBH if necessary.
2151 return true;
2152}
2153
2154/// Returns whether CPEMI is the first instruction in the block
2155/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2156/// we can switch the first register to PC and usually remove the address
2157/// calculation that preceded it.
2160 MachineFunction *MF = MBB->getParent();
2161 ++MBB;
2162
2163 return MBB != MF->end() && !MBB->empty() && &*MBB->begin() == CPEMI;
2164}
2165
2167 MachineInstr *JumpMI,
2168 unsigned &DeadSize) {
2169 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2170 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2171 // and is not clobbered / used.
2172 MachineInstr *RemovableAdd = nullptr;
2173 Register EntryReg = JumpMI->getOperand(0).getReg();
2174
2175 // Find the last ADD to set EntryReg
2177 for (++I; &*I != JumpMI; ++I) {
2178 if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2179 RemovableAdd = &*I;
2180 }
2181
2182 if (!RemovableAdd)
2183 return;
2184
2185 // Ensure EntryReg is not clobbered or used.
2186 MachineBasicBlock::iterator J(RemovableAdd);
2187 for (++J; &*J != JumpMI; ++J) {
2188 for (const MachineOperand &MO : J->operands()) {
2189 if (!MO.isReg() || !MO.getReg())
2190 continue;
2191 if (MO.isDef() && MO.getReg() == EntryReg)
2192 return;
2193 if (MO.isUse() && MO.getReg() == EntryReg)
2194 return;
2195 }
2196 }
2197
2198 LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
2199 RemovableAdd->eraseFromParent();
2200 DeadSize += 4;
2201}
2202
2203/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
2204/// jumptables when it's possible.
2205bool ARMConstantIslands::optimizeThumb2JumpTables() {
2206 bool MadeChange = false;
2207
2208 // FIXME: After the tables are shrunk, can we get rid some of the
2209 // constantpool tables?
2210 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2211 if (!MJTI) return false;
2212
2213 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2214 for (MachineInstr *MI : T2JumpTables) {
2215 const MCInstrDesc &MCID = MI->getDesc();
2216 unsigned NumOps = MCID.getNumOperands();
2217 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2218 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2219 unsigned JTI = JTOP.getIndex();
2220 assert(JTI < JT.size());
2221
2222 bool ByteOk = true;
2223 bool HalfWordOk = true;
2224 unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;
2225 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2226 BBInfoVector &BBInfo = BBUtils->getBBInfo();
2227 for (MachineBasicBlock *MBB : JTBBs) {
2228 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
2229 // Negative offset is not ok. FIXME: We should change BB layout to make
2230 // sure all the branches are forward.
2231 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
2232 ByteOk = false;
2233 unsigned TBHLimit = ((1<<16)-1)*2;
2234 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
2235 HalfWordOk = false;
2236 if (!ByteOk && !HalfWordOk)
2237 break;
2238 }
2239
2240 if (!ByteOk && !HalfWordOk)
2241 continue;
2242
2243 CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2244 MachineBasicBlock *MBB = MI->getParent();
2245 if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2246 continue;
2247
2248 unsigned DeadSize = 0;
2249 bool CanDeleteLEA = false;
2250 bool BaseRegKill = false;
2251
2252 unsigned IdxReg = ~0U;
2253 bool IdxRegKill = true;
2254 if (isThumb2) {
2255 IdxReg = MI->getOperand(1).getReg();
2256 IdxRegKill = MI->getOperand(1).isKill();
2257
2258 bool PreservedBaseReg =
2259 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2260 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2261 continue;
2262 } else {
2263 // We're in thumb-1 mode, so we must have something like:
2264 // %idx = tLSLri %idx, 2
2265 // %base = tLEApcrelJT
2266 // %t = tLDRr %base, %idx
2267 Register BaseReg = User.MI->getOperand(0).getReg();
2268
2269 MachineBasicBlock *UserMBB = User.MI->getParent();
2270 MachineBasicBlock::iterator Shift = User.MI->getIterator();
2271 if (Shift == UserMBB->begin())
2272 continue;
2273
2274 Shift = prev_nodbg(Shift, UserMBB->begin());
2275 if (Shift->getOpcode() != ARM::tLSLri ||
2276 Shift->getOperand(3).getImm() != 2 ||
2277 !Shift->getOperand(2).isKill())
2278 continue;
2279 IdxReg = Shift->getOperand(2).getReg();
2280 Register ShiftedIdxReg = Shift->getOperand(0).getReg();
2281
2282 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2283 // the range is checked later, but the LEA might still clobber it and not
2284 // actually get removed.
2285 if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2286 continue;
2287
2288 MachineInstr *Load = User.MI->getNextNode();
2289 if (Load->getOpcode() != ARM::tLDRr)
2290 continue;
2291 if (Load->getOperand(1).getReg() != BaseReg ||
2292 Load->getOperand(2).getReg() != ShiftedIdxReg ||
2293 !Load->getOperand(2).isKill())
2294 continue;
2295
2296 // If we're in PIC mode, there should be another ADD following.
2297 auto *TRI = STI->getRegisterInfo();
2298
2299 // %base cannot be redefined after the load as it will appear before
2300 // TBB/TBH like:
2301 // %base =
2302 // %base =
2303 // tBB %base, %idx
2304 if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
2305 continue;
2306
2307 if (isPositionIndependentOrROPI) {
2308 MachineInstr *Add = Load->getNextNode();
2309 if (Add->getOpcode() != ARM::tADDrr ||
2310 Add->getOperand(2).getReg() != BaseReg ||
2311 Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
2312 !Add->getOperand(3).isKill())
2313 continue;
2314 if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2315 continue;
2316 if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2317 // IdxReg gets redefined in the middle of the sequence.
2318 continue;
2319 Add->eraseFromParent();
2320 DeadSize += 2;
2321 } else {
2322 if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2323 continue;
2324 if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2325 // IdxReg gets redefined in the middle of the sequence.
2326 continue;
2327 }
2328
2329 // Now safe to delete the load and lsl. The LEA will be removed later.
2330 CanDeleteLEA = true;
2331 Shift->eraseFromParent();
2332 Load->eraseFromParent();
2333 DeadSize += 4;
2334 }
2335
2336 LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
2337 MachineInstr *CPEMI = User.CPEMI;
2338 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2339 if (!isThumb2)
2340 Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2341
2343 MachineInstr *NewJTMI =
2344 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
2345 .addReg(User.MI->getOperand(0).getReg(),
2346 getKillRegState(BaseRegKill))
2347 .addReg(IdxReg, getKillRegState(IdxRegKill))
2348 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2349 .addImm(CPEMI->getOperand(0).getImm());
2350 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
2351
2352 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2353 CPEMI->setDesc(TII->get(JTOpc));
2354
2355 if (jumpTableFollowsTB(MI, User.CPEMI)) {
2356 NewJTMI->getOperand(0).setReg(ARM::PC);
2357 NewJTMI->getOperand(0).setIsKill(false);
2358
2359 if (CanDeleteLEA) {
2360 if (isThumb2)
2361 RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2362
2363 User.MI->eraseFromParent();
2364 DeadSize += isThumb2 ? 4 : 2;
2365
2366 // The LEA was eliminated, the TBB instruction becomes the only new user
2367 // of the jump table.
2368 User.MI = NewJTMI;
2369 User.MaxDisp = 4;
2370 User.NegOk = false;
2371 User.IsSoImm = false;
2372 User.KnownAlignment = false;
2373 } else {
2374 // The LEA couldn't be eliminated, so we must add another CPUser to
2375 // record the TBB or TBH use.
2376 int CPEntryIdx = JumpTableEntryIndices[JTI];
2377 auto &CPEs = CPEntries[CPEntryIdx];
2378 auto Entry =
2379 find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
2380 ++Entry->RefCount;
2381 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2382 }
2383 }
2384
2385 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2386 unsigned OrigSize = TII->getInstSizeInBytes(*MI);
2387 MI->eraseFromParent();
2388
2389 int Delta = OrigSize - NewSize + DeadSize;
2390 BBInfo[MBB->getNumber()].Size -= Delta;
2391 BBUtils->adjustBBOffsetsAfter(MBB);
2392
2393 ++NumTBs;
2394 MadeChange = true;
2395 }
2396
2397 return MadeChange;
2398}
2399
2400/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
2401/// jump tables always branch forwards, since that's what tbb and tbh need.
2402bool ARMConstantIslands::reorderThumb2JumpTables() {
2403 bool MadeChange = false;
2404
2405 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2406 if (!MJTI) return false;
2407
2408 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2409 for (MachineInstr *MI : T2JumpTables) {
2410 const MCInstrDesc &MCID = MI->getDesc();
2411 unsigned NumOps = MCID.getNumOperands();
2412 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2413 MachineOperand JTOP = MI->getOperand(JTOpIdx);
2414 unsigned JTI = JTOP.getIndex();
2415 assert(JTI < JT.size());
2416
2417 // We prefer if target blocks for the jump table come after the jump
2418 // instruction so we can use TB[BH]. Loop through the target blocks
2419 // and try to adjust them such that that's true.
2420 int JTNumber = MI->getParent()->getNumber();
2421 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2422 for (MachineBasicBlock *MBB : JTBBs) {
2423 int DTNumber = MBB->getNumber();
2424
2425 if (DTNumber < JTNumber) {
2426 // The destination precedes the switch. Try to move the block forward
2427 // so we have a positive offset.
2428 MachineBasicBlock *NewBB =
2429 adjustJTTargetBlockForward(JTI, MBB, MI->getParent());
2430 if (NewBB)
2431 MJTI->ReplaceMBBInJumpTable(JTI, MBB, NewBB);
2432 MadeChange = true;
2433 }
2434 }
2435 }
2436
2437 return MadeChange;
2438}
2439
2440MachineBasicBlock *ARMConstantIslands::adjustJTTargetBlockForward(
2441 unsigned JTI, MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2442 // If the destination block is terminated by an unconditional branch,
2443 // try to move it; otherwise, create a new block following the jump
2444 // table that branches back to the actual target. This is a very simple
2445 // heuristic. FIXME: We can definitely improve it.
2446 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2447 SmallVector<MachineOperand, 4> Cond;
2448 SmallVector<MachineOperand, 4> CondPrior;
2450 MachineFunction::iterator OldPrior = std::prev(BBi);
2451 MachineFunction::iterator OldNext = std::next(BBi);
2452
2453 // If the block terminator isn't analyzable, don't try to move the block
2454 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
2455
2456 // If the block ends in an unconditional branch, move it. The prior block
2457 // has to have an analyzable terminator for us to move this one. Be paranoid
2458 // and make sure we're not trying to move the entry block of the function.
2459 if (!B && Cond.empty() && BB != &MF->front() &&
2460 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2461 BB->moveAfter(JTBB);
2462 OldPrior->updateTerminator(BB);
2463 BB->updateTerminator(OldNext != MF->end() ? &*OldNext : nullptr);
2464 // Update numbering to account for the block being moved.
2465 MF->RenumberBlocks();
2466 ++NumJTMoved;
2467 return nullptr;
2468 }
2469
2470 // Create a new MBB for the code after the jump BB.
2471 MachineBasicBlock *NewBB =
2472 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2474 MF->insert(MBBI, NewBB);
2475
2476 // Copy live-in information to new block.
2477 for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins())
2478 NewBB->addLiveIn(RegMaskPair);
2479
2480 // Add an unconditional branch from NewBB to BB.
2481 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2482 // correspond directly to anything in the source.
2483 if (isThumb2)
2484 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2485 .addMBB(BB)
2487 else
2488 BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2489 .addMBB(BB)
2491
2492 // Update internal data structures to account for the newly inserted MBB.
2493 MF->RenumberBlocks(NewBB);
2494
2495 // Update the CFG.
2496 NewBB->addSuccessor(BB);
2497 JTBB->replaceSuccessor(BB, NewBB);
2498
2499 ++NumJTInserted;
2500 return NewBB;
2501}
2502
2503/// createARMConstantIslandPass - returns an instance of the constpool
2504/// island pass.
2506 return new ARMConstantIslands();
2507}
2508
2509INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2510 false, false)
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static bool isThumb(const MCSubtargetInfo &STI)
static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg, unsigned BaseReg)
static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI)
Returns whether CPEMI is the first instruction in the block immediately following JTMI (assumed to be...
static bool CompareMBBNumbers(const MachineBasicBlock *LHS, const MachineBasicBlock *RHS)
CompareMBBNumbers - Little predicate function to sort the WaterList by MBB ID.
static unsigned getUnconditionalBrDisp(int Opc)
getUnconditionalBrDisp - Returns the maximum displacement that can fit in the specific unconditional ...
static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI, MachineInstr *JumpMI, unsigned &DeadSize)
static bool AlignBlocks(MachineFunction *MF, const ARMSubtarget *STI)
#define ARM_CP_ISLANDS_OPT_NAME
static bool BBIsJumpedOver(MachineBasicBlock *MBB)
BBIsJumpedOver - Return true of the specified basic block's only predecessor unconditionally branches...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:770
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file defines the DenseMap class.
#define op(i)
#define rc(i)
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static bool BBHasFallthrough(MachineBasicBlock *MBB)
BBHasFallthrough - Return true if the specified basic block can fallthrough into the block immediatel...
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
void initPICLabelUId(unsigned UId)
void recordCPEClone(unsigned CPIdx, unsigned CPCloneIdx)
const ARMBaseInstrInfo * getInstrInfo() const override
bool isTargetWindows() const
const ARMTargetLowering * getTargetLowering() const override
const ARMBaseRegisterInfo * getRegisterInfo() const override
const ARMOptions & getCLOpts() const
bool hasMinSize() const
AnalysisUsage & addRequired()
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
unsigned getSize() const
Return the number of bytes in the encoding of this instruction, or zero if the encoding size cannot b...
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI void dump() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
reverse_iterator rbegin()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI void moveAfter(MachineBasicBlock *NewBefore)
Align getConstantPoolAlign() const
Return the alignment required by the whole constant pool, of which the first element must be aligned.
const std::vector< MachineConstantPoolEntry > & getConstants() const
bool isEmpty() const
isEmpty - Return true if this constant pool contains no constants.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
void ensureAlignment(Align A)
ensureAlignment - Make sure the function is at least A bytes aligned.
Function & getFunction()
Return the LLVM function that this machine code represents.
Align getPreferredAlignment() const
Returns the preferred alignment which comes from the function attributes (optsize,...
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
BasicBlockListType::const_iterator const_iterator
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addJumpTableIndex(unsigned Idx, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
LLVM_ABI bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
MachineBasicBlock * getMBB() const
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
void setMBB(MachineBasicBlock *MBB)
unsigned getTargetFlags() const
Register getReg() const
getReg - Returns the register number.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
bool isPositionIndependent() const
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static CondCodes getOppositeCondition(CondCodes CC)
Definition ARMBaseInfo.h:49
@ MO_OPTION_MASK
MO_OPTION_MASK - Most flags are mutually exclusive; this mask selects just that part of the flag set.
@ MO_LO16
MO_LO16 - On a symbol operand, this represents a relocation containing lower 16 bit of the address.
@ MO_HI16
MO_HI16 - On a symbol operand, this represents a relocation containing higher 16 bit of the address.
@ Entry
Definition COFF.h:862
@ ARM
Windows AXP64.
Definition MCAsmInfo.h:50
@ User
could "use" a pointer
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstr * findCMPToFoldIntoCBZ(MachineInstr *Br, const TargetRegisterInfo *TRI)
Search backwards from a tBcc to find a tCMPi8 against 0, meaning we can convert them to a tCBZ or tCB...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr RegState getKillRegState(bool B)
static bool isARMLowRegister(MCRegister Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
@ Load
The value being inserted comes from a load (InsertElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool registerDefinedBetween(unsigned Reg, MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const TargetRegisterInfo *TRI)
Return true if Reg is defd between From and To.
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
ARMCC::CondCodes getITInstrPredicate(const MachineInstr &MI, Register &PredReg)
getITInstrPredicate - Valid only in Thumb2 mode.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
static bool isLoopStart(const MachineInstr &MI)
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RegState getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:191
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
ARMCC::CondCodes getInstrPredicate(const MachineInstr &MI, Register &PredReg)
getInstrPredicate - If instruction is predicated, returns its predicate condition,...
FunctionPass * createARMConstantIslandPass()
createARMConstantIslandPass - returns an instance of the constpool island pass.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
unsigned UnknownPadding(Align Alignment, unsigned KnownBits)
UnknownPadding - Return the worst case padding that could result from unknown offset bits.
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1775
SmallVectorImpl< BasicBlockInfo > BBInfoVector
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
static bool isSpeculationBarrierEndBBOpcode(int Opc)
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Align PostAlign
PostAlign - When > 1, the block terminator contains a .align directive, so the end of the block is al...
uint8_t KnownBits
KnownBits - The number of low bits in Offset that are known to be exact.
unsigned internalKnownBits() const
Compute the number of known offset bits internally to this block.
unsigned postOffset(Align Alignment=Align(1)) const
Compute the offset immediately following this block.
uint8_t Unalign
Unalign - When non-zero, the block contains instructions (inline asm) of unknown size.
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block.