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