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