LLVM 24.0.0git
PPCMIPeephole.cpp
Go to the documentation of this file.
1//===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===---------------------------------------------------------------------===//
8//
9// This pass performs peephole optimizations to clean up ugly code
10// sequences at the MachineInstruction layer. It runs at the end of
11// the SSA phases, following VSX swap removal. A pass of dead code
12// elimination follows this one for quick clean-up of any dead
13// instructions introduced here. Although we could do this as callbacks
14// from the generic peephole pass, this would have a couple of bad
15// effects: it might remove optimization opportunities for VSX swap
16// removal, and it would miss cleanups made possible following VSX
17// swap removal.
18//
19// NOTE: We run the verifier after this pass in Asserts/Debug builds so it
20// is important to keep the code valid after transformations.
21// Common causes of errors stem from violating the contract specified
22// by kill flags. Whenever a transformation changes the live range of
23// a register, that register should be added to the work list using
24// addRegToUpdate(RegsToUpdate, <Reg>). Furthermore, if a transformation
25// is changing the definition of a register (i.e. removing the single
26// definition of the original vreg), it needs to provide a dummy
27// definition of that register using addDummyDef(<MBB>, <Reg>).
28//===---------------------------------------------------------------------===//
29
32#include "PPC.h"
33#include "PPCInstrInfo.h"
35#include "PPCTargetMachine.h"
36#include "llvm/ADT/Statistic.h"
47#include "llvm/Support/Debug.h"
49
50using namespace llvm;
51
52#define DEBUG_TYPE "ppc-mi-peepholes"
53
54STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
55STATISTIC(MultiTOCSaves,
56 "Number of functions with multiple TOC saves that must be kept");
57STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue");
58STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
59STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
60STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
61STATISTIC(NumConvertedToImmediateForm,
62 "Number of instructions converted to their immediate form");
63STATISTIC(NumFunctionsEnteredInMIPeephole,
64 "Number of functions entered in PPC MI Peepholes");
65STATISTIC(NumFixedPointIterations,
66 "Number of fixed-point iterations converting reg-reg instructions "
67 "to reg-imm ones");
68STATISTIC(NumRotatesCollapsed,
69 "Number of pairs of rotate left, clear left/right collapsed");
70STATISTIC(NumEXTSWAndSLDICombined,
71 "Number of pairs of EXTSW and SLDI combined as EXTSWSLI");
72STATISTIC(NumLoadImmZeroFoldedAndRemoved,
73 "Number of LI(8) reg, 0 that are folded to r0 and removed");
74
75static cl::opt<bool>
76FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
77 cl::desc("Iterate to a fixed point when attempting to "
78 "convert reg-reg instructions to reg-imm"));
79
80static cl::opt<bool>
81ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
82 cl::desc("Convert eligible reg+reg instructions to reg+imm"));
83
84static cl::opt<bool>
85 EnableSExtElimination("ppc-eliminate-signext",
86 cl::desc("enable elimination of sign-extensions"),
87 cl::init(true), cl::Hidden);
88
89static cl::opt<bool>
90 EnableZExtElimination("ppc-eliminate-zeroext",
91 cl::desc("enable elimination of zero-extensions"),
92 cl::init(true), cl::Hidden);
93
94static cl::opt<bool>
95 EnableTrapOptimization("ppc-opt-conditional-trap",
96 cl::desc("enable optimization of conditional traps"),
97 cl::init(false), cl::Hidden);
98
100 PeepholeXToICounter, "ppc-xtoi-peephole",
101 "Controls whether PPC reg+reg to reg+imm peephole is performed on a MI");
102
103DEBUG_COUNTER(PeepholePerOpCounter, "ppc-per-op-peephole",
104 "Controls whether PPC per opcode peephole is performed on a MI");
105
106namespace {
107
108struct PPCMIPeephole : public MachineFunctionPass {
109
110 static char ID;
111 const PPCInstrInfo *TII;
112 MachineFunction *MF;
114
115 PPCMIPeephole() : MachineFunctionPass(ID) {}
116
117private:
118 MachineDominatorTree *MDT;
119 MachinePostDominatorTree *MPDT;
120 MachineBlockFrequencyInfo *MBFI;
121 BlockFrequency EntryFreq;
122 SmallSet<Register, 16> RegsToUpdate;
123
124 // Initialize class variables.
125 void initialize(MachineFunction &MFParm);
126
127 // Perform peepholes.
128 bool simplifyCode();
129
130 // Perform peepholes.
131 bool eliminateRedundantCompare();
132 bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
133 bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase);
134 bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI,
135 MachineInstr *&ToErase);
136 void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
137 MachineInstr *MI);
138
139 // A number of transformations will eliminate the definition of a register
140 // as all of its uses will be removed. However, this can leave a register
141 // used with no reaching definition until DCE removes the dead uses. Such
142 // transformations should use this function to provide a dummy definition of
143 // the register that will simply be removed by DCE.
144 void addDummyDef(MachineBasicBlock &MBB, MachineInstr *At, Register Reg) {
145 BuildMI(MBB, At, At->getDebugLoc(), TII->get(PPC::IMPLICIT_DEF), Reg);
146 }
147 void addRegToUpdateWithLine(Register Reg, int Line);
148 void convertUnprimedAccPHIs(const PPCInstrInfo *TII, MachineRegisterInfo *MRI,
149 SmallVectorImpl<MachineInstr *> &PHIs,
150 Register Dst);
151
152public:
153 void getAnalysisUsage(AnalysisUsage &AU) const override {
154 AU.addRequired<MachineDominatorTreeWrapperPass>();
155 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
156 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
157 AU.addPreserved<MachineDominatorTreeWrapperPass>();
158 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
159 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
160 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
162 }
163
164 // Main entry point for this pass.
165 bool runOnMachineFunction(MachineFunction &MF) override {
166 initialize(MF);
167 // At this point, TOC pointer should not be used in a function that uses
168 // PC-Relative addressing.
169 assert((MF.getRegInfo().use_empty(PPC::X2) ||
170 !MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) &&
171 "TOC pointer used in a function using PC-Relative addressing!");
172 if (skipFunction(MF.getFunction()))
173 return false;
174 return simplifyCode();
175 }
176};
177
178#define addRegToUpdate(R) addRegToUpdateWithLine(R, __LINE__)
179void PPCMIPeephole::addRegToUpdateWithLine(Register Reg, int Line) {
180 if (!Reg.isVirtual())
181 return;
182 if (RegsToUpdate.insert(Reg).second)
183 LLVM_DEBUG(dbgs() << "Adding register: " << printReg(Reg) << " on line "
184 << Line << " for re-computation of kill flags\n");
185}
186
187// Initialize class variables.
188void PPCMIPeephole::initialize(MachineFunction &MFParm) {
189 MF = &MFParm;
190 MRI = &MF->getRegInfo();
191 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
192 MPDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
193 MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
194 EntryFreq = MBFI->getEntryFreq();
195 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
196 RegsToUpdate.clear();
197 LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
198 LLVM_DEBUG(MF->dump());
199}
200
201static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
202 MachineRegisterInfo *MRI) {
203 assert(Op && "Invalid Operand!");
204 if (!Op->isReg())
205 return nullptr;
206
207 Register Reg = Op->getReg();
208 if (!Reg.isVirtual())
209 return nullptr;
210
211 return MRI->getVRegDef(Reg);
212}
213
214// This function returns number of known zero bits in output of MI
215// starting from the most significant bit.
216static unsigned getKnownLeadingZeroCount(const unsigned Reg,
217 const PPCInstrInfo *TII,
218 const MachineRegisterInfo *MRI) {
219 MachineInstr *MI = MRI->getVRegDef(Reg);
220 unsigned Opcode = MI->getOpcode();
221 if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
222 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec)
223 return MI->getOperand(3).getImm();
224
225 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
226 MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
227 return MI->getOperand(3).getImm();
228
229 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
230 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
231 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
232 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
233 return 32 + MI->getOperand(3).getImm();
234
235 if (Opcode == PPC::ANDI_rec) {
236 uint16_t Imm = MI->getOperand(2).getImm();
237 return 48 + llvm::countl_zero(Imm);
238 }
239
240 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
241 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
242 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
243 // The result ranges from 0 to 32.
244 return 58;
245
246 if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
247 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec)
248 // The result ranges from 0 to 64.
249 return 57;
250
251 if (Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
252 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 ||
253 Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
254 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
255 return 48;
256
257 if (Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
258 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
259 Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
260 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
261 return 56;
262
263 if (Opcode == PPC::AND || Opcode == PPC::AND8 || Opcode == PPC::AND_rec ||
264 Opcode == PPC::AND8_rec)
265 return std::max(
266 getKnownLeadingZeroCount(MI->getOperand(1).getReg(), TII, MRI),
267 getKnownLeadingZeroCount(MI->getOperand(2).getReg(), TII, MRI));
268
269 if (Opcode == PPC::OR || Opcode == PPC::OR8 || Opcode == PPC::XOR ||
270 Opcode == PPC::XOR8 || Opcode == PPC::OR_rec ||
271 Opcode == PPC::OR8_rec || Opcode == PPC::XOR_rec ||
272 Opcode == PPC::XOR8_rec)
273 return std::min(
274 getKnownLeadingZeroCount(MI->getOperand(1).getReg(), TII, MRI),
275 getKnownLeadingZeroCount(MI->getOperand(2).getReg(), TII, MRI));
276
277 if (TII->isZeroExtended(Reg, MRI))
278 return 32;
279
280 return 0;
281}
282
283// This function maintains a map for the pairs <TOC Save Instr, Keep>
284// Each time a new TOC save is encountered, it checks if any of the existing
285// ones are dominated by the new one. If so, it marks the existing one as
286// redundant by setting it's entry in the map as false. It then adds the new
287// instruction to the map with either true or false depending on if any
288// existing instructions dominated the new one.
289void PPCMIPeephole::UpdateTOCSaves(
290 std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
291 assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
292 // FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part,
293 // here only support it under ELFv2.
294 if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) {
295 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
296
297 MachineBasicBlock *Entry = &MF->front();
298 BlockFrequency CurrBlockFreq = MBFI->getBlockFreq(MI->getParent());
299
300 // If the block in which the TOC save resides is in a block that
301 // post-dominates Entry, or a block that is hotter than entry (keep in mind
302 // that early MachineLICM has already run so the TOC save won't be hoisted)
303 // we can just do the save in the prologue.
304 if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry))
305 FI->setMustSaveTOC(true);
306
307 // If we are saving the TOC in the prologue, all the TOC saves can be
308 // removed from the code.
309 if (FI->mustSaveTOC()) {
310 for (auto &TOCSave : TOCSaves)
311 TOCSave.second = false;
312 // Add new instruction to map.
313 TOCSaves[MI] = false;
314 return;
315 }
316 }
317
318 bool Keep = true;
319 for (auto &I : TOCSaves) {
320 MachineInstr *CurrInst = I.first;
321 // If new instruction dominates an existing one, mark existing one as
322 // redundant.
323 if (I.second && MDT->dominates(MI, CurrInst))
324 I.second = false;
325 // Check if the new instruction is redundant.
326 if (MDT->dominates(CurrInst, MI)) {
327 Keep = false;
328 break;
329 }
330 }
331 // Add new instruction to map.
332 TOCSaves[MI] = Keep;
333}
334
335// This function returns a list of all PHI nodes in the tree starting from
336// the RootPHI node. We perform a BFS traversal to get an ordered list of nodes.
337// The list initially only contains the root PHI. When we visit a PHI node, we
338// add it to the list. We continue to look for other PHI node operands while
339// there are nodes to visit in the list. The function returns false if the
340// optimization cannot be applied on this tree.
341static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI,
342 MachineInstr *RootPHI,
343 SmallVectorImpl<MachineInstr *> &PHIs) {
344 PHIs.push_back(RootPHI);
345 unsigned VisitedIndex = 0;
346 while (VisitedIndex < PHIs.size()) {
347 MachineInstr *VisitedPHI = PHIs[VisitedIndex];
348 for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands();
349 PHIOp != NumOps; PHIOp += 2) {
350 Register RegOp = VisitedPHI->getOperand(PHIOp).getReg();
351 if (!RegOp.isVirtual())
352 return false;
353 MachineInstr *Instr = MRI->getVRegDef(RegOp);
354 // While collecting the PHI nodes, we check if they can be converted (i.e.
355 // all the operands are either copies, implicit defs or PHI nodes).
356 unsigned Opcode = Instr->getOpcode();
357 if (Opcode == PPC::COPY) {
358 Register Reg = Instr->getOperand(1).getReg();
359 if (!Reg.isVirtual() || MRI->getRegClass(Reg) != &PPC::ACCRCRegClass)
360 return false;
361 } else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI)
362 return false;
363 // If we detect a cycle in the PHI nodes, we exit. It would be
364 // possible to change cycles as well, but that would add a lot
365 // of complexity for a case that is unlikely to occur with MMA
366 // code.
367 if (Opcode != PPC::PHI)
368 continue;
369 if (llvm::is_contained(PHIs, Instr))
370 return false;
371 PHIs.push_back(Instr);
372 }
373 VisitedIndex++;
374 }
375 return true;
376}
377
378// This function changes the unprimed accumulator PHI nodes in the PHIs list to
379// primed accumulator PHI nodes. The list is traversed in reverse order to
380// change all the PHI operands of a PHI node before changing the node itself.
381// We keep a map to associate each changed PHI node to its non-changed form.
382void PPCMIPeephole::convertUnprimedAccPHIs(
383 const PPCInstrInfo *TII, MachineRegisterInfo *MRI,
384 SmallVectorImpl<MachineInstr *> &PHIs, Register Dst) {
385 DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap;
386 for (MachineInstr *PHI : llvm::reverse(PHIs)) {
388 // We check if the current PHI node can be changed by looking at its
389 // operands. If all the operands are either copies from primed
390 // accumulators, implicit definitions or other unprimed accumulator
391 // PHI nodes, we change it.
392 for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
393 PHIOp += 2) {
394 Register RegOp = PHI->getOperand(PHIOp).getReg();
395 MachineInstr *PHIInput = MRI->getVRegDef(RegOp);
396 unsigned Opcode = PHIInput->getOpcode();
397 assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF ||
398 Opcode == PPC::PHI) &&
399 "Unexpected instruction");
400 if (Opcode == PPC::COPY) {
401 assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) ==
402 &PPC::ACCRCRegClass &&
403 "Unexpected register class");
404 PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)});
405 } else if (Opcode == PPC::IMPLICIT_DEF) {
406 Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
407 BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(),
408 TII->get(PPC::IMPLICIT_DEF), AccReg);
409 PHIOps.push_back({MachineOperand::CreateReg(AccReg, false),
410 PHI->getOperand(PHIOp + 1)});
411 } else if (Opcode == PPC::PHI) {
412 // We found a PHI operand. At this point we know this operand
413 // has already been changed so we get its associated changed form
414 // from the map.
415 assert(ChangedPHIMap.count(PHIInput) == 1 &&
416 "This PHI node should have already been changed.");
417 MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput);
419 PrimedAccPHI->getOperand(0).getReg(), false),
420 PHI->getOperand(PHIOp + 1)});
421 }
422 }
423 Register AccReg = Dst;
424 // If the PHI node we are changing is the root node, the register it defines
425 // will be the destination register of the original copy (of the PHI def).
426 // For all other PHI's in the list, we need to create another primed
427 // accumulator virtual register as the PHI will no longer define the
428 // unprimed accumulator.
429 if (PHI != PHIs[0])
430 AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
431 MachineInstrBuilder NewPHI = BuildMI(
432 *PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg);
433 for (auto RegMBB : PHIOps) {
434 NewPHI.add(RegMBB.first).add(RegMBB.second);
435 if (MRI->isSSA())
436 addRegToUpdate(RegMBB.first.getReg());
437 }
438 // The liveness of old PHI and new PHI have to be updated.
439 addRegToUpdate(PHI->getOperand(0).getReg());
440 addRegToUpdate(AccReg);
441 ChangedPHIMap[PHI] = NewPHI.getInstr();
442 LLVM_DEBUG(dbgs() << "Converting PHI: ");
443 LLVM_DEBUG(PHI->dump());
444 LLVM_DEBUG(dbgs() << "To: ");
445 LLVM_DEBUG(NewPHI.getInstr()->dump());
446 }
447}
448
449// Perform peephole optimizations.
450bool PPCMIPeephole::simplifyCode() {
451 bool Simplified = false;
452 bool TrapOpt = false;
453 MachineInstr* ToErase = nullptr;
454 std::map<MachineInstr *, bool> TOCSaves;
455 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
456 NumFunctionsEnteredInMIPeephole++;
457 if (ConvertRegReg) {
458 // Fixed-point conversion of reg/reg instructions fed by load-immediate
459 // into reg/imm instructions. FIXME: This is expensive, control it with
460 // an option.
461 bool SomethingChanged = false;
462 do {
463 NumFixedPointIterations++;
464 SomethingChanged = false;
465 for (MachineBasicBlock &MBB : *MF) {
466 for (MachineInstr &MI : MBB) {
467 if (MI.isDebugInstr())
468 continue;
469
470 if (!DebugCounter::shouldExecute(PeepholeXToICounter))
471 continue;
472
473 SmallSet<Register, 4> RRToRIRegsToUpdate;
474 if (!TII->convertToImmediateForm(MI, RRToRIRegsToUpdate))
475 continue;
476 for (Register R : RRToRIRegsToUpdate)
478 // The updated instruction may now have new register operands.
479 // Conservatively add them to recompute the flags as well.
480 for (const MachineOperand &MO : MI.operands())
481 if (MO.isReg())
482 addRegToUpdate(MO.getReg());
483 // We don't erase anything in case the def has other uses. Let DCE
484 // remove it if it can be removed.
485 LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
486 LLVM_DEBUG(MI.dump());
487 NumConvertedToImmediateForm++;
488 SomethingChanged = true;
489 Simplified = true;
490 }
491 }
492 } while (SomethingChanged && FixedPointRegToImm);
493 }
494
495 // Since we are deleting this instruction, clear the kill flags on any of its
496 // definitions that are marked as needing an update: the transforms only ever
497 // invalidate kill flags by removing uses (turning a non-last use into the
498 // last one), so a conservative clear is sufficient.
499 auto clearKillsForDyingInstr = [&]() {
500 if (RegsToUpdate.empty())
501 return;
502 for (MachineOperand &MO : ToErase->operands()) {
503 if (!MO.isReg() || !MO.isDef() || !RegsToUpdate.count(MO.getReg()))
504 continue;
505 Register RegToUpdate = MO.getReg();
506 RegsToUpdate.erase(RegToUpdate);
507 // If some transformation has introduced an additional definition of
508 // this register (breaking SSA), we can safely convert this def to
509 // a def of an invalid register as the instruction is going away.
510 if (!MRI->getUniqueVRegDef(RegToUpdate))
511 MO.setReg(PPC::NoRegister);
512 MRI->clearKillFlags(RegToUpdate);
513 for (MachineOperand &Def : MRI->def_operands(RegToUpdate))
514 Def.setIsDead(false);
515 }
516 };
517
518 for (MachineBasicBlock &MBB : *MF) {
519 for (MachineInstr &MI : MBB) {
520
521 // If the previous instruction was marked for elimination,
522 // remove it now.
523 if (ToErase) {
524 LLVM_DEBUG(dbgs() << "Deleting instruction: ");
525 LLVM_DEBUG(ToErase->dump());
526 clearKillsForDyingInstr();
527 ToErase->eraseFromParent();
528 ToErase = nullptr;
529 }
530 // If a conditional trap instruction got optimized to an
531 // unconditional trap, eliminate all the instructions after
532 // the trap.
533 if (EnableTrapOptimization && TrapOpt) {
534 ToErase = &MI;
535 continue;
536 }
537
538 // Ignore debug instructions.
539 if (MI.isDebugInstr())
540 continue;
541
542 if (!DebugCounter::shouldExecute(PeepholePerOpCounter))
543 continue;
544
545 // Per-opcode peepholes.
546 switch (MI.getOpcode()) {
547
548 default:
549 break;
550 case PPC::COPY: {
551 Register Src = MI.getOperand(1).getReg();
552 Register Dst = MI.getOperand(0).getReg();
553 if (!Src.isVirtual() || !Dst.isVirtual())
554 break;
555 if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
556 MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
557 break;
558
559 // We are copying an unprimed accumulator to a primed accumulator.
560 // If the input to the copy is a PHI that is fed only by (i) copies in
561 // the other direction (ii) implicitly defined unprimed accumulators or
562 // (iii) other PHI nodes satisfying (i) and (ii), we can change
563 // the PHI to a PHI on primed accumulators (as long as we also change
564 // its operands). To detect and change such copies, we first get a list
565 // of all the PHI nodes starting from the root PHI node in BFS order.
566 // We then visit all these PHI nodes to check if they can be changed to
567 // primed accumulator PHI nodes and if so, we change them.
568 MachineInstr *RootPHI = MRI->getVRegDef(Src);
569 if (RootPHI->getOpcode() != PPC::PHI)
570 break;
571
572 SmallVector<MachineInstr *, 4> PHIs;
573 if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
574 break;
575
576 convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
577
578 ToErase = &MI;
579 break;
580 }
581 case PPC::LI:
582 case PPC::LI8: {
583 // If we are materializing a zero, look for any use operands for which
584 // zero means immediate zero. All such operands can be replaced with
585 // PPC::ZERO.
586 if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
587 break;
588 Register MIDestReg = MI.getOperand(0).getReg();
589 bool Folded = false;
590 for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
591 Folded |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
592 if (MRI->use_nodbg_empty(MIDestReg)) {
593 ++NumLoadImmZeroFoldedAndRemoved;
594 ToErase = &MI;
595 }
596 if (Folded)
597 addRegToUpdate(MIDestReg);
598 Simplified |= Folded;
599 break;
600 }
601 case PPC::STW:
602 case PPC::STD: {
603 MachineFrameInfo &MFI = MF->getFrameInfo();
604 if (MFI.hasVarSizedObjects() ||
605 (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
606 !MF->getSubtarget<PPCSubtarget>().isAIXABI()))
607 break;
608 // When encountering a TOC save instruction, call UpdateTOCSaves
609 // to add it to the TOCSaves map and mark any existing TOC saves
610 // it dominates as redundant.
611 if (TII->isTOCSaveMI(MI))
612 UpdateTOCSaves(TOCSaves, &MI);
613 break;
614 }
615 case PPC::XXPERMDI: {
616 // Perform simplifications of 2x64 vector swaps and splats.
617 // A swap is identified by an immediate value of 2, and a splat
618 // is identified by an immediate value of 0 or 3.
619 int Immed = MI.getOperand(3).getImm();
620
621 if (Immed == 1)
622 break;
623
624 // For each of these simplifications, we need the two source
625 // regs to match. Unfortunately, MachineCSE ignores COPY and
626 // SUBREG_TO_REG, so for example we can see
627 // XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
628 // We have to look through chains of COPY and SUBREG_TO_REG
629 // to find the real source values for comparison.
630 Register TrueReg1 =
631 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
632 Register TrueReg2 =
633 TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
634
635 if (!(TrueReg1 == TrueReg2 && TrueReg1.isVirtual()))
636 break;
637
638 MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
639
640 if (!DefMI)
641 break;
642
643 unsigned DefOpc = DefMI->getOpcode();
644
645 // If this is a splat fed by a splatting load, the splat is
646 // redundant. Replace with a copy. This doesn't happen directly due
647 // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
648 // a load of a double to a vector of 64-bit integers.
649 auto isConversionOfLoadAndSplat = [=]() -> bool {
650 if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
651 return false;
652 Register FeedReg1 =
653 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
654 if (FeedReg1.isVirtual()) {
655 MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
656 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
657 return true;
658 }
659 return false;
660 };
661 if ((Immed == 0 || Immed == 3) &&
662 (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
663 LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
664 "to load-and-splat/copy: ");
665 LLVM_DEBUG(MI.dump());
666 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
667 MI.getOperand(0).getReg())
668 .add(MI.getOperand(1));
669 addRegToUpdate(MI.getOperand(1).getReg());
670 ToErase = &MI;
671 Simplified = true;
672 }
673
674 // If this is a splat or a swap fed by another splat, we
675 // can replace it with a copy.
676 if (DefOpc == PPC::XXPERMDI) {
677 Register DefReg1 = DefMI->getOperand(1).getReg();
678 Register DefReg2 = DefMI->getOperand(2).getReg();
679 unsigned DefImmed = DefMI->getOperand(3).getImm();
680
681 // If the two inputs are not the same register, check to see if
682 // they originate from the same virtual register after only
683 // copy-like instructions.
684 if (DefReg1 != DefReg2) {
685 Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
686 Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
687
688 if (!(FeedReg1 == FeedReg2 && FeedReg1.isVirtual()))
689 break;
690 }
691
692 if (DefImmed == 0 || DefImmed == 3) {
693 LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
694 "to splat/copy: ");
695 LLVM_DEBUG(MI.dump());
696 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
697 MI.getOperand(0).getReg())
698 .add(MI.getOperand(1));
699 addRegToUpdate(MI.getOperand(1).getReg());
700 ToErase = &MI;
701 Simplified = true;
702 }
703
704 // If this is a splat fed by a swap, we can simplify modify
705 // the splat to splat the other value from the swap's input
706 // parameter.
707 else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
708 LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
709 LLVM_DEBUG(MI.dump());
710 addRegToUpdate(MI.getOperand(1).getReg());
711 addRegToUpdate(MI.getOperand(2).getReg());
712 MI.getOperand(1).setReg(DefReg1);
713 MI.getOperand(2).setReg(DefReg2);
714 MI.getOperand(3).setImm(3 - Immed);
715 addRegToUpdate(DefReg1);
716 addRegToUpdate(DefReg2);
717 Simplified = true;
718 }
719
720 // If this is a swap fed by a swap, we can replace it
721 // with a copy from the first swap's input.
722 else if (Immed == 2 && DefImmed == 2) {
723 LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
724 LLVM_DEBUG(MI.dump());
725 addRegToUpdate(MI.getOperand(1).getReg());
726
727 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
728 MI.getOperand(0).getReg())
729 .add(DefMI->getOperand(1));
732 ToErase = &MI;
733 Simplified = true;
734 }
735 } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
736 DefOpc == PPC::XXPERMDIs &&
737 (DefMI->getOperand(2).getImm() == 0 ||
738 DefMI->getOperand(2).getImm() == 3)) {
739
740 if (!MRI->hasOneNonDBGUser(DefMI->getOperand(0).getReg()))
741 break;
742 Simplified = true;
743 // Swap of a splat, convert to copy.
744 if (Immed == 2) {
745 LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
746 LLVM_DEBUG(MI.dump());
747 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
748 MI.getOperand(0).getReg())
749 .add(MI.getOperand(1));
750 addRegToUpdate(MI.getOperand(1).getReg());
751 ToErase = &MI;
752 break;
753 }
754 // Splat fed by another splat - switch the output of the first
755 // and remove the second.
756 ToErase = &MI;
757 DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
758 LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
759 LLVM_DEBUG(MI.dump());
760 } else if (Immed == 2 &&
761 (DefOpc == PPC::VSPLTB || DefOpc == PPC::VSPLTH ||
762 DefOpc == PPC::VSPLTW || DefOpc == PPC::XXSPLTW ||
763 DefOpc == PPC::VSPLTISB || DefOpc == PPC::VSPLTISH ||
764 DefOpc == PPC::VSPLTISW)) {
765 // Swap of various vector splats, convert to copy.
766 ToErase = &MI;
767 Simplified = true;
768 LLVM_DEBUG(dbgs() << "Optimizing swap(vsplt(is)?[b|h|w]|xxspltw) => "
769 "copy(vsplt(is)?[b|h|w]|xxspltw): ");
770 LLVM_DEBUG(MI.dump());
771 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
772 MI.getOperand(0).getReg())
773 .add(MI.getOperand(1));
774 addRegToUpdate(MI.getOperand(1).getReg());
775 } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
776 TII->isLoadFromConstantPool(DefMI)) {
777 const Constant *C = TII->getConstantFromConstantPool(DefMI);
778 if (C && C->getType()->isVectorTy() && C->getSplatValue()) {
779 ToErase = &MI;
780 Simplified = true;
782 << "Optimizing swap(splat pattern from constant-pool) "
783 "=> copy(splat pattern from constant-pool): ");
784 LLVM_DEBUG(MI.dump());
785 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
786 MI.getOperand(0).getReg())
787 .add(MI.getOperand(1));
788 addRegToUpdate(MI.getOperand(1).getReg());
789 }
790 }
791 break;
792 }
793 case PPC::VSPLTB:
794 case PPC::VSPLTH:
795 case PPC::XXSPLTW: {
796 unsigned MyOpcode = MI.getOpcode();
797 // The operand number of the source register in the splat instruction.
798 unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
799 Register TrueReg =
800 TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
801 if (!TrueReg.isVirtual())
802 break;
803 MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
804 if (!DefMI)
805 break;
806 unsigned DefOpcode = DefMI->getOpcode();
807 auto isConvertOfSplat = [=]() -> bool {
808 if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
809 return false;
810 Register ConvReg = DefMI->getOperand(1).getReg();
811 if (!ConvReg.isVirtual())
812 return false;
813 MachineInstr *Splt = MRI->getVRegDef(ConvReg);
814 return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
815 Splt->getOpcode() == PPC::XXSPLTW);
816 };
817 bool AlreadySplat = (MyOpcode == DefOpcode) ||
818 (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
819 (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
820 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
821 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
822 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
823 (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
824
825 // If the instruction[s] that feed this splat have already splat
826 // the value, this splat is redundant.
827 if (AlreadySplat) {
828 LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
829 LLVM_DEBUG(MI.dump());
830 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
831 MI.getOperand(0).getReg())
832 .add(MI.getOperand(OpNo));
833 addRegToUpdate(MI.getOperand(OpNo).getReg());
834 ToErase = &MI;
835 Simplified = true;
836 }
837
838 // Splat fed by a shift. Usually when we align value to splat into
839 // vector element zero.
840 if (DefOpcode == PPC::XXSLDWI) {
841 Register ShiftOp1 = DefMI->getOperand(1).getReg();
842
843 if (ShiftOp1 == DefMI->getOperand(2).getReg()) {
844 // For example, We can erase XXSLDWI from in following:
845 // %2:vrrc = XXSLDWI killed %1:vrrc, %1:vrrc, 1
846 // %6:vrrc = VSPLTB 15, killed %2:vrrc
847 // %7:vsrc = XXLAND killed %6:vrrc, killed %1:vrrc
848 //
849 // --->
850 //
851 // %6:vrrc = VSPLTB 3, killed %1:vrrc
852 // %7:vsrc = XXLAND killed %6:vrrc, killed %1:vrrc
853
854 if (MRI->hasOneNonDBGUse(DefMI->getOperand(0).getReg())) {
855 LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
857 ToErase = DefMI;
858 }
859 Simplified = true;
860 unsigned ShiftImm = DefMI->getOperand(3).getImm();
861 // The operand number of the splat Imm in the instruction.
862 unsigned SplatImmNo = MyOpcode == PPC::XXSPLTW ? 2 : 1;
863 unsigned SplatImm = MI.getOperand(SplatImmNo).getImm();
864
865 // Calculate the new splat-element immediate. We need to convert the
866 // element index into the proper unit (byte for VSPLTB, halfword for
867 // VSPLTH, word for VSPLTW) because PPC::XXSLDWI interprets its
868 // ShiftImm in 32-bit word units.
869 auto CalculateNewElementIdx = [&](unsigned Opcode) {
870 if (Opcode == PPC::VSPLTB)
871 return (SplatImm + ShiftImm * 4) & 0xF;
872 else if (Opcode == PPC::VSPLTH)
873 return (SplatImm + ShiftImm * 2) & 0x7;
874 else
875 return (SplatImm + ShiftImm) & 0x3;
876 };
877
878 unsigned NewElem = CalculateNewElementIdx(MyOpcode);
879
880 LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
881 << " to " << NewElem << " in instruction: ");
882 LLVM_DEBUG(MI.dump());
883 if (!MRI->constrainRegClass(ShiftOp1, &PPC::VRRCRegClass))
884 llvm_unreachable("Can't fail because vrrc is subset of vsrc");
885 addRegToUpdate(MI.getOperand(OpNo).getReg());
886 addRegToUpdate(ShiftOp1);
887 MI.getOperand(OpNo).setReg(ShiftOp1);
888 MI.getOperand(SplatImmNo).setImm(NewElem);
889 }
890 }
891 break;
892 }
893 case PPC::XVCVDPSP: {
894 // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
895 Register TrueReg =
896 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
897 if (!TrueReg.isVirtual())
898 break;
899 MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
900
901 // This can occur when building a vector of single precision or integer
902 // values.
903 if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
904 Register DefsReg1 =
905 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
906 Register DefsReg2 =
907 TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
908 if (!DefsReg1.isVirtual() || !DefsReg2.isVirtual())
909 break;
910 MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
911 MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
912
913 if (!P1 || !P2)
914 break;
915
916 // Remove the passed FRSP/XSRSP instruction if it only feeds this MI
917 // and set any uses of that FRSP/XSRSP (in this MI) to the source of
918 // the FRSP/XSRSP.
919 auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
920 unsigned Opc = RoundInstr->getOpcode();
921 if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
922 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
923 Simplified = true;
924 Register ConvReg1 = RoundInstr->getOperand(1).getReg();
925 Register FRSPDefines = RoundInstr->getOperand(0).getReg();
926 MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
927 for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
928 if (Use.getOperand(i).isReg() &&
929 Use.getOperand(i).getReg() == FRSPDefines)
930 Use.getOperand(i).setReg(ConvReg1);
931 LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
932 LLVM_DEBUG(RoundInstr->dump());
933 LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
934 LLVM_DEBUG(MI.dump());
935 LLVM_DEBUG(dbgs() << "Through instruction:\n");
937 addRegToUpdate(ConvReg1);
938 addRegToUpdate(FRSPDefines);
939 ToErase = RoundInstr;
940 }
941 };
942
943 // If the input to XVCVDPSP is a vector that was built (even
944 // partially) out of FRSP's, the FRSP(s) can safely be removed
945 // since this instruction performs the same operation.
946 if (P1 != P2) {
947 removeFRSPIfPossible(P1);
948 removeFRSPIfPossible(P2);
949 break;
950 }
951 removeFRSPIfPossible(P1);
952 }
953 break;
954 }
955 case PPC::EXTSH:
956 case PPC::EXTSH8:
957 case PPC::EXTSH8_32_64: {
958 if (!EnableSExtElimination) break;
959 Register NarrowReg = MI.getOperand(1).getReg();
960 if (!NarrowReg.isVirtual())
961 break;
962
963 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
964 unsigned SrcOpcode = SrcMI->getOpcode();
965 // If we've used a zero-extending load that we will sign-extend,
966 // just do a sign-extending load.
967 if (SrcOpcode == PPC::LHZ || SrcOpcode == PPC::LHZX) {
968 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
969 break;
970 // Determine the new opcode. We need to make sure that if the original
971 // instruction has a 64 bit opcode we keep using a 64 bit opcode.
972 // Likewise if the source is X-Form the new opcode should also be
973 // X-Form.
974 unsigned Opc = PPC::LHA;
975 bool SourceIsXForm = SrcOpcode == PPC::LHZX;
976 bool MIIs64Bit = MI.getOpcode() == PPC::EXTSH8 ||
977 MI.getOpcode() == PPC::EXTSH8_32_64;
978
979 if (SourceIsXForm && MIIs64Bit)
980 Opc = PPC::LHAX8;
981 else if (SourceIsXForm && !MIIs64Bit)
982 Opc = PPC::LHAX;
983 else if (MIIs64Bit)
984 Opc = PPC::LHA8;
985
986 addRegToUpdate(NarrowReg);
987 addRegToUpdate(MI.getOperand(0).getReg());
988
989 // We are removing a definition of NarrowReg which will cause
990 // problems in AliveBlocks. Add an implicit def that will be
991 // removed so that AliveBlocks are updated correctly.
992 addDummyDef(MBB, &MI, NarrowReg);
993 LLVM_DEBUG(dbgs() << "Zero-extending load\n");
994 LLVM_DEBUG(SrcMI->dump());
995 LLVM_DEBUG(dbgs() << "and sign-extension\n");
996 LLVM_DEBUG(MI.dump());
997 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
998 SrcMI->setDesc(TII->get(Opc));
999 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
1000 ToErase = &MI;
1001 Simplified = true;
1002 NumEliminatedSExt++;
1003 }
1004 break;
1005 }
1006 case PPC::EXTSW:
1007 case PPC::EXTSW_32:
1008 case PPC::EXTSW_32_64: {
1009 if (!EnableSExtElimination) break;
1010 Register NarrowReg = MI.getOperand(1).getReg();
1011 if (!NarrowReg.isVirtual())
1012 break;
1013
1014 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
1015 unsigned SrcOpcode = SrcMI->getOpcode();
1016 // If we've used a zero-extending load that we will sign-extend,
1017 // just do a sign-extending load.
1018 if (SrcOpcode == PPC::LWZ || SrcOpcode == PPC::LWZX) {
1019 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
1020 break;
1021
1022 // The transformation from a zero-extending load to a sign-extending
1023 // load is only legal when the displacement is a multiple of 4.
1024 // If the displacement is not at least 4 byte aligned, don't perform
1025 // the transformation.
1026 bool IsWordAligned = false;
1027 if (SrcMI->getOperand(1).isGlobal()) {
1028 const GlobalVariable *GV =
1030 if (GV && GV->getAlign() && *GV->getAlign() >= 4 &&
1031 (SrcMI->getOperand(1).getOffset() % 4 == 0))
1032 IsWordAligned = true;
1033 } else if (SrcMI->getOperand(1).isImm()) {
1034 int64_t Value = SrcMI->getOperand(1).getImm();
1035 if (Value % 4 == 0)
1036 IsWordAligned = true;
1037 }
1038
1039 // Determine the new opcode. We need to make sure that if the original
1040 // instruction has a 64 bit opcode we keep using a 64 bit opcode.
1041 // Likewise if the source is X-Form the new opcode should also be
1042 // X-Form.
1043 unsigned Opc = PPC::LWA_32;
1044 bool SourceIsXForm = SrcOpcode == PPC::LWZX;
1045 bool MIIs64Bit = MI.getOpcode() == PPC::EXTSW ||
1046 MI.getOpcode() == PPC::EXTSW_32_64;
1047
1048 if (SourceIsXForm && MIIs64Bit)
1049 Opc = PPC::LWAX;
1050 else if (SourceIsXForm && !MIIs64Bit)
1051 Opc = PPC::LWAX_32;
1052 else if (MIIs64Bit)
1053 Opc = PPC::LWA;
1054
1055 if (!IsWordAligned && (Opc == PPC::LWA || Opc == PPC::LWA_32))
1056 break;
1057
1058 addRegToUpdate(NarrowReg);
1059 addRegToUpdate(MI.getOperand(0).getReg());
1060
1061 // We are removing a definition of NarrowReg which will cause
1062 // problems in AliveBlocks. Add an implicit def that will be
1063 // removed so that AliveBlocks are updated correctly.
1064 addDummyDef(MBB, &MI, NarrowReg);
1065 LLVM_DEBUG(dbgs() << "Zero-extending load\n");
1066 LLVM_DEBUG(SrcMI->dump());
1067 LLVM_DEBUG(dbgs() << "and sign-extension\n");
1068 LLVM_DEBUG(MI.dump());
1069 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
1070 SrcMI->setDesc(TII->get(Opc));
1071 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
1072 ToErase = &MI;
1073 Simplified = true;
1074 NumEliminatedSExt++;
1075 } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
1076 TII->isSignExtended(NarrowReg, MRI)) {
1077 // We can eliminate EXTSW if the input is known to be already
1078 // sign-extended. However, we are not sure whether a spill will occur
1079 // during register allocation. If there is no promotion, it will use
1080 // 'stw' instead of 'std', and 'lwz' instead of 'ld' when spilling,
1081 // since the register class is 32-bits. Consequently, the high 32-bit
1082 // information will be lost. Therefore, all these instructions in the
1083 // chain used to deduce sign extension to eliminate the 'extsw' will
1084 // need to be promoted to 64-bit pseudo instructions when the 'extsw'
1085 // is eliminated.
1086 TII->promoteInstr32To64ForElimEXTSW(NarrowReg, MRI, 0);
1087
1088 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
1089 Register TmpReg =
1090 MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
1091 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
1092 TmpReg);
1093 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
1094 MI.getOperand(0).getReg())
1095 .addReg(TmpReg)
1096 .addReg(NarrowReg)
1097 .addImm(PPC::sub_32);
1098 ToErase = &MI;
1099 Simplified = true;
1100 NumEliminatedSExt++;
1101 }
1102 break;
1103 }
1104 case PPC::RLDICL: {
1105 // We can eliminate RLDICL (e.g. for zero-extension)
1106 // if all bits to clear are already zero in the input.
1107 // This code assume following code sequence for zero-extension.
1108 // %6 = COPY %5:sub_32; (optional)
1109 // %8 = IMPLICIT_DEF;
1110 // %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
1111 if (!EnableZExtElimination) break;
1112
1113 if (MI.getOperand(2).getImm() != 0)
1114 break;
1115
1116 Register SrcReg = MI.getOperand(1).getReg();
1117 if (!SrcReg.isVirtual())
1118 break;
1119
1120 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1121 if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
1122 SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
1123 break;
1124
1125 MachineInstr *ImpDefMI, *SubRegMI;
1126 ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
1127 SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
1128 if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
1129
1130 SrcMI = SubRegMI;
1131 if (SubRegMI->getOpcode() == PPC::COPY) {
1132 Register CopyReg = SubRegMI->getOperand(1).getReg();
1133 if (CopyReg.isVirtual())
1134 SrcMI = MRI->getVRegDef(CopyReg);
1135 }
1136 if (!SrcMI->getOperand(0).isReg())
1137 break;
1138
1139 unsigned KnownZeroCount =
1140 getKnownLeadingZeroCount(SrcMI->getOperand(0).getReg(), TII, MRI);
1141 if (MI.getOperand(3).getImm() <= KnownZeroCount) {
1142 LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
1143 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
1144 MI.getOperand(0).getReg())
1145 .addReg(SrcReg);
1146 addRegToUpdate(SrcReg);
1147 ToErase = &MI;
1148 Simplified = true;
1149 NumEliminatedZExt++;
1150 }
1151 break;
1152 }
1153
1154 // TODO: Any instruction that has an immediate form fed only by a PHI
1155 // whose operands are all load immediate can be folded away. We currently
1156 // do this for ADD instructions, but should expand it to arithmetic and
1157 // binary instructions with immediate forms in the future.
1158 case PPC::ADD4:
1159 case PPC::ADD8: {
1160 auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
1161 assert(PhiOp && "Invalid Operand!");
1162 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
1163
1164 return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
1165 MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
1166 };
1167
1168 auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
1169 MachineOperand *PhiOp) {
1170 assert(PhiOp && "Invalid Operand!");
1171 assert(DominatorOp && "Invalid Operand!");
1172 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
1173 MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
1174
1175 // Note: the vregs only show up at odd indices position of PHI Node,
1176 // the even indices position save the BB info.
1177 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
1178 MachineInstr *LiMI =
1179 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
1180 if (!LiMI ||
1181 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
1182 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
1183 !MDT->dominates(DefDomMI, LiMI))
1184 return false;
1185 }
1186
1187 return true;
1188 };
1189
1190 MachineOperand Op1 = MI.getOperand(1);
1191 MachineOperand Op2 = MI.getOperand(2);
1192 if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
1193 std::swap(Op1, Op2);
1194 else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
1195 break; // We don't have an ADD fed by LI's that can be transformed
1196
1197 // Now we know that Op1 is the PHI node and Op2 is the dominator
1198 Register DominatorReg = Op2.getReg();
1199
1200 const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
1201 ? &PPC::G8RC_and_G8RC_NOX0RegClass
1202 : &PPC::GPRC_and_GPRC_NOR0RegClass;
1203 MRI->setRegClass(DominatorReg, TRC);
1204
1205 // replace LIs with ADDIs
1206 MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
1207 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
1208 MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
1209 LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
1210 LLVM_DEBUG(LiMI->dump());
1211
1212 // There could be repeated registers in the PHI, e.g: %1 =
1213 // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
1214 // already replaced the def instruction, skip.
1215 if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
1216 continue;
1217
1218 assert((LiMI->getOpcode() == PPC::LI ||
1219 LiMI->getOpcode() == PPC::LI8) &&
1220 "Invalid Opcode!");
1221 auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
1222 LiMI->removeOperand(1); // remove the imm of LI
1223 LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
1224 : PPC::ADDI8));
1225 MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
1226 .addReg(DominatorReg)
1227 .addImm(LiImm); // restore the imm of LI
1228 LLVM_DEBUG(LiMI->dump());
1229 }
1230
1231 // Replace ADD with COPY
1232 LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
1233 LLVM_DEBUG(MI.dump());
1234 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
1235 MI.getOperand(0).getReg())
1236 .add(Op1);
1237 addRegToUpdate(Op1.getReg());
1238 addRegToUpdate(Op2.getReg());
1239 ToErase = &MI;
1240 Simplified = true;
1241 NumOptADDLIs++;
1242 break;
1243 }
1244 case PPC::RLDICR: {
1245 Simplified |= emitRLDICWhenLoweringJumpTables(MI, ToErase) ||
1246 combineSEXTAndSHL(MI, ToErase);
1247 break;
1248 }
1249 case PPC::ANDI_rec:
1250 case PPC::ANDI8_rec:
1251 case PPC::ANDIS_rec:
1252 case PPC::ANDIS8_rec: {
1253 Register TrueReg =
1254 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
1255 if (!TrueReg.isVirtual() || !MRI->hasOneNonDBGUse(TrueReg))
1256 break;
1257
1258 MachineInstr *SrcMI = MRI->getVRegDef(TrueReg);
1259 if (!SrcMI)
1260 break;
1261
1262 unsigned SrcOpCode = SrcMI->getOpcode();
1263 if (SrcOpCode != PPC::RLDICL && SrcOpCode != PPC::RLDICR)
1264 break;
1265
1266 Register SrcReg, DstReg;
1267 SrcReg = SrcMI->getOperand(1).getReg();
1268 DstReg = MI.getOperand(1).getReg();
1269 const TargetRegisterClass *SrcRC = MRI->getRegClassOrNull(SrcReg);
1270 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(DstReg);
1271 if (DstRC != SrcRC)
1272 break;
1273
1274 uint64_t AndImm = MI.getOperand(2).getImm();
1275 if (MI.getOpcode() == PPC::ANDIS_rec ||
1276 MI.getOpcode() == PPC::ANDIS8_rec)
1277 AndImm <<= 16;
1278 uint64_t LZeroAndImm = llvm::countl_zero<uint64_t>(AndImm);
1279 uint64_t RZeroAndImm = llvm::countr_zero<uint64_t>(AndImm);
1280 uint64_t ImmSrc = SrcMI->getOperand(3).getImm();
1281
1282 // We can transfer `RLDICL/RLDICR + ANDI_rec/ANDIS_rec` to `ANDI_rec 0`
1283 // if all bits to AND are already zero in the input.
1284 bool PatternResultZero =
1285 (SrcOpCode == PPC::RLDICL && (RZeroAndImm + ImmSrc > 63)) ||
1286 (SrcOpCode == PPC::RLDICR && LZeroAndImm > ImmSrc);
1287
1288 // We can eliminate RLDICL/RLDICR if it's used to clear bits and all
1289 // bits cleared will be ANDed with 0 by ANDI_rec/ANDIS_rec.
1290 bool PatternRemoveRotate =
1291 SrcMI->getOperand(2).getImm() == 0 &&
1292 ((SrcOpCode == PPC::RLDICL && LZeroAndImm >= ImmSrc) ||
1293 (SrcOpCode == PPC::RLDICR && (RZeroAndImm + ImmSrc > 63)));
1294
1295 if (!PatternResultZero && !PatternRemoveRotate)
1296 break;
1297
1298 LLVM_DEBUG(dbgs() << "Combining pair: ");
1299 LLVM_DEBUG(SrcMI->dump());
1300 LLVM_DEBUG(MI.dump());
1301 if (PatternResultZero)
1302 MI.getOperand(2).setImm(0);
1303 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
1304 LLVM_DEBUG(dbgs() << "To: ");
1305 LLVM_DEBUG(MI.dump());
1306 addRegToUpdate(MI.getOperand(1).getReg());
1307 addRegToUpdate(SrcMI->getOperand(0).getReg());
1308 Simplified = true;
1309 break;
1310 }
1311 case PPC::RLWINM:
1312 case PPC::RLWINM_rec:
1313 case PPC::RLWINM8:
1314 case PPC::RLWINM8_rec: {
1315 // We might replace operand 1 of the instruction which will
1316 // require we recompute kill flags for it.
1317 Register OrigOp1Reg = MI.getOperand(1).isReg()
1318 ? MI.getOperand(1).getReg()
1319 : PPC::NoRegister;
1320 Simplified = TII->combineRLWINM(MI, &ToErase);
1321 if (Simplified) {
1322 addRegToUpdate(OrigOp1Reg);
1323 if (MI.getOperand(1).isReg())
1324 addRegToUpdate(MI.getOperand(1).getReg());
1325 if (ToErase && ToErase->getOperand(1).isReg())
1326 for (auto UseReg : ToErase->explicit_uses())
1327 if (UseReg.isReg())
1328 addRegToUpdate(UseReg.getReg());
1329 ++NumRotatesCollapsed;
1330 }
1331 break;
1332 }
1333 // We will replace TD/TW/TDI/TWI with an unconditional trap if it will
1334 // always trap, we will delete the node if it will never trap.
1335 case PPC::TDI:
1336 case PPC::TWI:
1337 case PPC::TD:
1338 case PPC::TW: {
1339 if (!EnableTrapOptimization) break;
1340 MachineInstr *LiMI1 = getVRegDefOrNull(&MI.getOperand(1), MRI);
1341 MachineInstr *LiMI2 = getVRegDefOrNull(&MI.getOperand(2), MRI);
1342 bool IsOperand2Immediate = MI.getOperand(2).isImm();
1343 // We can only do the optimization if we can get immediates
1344 // from both operands
1345 if (!(LiMI1 && (LiMI1->getOpcode() == PPC::LI ||
1346 LiMI1->getOpcode() == PPC::LI8)))
1347 break;
1348 if (!IsOperand2Immediate &&
1349 !(LiMI2 && (LiMI2->getOpcode() == PPC::LI ||
1350 LiMI2->getOpcode() == PPC::LI8)))
1351 break;
1352
1353 auto ImmOperand0 = MI.getOperand(0).getImm();
1354 auto ImmOperand1 = LiMI1->getOperand(1).getImm();
1355 auto ImmOperand2 = IsOperand2Immediate ? MI.getOperand(2).getImm()
1356 : LiMI2->getOperand(1).getImm();
1357
1358 // We will replace the MI with an unconditional trap if it will always
1359 // trap.
1360 if ((ImmOperand0 == 31) ||
1361 ((ImmOperand0 & 0x10) &&
1362 ((int64_t)ImmOperand1 < (int64_t)ImmOperand2)) ||
1363 ((ImmOperand0 & 0x8) &&
1364 ((int64_t)ImmOperand1 > (int64_t)ImmOperand2)) ||
1365 ((ImmOperand0 & 0x2) &&
1366 ((uint64_t)ImmOperand1 < (uint64_t)ImmOperand2)) ||
1367 ((ImmOperand0 & 0x1) &&
1368 ((uint64_t)ImmOperand1 > (uint64_t)ImmOperand2)) ||
1369 ((ImmOperand0 & 0x4) && (ImmOperand1 == ImmOperand2))) {
1370 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::TRAP));
1371 TrapOpt = true;
1372 }
1373 // We will delete the MI if it will never trap.
1374 ToErase = &MI;
1375 Simplified = true;
1376 break;
1377 }
1378 }
1379 }
1380
1381 // If the last instruction was marked for elimination,
1382 // remove it now.
1383 if (ToErase) {
1384 clearKillsForDyingInstr();
1385 ToErase->eraseFromParent();
1386 ToErase = nullptr;
1387 }
1388 // Reset TrapOpt to false at the end of the basic block.
1390 TrapOpt = false;
1391 }
1392
1393 // Eliminate all the TOC save instructions which are redundant.
1394 Simplified |= eliminateRedundantTOCSaves(TOCSaves);
1395 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
1396 if (FI->mustSaveTOC())
1397 NumTOCSavesInPrologue++;
1398
1399 // We try to eliminate redundant compare instruction.
1400 Simplified |= eliminateRedundantCompare();
1401
1402 // If we have made any modifications and added any registers to the set of
1403 // registers whose liveness flags may now be stale, clear those flags. A
1404 // transform may remove a use (leaving a stale kill on an earlier use) or add
1405 // a use of a previously dead def (leaving a stale dead flag), so clear both
1406 // kinds conservatively.
1407 for (Register Reg : RegsToUpdate) {
1408 if (MRI->reg_empty(Reg))
1409 continue;
1410 MRI->clearKillFlags(Reg);
1411 for (MachineOperand &Def : MRI->def_operands(Reg))
1412 Def.setIsDead(false);
1413 }
1414 return Simplified;
1415}
1416
1417// helper functions for eliminateRedundantCompare
1418static bool isEqOrNe(MachineInstr *BI) {
1420 unsigned PredCond = PPC::getPredicateCondition(Pred);
1421 return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
1422}
1423
1424static bool isSupportedCmpOp(unsigned opCode) {
1425 return (opCode == PPC::CMPLD || opCode == PPC::CMPD ||
1426 opCode == PPC::CMPLW || opCode == PPC::CMPW ||
1427 opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
1428 opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
1429}
1430
1431static bool is64bitCmpOp(unsigned opCode) {
1432 return (opCode == PPC::CMPLD || opCode == PPC::CMPD ||
1433 opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
1434}
1435
1436static bool isSignedCmpOp(unsigned opCode) {
1437 return (opCode == PPC::CMPD || opCode == PPC::CMPW ||
1438 opCode == PPC::CMPDI || opCode == PPC::CMPWI);
1439}
1440
1441static unsigned getSignedCmpOpCode(unsigned opCode) {
1442 if (opCode == PPC::CMPLD) return PPC::CMPD;
1443 if (opCode == PPC::CMPLW) return PPC::CMPW;
1444 if (opCode == PPC::CMPLDI) return PPC::CMPDI;
1445 if (opCode == PPC::CMPLWI) return PPC::CMPWI;
1446 return opCode;
1447}
1448
1449// We can decrement immediate x in (GE x) by changing it to (GT x-1) or
1450// (LT x) to (LE x-1)
1451static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
1452 uint64_t Imm = CMPI->getOperand(2).getImm();
1453 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1454 if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
1455 return 0;
1456
1458 unsigned PredCond = PPC::getPredicateCondition(Pred);
1459 unsigned PredHint = PPC::getPredicateHint(Pred);
1460 if (PredCond == PPC::PRED_GE)
1461 return PPC::getPredicate(PPC::PRED_GT, PredHint);
1462 if (PredCond == PPC::PRED_LT)
1463 return PPC::getPredicate(PPC::PRED_LE, PredHint);
1464
1465 return 0;
1466}
1467
1468// We can increment immediate x in (GT x) by changing it to (GE x+1) or
1469// (LE x) to (LT x+1)
1470static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
1471 uint64_t Imm = CMPI->getOperand(2).getImm();
1472 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1473 if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
1474 return 0;
1475
1477 unsigned PredCond = PPC::getPredicateCondition(Pred);
1478 unsigned PredHint = PPC::getPredicateHint(Pred);
1479 if (PredCond == PPC::PRED_GT)
1480 return PPC::getPredicate(PPC::PRED_GE, PredHint);
1481 if (PredCond == PPC::PRED_LE)
1482 return PPC::getPredicate(PPC::PRED_LT, PredHint);
1483
1484 return 0;
1485}
1486
1487// This takes a Phi node and returns a register value for the specified BB.
1488static unsigned getIncomingRegForBlock(MachineInstr *Phi,
1489 MachineBasicBlock *MBB) {
1490 for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
1491 MachineOperand &MO = Phi->getOperand(I);
1492 if (MO.getMBB() == MBB)
1493 return Phi->getOperand(I-1).getReg();
1494 }
1495 llvm_unreachable("invalid src basic block for this Phi node\n");
1496 return 0;
1497}
1498
1499// This function tracks the source of the register through register copy.
1500// If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
1501// assuming that the control comes from BB1 into BB2.
1502static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
1503 MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
1504 unsigned SrcReg = Reg;
1505 while (true) {
1506 unsigned NextReg = SrcReg;
1507 MachineInstr *Inst = MRI->getVRegDef(SrcReg);
1508 if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
1509 NextReg = getIncomingRegForBlock(Inst, BB1);
1510 // We track through PHI only once to avoid infinite loop.
1511 BB1 = nullptr;
1512 }
1513 else if (Inst->isFullCopy())
1514 NextReg = Inst->getOperand(1).getReg();
1515 if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg))
1516 break;
1517 SrcReg = NextReg;
1518 }
1519 return SrcReg;
1520}
1521
1522static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
1523 MachineBasicBlock *&PredMBB,
1524 MachineBasicBlock *&MBBtoMoveCmp,
1525 MachineRegisterInfo *MRI) {
1526
1527 auto isEligibleBB = [&](MachineBasicBlock &BB) {
1528 auto BII = BB.getFirstInstrTerminator();
1529 // We optimize BBs ending with a conditional branch.
1530 // We check only for BCC here, not BCCLR, because BCCLR
1531 // will be formed only later in the pipeline.
1532 if (BB.succ_size() == 2 &&
1533 BII != BB.instr_end() &&
1534 (*BII).getOpcode() == PPC::BCC &&
1535 (*BII).getOperand(1).isReg()) {
1536 // We optimize only if the condition code is used only by one BCC.
1537 Register CndReg = (*BII).getOperand(1).getReg();
1538 if (!CndReg.isVirtual() || !MRI->hasOneNonDBGUse(CndReg))
1539 return false;
1540
1541 MachineInstr *CMPI = MRI->getVRegDef(CndReg);
1542 // We assume compare and branch are in the same BB for ease of analysis.
1543 if (CMPI->getParent() != &BB)
1544 return false;
1545
1546 // We skip this BB if a physical register is used in comparison.
1547 for (MachineOperand &MO : CMPI->operands())
1548 if (MO.isReg() && !MO.getReg().isVirtual())
1549 return false;
1550
1551 return true;
1552 }
1553 return false;
1554 };
1555
1556 // If this BB has more than one successor, we can create a new BB and
1557 // move the compare instruction in the new BB.
1558 // So far, we do not move compare instruction to a BB having multiple
1559 // successors to avoid potentially increasing code size.
1560 auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
1561 return BB.succ_size() == 1;
1562 };
1563
1564 if (!isEligibleBB(MBB))
1565 return false;
1566
1567 unsigned NumPredBBs = MBB.pred_size();
1568 if (NumPredBBs == 1) {
1569 MachineBasicBlock *TmpMBB = *MBB.pred_begin();
1570 if (isEligibleBB(*TmpMBB)) {
1571 PredMBB = TmpMBB;
1572 MBBtoMoveCmp = nullptr;
1573 return true;
1574 }
1575 }
1576 else if (NumPredBBs == 2) {
1577 // We check for partially redundant case.
1578 // So far, we support cases with only two predecessors
1579 // to avoid increasing the number of instructions.
1581 MachineBasicBlock *Pred1MBB = *PI;
1582 MachineBasicBlock *Pred2MBB = *(PI+1);
1583
1584 if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
1585 // We assume Pred1MBB is the BB containing the compare to be merged and
1586 // Pred2MBB is the BB to which we will append a compare instruction.
1587 // Proceed as is if Pred1MBB is different from MBB.
1588 }
1589 else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
1590 // We need to swap Pred1MBB and Pred2MBB to canonicalize.
1591 std::swap(Pred1MBB, Pred2MBB);
1592 }
1593 else return false;
1594
1595 if (Pred1MBB == &MBB)
1596 return false;
1597
1598 // Here, Pred2MBB is the BB to which we need to append a compare inst.
1599 // We cannot move the compare instruction if operands are not available
1600 // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
1601 MachineInstr *BI = &*MBB.getFirstInstrTerminator();
1602 MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
1603 for (int I = 1; I <= 2; I++)
1604 if (CMPI->getOperand(I).isReg()) {
1605 MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
1606 if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
1607 return false;
1608 }
1609
1610 PredMBB = Pred1MBB;
1611 MBBtoMoveCmp = Pred2MBB;
1612 return true;
1613 }
1614
1615 return false;
1616}
1617
1618// This function will iterate over the input map containing a pair of TOC save
1619// instruction and a flag. The flag will be set to false if the TOC save is
1620// proven redundant. This function will erase from the basic block all the TOC
1621// saves marked as redundant.
1622bool PPCMIPeephole::eliminateRedundantTOCSaves(
1623 std::map<MachineInstr *, bool> &TOCSaves) {
1624 bool Simplified = false;
1625 int NumKept = 0;
1626 for (auto TOCSave : TOCSaves) {
1627 if (!TOCSave.second) {
1628 TOCSave.first->eraseFromParent();
1629 RemoveTOCSave++;
1630 Simplified = true;
1631 } else {
1632 NumKept++;
1633 }
1634 }
1635
1636 if (NumKept > 1)
1637 MultiTOCSaves++;
1638
1639 return Simplified;
1640}
1641
1642// If multiple conditional branches are executed based on the (essentially)
1643// same comparison, we merge compare instructions into one and make multiple
1644// conditional branches on this comparison.
1645// For example,
1646// if (a == 0) { ... }
1647// else if (a < 0) { ... }
1648// can be executed by one compare and two conditional branches instead of
1649// two pairs of a compare and a conditional branch.
1650//
1651// This method merges two compare instructions in two MBBs and modifies the
1652// compare and conditional branch instructions if needed.
1653// For the above example, the input for this pass looks like:
1654// cmplwi r3, 0
1655// beq 0, .LBB0_3
1656// cmpwi r3, -1
1657// bgt 0, .LBB0_4
1658// So, before merging two compares, we need to modify these instructions as
1659// cmpwi r3, 0 ; cmplwi and cmpwi yield same result for beq
1660// beq 0, .LBB0_3
1661// cmpwi r3, 0 ; greather than -1 means greater or equal to 0
1662// bge 0, .LBB0_4
1663
1664bool PPCMIPeephole::eliminateRedundantCompare() {
1665 bool Simplified = false;
1666
1667 for (MachineBasicBlock &MBB2 : *MF) {
1668 MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
1669
1670 // For fully redundant case, we select two basic blocks MBB1 and MBB2
1671 // as an optimization target if
1672 // - both MBBs end with a conditional branch,
1673 // - MBB1 is the only predecessor of MBB2, and
1674 // - compare does not take a physical register as a operand in both MBBs.
1675 // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
1676 //
1677 // As partially redundant case, we additionally handle if MBB2 has one
1678 // additional predecessor, which has only one successor (MBB2).
1679 // In this case, we move the compare instruction originally in MBB2 into
1680 // MBBtoMoveCmp. This partially redundant case is typically appear by
1681 // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
1682 //
1683 // Overview of CFG of related basic blocks
1684 // Fully redundant case Partially redundant case
1685 // -------- ---------------- --------
1686 // | MBB1 | (w/ 2 succ) | MBBtoMoveCmp | | MBB1 | (w/ 2 succ)
1687 // -------- ---------------- --------
1688 // | \ (w/ 1 succ) \ | \
1689 // | \ \ | \
1690 // | \ |
1691 // -------- --------
1692 // | MBB2 | (w/ 1 pred | MBB2 | (w/ 2 pred
1693 // -------- and 2 succ) -------- and 2 succ)
1694 // | \ | \
1695 // | \ | \
1696 //
1697 if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
1698 continue;
1699
1700 MachineInstr *BI1 = &*MBB1->getFirstInstrTerminator();
1701 MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
1702
1703 MachineInstr *BI2 = &*MBB2.getFirstInstrTerminator();
1704 MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
1705 bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
1706
1707 // We cannot optimize an unsupported compare opcode or
1708 // a mix of 32-bit and 64-bit comparisons
1709 if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1710 !isSupportedCmpOp(CMPI2->getOpcode()) ||
1711 is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1712 continue;
1713
1714 unsigned NewOpCode = 0;
1715 unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1716 int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
1717 bool SwapOperands = false;
1718
1719 if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1720 // Typically, unsigned comparison is used for equality check, but
1721 // we replace it with a signed comparison if the comparison
1722 // to be merged is a signed comparison.
1723 // In other cases of opcode mismatch, we cannot optimize this.
1724
1725 // We cannot change opcode when comparing against an immediate
1726 // if the most significant bit of the immediate is one
1727 // due to the difference in sign extension.
1728 auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
1729 if (!I->getOperand(2).isImm())
1730 return false;
1731 int16_t Imm = (int16_t)I->getOperand(2).getImm();
1732 return Imm < 0;
1733 };
1734
1735 if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
1736 CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1737 NewOpCode = CMPI1->getOpcode();
1738 else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
1739 getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1740 NewOpCode = CMPI2->getOpcode();
1741 else continue;
1742 }
1743
1744 if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1745 // In case of comparisons between two registers, these two registers
1746 // must be same to merge two comparisons.
1747 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1748 nullptr, nullptr, MRI);
1749 unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
1750 nullptr, nullptr, MRI);
1751 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1752 MBB1, &MBB2, MRI);
1753 unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
1754 MBB1, &MBB2, MRI);
1755
1756 if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1757 // Same pair of registers in the same order; ready to merge as is.
1758 }
1759 else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1760 // Same pair of registers in different order.
1761 // We reverse the predicate to merge compare instructions.
1763 NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
1764 // In case of partial redundancy, we need to swap operands
1765 // in another compare instruction.
1766 SwapOperands = true;
1767 }
1768 else continue;
1769 }
1770 else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1771 // In case of comparisons between a register and an immediate,
1772 // the operand register must be same for two compare instructions.
1773 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1774 nullptr, nullptr, MRI);
1775 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1776 MBB1, &MBB2, MRI);
1777 if (Cmp1Operand1 != Cmp2Operand1)
1778 continue;
1779
1780 NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1781 NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1782
1783 // If immediate are not same, we try to adjust by changing predicate;
1784 // e.g. GT imm means GE (imm+1).
1785 if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1786 int Diff = Imm1 - Imm2;
1787 if (Diff < -2 || Diff > 2)
1788 continue;
1789
1790 unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1791 unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1792 unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1793 unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1794 if (Diff == 2) {
1795 if (PredToInc2 && PredToDec1) {
1796 NewPredicate2 = PredToInc2;
1797 NewPredicate1 = PredToDec1;
1798 NewImm2++;
1799 NewImm1--;
1800 }
1801 }
1802 else if (Diff == 1) {
1803 if (PredToInc2) {
1804 NewImm2++;
1805 NewPredicate2 = PredToInc2;
1806 }
1807 else if (PredToDec1) {
1808 NewImm1--;
1809 NewPredicate1 = PredToDec1;
1810 }
1811 }
1812 else if (Diff == -1) {
1813 if (PredToDec2) {
1814 NewImm2--;
1815 NewPredicate2 = PredToDec2;
1816 }
1817 else if (PredToInc1) {
1818 NewImm1++;
1819 NewPredicate1 = PredToInc1;
1820 }
1821 }
1822 else if (Diff == -2) {
1823 if (PredToDec2 && PredToInc1) {
1824 NewPredicate2 = PredToDec2;
1825 NewPredicate1 = PredToInc1;
1826 NewImm2--;
1827 NewImm1++;
1828 }
1829 }
1830 }
1831
1832 // We cannot merge two compares if the immediates are not same.
1833 if (NewImm2 != NewImm1)
1834 continue;
1835 }
1836
1837 LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1838 LLVM_DEBUG(CMPI1->dump());
1839 LLVM_DEBUG(BI1->dump());
1840 LLVM_DEBUG(CMPI2->dump());
1841 LLVM_DEBUG(BI2->dump());
1842 for (const MachineOperand &MO : CMPI1->operands())
1843 if (MO.isReg())
1844 addRegToUpdate(MO.getReg());
1845 for (const MachineOperand &MO : CMPI2->operands())
1846 if (MO.isReg())
1847 addRegToUpdate(MO.getReg());
1848
1849 // We adjust opcode, predicates and immediate as we determined above.
1850 if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1851 CMPI1->setDesc(TII->get(NewOpCode));
1852 }
1853 if (NewPredicate1) {
1854 BI1->getOperand(0).setImm(NewPredicate1);
1855 }
1856 if (NewPredicate2) {
1857 BI2->getOperand(0).setImm(NewPredicate2);
1858 }
1859 if (NewImm1 != Imm1) {
1860 CMPI1->getOperand(2).setImm(NewImm1);
1861 }
1862
1863 if (IsPartiallyRedundant) {
1864 // We touch up the compare instruction in MBB2 and move it to
1865 // a previous BB to handle partially redundant case.
1866 if (SwapOperands) {
1867 Register Op1 = CMPI2->getOperand(1).getReg();
1868 Register Op2 = CMPI2->getOperand(2).getReg();
1869 CMPI2->getOperand(1).setReg(Op2);
1870 CMPI2->getOperand(2).setReg(Op1);
1871 }
1872 if (NewImm2 != Imm2)
1873 CMPI2->getOperand(2).setImm(NewImm2);
1874
1875 for (int I = 1; I <= 2; I++) {
1876 if (CMPI2->getOperand(I).isReg()) {
1877 MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
1878 if (Inst->getParent() != &MBB2)
1879 continue;
1880
1881 assert(Inst->getOpcode() == PPC::PHI &&
1882 "We cannot support if an operand comes from this BB.");
1883 unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
1884 CMPI2->getOperand(I).setReg(SrcReg);
1885 addRegToUpdate(SrcReg);
1886 }
1887 }
1888 auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
1889 MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
1890
1891 DebugLoc DL = CMPI2->getDebugLoc();
1892 Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
1893 BuildMI(MBB2, MBB2.begin(), DL,
1894 TII->get(PPC::PHI), NewVReg)
1895 .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
1896 .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
1897 BI2->getOperand(1).setReg(NewVReg);
1898 addRegToUpdate(NewVReg);
1899 }
1900 else {
1901 // We finally eliminate compare instruction in MBB2.
1902 // We do not need to treat CMPI2 specially here in terms of re-computing
1903 // live variables even though it is being deleted because:
1904 // - It defines a register that has a single use (already checked in
1905 // eligibleForCompareElimination())
1906 // - The only user (BI2) is no longer using it so the register is dead (no
1907 // def, no uses)
1908 // - We do not attempt to recompute live variables for dead registers
1909 BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
1910 CMPI2->eraseFromParent();
1911 }
1912
1913 LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
1914 LLVM_DEBUG(CMPI1->dump());
1915 LLVM_DEBUG(BI1->dump());
1916 LLVM_DEBUG(BI2->dump());
1917 if (IsPartiallyRedundant) {
1918 LLVM_DEBUG(dbgs() << "The following compare is moved into "
1919 << printMBBReference(*MBBtoMoveCmp)
1920 << " to handle partial redundancy.\n");
1921 LLVM_DEBUG(CMPI2->dump());
1922 }
1923 Simplified = true;
1924 }
1925
1926 return Simplified;
1927}
1928
1929// We miss the opportunity to emit an RLDIC when lowering jump tables
1930// since ISEL sees only a single basic block. When selecting, the clear
1931// and shift left will be in different blocks.
1932bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI,
1933 MachineInstr *&ToErase) {
1934 if (MI.getOpcode() != PPC::RLDICR)
1935 return false;
1936
1937 Register SrcReg = MI.getOperand(1).getReg();
1938 if (!SrcReg.isVirtual())
1939 return false;
1940
1941 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1942 if (SrcMI->getOpcode() != PPC::RLDICL)
1943 return false;
1944
1945 MachineOperand MOpSHSrc = SrcMI->getOperand(2);
1946 MachineOperand MOpMBSrc = SrcMI->getOperand(3);
1947 MachineOperand MOpSHMI = MI.getOperand(2);
1948 MachineOperand MOpMEMI = MI.getOperand(3);
1949 if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() &&
1950 MOpMEMI.isImm()))
1951 return false;
1952
1953 uint64_t SHSrc = MOpSHSrc.getImm();
1954 uint64_t MBSrc = MOpMBSrc.getImm();
1955 uint64_t SHMI = MOpSHMI.getImm();
1956 uint64_t MEMI = MOpMEMI.getImm();
1957 uint64_t NewSH = SHSrc + SHMI;
1958 uint64_t NewMB = MBSrc - SHMI;
1959 if (NewMB > 63 || NewSH > 63)
1960 return false;
1961
1962 // The bits cleared with RLDICL are [0, MBSrc).
1963 // The bits cleared with RLDICR are (MEMI, 63].
1964 // After the sequence, the bits cleared are:
1965 // [0, MBSrc-SHMI) and (MEMI, 63).
1966 //
1967 // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63].
1968 if ((63 - NewSH) != MEMI)
1969 return false;
1970
1971 LLVM_DEBUG(dbgs() << "Converting pair: ");
1972 LLVM_DEBUG(SrcMI->dump());
1973 LLVM_DEBUG(MI.dump());
1974
1975 MI.setDesc(TII->get(PPC::RLDIC));
1976 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
1977 MI.getOperand(2).setImm(NewSH);
1978 MI.getOperand(3).setImm(NewMB);
1979 addRegToUpdate(MI.getOperand(1).getReg());
1980 addRegToUpdate(SrcMI->getOperand(0).getReg());
1981
1982 LLVM_DEBUG(dbgs() << "To: ");
1983 LLVM_DEBUG(MI.dump());
1984 NumRotatesCollapsed++;
1985 // If SrcReg has no non-debug use it's safe to delete its def SrcMI.
1986 if (MRI->use_nodbg_empty(SrcReg)) {
1987 assert(!SrcMI->hasImplicitDef() &&
1988 "Not expecting an implicit def with this instr.");
1989 ToErase = SrcMI;
1990 }
1991 return true;
1992}
1993
1994// For case in LLVM IR
1995// entry:
1996// %iconv = sext i32 %index to i64
1997// br i1 undef label %true, label %false
1998// true:
1999// %ptr = getelementptr inbounds i32, i32* null, i64 %iconv
2000// ...
2001// PPCISelLowering::combineSHL fails to combine, because sext and shl are in
2002// different BBs when conducting instruction selection. We can do a peephole
2003// optimization to combine these two instructions into extswsli after
2004// instruction selection.
2005bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI,
2006 MachineInstr *&ToErase) {
2007 if (MI.getOpcode() != PPC::RLDICR)
2008 return false;
2009
2010 if (!MF->getSubtarget<PPCSubtarget>().isISA3_0())
2011 return false;
2012
2013 assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands");
2014
2015 MachineOperand MOpSHMI = MI.getOperand(2);
2016 MachineOperand MOpMEMI = MI.getOperand(3);
2017 if (!(MOpSHMI.isImm() && MOpMEMI.isImm()))
2018 return false;
2019
2020 uint64_t SHMI = MOpSHMI.getImm();
2021 uint64_t MEMI = MOpMEMI.getImm();
2022 if (SHMI + MEMI != 63)
2023 return false;
2024
2025 Register SrcReg = MI.getOperand(1).getReg();
2026 if (!SrcReg.isVirtual())
2027 return false;
2028
2029 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
2030 if (SrcMI->getOpcode() != PPC::EXTSW &&
2031 SrcMI->getOpcode() != PPC::EXTSW_32_64)
2032 return false;
2033
2034 // If the register defined by extsw has more than one use, combination is not
2035 // needed.
2036 if (!MRI->hasOneNonDBGUse(SrcReg))
2037 return false;
2038
2039 assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands");
2040 assert(SrcMI->getOperand(1).isReg() &&
2041 "EXTSW's second operand should be a register");
2042 if (!SrcMI->getOperand(1).getReg().isVirtual())
2043 return false;
2044
2045 LLVM_DEBUG(dbgs() << "Combining pair: ");
2046 LLVM_DEBUG(SrcMI->dump());
2047 LLVM_DEBUG(MI.dump());
2048
2049 MachineInstr *NewInstr =
2050 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
2051 SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI)
2052 : TII->get(PPC::EXTSWSLI_32_64),
2053 MI.getOperand(0).getReg())
2054 .add(SrcMI->getOperand(1))
2055 .add(MOpSHMI);
2056 (void)NewInstr;
2057
2058 LLVM_DEBUG(dbgs() << "TO: ");
2059 LLVM_DEBUG(NewInstr->dump());
2060 ++NumEXTSWAndSLDICombined;
2061 ToErase = &MI;
2062 // SrcMI, which is extsw, is of no use now, but we don't erase it here so we
2063 // can recompute its kill flags. We run DCE immediately after this pass
2064 // to clean up dead instructions such as this.
2065 addRegToUpdate(NewInstr->getOperand(1).getReg());
2066 addRegToUpdate(SrcMI->getOperand(0).getReg());
2067 return true;
2068}
2069
2070} // end default namespace
2071
2073 "PowerPC MI Peephole Optimization", false, false)
2078 "PowerPC MI Peephole Optimization", false, false)
2079
2080char PPCMIPeephole::ID = 0;
2082llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
Rewrite undef for PHI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define addRegToUpdate(R)
static cl::opt< bool > EnableZExtElimination("ppc-eliminate-zeroext", cl::desc("enable elimination of zero-extensions"), cl::init(true), cl::Hidden)
static cl::opt< bool > FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true), cl::desc("Iterate to a fixed point when attempting to " "convert reg-reg instructions to reg-imm"))
static cl::opt< bool > EnableTrapOptimization("ppc-opt-conditional-trap", cl::desc("enable optimization of conditional traps"), cl::init(false), cl::Hidden)
static cl::opt< bool > ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true), cl::desc("Convert eligible reg+reg instructions to reg+imm"))
static cl::opt< bool > EnableSExtElimination("ppc-eliminate-signext", cl::desc("enable elimination of sign-extensions"), cl::init(true), cl::Hidden)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
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
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static bool shouldExecute(CounterInfo &Counter)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:285
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:254
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
MaybeAlign getAlign() const
Returns the alignment of the given variable.
const HexagonRegisterInfo & getRegisterInfo() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1578
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
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 '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BlockFrequency getEntryFreq() const
Divide a block's BlockFrequency::getFrequency() value by this value to obtain the entry block - relat...
Analysis pass which computes a MachineDominatorTree.
bool dominates(const MachineInstr *A, const MachineInstr *B) const
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
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 & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
bool hasImplicitDef() const
Returns true if the instruction has implicit definition.
bool isFullCopy() const
mop_range operands()
mop_range explicit_uses()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const GlobalValue * getGlobal() const
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
LLVM_ABI bool hasOneNonDBGUser(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
iterator_range< def_iterator > def_operands(Register Reg) const
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
bool reg_empty(Register RegNo) const
reg_empty - Return true if there are no instructions using or defining the specified register (it may...
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
Predicate getSwappedPredicate(Predicate Opcode)
Assume the condition register is set by MI(a,b), return the predicate if we modify the instructions s...
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
unsigned getPredicateCondition(Predicate Opcode)
Return the condition without hint bits.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
unsigned getPredicateHint(Predicate Opcode)
Return the hint bits of the predicate.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
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
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
@ Keep
No function return thunk.
Definition CodeGen.h:307
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
FunctionPass * createPPCMIPeepholePass()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880