LLVM 24.0.0git
PPCInstrInfo.cpp
Go to the documentation of this file.
1//===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the PowerPC implementation of the TargetInstrInfo class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "PPCInstrInfo.h"
15#include "PPC.h"
17#include "PPCInstrBuilder.h"
19#include "PPCTargetMachine.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Statistic.h"
37#include "llvm/IR/Module.h"
38#include "llvm/MC/MCInst.h"
40#include "llvm/Support/Debug.h"
43
44using namespace llvm;
45
46#define DEBUG_TYPE "ppc-instr-info"
47
48#define GET_INSTRMAP_INFO
49#define GET_INSTRINFO_CTOR_DTOR
50#include "PPCGenInstrInfo.inc"
51
52STATISTIC(NumStoreSPILLVSRRCAsVec,
53 "Number of spillvsrrc spilled to stack as vec");
54STATISTIC(NumStoreSPILLVSRRCAsGpr,
55 "Number of spillvsrrc spilled to stack as gpr");
56STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
57STATISTIC(CmpIselsConverted,
58 "Number of ISELs that depend on comparison of constants converted");
59STATISTIC(MissedConvertibleImmediateInstrs,
60 "Number of compare-immediate instructions fed by constants");
61STATISTIC(NumRcRotatesConvertedToRcAnd,
62 "Number of record-form rotates converted to record-form andi");
63
64// Pin the vtable to this file.
65void PPCInstrInfo::anchor() {}
66
68 : PPCGenInstrInfo(STI, RI, PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
69 /* CatchRetOpcode */ -1,
70 STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
71 Subtarget(STI), RI(STI.getTargetMachine()) {}
72
75 return Subtarget.isPPC64() ? &PPC::G8RC_NOX0RegClass
76 : &PPC::GPRC_NOR0RegClass;
77}
78
79/// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
80/// this target when scheduling the DAG.
83 const ScheduleDAG *DAG) const {
84 unsigned Directive =
85 static_cast<const PPCSubtarget *>(STI)->getCPUDirective();
88 const InstrItineraryData *II =
89 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
90 return new ScoreboardHazardRecognizer(II, DAG);
91 }
92
94}
95
96/// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
97/// to use for this target when scheduling the DAG.
100 const ScheduleDAG *DAG) const {
101 unsigned Directive =
102 DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective();
103
104 // FIXME: Leaving this as-is until we have POWER9 scheduling info
106 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
107
108 // Most subtargets use a PPC970 recognizer.
111 assert(DAG->TII && "No InstrInfo?");
112
113 return new PPCHazardRecognizer970(*DAG);
114 }
115
116 return new ScoreboardHazardRecognizer(II, DAG);
117}
118
120 const MachineInstr &MI,
121 unsigned *PredCost) const {
122 if (!ItinData || Subtarget.getCLOpts().old_latency_calc)
123 return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
124
125 // The default implementation of getInstrLatency calls getStageLatency, but
126 // getStageLatency does not do the right thing for us. While we have
127 // itinerary, most cores are fully pipelined, and so the itineraries only
128 // express the first part of the pipeline, not every stage. Instead, we need
129 // to use the listed output operand cycle number (using operand 0 here, which
130 // is an output).
131
132 unsigned Latency = 1;
133 unsigned DefClass = MI.getDesc().getSchedClass();
134 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
135 const MachineOperand &MO = MI.getOperand(i);
136 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
137 continue;
138
139 std::optional<unsigned> Cycle = ItinData->getOperandCycle(DefClass, i);
140 if (!Cycle)
141 continue;
142
143 Latency = std::max(Latency, *Cycle);
144 }
145
146 return Latency;
147}
148
149std::optional<unsigned> PPCInstrInfo::getOperandLatency(
150 const InstrItineraryData *ItinData, const MachineInstr &DefMI,
151 unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const {
152 std::optional<unsigned> Latency = PPCGenInstrInfo::getOperandLatency(
153 ItinData, DefMI, DefIdx, UseMI, UseIdx);
154
155 if (!DefMI.getParent())
156 return Latency;
157
158 const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
159 Register Reg = DefMO.getReg();
160
161 bool IsRegCR;
162 if (Reg.isVirtual()) {
163 const MachineRegisterInfo *MRI =
164 &DefMI.getParent()->getParent()->getRegInfo();
165 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
166 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
167 } else {
168 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
169 PPC::CRBITRCRegClass.contains(Reg);
170 }
171
172 if (UseMI.isBranch() && IsRegCR) {
173 if (!Latency)
174 Latency = getInstrLatency(ItinData, DefMI);
175
176 // On some cores, there is an additional delay between writing to a condition
177 // register, and using it from a branch.
178 unsigned Directive = Subtarget.getCPUDirective();
179 switch (Directive) {
180 default: break;
181 case PPC::DIR_7400:
182 case PPC::DIR_750:
183 case PPC::DIR_970:
184 case PPC::DIR_E5500:
185 case PPC::DIR_PWR4:
186 case PPC::DIR_PWR5:
187 case PPC::DIR_PWR5X:
188 case PPC::DIR_PWR6:
189 case PPC::DIR_PWR6X:
190 case PPC::DIR_PWR7:
191 case PPC::DIR_PWR8:
192 // FIXME: Is this needed for POWER9?
193 Latency = *Latency + 2;
194 break;
195 }
196 }
197
198 return Latency;
199}
200
202 uint32_t Flags) const {
203 MI.setFlags(Flags);
207}
208
209// This function does not list all associative and commutative operations, but
210// only those worth feeding through the machine combiner in an attempt to
211// reduce the critical path. Mostly, this means floating-point operations,
212// because they have high latencies(>=5) (compared to other operations, such as
213// and/or, which are also associative and commutative, but have low latencies).
215 bool Invert) const {
216 if (Invert)
217 return false;
218 switch (Inst.getOpcode()) {
219 // Floating point:
220 // FP Add:
221 case PPC::FADD:
222 case PPC::FADDS:
223 // FP Multiply:
224 case PPC::FMUL:
225 case PPC::FMULS:
226 // Altivec Add:
227 case PPC::VADDFP:
228 // VSX Add:
229 case PPC::XSADDDP:
230 case PPC::XVADDDP:
231 case PPC::XVADDSP:
232 case PPC::XSADDSP:
233 // VSX Multiply:
234 case PPC::XSMULDP:
235 case PPC::XVMULDP:
236 case PPC::XVMULSP:
237 case PPC::XSMULSP:
240 // Fixed point:
241 // Multiply:
242 case PPC::MULHD:
243 case PPC::MULLD:
244 case PPC::MULHW:
245 case PPC::MULLW:
246 return true;
247 default:
248 return false;
249 }
250}
251
252#define InfoArrayIdxFMAInst 0
253#define InfoArrayIdxFAddInst 1
254#define InfoArrayIdxFMULInst 2
255#define InfoArrayIdxAddOpIdx 3
256#define InfoArrayIdxMULOpIdx 4
257#define InfoArrayIdxFSubInst 5
258// Array keeps info for FMA instructions:
259// Index 0(InfoArrayIdxFMAInst): FMA instruction;
260// Index 1(InfoArrayIdxFAddInst): ADD instruction associated with FMA;
261// Index 2(InfoArrayIdxFMULInst): MUL instruction associated with FMA;
262// Index 3(InfoArrayIdxAddOpIdx): ADD operand index in FMA operands;
263// Index 4(InfoArrayIdxMULOpIdx): first MUL operand index in FMA operands;
264// second MUL operand index is plus 1;
265// Index 5(InfoArrayIdxFSubInst): SUB instruction associated with FMA.
266static const uint16_t FMAOpIdxInfo[][6] = {
267 // FIXME: Add more FMA instructions like XSNMADDADP and so on.
268 {PPC::XSMADDADP, PPC::XSADDDP, PPC::XSMULDP, 1, 2, PPC::XSSUBDP},
269 {PPC::XSMADDASP, PPC::XSADDSP, PPC::XSMULSP, 1, 2, PPC::XSSUBSP},
270 {PPC::XVMADDADP, PPC::XVADDDP, PPC::XVMULDP, 1, 2, PPC::XVSUBDP},
271 {PPC::XVMADDASP, PPC::XVADDSP, PPC::XVMULSP, 1, 2, PPC::XVSUBSP},
272 {PPC::FMADD, PPC::FADD, PPC::FMUL, 3, 1, PPC::FSUB},
273 {PPC::FMADDS, PPC::FADDS, PPC::FMULS, 3, 1, PPC::FSUBS}};
274
275// Check if an opcode is a FMA instruction. If it is, return the index in array
276// FMAOpIdxInfo. Otherwise, return -1.
277int16_t PPCInstrInfo::getFMAOpIdxInfo(unsigned Opcode) const {
278 for (unsigned I = 0; I < std::size(FMAOpIdxInfo); I++)
279 if (FMAOpIdxInfo[I][InfoArrayIdxFMAInst] == Opcode)
280 return I;
281 return -1;
282}
283
284// On PowerPC target, we have two kinds of patterns related to FMA:
285// 1: Improve ILP.
286// Try to reassociate FMA chains like below:
287//
288// Pattern 1:
289// A = FADD X, Y (Leaf)
290// B = FMA A, M21, M22 (Prev)
291// C = FMA B, M31, M32 (Root)
292// -->
293// A = FMA X, M21, M22
294// B = FMA Y, M31, M32
295// C = FADD A, B
296//
297// Pattern 2:
298// A = FMA X, M11, M12 (Leaf)
299// B = FMA A, M21, M22 (Prev)
300// C = FMA B, M31, M32 (Root)
301// -->
302// A = FMUL M11, M12
303// B = FMA X, M21, M22
304// D = FMA A, M31, M32
305// C = FADD B, D
306//
307// breaking the dependency between A and B, allowing FMA to be executed in
308// parallel (or back-to-back in a pipeline) instead of depending on each other.
309//
310// 2: Reduce register pressure.
311// Try to reassociate FMA with FSUB and a constant like below:
312// C is a floating point const.
313//
314// Pattern 1:
315// A = FSUB X, Y (Leaf)
316// D = FMA B, C, A (Root)
317// -->
318// A = FMA B, Y, -C
319// D = FMA A, X, C
320//
321// Pattern 2:
322// A = FSUB X, Y (Leaf)
323// D = FMA B, A, C (Root)
324// -->
325// A = FMA B, Y, -C
326// D = FMA A, X, C
327//
328// Before the transformation, A must be assigned with different hardware
329// register with D. After the transformation, A and D must be assigned with
330// same hardware register due to TIE attribute of FMA instructions.
331//
334 bool DoRegPressureReduce) const {
336 const MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
337
338 auto IsAllOpsVirtualReg = [](const MachineInstr &Instr) {
339 for (const auto &MO : Instr.explicit_operands())
340 if (!(MO.isReg() && MO.getReg().isVirtual()))
341 return false;
342 return true;
343 };
344
345 auto IsReassociableAddOrSub = [&](const MachineInstr &Instr,
346 unsigned OpType) {
347 if (Instr.getOpcode() !=
348 FMAOpIdxInfo[getFMAOpIdxInfo(Root.getOpcode())][OpType])
349 return false;
350
351 // Instruction can be reassociated.
352 // fast math flags may prohibit reassociation.
353 if (!(Instr.getFlag(MachineInstr::MIFlag::FmReassoc) &&
354 Instr.getFlag(MachineInstr::MIFlag::FmNsz)))
355 return false;
356
357 // Instruction operands are virtual registers for reassociation.
358 if (!IsAllOpsVirtualReg(Instr))
359 return false;
360
361 // For register pressure reassociation, the FSub must have only one use as
362 // we want to delete the sub to save its def.
363 if (OpType == InfoArrayIdxFSubInst &&
364 !MRI->hasOneNonDBGUse(Instr.getOperand(0).getReg()))
365 return false;
366
367 return true;
368 };
369
370 auto IsReassociableFMA = [&](const MachineInstr &Instr, int16_t &AddOpIdx,
371 int16_t &MulOpIdx, bool IsLeaf) {
372 int16_t Idx = getFMAOpIdxInfo(Instr.getOpcode());
373 if (Idx < 0)
374 return false;
375
376 // Instruction can be reassociated.
377 // fast math flags may prohibit reassociation.
378 if (!(Instr.getFlag(MachineInstr::MIFlag::FmReassoc) &&
379 Instr.getFlag(MachineInstr::MIFlag::FmNsz)))
380 return false;
381
382 // Instruction operands are virtual registers for reassociation.
383 if (!IsAllOpsVirtualReg(Instr))
384 return false;
385
386 MulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
387 if (IsLeaf)
388 return true;
389
390 AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
391
392 const MachineOperand &OpAdd = Instr.getOperand(AddOpIdx);
393 MachineInstr *MIAdd = MRI->getUniqueVRegDef(OpAdd.getReg());
394 // If 'add' operand's def is not in current block, don't do ILP related opt.
395 if (!MIAdd || MIAdd->getParent() != MBB)
396 return false;
397
398 // If this is not Leaf FMA Instr, its 'add' operand should only have one use
399 // as this fma will be changed later.
400 return MRI->hasOneNonDBGUse(OpAdd.getReg());
401 };
402
403 int16_t AddOpIdx = -1;
404 int16_t MulOpIdx = -1;
405
406 bool IsUsedOnceL = false;
407 bool IsUsedOnceR = false;
408 MachineInstr *MULInstrL = nullptr;
409 MachineInstr *MULInstrR = nullptr;
410
411 auto IsRPReductionCandidate = [&]() {
412 // Currently, we only support float and double.
413 // FIXME: add support for other types.
414 unsigned Opcode = Root.getOpcode();
415 if (Opcode != PPC::XSMADDASP && Opcode != PPC::XSMADDADP)
416 return false;
417
418 // Root must be a valid FMA like instruction.
419 // Treat it as leaf as we don't care its add operand.
420 if (IsReassociableFMA(Root, AddOpIdx, MulOpIdx, true)) {
421 assert((MulOpIdx >= 0) && "mul operand index not right!");
422 Register MULRegL = RI.lookThruSingleUseCopyChain(
423 Root.getOperand(MulOpIdx).getReg(), MRI);
424 Register MULRegR = RI.lookThruSingleUseCopyChain(
425 Root.getOperand(MulOpIdx + 1).getReg(), MRI);
426 if (!MULRegL && !MULRegR)
427 return false;
428
429 if (MULRegL && !MULRegR) {
430 MULRegR =
431 RI.lookThruCopyLike(Root.getOperand(MulOpIdx + 1).getReg(), MRI);
432 IsUsedOnceL = true;
433 } else if (!MULRegL && MULRegR) {
434 MULRegL = RI.lookThruCopyLike(Root.getOperand(MulOpIdx).getReg(), MRI);
435 IsUsedOnceR = true;
436 } else {
437 IsUsedOnceL = true;
438 IsUsedOnceR = true;
439 }
440
441 if (!MULRegL.isVirtual() || !MULRegR.isVirtual())
442 return false;
443
444 MULInstrL = MRI->getVRegDef(MULRegL);
445 MULInstrR = MRI->getVRegDef(MULRegR);
446 return MULInstrL && MULInstrR;
447 }
448 return false;
449 };
450
451 // Register pressure fma reassociation patterns.
452 if (DoRegPressureReduce && IsRPReductionCandidate()) {
453 assert((MULInstrL && MULInstrR) && "wrong register preduction candidate!");
454 // Register pressure pattern 1
455 if (isLoadFromConstantPool(MULInstrL) && IsUsedOnceR &&
456 IsReassociableAddOrSub(*MULInstrR, InfoArrayIdxFSubInst)) {
457 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_BCA\n");
459 return true;
460 }
461
462 // Register pressure pattern 2
463 if ((isLoadFromConstantPool(MULInstrR) && IsUsedOnceL &&
464 IsReassociableAddOrSub(*MULInstrL, InfoArrayIdxFSubInst))) {
465 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_BAC\n");
467 return true;
468 }
469 }
470
471 // ILP fma reassociation patterns.
472 // Root must be a valid FMA like instruction.
473 AddOpIdx = -1;
474 if (!IsReassociableFMA(Root, AddOpIdx, MulOpIdx, false))
475 return false;
476
477 assert((AddOpIdx >= 0) && "add operand index not right!");
478
479 Register RegB = Root.getOperand(AddOpIdx).getReg();
480 MachineInstr *Prev = MRI->getUniqueVRegDef(RegB);
481
482 // Prev must be a valid FMA like instruction.
483 AddOpIdx = -1;
484 if (!IsReassociableFMA(*Prev, AddOpIdx, MulOpIdx, false))
485 return false;
486
487 assert((AddOpIdx >= 0) && "add operand index not right!");
488
489 Register RegA = Prev->getOperand(AddOpIdx).getReg();
490 MachineInstr *Leaf = MRI->getUniqueVRegDef(RegA);
491 AddOpIdx = -1;
492 if (IsReassociableFMA(*Leaf, AddOpIdx, MulOpIdx, true)) {
494 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XMM_AMM_BMM\n");
495 return true;
496 }
497 if (IsReassociableAddOrSub(*Leaf, InfoArrayIdxFAddInst)) {
499 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_AMM_BMM\n");
500 return true;
501 }
502 return false;
503}
504
506 MachineInstr &Root, unsigned &Pattern,
507 SmallVectorImpl<MachineInstr *> &InsInstrs) const {
508 assert(!InsInstrs.empty() && "Instructions set to be inserted is empty!");
509
510 MachineFunction *MF = Root.getMF();
513
514 int16_t Idx = getFMAOpIdxInfo(Root.getOpcode());
515 if (Idx < 0)
516 return;
517
518 uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
519
520 // For now we only need to fix up placeholder for register pressure reduce
521 // patterns.
522 Register ConstReg = 0;
523 switch (Pattern) {
525 ConstReg =
526 RI.lookThruCopyLike(Root.getOperand(FirstMulOpIdx).getReg(), MRI);
527 break;
529 ConstReg =
530 RI.lookThruCopyLike(Root.getOperand(FirstMulOpIdx + 1).getReg(), MRI);
531 break;
532 default:
533 // Not register pressure reduce patterns.
534 return;
535 }
536
537 MachineInstr *ConstDefInstr = MRI->getVRegDef(ConstReg);
538 // Get const value from const pool.
539 const Constant *C = getConstantFromConstantPool(ConstDefInstr);
540 assert(isa<llvm::ConstantFP>(C) && "not a valid constant!");
541
542 // Get negative fp const.
543 APFloat F1((dyn_cast<ConstantFP>(C))->getValueAPF());
544 F1.changeSign();
545 Constant *NegC = ConstantFP::get(dyn_cast<ConstantFP>(C)->getContext(), F1);
546 Align Alignment = MF->getDataLayout().getPrefTypeAlign(C->getType());
547
548 // Put negative fp const into constant pool.
549 unsigned ConstPoolIdx = MCP->getConstantPoolIndex(NegC, Alignment);
550
551 MachineOperand *Placeholder = nullptr;
552 // Record the placeholder PPC::ZERO8 we add in reassociateFMA.
553 for (auto *Inst : InsInstrs) {
554 for (MachineOperand &Operand : Inst->explicit_operands()) {
555 assert(Operand.isReg() && "Invalid instruction in InsInstrs!");
556 if (Operand.getReg() == PPC::ZERO8) {
557 Placeholder = &Operand;
558 break;
559 }
560 }
561 }
562
563 assert(Placeholder && "Placeholder does not exist!");
564
565 // Generate instructions to load the const fp from constant pool.
566 // We only support PPC64 and medium code model.
567 Register LoadNewConst =
568 generateLoadForNewConst(ConstPoolIdx, &Root, C->getType(), InsInstrs);
569
570 // Fill the placeholder with the new load from constant pool.
571 Placeholder->setReg(LoadNewConst);
572}
573
575 const MachineBasicBlock *MBB, const RegisterClassInfo *RegClassInfo) const {
576
577 if (!Subtarget.getCLOpts().fma_rp_reduction)
578 return false;
579
580 // Currently, we only enable register pressure reducing in machine combiner
581 // for: 1: PPC64; 2: Code Model is Medium; 3: Power9 which also has vector
582 // support.
583 //
584 // So we need following instructions to access a TOC entry:
585 //
586 // %6:g8rc_and_g8rc_nox0 = ADDIStocHA8 $x2, %const.0
587 // %7:vssrc = DFLOADf32 target-flags(ppc-toc-lo) %const.0,
588 // killed %6:g8rc_and_g8rc_nox0, implicit $x2 :: (load 4 from constant-pool)
589 //
590 // FIXME: add more supported targets, like Small and Large code model, PPC32,
591 // AIX.
592 if (!(Subtarget.isPPC64() && Subtarget.hasP9Vector() &&
593 Subtarget.getTargetMachine().getCodeModel() == CodeModel::Medium))
594 return false;
595
596 const MachineFunction *MF = MBB->getParent();
597 const MachineRegisterInfo *MRI = &MF->getRegInfo();
598
599 auto GetMBBPressure =
600 [&](const MachineBasicBlock *MBB) -> std::vector<unsigned> {
601 RegionPressure Pressure;
602 RegPressureTracker RPTracker(Pressure);
603
604 // Initialize the register pressure tracker.
605 RPTracker.init(MBB->getParent(), RegClassInfo, nullptr, MBB, MBB->end(),
606 /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
607
608 for (const auto &MI : reverse(*MBB)) {
609 if (MI.isDebugValue() || MI.isDebugLabel())
610 continue;
611 RegisterOperands RegOpers;
612 RegOpers.collect(MI, RI, *MRI, false, false);
613 RPTracker.recedeSkipDebugValues();
614 assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
615 RPTracker.recede(RegOpers);
616 }
617
618 // Close the RPTracker to finalize live ins.
619 RPTracker.closeRegion();
620
621 return RPTracker.getPressure().MaxSetPressure;
622 };
623
624 // For now we only care about float and double type fma.
625 unsigned VSSRCLimit =
626 RegClassInfo->getRegPressureSetLimit(PPC::RegisterPressureSets::VSSRC);
627
628 // Only reduce register pressure when pressure is high.
629 return GetMBBPressure(MBB)[PPC::RegisterPressureSets::VSSRC] >
630 (float)VSSRCLimit * Subtarget.getCLOpts().fma_rp_factor;
631}
632
634 // I has only one memory operand which is load from constant pool.
635 if (!I->hasOneMemOperand())
636 return false;
637
638 MachineMemOperand *Op = I->memoperands()[0];
639 return Op->isLoad() && Op->getPseudoValue() &&
640 Op->getPseudoValue()->kind() == PseudoSourceValue::ConstantPool;
641}
642
643Register PPCInstrInfo::generateLoadForNewConst(
644 unsigned Idx, MachineInstr *MI, Type *Ty,
645 SmallVectorImpl<MachineInstr *> &InsInstrs) const {
646 // Now we only support PPC64, Medium code model and P9 with vector.
647 // We have immutable pattern to access const pool. See function
648 // shouldReduceRegisterPressure.
649 assert((Subtarget.isPPC64() && Subtarget.hasP9Vector() &&
650 Subtarget.getTargetMachine().getCodeModel() == CodeModel::Medium) &&
651 "Target not supported!\n");
652
653 MachineFunction *MF = MI->getMF();
655
656 // Generate ADDIStocHA8
657 Register VReg1 = MRI->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
658 MachineInstrBuilder TOCOffset =
659 BuildMI(*MF, MI->getDebugLoc(), get(PPC::ADDIStocHA8), VReg1)
660 .addReg(PPC::X2)
662
663 assert((Ty->isFloatTy() || Ty->isDoubleTy()) &&
664 "Only float and double are supported!");
665
666 unsigned LoadOpcode;
667 // Should be float type or double type.
668 if (Ty->isFloatTy())
669 LoadOpcode = PPC::DFLOADf32;
670 else
671 LoadOpcode = PPC::DFLOADf64;
672
673 const TargetRegisterClass *RC = MRI->getRegClass(MI->getOperand(0).getReg());
674 Register VReg2 = MRI->createVirtualRegister(RC);
677 Ty->getScalarSizeInBits() / 8, MF->getDataLayout().getPrefTypeAlign(Ty));
678
679 // Generate Load from constant pool.
681 BuildMI(*MF, MI->getDebugLoc(), get(LoadOpcode), VReg2)
683 .addReg(VReg1)
684 .addMemOperand(MMO);
685
686 Load->getOperand(1).setTargetFlags(PPCII::MO_TOC_LO);
687
688 // Insert the toc load instructions into InsInstrs.
689 InsInstrs.insert(InsInstrs.begin(), Load);
690 InsInstrs.insert(InsInstrs.begin(), TOCOffset);
691 return VReg2;
692}
693
694// This function returns the const value in constant pool if the \p I is a load
695// from constant pool.
696const Constant *
698 MachineFunction *MF = I->getMF();
701 assert(I->mayLoad() && "Should be a load instruction.\n");
702 for (auto MO : I->uses()) {
703 if (!MO.isReg())
704 continue;
705 Register Reg = MO.getReg();
706 if (Reg == 0 || !Reg.isVirtual())
707 continue;
708 // Find the toc address.
709 MachineInstr *DefMI = MRI->getVRegDef(Reg);
710 for (auto MO2 : DefMI->uses())
711 if (MO2.isCPI())
712 return (MCP->getConstants())[MO2.getIndex()].Val.ConstVal;
713 }
714 return nullptr;
715}
716
729
732 bool DoRegPressureReduce) const {
733 // Using the machine combiner in this way is potentially expensive, so
734 // restrict to when aggressive optimizations are desired.
735 if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOptLevel::Aggressive)
736 return false;
737
738 if (getFMAPatterns(Root, Patterns, DoRegPressureReduce))
739 return true;
740
742 DoRegPressureReduce);
743}
744
746 MachineInstr &Root, unsigned Pattern,
749 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
750 switch (Pattern) {
755 reassociateFMA(Root, Pattern, InsInstrs, DelInstrs, InstrIdxForVirtReg);
756 break;
757 default:
758 // Reassociate default patterns.
760 DelInstrs, InstrIdxForVirtReg);
761 break;
762 }
763}
764
765void PPCInstrInfo::reassociateFMA(
766 MachineInstr &Root, unsigned Pattern,
769 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
770 MachineFunction *MF = Root.getMF();
772 MachineOperand &OpC = Root.getOperand(0);
773 Register RegC = OpC.getReg();
774 const TargetRegisterClass *RC = MRI.getRegClass(RegC);
775 MRI.constrainRegClass(RegC, RC);
776
777 unsigned FmaOp = Root.getOpcode();
778 int16_t Idx = getFMAOpIdxInfo(FmaOp);
779 assert(Idx >= 0 && "Root must be a FMA instruction");
780
781 bool IsILPReassociate =
784
785 uint16_t AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
786 uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
787
788 MachineInstr *Prev = nullptr;
789 MachineInstr *Leaf = nullptr;
790 switch (Pattern) {
791 default:
792 llvm_unreachable("not recognized pattern!");
795 Prev = MRI.getUniqueVRegDef(Root.getOperand(AddOpIdx).getReg());
796 Leaf = MRI.getUniqueVRegDef(Prev->getOperand(AddOpIdx).getReg());
797 break;
799 Register MULReg =
800 RI.lookThruCopyLike(Root.getOperand(FirstMulOpIdx).getReg(), &MRI);
801 Leaf = MRI.getVRegDef(MULReg);
802 break;
803 }
805 Register MULReg =
806 RI.lookThruCopyLike(Root.getOperand(FirstMulOpIdx + 1).getReg(), &MRI);
807 Leaf = MRI.getVRegDef(MULReg);
808 break;
809 }
810 }
811
812 uint32_t IntersectedFlags = 0;
813 if (IsILPReassociate)
814 IntersectedFlags = Root.getFlags() & Prev->getFlags() & Leaf->getFlags();
815 else
816 IntersectedFlags = Root.getFlags() & Leaf->getFlags();
817
818 auto GetOperandInfo = [&](const MachineOperand &Operand, Register &Reg) {
819 Reg = Operand.getReg();
821 };
822
823 auto GetFMAInstrInfo = [&](const MachineInstr &Instr, Register &MulOp1,
824 Register &MulOp2, Register &AddOp) {
825 GetOperandInfo(Instr.getOperand(FirstMulOpIdx), MulOp1);
826 GetOperandInfo(Instr.getOperand(FirstMulOpIdx + 1), MulOp2);
827 GetOperandInfo(Instr.getOperand(AddOpIdx), AddOp);
828 };
829
830 Register RegM11, RegM12, RegX, RegY, RegM21, RegM22, RegM31, RegM32, RegA11,
831 RegA21, RegB;
832
833 GetFMAInstrInfo(Root, RegM31, RegM32, RegB);
834
835 if (IsILPReassociate)
836 GetFMAInstrInfo(*Prev, RegM21, RegM22, RegA21);
837
839 GetFMAInstrInfo(*Leaf, RegM11, RegM12, RegA11);
840 GetOperandInfo(Leaf->getOperand(AddOpIdx), RegX);
841 } else if (Pattern == PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM) {
842 GetOperandInfo(Leaf->getOperand(1), RegX);
843 GetOperandInfo(Leaf->getOperand(2), RegY);
844 } else {
845 // Get FSUB instruction info.
846 GetOperandInfo(Leaf->getOperand(1), RegX);
847 GetOperandInfo(Leaf->getOperand(2), RegY);
848 }
849
850 // Create new virtual registers for the new results instead of
851 // recycling legacy ones because the MachineCombiner's computation of the
852 // critical path requires a new register definition rather than an existing
853 // one.
854 // For register pressure reassociation, we only need create one virtual
855 // register for the new fma.
857 InstrIdxForVirtReg.insert(std::make_pair(NewVRA, 0));
858
859 Register NewVRB = 0;
860 if (IsILPReassociate) {
861 NewVRB = MRI.createVirtualRegister(RC);
862 InstrIdxForVirtReg.insert(std::make_pair(NewVRB, 1));
863 }
864
865 Register NewVRD = 0;
867 NewVRD = MRI.createVirtualRegister(RC);
868 InstrIdxForVirtReg.insert(std::make_pair(NewVRD, 2));
869 }
870
871 auto AdjustOperandOrder = [&](MachineInstr *MI, Register RegAdd,
872 Register RegMul1, Register RegMul2) {
873 MI->getOperand(AddOpIdx).setReg(RegAdd);
874 MI->getOperand(FirstMulOpIdx).setReg(RegMul1);
875 MI->getOperand(FirstMulOpIdx + 1).setReg(RegMul2);
876 };
877
878 MachineInstrBuilder NewARegPressure, NewCRegPressure;
879 switch (Pattern) {
880 default:
881 llvm_unreachable("not recognized pattern!");
883 // Create new instructions for insertion.
884 MachineInstrBuilder MINewB =
885 BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB)
886 .addReg(RegX)
887 .addReg(RegM21)
888 .addReg(RegM22);
889 MachineInstrBuilder MINewA =
890 BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRA)
891 .addReg(RegY)
892 .addReg(RegM31)
893 .addReg(RegM32);
894 // If AddOpIdx is not 1, adjust the order.
895 if (AddOpIdx != 1) {
896 AdjustOperandOrder(MINewB, RegX, RegM21, RegM22);
897 AdjustOperandOrder(MINewA, RegY, RegM31, RegM32);
898 }
899
900 MachineInstrBuilder MINewC =
901 BuildMI(*MF, Root.getDebugLoc(),
903 .addReg(NewVRB)
904 .addReg(NewVRA);
905
906 // Update flags for newly created instructions.
907 setSpecialOperandAttr(*MINewA, IntersectedFlags);
908 setSpecialOperandAttr(*MINewB, IntersectedFlags);
909 setSpecialOperandAttr(*MINewC, IntersectedFlags);
910
911 // Record new instructions for insertion.
912 InsInstrs.push_back(MINewA);
913 InsInstrs.push_back(MINewB);
914 InsInstrs.push_back(MINewC);
915 break;
916 }
918 assert(NewVRD && "new FMA register not created!");
919 // Create new instructions for insertion.
920 MachineInstrBuilder MINewA =
921 BuildMI(*MF, Leaf->getDebugLoc(),
923 .addReg(RegM11)
924 .addReg(RegM12);
925 MachineInstrBuilder MINewB =
926 BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB)
927 .addReg(RegX)
928 .addReg(RegM21)
929 .addReg(RegM22);
930 MachineInstrBuilder MINewD =
931 BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRD)
932 .addReg(NewVRA)
933 .addReg(RegM31)
934 .addReg(RegM32);
935 // If AddOpIdx is not 1, adjust the order.
936 if (AddOpIdx != 1) {
937 AdjustOperandOrder(MINewB, RegX, RegM21, RegM22);
938 AdjustOperandOrder(MINewD, NewVRA, RegM31, RegM32);
939 }
940
941 MachineInstrBuilder MINewC =
942 BuildMI(*MF, Root.getDebugLoc(),
944 .addReg(NewVRB)
945 .addReg(NewVRD);
946
947 // Update flags for newly created instructions.
948 setSpecialOperandAttr(*MINewA, IntersectedFlags);
949 setSpecialOperandAttr(*MINewB, IntersectedFlags);
950 setSpecialOperandAttr(*MINewD, IntersectedFlags);
951 setSpecialOperandAttr(*MINewC, IntersectedFlags);
952
953 // Record new instructions for insertion.
954 InsInstrs.push_back(MINewA);
955 InsInstrs.push_back(MINewB);
956 InsInstrs.push_back(MINewD);
957 InsInstrs.push_back(MINewC);
958 break;
959 }
962 Register VarReg =
963 Pattern == PPCMachineCombinerPattern::REASSOC_XY_BCA ? RegM31 : RegM32;
964 // We don't want to get negative const from memory pool too early, as the
965 // created entry will not be deleted even if it has no users. Since all
966 // operand of Leaf and Root are virtual register, we use zero register
967 // here as a placeholder. When the InsInstrs is selected in
968 // MachineCombiner, we call finalizeInsInstrs to replace the zero register
969 // with a virtual register which is a load from constant pool.
970 NewARegPressure = BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRA)
971 .addReg(RegB)
972 .addReg(RegY)
973 .addReg(PPC::ZERO8);
974 NewCRegPressure = BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), RegC)
975 .addReg(NewVRA)
976 .addReg(RegX)
977 .addReg(VarReg);
978 // For now, we only support xsmaddadp/xsmaddasp, their add operand are
979 // both at index 1, no need to adjust.
980 // FIXME: when add more fma instructions support, like fma/fmas, adjust
981 // the operand index here.
982 break;
983 }
984 }
985
986 if (!IsILPReassociate) {
987 setSpecialOperandAttr(*NewARegPressure, IntersectedFlags);
988 setSpecialOperandAttr(*NewCRegPressure, IntersectedFlags);
989
990 InsInstrs.push_back(NewARegPressure);
991 InsInstrs.push_back(NewCRegPressure);
992 }
993
994 assert(!InsInstrs.empty() &&
995 "Insertion instructions set should not be empty!");
996
997 // Record old instructions for deletion.
998 DelInstrs.push_back(Leaf);
999 if (IsILPReassociate)
1000 DelInstrs.push_back(Prev);
1001 DelInstrs.push_back(&Root);
1002}
1003
1004// Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
1006 Register &SrcReg, Register &DstReg,
1007 unsigned &SubIdx) const {
1008 switch (MI.getOpcode()) {
1009 default: return false;
1010 case PPC::EXTSW:
1011 case PPC::EXTSW_32:
1012 case PPC::EXTSW_32_64:
1013 SrcReg = MI.getOperand(1).getReg();
1014 DstReg = MI.getOperand(0).getReg();
1015 SubIdx = PPC::sub_32;
1016 return true;
1017 }
1018}
1019
1021 int &FrameIndex) const {
1022 if (llvm::is_contained(getLoadOpcodesForSpillArray(), MI.getOpcode())) {
1023 // Check for the operands added by addFrameReference (the immediate is the
1024 // offset which defaults to 0).
1025 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
1026 MI.getOperand(2).isFI()) {
1027 FrameIndex = MI.getOperand(2).getIndex();
1028 return MI.getOperand(0).getReg();
1029 }
1030 }
1031 return 0;
1032}
1033
1034// For opcodes with the ReMaterializable flag set, this function is called to
1035// verify the instruction is really rematable.
1037 const MachineInstr &MI) const {
1038 switch (MI.getOpcode()) {
1039 default:
1040 // Let base implementaion decide.
1041 break;
1042 case PPC::LI:
1043 case PPC::LI8:
1044 case PPC::PLI:
1045 case PPC::PLI8:
1046 case PPC::LIS:
1047 case PPC::LIS8:
1048 case PPC::ADDIStocHA:
1049 case PPC::ADDIStocHA8:
1050 case PPC::ADDItocL:
1051 case PPC::ADDItocL8:
1052 case PPC::LOAD_STACK_GUARD:
1053 case PPC::PPCLdFixedAddr:
1054 case PPC::XXLXORz:
1055 case PPC::XXLXORspz:
1056 case PPC::XXLXORdpz:
1057 case PPC::XXLEQVOnes:
1058 case PPC::XXSPLTI32DX:
1059 case PPC::XXSPLTIW:
1060 case PPC::XXSPLTIDP:
1061 case PPC::V_SET0B:
1062 case PPC::V_SET0H:
1063 case PPC::V_SET0:
1064 case PPC::V_SETALLONESB:
1065 case PPC::V_SETALLONESH:
1066 case PPC::V_SETALLONES:
1067 case PPC::CRSET:
1068 case PPC::CRUNSET:
1069 case PPC::XXSETACCZ:
1070 case PPC::DMXXSETACCZ:
1071 return true;
1072 }
1074}
1075
1077 int &FrameIndex) const {
1078 if (llvm::is_contained(getStoreOpcodesForSpillArray(), MI.getOpcode())) {
1079 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
1080 MI.getOperand(2).isFI()) {
1081 FrameIndex = MI.getOperand(2).getIndex();
1082 return MI.getOperand(0).getReg();
1083 }
1084 }
1085 return 0;
1086}
1087
1089 unsigned OpIdx1,
1090 unsigned OpIdx2) const {
1091 MachineFunction &MF = *MI.getParent()->getParent();
1092
1093 // Normal instructions can be commuted the obvious way.
1094 if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec)
1095 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
1096 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
1097 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
1098 // changing the relative order of the mask operands might change what happens
1099 // to the high-bits of the mask (and, thus, the result).
1100
1101 // Cannot commute if it has a non-zero rotate count.
1102 if (MI.getOperand(3).getImm() != 0)
1103 return nullptr;
1104
1105 // If we have a zero rotate count, we have:
1106 // M = mask(MB,ME)
1107 // Op0 = (Op1 & ~M) | (Op2 & M)
1108 // Change this to:
1109 // M = mask((ME+1)&31, (MB-1)&31)
1110 // Op0 = (Op2 & ~M) | (Op1 & M)
1111
1112 // Swap op1/op2
1113 assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
1114 "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec.");
1115 Register Reg0 = MI.getOperand(0).getReg();
1116 Register Reg1 = MI.getOperand(1).getReg();
1117 Register Reg2 = MI.getOperand(2).getReg();
1118 unsigned SubReg1 = MI.getOperand(1).getSubReg();
1119 unsigned SubReg2 = MI.getOperand(2).getSubReg();
1120 bool Reg1IsKill = MI.getOperand(1).isKill();
1121 bool Reg2IsKill = MI.getOperand(2).isKill();
1122 bool ChangeReg0 = false;
1123 // If machine instrs are no longer in two-address forms, update
1124 // destination register as well.
1125 if (Reg0 == Reg1) {
1126 // Must be two address instruction (i.e. op1 is tied to op0).
1127 assert(MI.getDesc().getOperandConstraint(1, MCOI::TIED_TO) == 0 &&
1128 "Expecting a two-address instruction!");
1129 assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
1130 Reg2IsKill = false;
1131 ChangeReg0 = true;
1132 }
1133
1134 // Masks.
1135 unsigned MB = MI.getOperand(4).getImm();
1136 unsigned ME = MI.getOperand(5).getImm();
1137
1138 // We can't commute a trivial mask (there is no way to represent an all-zero
1139 // mask).
1140 if (MB == 0 && ME == 31)
1141 return nullptr;
1142
1143 if (NewMI) {
1144 // Create a new instruction.
1145 Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
1146 bool Reg0IsDead = MI.getOperand(0).isDead();
1147 return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
1148 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
1149 .addReg(Reg2, getKillRegState(Reg2IsKill))
1150 .addReg(Reg1, getKillRegState(Reg1IsKill))
1151 .addImm((ME + 1) & 31)
1152 .addImm((MB - 1) & 31);
1153 }
1154
1155 if (ChangeReg0) {
1156 MI.getOperand(0).setReg(Reg2);
1157 MI.getOperand(0).setSubReg(SubReg2);
1158 }
1159 MI.getOperand(2).setReg(Reg1);
1160 MI.getOperand(1).setReg(Reg2);
1161 MI.getOperand(2).setSubReg(SubReg1);
1162 MI.getOperand(1).setSubReg(SubReg2);
1163 MI.getOperand(2).setIsKill(Reg1IsKill);
1164 MI.getOperand(1).setIsKill(Reg2IsKill);
1165
1166 // Swap the mask around.
1167 MI.getOperand(4).setImm((ME + 1) & 31);
1168 MI.getOperand(5).setImm((MB - 1) & 31);
1169 return &MI;
1170}
1171
1173 unsigned &SrcOpIdx1,
1174 unsigned &SrcOpIdx2) const {
1175 // For VSX A-Type FMA instructions, it is the first two operands that can be
1176 // commuted, however, because the non-encoded tied input operand is listed
1177 // first, the operands to swap are actually the second and third.
1178
1179 int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
1180 if (AltOpc == -1)
1181 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
1182
1183 // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
1184 // and SrcOpIdx2.
1185 return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
1186}
1187
1190 // This function is used for scheduling, and the nop wanted here is the type
1191 // that terminates dispatch groups on the POWER cores.
1192 unsigned Directive = Subtarget.getCPUDirective();
1193 unsigned Opcode;
1194 switch (Directive) {
1195 default: Opcode = PPC::NOP; break;
1196 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
1197 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
1198 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
1199 // FIXME: Update when POWER9 scheduling model is ready.
1200 case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
1201 }
1202
1203 DebugLoc DL;
1204 BuildMI(MBB, MI, DL, get(Opcode));
1205}
1206
1207/// Return the noop instruction to use for a noop.
1209 MCInst Nop;
1210 Nop.setOpcode(PPC::NOP);
1211 return Nop;
1212}
1213
1214// Branch analysis.
1215// Note: If the condition register is set to CTR or CTR8 then this is a
1216// BDNZ (imm == 1) or BDZ (imm == 0) branch.
1219 MachineBasicBlock *&FBB,
1221 bool AllowModify) const {
1222 bool isPPC64 = Subtarget.isPPC64();
1223
1224 // If the block has no terminators, it just falls into the block after it.
1225 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1226 if (I == MBB.end())
1227 return false;
1228
1229 if (!isUnpredicatedTerminator(*I))
1230 return false;
1231
1232 if (AllowModify) {
1233 // If the BB ends with an unconditional branch to the fallthrough BB,
1234 // we eliminate the branch instruction.
1235 if (I->getOpcode() == PPC::B &&
1236 MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
1237 I->eraseFromParent();
1238
1239 // We update iterator after deleting the last branch.
1240 I = MBB.getLastNonDebugInstr();
1241 if (I == MBB.end() || !isUnpredicatedTerminator(*I))
1242 return false;
1243 }
1244 }
1245
1246 // Get the last instruction in the block.
1247 MachineInstr &LastInst = *I;
1248
1249 // If there is only one terminator instruction, process it.
1250 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
1251 if (LastInst.getOpcode() == PPC::B) {
1252 if (!LastInst.getOperand(0).isMBB())
1253 return true;
1254 TBB = LastInst.getOperand(0).getMBB();
1255 return false;
1256 } else if (LastInst.getOpcode() == PPC::BCC) {
1257 if (!LastInst.getOperand(2).isMBB())
1258 return true;
1259 // Block ends with fall-through condbranch.
1260 TBB = LastInst.getOperand(2).getMBB();
1261 Cond.push_back(LastInst.getOperand(0));
1262 Cond.push_back(LastInst.getOperand(1));
1263 return false;
1264 } else if (LastInst.getOpcode() == PPC::BC) {
1265 if (!LastInst.getOperand(1).isMBB())
1266 return true;
1267 // Block ends with fall-through condbranch.
1268 TBB = LastInst.getOperand(1).getMBB();
1270 Cond.push_back(LastInst.getOperand(0));
1271 return false;
1272 } else if (LastInst.getOpcode() == PPC::BCn) {
1273 if (!LastInst.getOperand(1).isMBB())
1274 return true;
1275 // Block ends with fall-through condbranch.
1276 TBB = LastInst.getOperand(1).getMBB();
1278 Cond.push_back(LastInst.getOperand(0));
1279 return false;
1280 } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
1281 LastInst.getOpcode() == PPC::BDNZ) {
1282 if (!LastInst.getOperand(0).isMBB())
1283 return true;
1284 if (!Subtarget.getCLOpts().ctr_loop_analysis)
1285 return true;
1286 TBB = LastInst.getOperand(0).getMBB();
1287 Cond.push_back(MachineOperand::CreateImm(1));
1288 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1289 true));
1290 return false;
1291 } else if (LastInst.getOpcode() == PPC::BDZ8 ||
1292 LastInst.getOpcode() == PPC::BDZ) {
1293 if (!LastInst.getOperand(0).isMBB())
1294 return true;
1295 if (!Subtarget.getCLOpts().ctr_loop_analysis)
1296 return true;
1297 TBB = LastInst.getOperand(0).getMBB();
1298 Cond.push_back(MachineOperand::CreateImm(0));
1299 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1300 true));
1301 return false;
1302 }
1303
1304 // Otherwise, don't know what this is.
1305 return true;
1306 }
1307
1308 // Get the instruction before it if it's a terminator.
1309 MachineInstr &SecondLastInst = *I;
1310
1311 // If there are three terminators, we don't know what sort of block this is.
1312 if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
1313 return true;
1314
1315 // If the block ends with PPC::B and PPC:BCC, handle it.
1316 if (SecondLastInst.getOpcode() == PPC::BCC &&
1317 LastInst.getOpcode() == PPC::B) {
1318 if (!SecondLastInst.getOperand(2).isMBB() ||
1319 !LastInst.getOperand(0).isMBB())
1320 return true;
1321 TBB = SecondLastInst.getOperand(2).getMBB();
1322 Cond.push_back(SecondLastInst.getOperand(0));
1323 Cond.push_back(SecondLastInst.getOperand(1));
1324 FBB = LastInst.getOperand(0).getMBB();
1325 return false;
1326 } else if (SecondLastInst.getOpcode() == PPC::BC &&
1327 LastInst.getOpcode() == PPC::B) {
1328 if (!SecondLastInst.getOperand(1).isMBB() ||
1329 !LastInst.getOperand(0).isMBB())
1330 return true;
1331 TBB = SecondLastInst.getOperand(1).getMBB();
1333 Cond.push_back(SecondLastInst.getOperand(0));
1334 FBB = LastInst.getOperand(0).getMBB();
1335 return false;
1336 } else if (SecondLastInst.getOpcode() == PPC::BCn &&
1337 LastInst.getOpcode() == PPC::B) {
1338 if (!SecondLastInst.getOperand(1).isMBB() ||
1339 !LastInst.getOperand(0).isMBB())
1340 return true;
1341 TBB = SecondLastInst.getOperand(1).getMBB();
1343 Cond.push_back(SecondLastInst.getOperand(0));
1344 FBB = LastInst.getOperand(0).getMBB();
1345 return false;
1346 } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
1347 SecondLastInst.getOpcode() == PPC::BDNZ) &&
1348 LastInst.getOpcode() == PPC::B) {
1349 if (!SecondLastInst.getOperand(0).isMBB() ||
1350 !LastInst.getOperand(0).isMBB())
1351 return true;
1352 if (!Subtarget.getCLOpts().ctr_loop_analysis)
1353 return true;
1354 TBB = SecondLastInst.getOperand(0).getMBB();
1355 Cond.push_back(MachineOperand::CreateImm(1));
1356 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1357 true));
1358 FBB = LastInst.getOperand(0).getMBB();
1359 return false;
1360 } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
1361 SecondLastInst.getOpcode() == PPC::BDZ) &&
1362 LastInst.getOpcode() == PPC::B) {
1363 if (!SecondLastInst.getOperand(0).isMBB() ||
1364 !LastInst.getOperand(0).isMBB())
1365 return true;
1366 if (!Subtarget.getCLOpts().ctr_loop_analysis)
1367 return true;
1368 TBB = SecondLastInst.getOperand(0).getMBB();
1369 Cond.push_back(MachineOperand::CreateImm(0));
1370 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
1371 true));
1372 FBB = LastInst.getOperand(0).getMBB();
1373 return false;
1374 }
1375
1376 // If the block ends with two PPC:Bs, handle it. The second one is not
1377 // executed, so remove it.
1378 if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
1379 if (!SecondLastInst.getOperand(0).isMBB())
1380 return true;
1381 TBB = SecondLastInst.getOperand(0).getMBB();
1382 I = LastInst;
1383 if (AllowModify)
1384 I->eraseFromParent();
1385 return false;
1386 }
1387
1388 // Otherwise, can't handle this.
1389 return true;
1390}
1391
1393 int *BytesRemoved) const {
1394 assert(!BytesRemoved && "code size not handled");
1395
1396 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1397 if (I == MBB.end())
1398 return 0;
1399
1400 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
1401 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1402 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1403 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
1404 return 0;
1405
1406 // Remove the branch.
1407 I->eraseFromParent();
1408
1409 I = MBB.end();
1410
1411 if (I == MBB.begin()) return 1;
1412 --I;
1413 if (I->getOpcode() != PPC::BCC &&
1414 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1415 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1416 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
1417 return 1;
1418
1419 // Remove the branch.
1420 I->eraseFromParent();
1421 return 2;
1422}
1423
1426 MachineBasicBlock *FBB,
1428 const DebugLoc &DL,
1429 int *BytesAdded) const {
1430 // Shouldn't be a fall through.
1431 assert(TBB && "insertBranch must not be told to insert a fallthrough");
1432 assert((Cond.size() == 2 || Cond.size() == 0) &&
1433 "PPC branch conditions have two components!");
1434 assert(!BytesAdded && "code size not handled");
1435
1436 bool isPPC64 = Subtarget.isPPC64();
1437
1438 // One-way branch.
1439 if (!FBB) {
1440 if (Cond.empty()) // Unconditional branch
1441 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
1442 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1443 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
1444 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1445 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
1446 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1447 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
1448 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1449 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
1450 else // Conditional branch
1451 BuildMI(&MBB, DL, get(PPC::BCC))
1452 .addImm(Cond[0].getImm())
1453 .add(Cond[1])
1454 .addMBB(TBB);
1455 return 1;
1456 }
1457
1458 // Two-way Conditional Branch.
1459 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1460 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
1461 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1462 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
1463 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1464 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
1465 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1466 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
1467 else
1468 BuildMI(&MBB, DL, get(PPC::BCC))
1469 .addImm(Cond[0].getImm())
1470 .add(Cond[1])
1471 .addMBB(TBB);
1472 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
1473 return 2;
1474}
1475
1476// Select analysis.
1479 Register DstReg, Register TrueReg,
1480 Register FalseReg,
1481 SelectExpansion &Exp) const {
1482 if (!Subtarget.hasISEL())
1483 return false;
1484
1485 if (Cond.size() != 2)
1486 return false;
1487
1488 // If this is really a bdnz-like condition, then it cannot be turned into a
1489 // select.
1490 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1491 return false;
1492
1493 // If the conditional branch uses a physical register, then it cannot be
1494 // turned into a select.
1495 if (Cond[1].getReg().isPhysical())
1496 return false;
1497
1498 // Check register classes.
1499 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1500 const TargetRegisterClass *RC =
1501 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1502 if (!RC)
1503 return false;
1504
1505 // isel is for regular integer GPRs only.
1506 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
1507 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
1508 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
1509 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
1510 return false;
1511
1512 // FIXME: These numbers are for the A2, how well they work for other cores is
1513 // an open question. On the A2, the isel instruction has a 2-cycle latency
1514 // but single-cycle throughput. These numbers are used in combination with
1515 // the MispredictPenalty setting from the active SchedMachineModel.
1516 Exp.CondCycles = 1;
1517 Exp.TrueCycles = 1;
1518 Exp.FalseCycles = 1;
1519
1520 return true;
1521}
1522
1525 const DebugLoc &dl, Register DestReg,
1527 Register FalseReg) const {
1528 assert(Cond.size() == 2 &&
1529 "PPC branch conditions have two components!");
1530
1531 // Get the register classes.
1532 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1533 const TargetRegisterClass *RC =
1534 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1535 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
1536
1537 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
1538 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
1539 assert((Is64Bit ||
1540 PPC::GPRCRegClass.hasSubClassEq(RC) ||
1541 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
1542 "isel is for regular integer GPRs only");
1543
1544 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
1545 auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
1546
1547 unsigned SubIdx = 0;
1548 bool SwapOps = false;
1549 switch (SelectPred) {
1550 case PPC::PRED_EQ:
1551 case PPC::PRED_EQ_MINUS:
1552 case PPC::PRED_EQ_PLUS:
1553 SubIdx = PPC::sub_eq; SwapOps = false; break;
1554 case PPC::PRED_NE:
1555 case PPC::PRED_NE_MINUS:
1556 case PPC::PRED_NE_PLUS:
1557 SubIdx = PPC::sub_eq; SwapOps = true; break;
1558 case PPC::PRED_LT:
1559 case PPC::PRED_LT_MINUS:
1560 case PPC::PRED_LT_PLUS:
1561 SubIdx = PPC::sub_lt; SwapOps = false; break;
1562 case PPC::PRED_GE:
1563 case PPC::PRED_GE_MINUS:
1564 case PPC::PRED_GE_PLUS:
1565 SubIdx = PPC::sub_lt; SwapOps = true; break;
1566 case PPC::PRED_GT:
1567 case PPC::PRED_GT_MINUS:
1568 case PPC::PRED_GT_PLUS:
1569 SubIdx = PPC::sub_gt; SwapOps = false; break;
1570 case PPC::PRED_LE:
1571 case PPC::PRED_LE_MINUS:
1572 case PPC::PRED_LE_PLUS:
1573 SubIdx = PPC::sub_gt; SwapOps = true; break;
1574 case PPC::PRED_UN:
1575 case PPC::PRED_UN_MINUS:
1576 case PPC::PRED_UN_PLUS:
1577 SubIdx = PPC::sub_un; SwapOps = false; break;
1578 case PPC::PRED_NU:
1579 case PPC::PRED_NU_MINUS:
1580 case PPC::PRED_NU_PLUS:
1581 SubIdx = PPC::sub_un; SwapOps = true; break;
1582 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
1583 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
1584 }
1585
1586 Register FirstReg = SwapOps ? FalseReg : TrueReg,
1587 SecondReg = SwapOps ? TrueReg : FalseReg;
1588
1589 // The first input register of isel cannot be r0. If it is a member
1590 // of a register class that can be r0, then copy it first (the
1591 // register allocator should eliminate the copy).
1592 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
1593 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
1594 const TargetRegisterClass *FirstRC =
1595 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
1596 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
1597 Register OldFirstReg = FirstReg;
1598 FirstReg = MRI.createVirtualRegister(FirstRC);
1599 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
1600 .addReg(OldFirstReg);
1601 }
1602
1603 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
1604 .addReg(FirstReg)
1605 .addReg(SecondReg)
1606 .addReg(Cond[1].getReg(), {}, SubIdx);
1607}
1608
1609static unsigned getCRBitValue(unsigned CRBit) {
1610 unsigned Ret = 4;
1611 if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
1612 CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
1613 CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
1614 CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
1615 Ret = 3;
1616 if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
1617 CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
1618 CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
1619 CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
1620 Ret = 2;
1621 if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
1622 CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
1623 CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
1624 CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
1625 Ret = 1;
1626 if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
1627 CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
1628 CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
1629 CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
1630 Ret = 0;
1631
1632 assert(Ret != 4 && "Invalid CR bit register");
1633 return Ret;
1634}
1635
1638 const DebugLoc &DL, Register DestReg,
1639 Register SrcReg, bool KillSrc,
1640 bool RenamableDest, bool RenamableSrc) const {
1641 // We can end up with self copies and similar things as a result of VSX copy
1642 // legalization. Promote them here.
1643 if (PPC::F8RCRegClass.contains(DestReg) &&
1644 PPC::VSRCRegClass.contains(SrcReg)) {
1645 MCRegister SuperReg =
1646 RI.getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
1647
1648 if (Subtarget.getCLOpts().crash_on_vsx_self_copy && SrcReg == SuperReg)
1649 llvm_unreachable("nop VSX copy");
1650
1651 DestReg = SuperReg;
1652 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
1653 PPC::VSRCRegClass.contains(DestReg)) {
1654 MCRegister SuperReg =
1655 RI.getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
1656
1657 if (Subtarget.getCLOpts().crash_on_vsx_self_copy && DestReg == SuperReg)
1658 llvm_unreachable("nop VSX copy");
1659
1660 SrcReg = SuperReg;
1661 }
1662
1663 // Different class register copy
1664 if (PPC::CRBITRCRegClass.contains(SrcReg) &&
1665 PPC::GPRCRegClass.contains(DestReg)) {
1666 MCRegister CRReg = getCRFromCRBit(SrcReg);
1667 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
1668 getKillRegState(KillSrc);
1669 // Rotate the CR bit in the CR fields to be the least significant bit and
1670 // then mask with 0x1 (MB = ME = 31).
1671 BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
1672 .addReg(DestReg, RegState::Kill)
1673 .addImm(RI.getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
1674 .addImm(31)
1675 .addImm(31);
1676 return;
1677 } else if (PPC::CRRCRegClass.contains(SrcReg) &&
1678 (PPC::G8RCRegClass.contains(DestReg) ||
1679 PPC::GPRCRegClass.contains(DestReg))) {
1680 bool Is64Bit = PPC::G8RCRegClass.contains(DestReg);
1681 unsigned MvCode = Is64Bit ? PPC::MFOCRF8 : PPC::MFOCRF;
1682 unsigned ShCode = Is64Bit ? PPC::RLWINM8 : PPC::RLWINM;
1683 unsigned CRNum = RI.getEncodingValue(SrcReg);
1684 BuildMI(MBB, I, DL, get(MvCode), DestReg).addReg(SrcReg);
1685 getKillRegState(KillSrc);
1686 if (CRNum == 7)
1687 return;
1688 // Shift the CR bits to make the CR field in the lowest 4 bits of GRC.
1689 BuildMI(MBB, I, DL, get(ShCode), DestReg)
1690 .addReg(DestReg, RegState::Kill)
1691 .addImm(CRNum * 4 + 4)
1692 .addImm(28)
1693 .addImm(31);
1694 return;
1695 } else if (PPC::G8RCRegClass.contains(SrcReg) &&
1696 PPC::VSFRCRegClass.contains(DestReg)) {
1697 assert(Subtarget.hasDirectMove() &&
1698 "Subtarget doesn't support directmove, don't know how to copy.");
1699 BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
1700 NumGPRtoVSRSpill++;
1701 getKillRegState(KillSrc);
1702 return;
1703 } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
1704 PPC::G8RCRegClass.contains(DestReg)) {
1705 assert(Subtarget.hasDirectMove() &&
1706 "Subtarget doesn't support directmove, don't know how to copy.");
1707 BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
1708 getKillRegState(KillSrc);
1709 return;
1710 } else if (PPC::SPERCRegClass.contains(SrcReg) &&
1711 PPC::GPRCRegClass.contains(DestReg)) {
1712 BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
1713 getKillRegState(KillSrc);
1714 return;
1715 } else if (PPC::GPRCRegClass.contains(SrcReg) &&
1716 PPC::SPERCRegClass.contains(DestReg)) {
1717 BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
1718 getKillRegState(KillSrc);
1719 return;
1720 } else if ((PPC::G8RCRegClass.contains(DestReg) ||
1721 PPC::GPRCRegClass.contains(DestReg)) &&
1722 SrcReg == PPC::CARRY) {
1723 bool Is64Bit = PPC::G8RCRegClass.contains(DestReg);
1724 BuildMI(MBB, I, DL, get(Is64Bit ? PPC::MFSPR8 : PPC::MFSPR), DestReg)
1725 .addImm(1)
1726 .addReg(PPC::CARRY, RegState::Implicit);
1727 return;
1728 } else if ((PPC::G8RCRegClass.contains(SrcReg) ||
1729 PPC::GPRCRegClass.contains(SrcReg)) &&
1730 DestReg == PPC::CARRY) {
1731 bool Is64Bit = PPC::G8RCRegClass.contains(SrcReg);
1732 BuildMI(MBB, I, DL, get(Is64Bit ? PPC::MTSPR8 : PPC::MTSPR))
1733 .addImm(1)
1734 .addReg(SrcReg)
1735 .addReg(PPC::CARRY, RegState::ImplicitDefine);
1736 return;
1737 }
1738
1739 unsigned Opc;
1740 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
1741 Opc = PPC::OR;
1742 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
1743 Opc = PPC::OR8;
1744 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
1745 Opc = PPC::FMR;
1746 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
1747 Opc = PPC::MCRF;
1748 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
1749 Opc = PPC::VOR;
1750 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
1751 // There are two different ways this can be done:
1752 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
1753 // issue in VSU pipeline 0.
1754 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
1755 // can go to either pipeline.
1756 // We'll always use xxlor here, because in practically all cases where
1757 // copies are generated, they are close enough to some use that the
1758 // lower-latency form is preferable.
1759 Opc = PPC::XXLOR;
1760 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1761 PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1762 Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1763 else if (Subtarget.pairedVectorMemops() &&
1764 PPC::VSRpRCRegClass.contains(DestReg, SrcReg)) {
1765 if (SrcReg > PPC::VSRp15)
1766 SrcReg = PPC::V0 + (SrcReg - PPC::VSRp16) * 2;
1767 else
1768 SrcReg = PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
1769 if (DestReg > PPC::VSRp15)
1770 DestReg = PPC::V0 + (DestReg - PPC::VSRp16) * 2;
1771 else
1772 DestReg = PPC::VSL0 + (DestReg - PPC::VSRp0) * 2;
1773 BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg).
1774 addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1775 BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg + 1).
1776 addReg(SrcReg + 1).addReg(SrcReg + 1, getKillRegState(KillSrc));
1777 return;
1778 }
1779 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1780 Opc = PPC::CROR;
1781 else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
1782 Opc = PPC::EVOR;
1783 else if ((PPC::ACCRCRegClass.contains(DestReg) ||
1784 PPC::UACCRCRegClass.contains(DestReg)) &&
1785 (PPC::ACCRCRegClass.contains(SrcReg) ||
1786 PPC::UACCRCRegClass.contains(SrcReg))) {
1787 // If primed, de-prime the source register, copy the individual registers
1788 // and prime the destination if needed. The vector subregisters are
1789 // vs[(u)acc * 4] - vs[(u)acc * 4 + 3]. If the copy is not a kill and the
1790 // source is primed, we need to re-prime it after the copy as well.
1791 PPCRegisterInfo::emitAccCopyInfo(MBB, DestReg, SrcReg);
1792 bool DestPrimed = PPC::ACCRCRegClass.contains(DestReg);
1793 bool SrcPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1794 MCRegister VSLSrcReg =
1795 PPC::VSL0 + (SrcReg - (SrcPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1796 MCRegister VSLDestReg =
1797 PPC::VSL0 + (DestReg - (DestPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1798 if (SrcPrimed)
1799 BuildMI(MBB, I, DL, get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1800 for (unsigned Idx = 0; Idx < 4; Idx++)
1801 BuildMI(MBB, I, DL, get(PPC::XXLOR), VSLDestReg + Idx)
1802 .addReg(VSLSrcReg + Idx)
1803 .addReg(VSLSrcReg + Idx, getKillRegState(KillSrc));
1804 if (DestPrimed)
1805 BuildMI(MBB, I, DL, get(PPC::XXMTACC), DestReg).addReg(DestReg);
1806 if (SrcPrimed && !KillSrc)
1807 BuildMI(MBB, I, DL, get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1808 return;
1809 } else if (PPC::G8pRCRegClass.contains(DestReg) &&
1810 PPC::G8pRCRegClass.contains(SrcReg)) {
1811 // TODO: Handle G8RC to G8pRC (and vice versa) copy.
1812 unsigned DestRegIdx = DestReg - PPC::G8p0;
1813 MCRegister DestRegSub0 = PPC::X0 + 2 * DestRegIdx;
1814 MCRegister DestRegSub1 = PPC::X0 + 2 * DestRegIdx + 1;
1815 unsigned SrcRegIdx = SrcReg - PPC::G8p0;
1816 MCRegister SrcRegSub0 = PPC::X0 + 2 * SrcRegIdx;
1817 MCRegister SrcRegSub1 = PPC::X0 + 2 * SrcRegIdx + 1;
1818 BuildMI(MBB, I, DL, get(PPC::OR8), DestRegSub0)
1819 .addReg(SrcRegSub0)
1820 .addReg(SrcRegSub0, getKillRegState(KillSrc));
1821 BuildMI(MBB, I, DL, get(PPC::OR8), DestRegSub1)
1822 .addReg(SrcRegSub1)
1823 .addReg(SrcRegSub1, getKillRegState(KillSrc));
1824 return;
1825 } else if ((PPC::WACCRCRegClass.contains(DestReg) ||
1826 PPC::WACC_HIRCRegClass.contains(DestReg)) &&
1827 (PPC::WACCRCRegClass.contains(SrcReg) ||
1828 PPC::WACC_HIRCRegClass.contains(SrcReg))) {
1829
1830 Opc = PPC::WACCRCRegClass.contains(SrcReg) ? PPC::DMXXEXTFDMR512
1831 : PPC::DMXXEXTFDMR512_HI;
1832
1833 RegScavenger RS;
1834 RS.enterBasicBlockEnd(MBB);
1835 RS.backward(std::next(I));
1836
1837 Register TmpReg1 = RS.scavengeRegisterBackwards(PPC::VSRpRCRegClass, I,
1838 /* RestoreAfter */ false, 0,
1839 /* AllowSpill */ false);
1840
1841 RS.setRegUsed(TmpReg1);
1842 Register TmpReg2 = RS.scavengeRegisterBackwards(PPC::VSRpRCRegClass, I,
1843 /* RestoreAfter */ false, 0,
1844 /* AllowSpill */ false);
1845
1846 BuildMI(MBB, I, DL, get(Opc))
1847 .addReg(TmpReg1, RegState::Define)
1848 .addReg(TmpReg2, RegState::Define)
1849 .addReg(SrcReg, getKillRegState(KillSrc));
1850
1851 Opc = PPC::WACCRCRegClass.contains(DestReg) ? PPC::DMXXINSTDMR512
1852 : PPC::DMXXINSTDMR512_HI;
1853
1854 BuildMI(MBB, I, DL, get(Opc), DestReg)
1855 .addReg(TmpReg1, RegState::Kill)
1856 .addReg(TmpReg2, RegState::Kill);
1857
1858 return;
1859 } else if (PPC::DMRRCRegClass.contains(DestReg) &&
1860 PPC::DMRRCRegClass.contains(SrcReg)) {
1861
1862 BuildMI(MBB, I, DL, get(PPC::DMMR), DestReg)
1863 .addReg(SrcReg, getKillRegState(KillSrc));
1864
1865 return;
1866
1867 } else
1868 llvm_unreachable("Impossible reg-to-reg copy");
1869
1870 const MCInstrDesc &MCID = get(Opc);
1871 if (MCID.getNumOperands() == 3)
1872 BuildMI(MBB, I, DL, MCID, DestReg)
1873 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1874 else
1875 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1876}
1877
1878unsigned PPCInstrInfo::getSpillIndex(const TargetRegisterClass *RC) const {
1879 int OpcodeIndex = 0;
1880
1881 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1882 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1884 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1885 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1887 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1889 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1891 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1893 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1895 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1897 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1899 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1901 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1903 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1905 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1907 } else if (PPC::ACCRCRegClass.hasSubClassEq(RC)) {
1908 assert(Subtarget.pairedVectorMemops() &&
1909 "Register unexpected when paired memops are disabled.");
1911 } else if (PPC::UACCRCRegClass.hasSubClassEq(RC)) {
1912 assert(Subtarget.pairedVectorMemops() &&
1913 "Register unexpected when paired memops are disabled.");
1915 } else if (PPC::WACCRCRegClass.hasSubClassEq(RC)) {
1916 assert(Subtarget.pairedVectorMemops() &&
1917 "Register unexpected when paired memops are disabled.");
1919 } else if (PPC::VSRpRCRegClass.hasSubClassEq(RC)) {
1920 assert(Subtarget.pairedVectorMemops() &&
1921 "Register unexpected when paired memops are disabled.");
1923 } else if (PPC::G8pRCRegClass.hasSubClassEq(RC)) {
1925 } else if (PPC::DMRROWRCRegClass.hasSubClassEq(RC)) {
1926 llvm_unreachable("TODO: Implement spill DMRROW regclass!");
1927 } else if (PPC::DMRROWpRCRegClass.hasSubClassEq(RC)) {
1928 llvm_unreachable("TODO: Implement spill DMRROWp regclass!");
1929 } else if (PPC::DMRpRCRegClass.hasSubClassEq(RC)) {
1931 } else if (PPC::DMRRCRegClass.hasSubClassEq(RC)) {
1933 } else {
1934 llvm_unreachable("Unknown regclass!");
1935 }
1936 return OpcodeIndex;
1937}
1938
1939unsigned
1941 ArrayRef<unsigned> OpcodesForSpill = getStoreOpcodesForSpillArray();
1942 return OpcodesForSpill[getSpillIndex(RC)];
1943}
1944
1945unsigned
1947 ArrayRef<unsigned> OpcodesForSpill = getLoadOpcodesForSpillArray();
1948 return OpcodesForSpill[getSpillIndex(RC)];
1949}
1950
1951void PPCInstrInfo::StoreRegToStackSlot(
1952 MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1953 const TargetRegisterClass *RC,
1954 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1955 unsigned Opcode = getStoreOpcodeForSpill(RC);
1956 DebugLoc DL;
1957
1958 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1959 FuncInfo->setHasSpills();
1960
1962 BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1963 FrameIdx));
1964
1965 if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1966 PPC::CRBITRCRegClass.hasSubClassEq(RC))
1967 FuncInfo->setSpillsCR();
1968
1969 if (isXFormMemOp(Opcode))
1970 FuncInfo->setHasNonRISpills();
1971}
1972
1975 bool isKill, int FrameIdx, const TargetRegisterClass *RC) const {
1976 MachineFunction &MF = *MBB.getParent();
1978
1979 StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1980
1981 for (MachineInstr *NewMI : NewMIs)
1982 MBB.insert(MI, NewMI);
1983
1984 const MachineFrameInfo &MFI = MF.getFrameInfo();
1988 MFI.getObjectAlign(FrameIdx));
1989 NewMIs.back()->addMemOperand(MF, MMO);
1990}
1991
1994 bool isKill, int FrameIdx, const TargetRegisterClass *RC, Register VReg,
1995 MachineInstr::MIFlag Flags) const {
1996 // We need to avoid a situation in which the value from a VRRC register is
1997 // spilled using an Altivec instruction and reloaded into a VSRC register
1998 // using a VSX instruction. The issue with this is that the VSX
1999 // load/store instructions swap the doublewords in the vector and the Altivec
2000 // ones don't. The register classes on the spill/reload may be different if
2001 // the register is defined using an Altivec instruction and is then used by a
2002 // VSX instruction.
2003 RC = updatedRC(RC);
2004 storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC);
2005}
2006
2007void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
2008 unsigned DestReg, int FrameIdx,
2009 const TargetRegisterClass *RC,
2011 const {
2012 unsigned Opcode = getLoadOpcodeForSpill(RC);
2013 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
2014 FrameIdx));
2015}
2016
2019 int FrameIdx, const TargetRegisterClass *RC) const {
2020 MachineFunction &MF = *MBB.getParent();
2022 DebugLoc DL;
2023 if (MI != MBB.end()) DL = MI->getDebugLoc();
2024
2025 LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
2026
2027 for (MachineInstr *NewMI : NewMIs)
2028 MBB.insert(MI, NewMI);
2029
2030 const MachineFrameInfo &MFI = MF.getFrameInfo();
2034 MFI.getObjectAlign(FrameIdx));
2035 NewMIs.back()->addMemOperand(MF, MMO);
2036}
2037
2040 Register DestReg, int FrameIdx,
2041 const TargetRegisterClass *RC,
2042 Register VReg, unsigned SubReg,
2043 MachineInstr::MIFlag Flags) const {
2044 // We need to avoid a situation in which the value from a VRRC register is
2045 // spilled using an Altivec instruction and reloaded into a VSRC register
2046 // using a VSX instruction. The issue with this is that the VSX
2047 // load/store instructions swap the doublewords in the vector and the Altivec
2048 // ones don't. The register classes on the spill/reload may be different if
2049 // the register is defined using an Altivec instruction and is then used by a
2050 // VSX instruction.
2051 RC = updatedRC(RC);
2052
2053 loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC);
2054}
2055
2058 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
2059 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
2060 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
2061 else
2062 // Leave the CR# the same, but invert the condition.
2064 return false;
2065}
2066
2067// For some instructions, it is legal to fold ZERO into the RA register field.
2068// This function performs that fold by replacing the operand with PPC::ZERO,
2069// it does not consider whether the load immediate zero is no longer in use.
2071 Register Reg) const {
2072 // A zero immediate should always be loaded with a single li.
2073 unsigned DefOpc = DefMI.getOpcode();
2074 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
2075 return false;
2076 if (!DefMI.getOperand(1).isImm())
2077 return false;
2078 if (DefMI.getOperand(1).getImm() != 0)
2079 return false;
2080
2081 // Note that we cannot here invert the arguments of an isel in order to fold
2082 // a ZERO into what is presented as the second argument. All we have here
2083 // is the condition bit, and that might come from a CR-logical bit operation.
2084
2085 const MCInstrDesc &UseMCID = UseMI.getDesc();
2086
2087 // Only fold into real machine instructions.
2088 if (UseMCID.isPseudo())
2089 return false;
2090
2091 // We need to find which of the User's operands is to be folded, that will be
2092 // the operand that matches the given register ID.
2093 unsigned UseIdx;
2094 for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
2095 if (UseMI.getOperand(UseIdx).isReg() &&
2096 UseMI.getOperand(UseIdx).getReg() == Reg)
2097 break;
2098
2099 assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
2100 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
2101
2102 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
2103 // register (which might also be specified as a pointer class kind).
2104
2105 const MCOperandInfo &UseInfo = UseMCID.operands()[UseIdx];
2106 int16_t RegClass = getOpRegClassID(UseInfo);
2107 if (UseInfo.RegClass != PPC::GPRC_NOR0RegClassID &&
2108 UseInfo.RegClass != PPC::G8RC_NOX0RegClassID)
2109 return false;
2110
2111 // Make sure this is not tied to an output register (or otherwise
2112 // constrained). This is true for ST?UX registers, for example, which
2113 // are tied to their output registers.
2114 if (UseInfo.Constraints != 0)
2115 return false;
2116
2117 MCRegister ZeroReg =
2118 RegClass == PPC::G8RC_NOX0RegClassID ? PPC::ZERO8 : PPC::ZERO;
2119
2120 LLVM_DEBUG(dbgs() << "Folded immediate zero for: ");
2121 LLVM_DEBUG(UseMI.dump());
2122 UseMI.getOperand(UseIdx).setReg(ZeroReg);
2123 LLVM_DEBUG(dbgs() << "Into: ");
2124 LLVM_DEBUG(UseMI.dump());
2125 return true;
2126}
2127
2128// Folds zero into instructions which have a load immediate zero as an operand
2129// but also recognize zero as immediate zero. If the definition of the load
2130// has no more users it is deleted.
2132 Register Reg, MachineRegisterInfo *MRI) const {
2133 bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg);
2134 if (MRI->use_nodbg_empty(Reg))
2135 DefMI.eraseFromParent();
2136 return Changed;
2137}
2138
2140 for (MachineInstr &MI : MBB)
2141 if (MI.definesRegister(PPC::CTR, /*TRI=*/nullptr) ||
2142 MI.definesRegister(PPC::CTR8, /*TRI=*/nullptr))
2143 return true;
2144 return false;
2145}
2146
2147// We should make sure that, if we're going to predicate both sides of a
2148// condition (a diamond), that both sides don't define the counter register. We
2149// can predicate counter-decrement-based branches, but while that predicates
2150// the branching, it does not predicate the counter decrement. If we tried to
2151// merge the triangle into one predicated block, we'd decrement the counter
2152// twice.
2154 unsigned NumT, unsigned ExtraT,
2155 MachineBasicBlock &FMBB,
2156 unsigned NumF, unsigned ExtraF,
2157 BranchProbability Probability) const {
2158 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
2159}
2160
2161
2163 // The predicated branches are identified by their type, not really by the
2164 // explicit presence of a predicate. Furthermore, some of them can be
2165 // predicated more than once. Because if conversion won't try to predicate
2166 // any instruction which already claims to be predicated (by returning true
2167 // here), always return false. In doing so, we let isPredicable() be the
2168 // final word on whether not the instruction can be (further) predicated.
2169
2170 return false;
2171}
2172
2174 const MachineBasicBlock *MBB,
2175 const MachineFunction &MF) const {
2176 switch (MI.getOpcode()) {
2177 default:
2178 break;
2179 // Set MFFS and MTFSF as scheduling boundary to avoid unexpected code motion
2180 // across them, since some FP operations may change content of FPSCR.
2181 // TODO: Model FPSCR in PPC instruction definitions and remove the workaround
2182 case PPC::MFFS:
2183 case PPC::MTFSF:
2184 case PPC::FENCE:
2185 return true;
2186 }
2188}
2189
2191 ArrayRef<MachineOperand> Pred) const {
2192 unsigned OpC = MI.getOpcode();
2193 if (OpC == PPC::BLR || OpC == PPC::BLR8) {
2194 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
2195 bool isPPC64 = Subtarget.isPPC64();
2196 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
2197 : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
2198 // Need add Def and Use for CTR implicit operand.
2199 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2200 .addReg(Pred[1].getReg(), RegState::Implicit)
2202 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2203 MI.setDesc(get(PPC::BCLR));
2204 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2205 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2206 MI.setDesc(get(PPC::BCLRn));
2207 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2208 } else {
2209 MI.setDesc(get(PPC::BCCLR));
2210 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2211 .addImm(Pred[0].getImm())
2212 .add(Pred[1]);
2213 }
2214
2215 return true;
2216 } else if (OpC == PPC::B) {
2217 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
2218 bool isPPC64 = Subtarget.isPPC64();
2219 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
2220 : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
2221 // Need add Def and Use for CTR implicit operand.
2222 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2223 .addReg(Pred[1].getReg(), RegState::Implicit)
2225 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2226 MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
2227 MI.removeOperand(0);
2228
2229 MI.setDesc(get(PPC::BC));
2230 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2231 .add(Pred[1])
2232 .addMBB(MBB);
2233 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2234 MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
2235 MI.removeOperand(0);
2236
2237 MI.setDesc(get(PPC::BCn));
2238 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2239 .add(Pred[1])
2240 .addMBB(MBB);
2241 } else {
2242 MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
2243 MI.removeOperand(0);
2244
2245 MI.setDesc(get(PPC::BCC));
2246 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2247 .addImm(Pred[0].getImm())
2248 .add(Pred[1])
2249 .addMBB(MBB);
2250 }
2251
2252 return true;
2253 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
2254 OpC == PPC::BCTRL8 || OpC == PPC::BCTRL_RM ||
2255 OpC == PPC::BCTRL8_RM) {
2256 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
2257 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
2258
2259 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8 ||
2260 OpC == PPC::BCTRL_RM || OpC == PPC::BCTRL8_RM;
2261 bool isPPC64 = Subtarget.isPPC64();
2262
2263 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2264 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
2265 : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
2266 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2267 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2268 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
2269 : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
2270 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
2271 } else {
2272 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
2273 : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
2274 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2275 .addImm(Pred[0].getImm())
2276 .add(Pred[1]);
2277 }
2278
2279 // Need add Def and Use for LR implicit operand.
2280 if (setLR)
2281 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2282 .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::Implicit)
2283 .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::ImplicitDefine);
2284 if (OpC == PPC::BCTRL_RM || OpC == PPC::BCTRL8_RM)
2285 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2287
2288 return true;
2289 }
2290
2291 return false;
2292}
2293
2295 ArrayRef<MachineOperand> Pred2) const {
2296 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
2297 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
2298
2299 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
2300 return false;
2301 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
2302 return false;
2303
2304 // P1 can only subsume P2 if they test the same condition register.
2305 if (Pred1[1].getReg() != Pred2[1].getReg())
2306 return false;
2307
2308 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
2309 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
2310
2311 if (P1 == P2)
2312 return true;
2313
2314 // Does P1 subsume P2, e.g. GE subsumes GT.
2315 if (P1 == PPC::PRED_LE &&
2316 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
2317 return true;
2318 if (P1 == PPC::PRED_GE &&
2319 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
2320 return true;
2321
2322 return false;
2323}
2324
2326 std::vector<MachineOperand> &Pred,
2327 bool SkipDead) const {
2328 // Note: At the present time, the contents of Pred from this function is
2329 // unused by IfConversion. This implementation follows ARM by pushing the
2330 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
2331 // predicate, instructions defining CTR or CTR8 are also included as
2332 // predicate-defining instructions.
2333
2334 const TargetRegisterClass *RCs[] =
2335 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
2336 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
2337
2338 bool Found = false;
2339 for (const MachineOperand &MO : MI.operands()) {
2340 for (unsigned c = 0; c < std::size(RCs) && !Found; ++c) {
2341 const TargetRegisterClass *RC = RCs[c];
2342 if (MO.isReg()) {
2343 if (MO.isDef() && RC->contains(MO.getReg())) {
2344 Pred.push_back(MO);
2345 Found = true;
2346 }
2347 } else if (MO.isRegMask()) {
2348 for (MCPhysReg R : *RC)
2349 if (MO.clobbersPhysReg(R)) {
2350 Pred.push_back(MO);
2351 Found = true;
2352 }
2353 }
2354 }
2355 }
2356
2357 return Found;
2358}
2359
2361 Register &SrcReg2, int64_t &Mask,
2362 int64_t &Value) const {
2363 unsigned Opc = MI.getOpcode();
2364
2365 switch (Opc) {
2366 default: return false;
2367 case PPC::CMPWI:
2368 case PPC::CMPLWI:
2369 case PPC::CMPDI:
2370 case PPC::CMPLDI:
2371 SrcReg = MI.getOperand(1).getReg();
2372 SrcReg2 = 0;
2373 Value = MI.getOperand(2).getImm();
2374 Mask = 0xFFFF;
2375 return true;
2376 case PPC::CMPW:
2377 case PPC::CMPLW:
2378 case PPC::CMPD:
2379 case PPC::CMPLD:
2380 case PPC::FCMPUS:
2381 case PPC::FCMPUD:
2382 SrcReg = MI.getOperand(1).getReg();
2383 SrcReg2 = MI.getOperand(2).getReg();
2384 Value = 0;
2385 Mask = 0;
2386 return true;
2387 }
2388}
2389
2391 Register SrcReg2, int64_t Mask,
2392 int64_t Value,
2393 const MachineRegisterInfo *MRI) const {
2394 if (!Subtarget.getCLOpts().cmp_opt)
2395 return false;
2396
2397 int OpC = CmpInstr.getOpcode();
2398 Register CRReg = CmpInstr.getOperand(0).getReg();
2399
2400 // FP record forms set CR1 based on the exception status bits, not a
2401 // comparison with zero.
2402 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
2403 return false;
2404
2405 // The record forms set the condition register based on a signed comparison
2406 // with zero (so says the ISA manual). This is not as straightforward as it
2407 // seems, however, because this is always a 64-bit comparison on PPC64, even
2408 // for instructions that are 32-bit in nature (like slw for example).
2409 // So, on PPC32, for unsigned comparisons, we can use the record forms only
2410 // for equality checks (as those don't depend on the sign). On PPC64,
2411 // we are restricted to equality for unsigned 64-bit comparisons and for
2412 // signed 32-bit comparisons the applicability is more restricted.
2413 bool isPPC64 = Subtarget.isPPC64();
2414 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
2415 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
2416 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
2417
2418 // Look through copies unless that gets us to a physical register.
2419 Register ActualSrc = RI.lookThruCopyLike(SrcReg, MRI);
2420 if (ActualSrc.isVirtual())
2421 SrcReg = ActualSrc;
2422
2423 // Get the unique definition of SrcReg.
2424 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2425 if (!MI) return false;
2426
2427 bool equalityOnly = false;
2428 bool noSub = false;
2429 if (isPPC64) {
2430 if (is32BitSignedCompare) {
2431 // We can perform this optimization only if SrcReg is sign-extending.
2432 if (isSignExtended(SrcReg, MRI))
2433 noSub = true;
2434 else
2435 return false;
2436 } else if (is32BitUnsignedCompare) {
2437 // We can perform this optimization, equality only, if SrcReg is
2438 // zero-extending.
2439 if (isZeroExtended(SrcReg, MRI)) {
2440 noSub = true;
2441 equalityOnly = true;
2442 } else
2443 return false;
2444 } else
2445 equalityOnly = is64BitUnsignedCompare;
2446 } else
2447 equalityOnly = is32BitUnsignedCompare;
2448
2449 if (equalityOnly) {
2450 // We need to check the uses of the condition register in order to reject
2451 // non-equality comparisons.
2453 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
2454 I != IE; ++I) {
2455 MachineInstr *UseMI = &*I;
2456 if (UseMI->getOpcode() == PPC::BCC) {
2457 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
2458 unsigned PredCond = PPC::getPredicateCondition(Pred);
2459 // We ignore hint bits when checking for non-equality comparisons.
2460 if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
2461 return false;
2462 } else if (UseMI->getOpcode() == PPC::ISEL ||
2463 UseMI->getOpcode() == PPC::ISEL8) {
2464 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
2465 if (SubIdx != PPC::sub_eq)
2466 return false;
2467 } else
2468 return false;
2469 }
2470 }
2471
2472 MachineBasicBlock::iterator I = CmpInstr;
2473
2474 // Scan forward to find the first use of the compare.
2475 for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
2476 ++I) {
2477 bool FoundUse = false;
2479 J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
2480 J != JE; ++J)
2481 if (&*J == &*I) {
2482 FoundUse = true;
2483 break;
2484 }
2485
2486 if (FoundUse)
2487 break;
2488 }
2489
2492
2493 // There are two possible candidates which can be changed to set CR[01].
2494 // One is MI, the other is a SUB instruction.
2495 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2496 MachineInstr *Sub = nullptr;
2497 if (SrcReg2 != 0)
2498 // MI is not a candidate for CMPrr.
2499 MI = nullptr;
2500 // FIXME: Conservatively refuse to convert an instruction which isn't in the
2501 // same BB as the comparison. This is to allow the check below to avoid calls
2502 // (and other explicit clobbers); instead we should really check for these
2503 // more explicitly (in at least a few predecessors).
2504 else if (MI->getParent() != CmpInstr.getParent())
2505 return false;
2506 else if (Value != 0) {
2507 // The record-form instructions set CR bit based on signed comparison
2508 // against 0. We try to convert a compare against 1 or -1 into a compare
2509 // against 0 to exploit record-form instructions. For example, we change
2510 // the condition "greater than -1" into "greater than or equal to 0"
2511 // and "less than 1" into "less than or equal to 0".
2512
2513 // Since we optimize comparison based on a specific branch condition,
2514 // we don't optimize if condition code is used by more than once.
2515 if (equalityOnly || !MRI->hasOneUse(CRReg))
2516 return false;
2517
2518 MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
2519 if (UseMI->getOpcode() != PPC::BCC)
2520 return false;
2521
2522 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
2523 unsigned PredCond = PPC::getPredicateCondition(Pred);
2524 unsigned PredHint = PPC::getPredicateHint(Pred);
2525 int16_t Immed = (int16_t)Value;
2526
2527 // When modifying the condition in the predicate, we propagate hint bits
2528 // from the original predicate to the new one.
2529 if (Immed == -1 && PredCond == PPC::PRED_GT)
2530 // We convert "greater than -1" into "greater than or equal to 0",
2531 // since we are assuming signed comparison by !equalityOnly
2532 Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
2533 else if (Immed == -1 && PredCond == PPC::PRED_LE)
2534 // We convert "less than or equal to -1" into "less than 0".
2535 Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
2536 else if (Immed == 1 && PredCond == PPC::PRED_LT)
2537 // We convert "less than 1" into "less than or equal to 0".
2538 Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
2539 else if (Immed == 1 && PredCond == PPC::PRED_GE)
2540 // We convert "greater than or equal to 1" into "greater than 0".
2541 Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
2542 else
2543 return false;
2544
2545 // Convert the comparison and its user to a compare against zero with the
2546 // appropriate predicate on the branch. Zero comparison might provide
2547 // optimization opportunities post-RA (see optimization in
2548 // PPCPreEmitPeephole.cpp).
2549 UseMI->getOperand(0).setImm(Pred);
2550 CmpInstr.getOperand(2).setImm(0);
2551 }
2552
2553 // Search for Sub.
2554 --I;
2555
2556 // Get ready to iterate backward from CmpInstr.
2557 MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
2558
2559 for (; I != E && !noSub; --I) {
2560 const MachineInstr &Instr = *I;
2561 unsigned IOpC = Instr.getOpcode();
2562
2563 if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, &RI) ||
2564 Instr.readsRegister(PPC::CR0, &RI)))
2565 // This instruction modifies or uses the record condition register after
2566 // the one we want to change. While we could do this transformation, it
2567 // would likely not be profitable. This transformation removes one
2568 // instruction, and so even forcing RA to generate one move probably
2569 // makes it unprofitable.
2570 return false;
2571
2572 // Check whether CmpInstr can be made redundant by the current instruction.
2573 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
2574 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
2575 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
2576 ((Instr.getOperand(1).getReg() == SrcReg &&
2577 Instr.getOperand(2).getReg() == SrcReg2) ||
2578 (Instr.getOperand(1).getReg() == SrcReg2 &&
2579 Instr.getOperand(2).getReg() == SrcReg))) {
2580 Sub = &*I;
2581 break;
2582 }
2583
2584 if (I == B)
2585 // The 'and' is below the comparison instruction.
2586 return false;
2587 }
2588
2589 // Return false if no candidates exist.
2590 if (!MI && !Sub)
2591 return false;
2592
2593 // The single candidate is called MI.
2594 if (!MI) MI = Sub;
2595
2596 int NewOpC = -1;
2597 int MIOpC = MI->getOpcode();
2598 if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
2599 MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
2600 NewOpC = MIOpC;
2601 else {
2602 NewOpC = PPC::getRecordFormOpcode(MIOpC);
2603 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
2604 NewOpC = MIOpC;
2605 }
2606
2607 // FIXME: On the non-embedded POWER architectures, only some of the record
2608 // forms are fast, and we should use only the fast ones.
2609
2610 // The defining instruction has a record form (or is already a record
2611 // form). It is possible, however, that we'll need to reverse the condition
2612 // code of the users.
2613 if (NewOpC == -1)
2614 return false;
2615
2616 // Converting MI to its record form makes it define CR0, which is only legal
2617 // if CR0 is dead at that point. CR0 may still be live from an earlier
2618 // record-form instruction with a use scheduled after MI: expanding the
2619 // ANDI_rec_1_{EQ,GT}_BIT pseudos produces COPYs of CR0 subregisters, and
2620 // nothing keeps those adjacent to their `andi.` once other instructions are
2621 // scheduled in between. The backward scan above only covers the range
2622 // between MI and CmpInstr, so it cannot see such a use. Query CR0's
2623 // liveness right after MI, using the block size as the neighborhood so the
2624 // query can inspect the remainder of the block, and be conservative about
2625 // an unknown answer.
2626 const bool IntroducesRecFormInstr = MIOpC != NewOpC;
2627 if (IntroducesRecFormInstr) {
2628 const MachineBasicBlock *MBB = MI->getParent();
2629 if (MBB->computeRegisterLiveness(
2630 &RI, PPC::CR0, std::next(MachineBasicBlock::const_iterator(MI)),
2631 /*Neighborhood=*/MBB->size()) != MachineBasicBlock::LQR_Dead)
2632 return false;
2633 }
2634
2635 // This transformation should not be performed if `nsw` is missing and is not
2636 // `equalityOnly` comparison. Since if there is overflow, sub_lt, sub_gt in
2637 // CRReg do not reflect correct order. If `equalityOnly` is true, sub_eq in
2638 // CRReg can reflect if compared values are equal, this optz is still valid.
2639 if (!equalityOnly && (NewOpC == PPC::SUBF_rec || NewOpC == PPC::SUBF8_rec) &&
2640 Sub && !Sub->getFlag(MachineInstr::NoSWrap))
2641 return false;
2642
2643 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
2644 // needs to be updated to be based on SUB. Push the condition code
2645 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
2646 // condition code of these operands will be modified.
2647 // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
2648 // comparison against 0, which may modify predicate.
2649 bool ShouldSwap = false;
2650 if (Sub && Value == 0) {
2651 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2652 Sub->getOperand(2).getReg() == SrcReg;
2653
2654 // The operands to subf are the opposite of sub, so only in the fixed-point
2655 // case, invert the order.
2656 ShouldSwap = !ShouldSwap;
2657 }
2658
2659 if (ShouldSwap)
2661 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
2662 I != IE; ++I) {
2663 MachineInstr *UseMI = &*I;
2664 if (UseMI->getOpcode() == PPC::BCC) {
2665 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
2666 unsigned PredCond = PPC::getPredicateCondition(Pred);
2667 assert((!equalityOnly ||
2668 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
2669 "Invalid predicate for equality-only optimization");
2670 (void)PredCond; // To suppress warning in release build.
2671 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
2673 } else if (UseMI->getOpcode() == PPC::ISEL ||
2674 UseMI->getOpcode() == PPC::ISEL8) {
2675 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
2676 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
2677 "Invalid CR bit for equality-only optimization");
2678
2679 if (NewSubReg == PPC::sub_lt)
2680 NewSubReg = PPC::sub_gt;
2681 else if (NewSubReg == PPC::sub_gt)
2682 NewSubReg = PPC::sub_lt;
2683
2684 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
2685 NewSubReg));
2686 } else // We need to abort on a user we don't understand.
2687 return false;
2688 }
2689 assert(!(Value != 0 && ShouldSwap) &&
2690 "Non-zero immediate support and ShouldSwap"
2691 "may conflict in updating predicate");
2692
2693 // Create a new virtual register to hold the value of the CR set by the
2694 // record-form instruction. If the instruction was not previously in
2695 // record form, then set the kill flag on the CR.
2696 CmpInstr.eraseFromParent();
2697
2699 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
2700 get(TargetOpcode::COPY), CRReg)
2701 .addReg(PPC::CR0, getKillRegState(MIOpC != NewOpC));
2702
2703 // Even if CR0 register were dead before, it is alive now since the
2704 // instruction we just built uses it.
2705 MI->clearRegisterDeads(PPC::CR0);
2706
2707 if (MIOpC != NewOpC) {
2708 // We need to be careful here: we're replacing one instruction with
2709 // another, and we need to make sure that we get all of the right
2710 // implicit uses and defs. On the other hand, the caller may be holding
2711 // an iterator to this instruction, and so we can't delete it (this is
2712 // specifically the case if this is the instruction directly after the
2713 // compare).
2714
2715 // Rotates are expensive instructions. If we're emitting a record-form
2716 // rotate that can just be an andi/andis, we should just emit that.
2717 if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
2718 Register GPRRes = MI->getOperand(0).getReg();
2719 int64_t SH = MI->getOperand(2).getImm();
2720 int64_t MB = MI->getOperand(3).getImm();
2721 int64_t ME = MI->getOperand(4).getImm();
2722 // We can only do this if both the start and end of the mask are in the
2723 // same halfword.
2724 bool MBInLoHWord = MB >= 16;
2725 bool MEInLoHWord = ME >= 16;
2726 uint64_t Mask = ~0LLU;
2727
2728 if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
2729 Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2730 // The mask value needs to shift right 16 if we're emitting andis.
2731 Mask >>= MBInLoHWord ? 0 : 16;
2732 NewOpC = MIOpC == PPC::RLWINM
2733 ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
2734 : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
2735 } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
2736 (ME - MB + 1 == SH) && (MB >= 16)) {
2737 // If we are rotating by the exact number of bits as are in the mask
2738 // and the mask is in the least significant bits of the register,
2739 // that's just an andis. (as long as the GPR result has no uses).
2740 Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
2741 Mask >>= 16;
2742 NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
2743 }
2744 // If we've set the mask, we can transform.
2745 if (Mask != ~0LLU) {
2746 MI->removeOperand(4);
2747 MI->removeOperand(3);
2748 MI->getOperand(2).setImm(Mask);
2749 NumRcRotatesConvertedToRcAnd++;
2750 }
2751 } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
2752 int64_t MB = MI->getOperand(3).getImm();
2753 if (MB >= 48) {
2754 uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2755 NewOpC = PPC::ANDI8_rec;
2756 MI->removeOperand(3);
2757 MI->getOperand(2).setImm(Mask);
2758 NumRcRotatesConvertedToRcAnd++;
2759 }
2760 }
2761
2762 const MCInstrDesc &NewDesc = get(NewOpC);
2763 MI->setDesc(NewDesc);
2764
2765 for (MCPhysReg ImpDef : NewDesc.implicit_defs()) {
2766 if (!MI->definesRegister(ImpDef, /*TRI=*/nullptr)) {
2767 MI->addOperand(*MI->getParent()->getParent(),
2768 MachineOperand::CreateReg(ImpDef, true, true));
2769 }
2770 }
2771 for (MCPhysReg ImpUse : NewDesc.implicit_uses()) {
2772 if (!MI->readsRegister(ImpUse, /*TRI=*/nullptr)) {
2773 MI->addOperand(*MI->getParent()->getParent(),
2774 MachineOperand::CreateReg(ImpUse, false, true));
2775 }
2776 }
2777 }
2778 assert(MI->definesRegister(PPC::CR0, /*TRI=*/nullptr) &&
2779 "Record-form instruction does not define cr0?");
2780
2781 // Modify the condition code of operands in OperandsToUpdate.
2782 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2783 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2784 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
2785 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2786
2787 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2788 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2789
2790 return true;
2791}
2792
2795 if (MRI->isSSA())
2796 return false;
2797
2798 Register SrcReg, SrcReg2;
2799 int64_t CmpMask, CmpValue;
2800 if (!analyzeCompare(CmpMI, SrcReg, SrcReg2, CmpMask, CmpValue))
2801 return false;
2802
2803 // Try to optimize the comparison against 0.
2804 if (CmpValue || !CmpMask || SrcReg2)
2805 return false;
2806
2807 // The record forms set the condition register based on a signed comparison
2808 // with zero (see comments in optimizeCompareInstr). Since we can't do the
2809 // equality checks in post-RA, we are more restricted on a unsigned
2810 // comparison.
2811 unsigned Opc = CmpMI.getOpcode();
2812 if (Opc == PPC::CMPLWI || Opc == PPC::CMPLDI)
2813 return false;
2814
2815 // The record forms are always based on a 64-bit comparison on PPC64
2816 // (similary, a 32-bit comparison on PPC32), while the CMPWI is a 32-bit
2817 // comparison. Since we can't do the equality checks in post-RA, we bail out
2818 // the case.
2819 if (Subtarget.isPPC64() && Opc == PPC::CMPWI)
2820 return false;
2821
2822 // CmpMI can't be deleted if it has implicit def.
2823 if (CmpMI.hasImplicitDef())
2824 return false;
2825
2826 bool SrcRegHasOtherUse = false;
2827 MachineInstr *SrcMI = getDefMIPostRA(SrcReg, CmpMI, SrcRegHasOtherUse);
2828 if (!SrcMI || !SrcMI->definesRegister(SrcReg, /*TRI=*/nullptr))
2829 return false;
2830
2831 MachineOperand RegMO = CmpMI.getOperand(0);
2832 Register CRReg = RegMO.getReg();
2833 if (CRReg != PPC::CR0)
2834 return false;
2835
2836 // Make sure there is no def/use of CRReg between SrcMI and CmpMI.
2837 bool SeenUseOfCRReg = false;
2838 bool IsCRRegKilled = false;
2839 if (!isRegElgibleForForwarding(RegMO, *SrcMI, CmpMI, false, IsCRRegKilled,
2840 SeenUseOfCRReg) ||
2841 SrcMI->definesRegister(CRReg, /*TRI=*/nullptr) || SeenUseOfCRReg)
2842 return false;
2843
2844 int SrcMIOpc = SrcMI->getOpcode();
2845 int NewOpC = PPC::getRecordFormOpcode(SrcMIOpc);
2846 if (NewOpC == -1)
2847 return false;
2848
2849 LLVM_DEBUG(dbgs() << "Replace Instr: ");
2850 LLVM_DEBUG(SrcMI->dump());
2851
2852 const MCInstrDesc &NewDesc = get(NewOpC);
2853 SrcMI->setDesc(NewDesc);
2854 MachineInstrBuilder(*SrcMI->getParent()->getParent(), SrcMI)
2856 SrcMI->clearRegisterDeads(CRReg);
2857
2858 assert(SrcMI->definesRegister(PPC::CR0, /*TRI=*/nullptr) &&
2859 "Record-form instruction does not define cr0?");
2860
2861 LLVM_DEBUG(dbgs() << "with: ");
2862 LLVM_DEBUG(SrcMI->dump());
2863 LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
2864 LLVM_DEBUG(CmpMI.dump());
2865 return true;
2866}
2867
2870 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const {
2871 const MachineOperand *BaseOp;
2872 OffsetIsScalable = false;
2873 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width))
2874 return false;
2875 BaseOps.push_back(BaseOp);
2876 return true;
2877}
2878
2879static bool isLdStSafeToCluster(const MachineInstr &LdSt,
2880 const TargetRegisterInfo *TRI) {
2881 // If this is a volatile load/store, don't mess with it.
2882 if (LdSt.hasOrderedMemoryRef() || LdSt.getNumExplicitOperands() != 3)
2883 return false;
2884
2885 if (LdSt.getOperand(2).isFI())
2886 return true;
2887
2888 assert(LdSt.getOperand(2).isReg() && "Expected a reg operand.");
2889 // Can't cluster if the instruction modifies the base register
2890 // or it is update form. e.g. ld r2,3(r2)
2891 if (LdSt.modifiesRegister(LdSt.getOperand(2).getReg(), TRI))
2892 return false;
2893
2894 return true;
2895}
2896
2897// Only cluster instruction pair that have the same opcode, and they are
2898// clusterable according to PowerPC specification.
2899static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc,
2900 const PPCSubtarget &Subtarget) {
2901 switch (FirstOpc) {
2902 default:
2903 return false;
2904 case PPC::STD:
2905 case PPC::STFD:
2906 case PPC::STXSD:
2907 case PPC::DFSTOREf64:
2908 return FirstOpc == SecondOpc;
2909 // PowerPC backend has opcode STW/STW8 for instruction "stw" to deal with
2910 // 32bit and 64bit instruction selection. They are clusterable pair though
2911 // they are different opcode.
2912 case PPC::STW:
2913 case PPC::STW8:
2914 return SecondOpc == PPC::STW || SecondOpc == PPC::STW8;
2915 }
2916}
2917
2919 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
2920 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
2921 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
2922 unsigned NumBytes) const {
2923
2924 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
2925 const MachineOperand &BaseOp1 = *BaseOps1.front();
2926 const MachineOperand &BaseOp2 = *BaseOps2.front();
2927 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
2928 "Only base registers and frame indices are supported.");
2929
2930 // ClusterSize means the number of memory operations that will have been
2931 // clustered if this hook returns true.
2932 // Don't cluster memory op if there are already two ops clustered at least.
2933 if (ClusterSize > 2)
2934 return false;
2935
2936 // Cluster the load/store only when they have the same base
2937 // register or FI.
2938 if ((BaseOp1.isReg() != BaseOp2.isReg()) ||
2939 (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) ||
2940 (BaseOp1.isFI() && BaseOp1.getIndex() != BaseOp2.getIndex()))
2941 return false;
2942
2943 // Check if the load/store are clusterable according to the PowerPC
2944 // specification.
2945 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
2946 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
2947 unsigned FirstOpc = FirstLdSt.getOpcode();
2948 unsigned SecondOpc = SecondLdSt.getOpcode();
2949 // Cluster the load/store only when they have the same opcode, and they are
2950 // clusterable opcode according to PowerPC specification.
2951 if (!isClusterableLdStOpcPair(FirstOpc, SecondOpc, Subtarget))
2952 return false;
2953
2954 // Can't cluster load/store that have ordered or volatile memory reference.
2955 if (!isLdStSafeToCluster(FirstLdSt, &RI) ||
2956 !isLdStSafeToCluster(SecondLdSt, &RI))
2957 return false;
2958
2959 int64_t Offset1 = 0, Offset2 = 0;
2961 Width2 = LocationSize::precise(0);
2962 const MachineOperand *Base1 = nullptr, *Base2 = nullptr;
2963 if (!getMemOperandWithOffsetWidth(FirstLdSt, Base1, Offset1, Width1) ||
2964 !getMemOperandWithOffsetWidth(SecondLdSt, Base2, Offset2, Width2) ||
2965 Width1 != Width2)
2966 return false;
2967
2968 assert(Base1 == &BaseOp1 && Base2 == &BaseOp2 &&
2969 "getMemOperandWithOffsetWidth return incorrect base op");
2970 // The caller should already have ordered FirstMemOp/SecondMemOp by offset.
2971 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
2972 return Offset1 + (int64_t)Width1.getValue() == Offset2;
2973}
2974
2975/// GetInstSize - Return the number of bytes of code the specified
2976/// instruction may be. This returns the maximum number of bytes.
2977///
2979 unsigned Opcode = MI.getOpcode();
2980
2981 switch (Opcode) {
2982 case PPC::INLINEASM:
2983 case PPC::INLINEASM_BR: {
2984 const MachineFunction *MF = MI.getParent()->getParent();
2985 const char *AsmStr = MI.getOperand(0).getSymbolName();
2986 return getInlineAsmLength(AsmStr, MF->getTarget().getMCAsmInfo());
2987 }
2988 case TargetOpcode::STACKMAP: {
2989 StackMapOpers Opers(&MI);
2990 return Opers.getNumPatchBytes();
2991 }
2992 case TargetOpcode::PATCHPOINT: {
2993 PatchPointOpers Opers(&MI);
2994 return Opers.getNumPatchBytes();
2995 }
2996 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
2997 const MachineFunction *MF = MI.getParent()->getParent();
2998 const Function &F = MF->getFunction();
2999 unsigned Num = F.getFnAttributeAsParsedInteger("patchable-function-entry");
3000 if (Num || MF->getTarget().getTargetTriple().isOSAIX() ||
3002 return Num * 4;
3003 // Size of xray sled.
3004 return 7 * 4;
3005 }
3006 case TargetOpcode::PATCHABLE_RET: {
3007 // Size of xray sled.
3008 unsigned RetOpcode = MI.getOperand(0).getImm();
3009 bool IsConditional = isPredicatedBLR8(RetOpcode);
3010 return (8 + IsConditional) * 4;
3011 }
3012 case TargetOpcode::BUNDLE:
3013 return getInstBundleSize(MI);
3014 default:
3015 return get(Opcode).getSize();
3016 }
3017}
3018
3021 // FIXME: The size of STACKMAP is currently over-estimated.
3022 return MI.getOpcode() == TargetOpcode::STACKMAP
3023 ? InstSizeVerifyMode::AllowOverEstimate
3024 : InstSizeVerifyMode::ExactSize;
3025}
3026
3027std::pair<unsigned, unsigned>
3029 // PPC always uses a direct mask.
3030 return std::make_pair(TF, 0u);
3031}
3032
3035 using namespace PPCII;
3036 static const std::pair<unsigned, const char *> TargetFlags[] = {
3037 {MO_PLT, "ppc-plt"},
3038 {MO_PIC_FLAG, "ppc-pic"},
3039 {MO_PCREL_FLAG, "ppc-pcrel"},
3040 {MO_GOT_FLAG, "ppc-got"},
3041 {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"},
3042 {MO_TLSGD_FLAG, "ppc-tlsgd"},
3043 {MO_TPREL_FLAG, "ppc-tprel"},
3044 {MO_TLSLDM_FLAG, "ppc-tlsldm"},
3045 {MO_TLSLD_FLAG, "ppc-tlsld"},
3046 {MO_TLSGDM_FLAG, "ppc-tlsgdm"},
3047 {MO_GOT_TLSGD_PCREL_FLAG, "ppc-got-tlsgd-pcrel"},
3048 {MO_GOT_TLSLD_PCREL_FLAG, "ppc-got-tlsld-pcrel"},
3049 {MO_GOT_TPREL_PCREL_FLAG, "ppc-got-tprel-pcrel"},
3050 {MO_LO, "ppc-lo"},
3051 {MO_HA, "ppc-ha"},
3052 {MO_TPREL_LO, "ppc-tprel-lo"},
3053 {MO_TPREL_HA, "ppc-tprel-ha"},
3054 {MO_DTPREL_LO, "ppc-dtprel-lo"},
3055 {MO_TLSLD_LO, "ppc-tlsld-lo"},
3056 {MO_TOC_LO, "ppc-toc-lo"},
3057 {MO_TLS, "ppc-tls"},
3058 {MO_PIC_HA_FLAG, "ppc-ha-pic"},
3059 {MO_PIC_LO_FLAG, "ppc-lo-pic"},
3060 {MO_TPREL_PCREL_FLAG, "ppc-tprel-pcrel"},
3061 {MO_TLS_PCREL_FLAG, "ppc-tls-pcrel"},
3062 {MO_GOT_PCREL_FLAG, "ppc-got-pcrel"},
3063 };
3064 return ArrayRef(TargetFlags);
3065}
3066
3067// Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
3068// The VSX versions have the advantage of a full 64-register target whereas
3069// the FP ones have the advantage of lower latency and higher throughput. So
3070// what we are after is using the faster instructions in low register pressure
3071// situations and using the larger register file in high register pressure
3072// situations.
3074 unsigned UpperOpcode, LowerOpcode;
3075 switch (MI.getOpcode()) {
3076 case PPC::DFLOADf32:
3077 UpperOpcode = PPC::LXSSP;
3078 LowerOpcode = PPC::LFS;
3079 break;
3080 case PPC::DFLOADf64:
3081 UpperOpcode = PPC::LXSD;
3082 LowerOpcode = PPC::LFD;
3083 break;
3084 case PPC::DFSTOREf32:
3085 UpperOpcode = PPC::STXSSP;
3086 LowerOpcode = PPC::STFS;
3087 break;
3088 case PPC::DFSTOREf64:
3089 UpperOpcode = PPC::STXSD;
3090 LowerOpcode = PPC::STFD;
3091 break;
3092 case PPC::XFLOADf32:
3093 UpperOpcode = PPC::LXSSPX;
3094 LowerOpcode = PPC::LFSX;
3095 break;
3096 case PPC::XFLOADf64:
3097 UpperOpcode = PPC::LXSDX;
3098 LowerOpcode = PPC::LFDX;
3099 break;
3100 case PPC::XFSTOREf32:
3101 UpperOpcode = PPC::STXSSPX;
3102 LowerOpcode = PPC::STFSX;
3103 break;
3104 case PPC::XFSTOREf64:
3105 UpperOpcode = PPC::STXSDX;
3106 LowerOpcode = PPC::STFDX;
3107 break;
3108 case PPC::LIWAX:
3109 UpperOpcode = PPC::LXSIWAX;
3110 LowerOpcode = PPC::LFIWAX;
3111 break;
3112 case PPC::LIWZX:
3113 UpperOpcode = PPC::LXSIWZX;
3114 LowerOpcode = PPC::LFIWZX;
3115 break;
3116 case PPC::STIWX:
3117 UpperOpcode = PPC::STXSIWX;
3118 LowerOpcode = PPC::STFIWX;
3119 break;
3120 default:
3121 llvm_unreachable("Unknown Operation!");
3122 }
3123
3124 Register TargetReg = MI.getOperand(0).getReg();
3125 unsigned Opcode;
3126 if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
3127 (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
3128 Opcode = LowerOpcode;
3129 else
3130 Opcode = UpperOpcode;
3131 MI.setDesc(get(Opcode));
3132 return true;
3133}
3134
3135static bool isAnImmediateOperand(const MachineOperand &MO) {
3136 return MO.isCPI() || MO.isGlobal() || MO.isImm();
3137}
3138
3140 auto &MBB = *MI.getParent();
3141 auto DL = MI.getDebugLoc();
3142
3143 switch (MI.getOpcode()) {
3144 case PPC::BUILD_UACC: {
3145 MCRegister ACC = MI.getOperand(0).getReg();
3146 MCRegister UACC = MI.getOperand(1).getReg();
3147 if (ACC - PPC::ACC0 != UACC - PPC::UACC0) {
3148 MCRegister SrcVSR = PPC::VSL0 + (UACC - PPC::UACC0) * 4;
3149 MCRegister DstVSR = PPC::VSL0 + (ACC - PPC::ACC0) * 4;
3150 // FIXME: This can easily be improved to look up to the top of the MBB
3151 // to see if the inputs are XXLOR's. If they are and SrcReg is killed,
3152 // we can just re-target any such XXLOR's to DstVSR + offset.
3153 for (int VecNo = 0; VecNo < 4; VecNo++)
3154 BuildMI(MBB, MI, DL, get(PPC::XXLOR), DstVSR + VecNo)
3155 .addReg(SrcVSR + VecNo)
3156 .addReg(SrcVSR + VecNo);
3157 }
3158 // BUILD_UACC is expanded to 4 copies of the underlying vsx registers.
3159 // So after building the 4 copies, we can replace the BUILD_UACC instruction
3160 // with a NOP.
3161 [[fallthrough]];
3162 }
3163 case PPC::KILL_PAIR: {
3164 MI.setDesc(get(PPC::UNENCODED_NOP));
3165 MI.removeOperand(1);
3166 MI.removeOperand(0);
3167 return true;
3168 }
3169 case TargetOpcode::LOAD_STACK_GUARD: {
3170 auto M = MBB.getParent()->getFunction().getParent();
3171 assert(
3172 (Subtarget.isTargetLinux() || M->getStackProtectorGuard() == "tls") &&
3173 "Only Linux target or tls mode are expected to contain "
3174 "LOAD_STACK_GUARD");
3175 int64_t Offset;
3176 if (M->getStackProtectorGuard() == "tls")
3177 Offset = M->getStackProtectorGuardOffset();
3178 else
3179 Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
3180 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
3181 MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
3182 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3183 .addImm(Offset)
3184 .addReg(Reg);
3185 return true;
3186 }
3187 case PPC::PPCLdFixedAddr: {
3188 assert((Subtarget.getTargetTriple().isOSGlibc() ||
3189 Subtarget.getTargetTriple().isMusl()) &&
3190 "Only targets with Glibc expected to contain PPCLdFixedAddr");
3191 int64_t Offset = 0;
3192 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
3193 MI.setDesc(get(PPC::LWZ));
3194 uint64_t FAType = MI.getOperand(1).getImm();
3195#undef PPC_LNX_FEATURE
3196#undef PPC_CPU
3197#define PPC_LNX_DEFINE_OFFSETS
3198#include "llvm/TargetParser/PPCTargetParser.def"
3199 bool IsLE = Subtarget.isLittleEndian();
3200 bool Is64 = Subtarget.isPPC64();
3201 if (FAType == PPC_FAWORD_HWCAP) {
3202 if (IsLE)
3203 Offset = Is64 ? PPC_HWCAP_OFFSET_LE64 : PPC_HWCAP_OFFSET_LE32;
3204 else
3205 Offset = Is64 ? PPC_HWCAP_OFFSET_BE64 : PPC_HWCAP_OFFSET_BE32;
3206 } else if (FAType == PPC_FAWORD_HWCAP2) {
3207 if (IsLE)
3208 Offset = Is64 ? PPC_HWCAP2_OFFSET_LE64 : PPC_HWCAP2_OFFSET_LE32;
3209 else
3210 Offset = Is64 ? PPC_HWCAP2_OFFSET_BE64 : PPC_HWCAP2_OFFSET_BE32;
3211 } else if (FAType == PPC_FAWORD_CPUID) {
3212 if (IsLE)
3213 Offset = Is64 ? PPC_CPUID_OFFSET_LE64 : PPC_CPUID_OFFSET_LE32;
3214 else
3215 Offset = Is64 ? PPC_CPUID_OFFSET_BE64 : PPC_CPUID_OFFSET_BE32;
3216 }
3217 assert(Offset && "Do not know the offset for this fixed addr load");
3218 MI.removeOperand(1);
3219 Subtarget.getTargetMachine().setGlibcHWCAPAccess();
3220 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3221 .addImm(Offset)
3222 .addReg(Reg);
3223 return true;
3224#define PPC_TGT_PARSER_UNDEF_MACROS
3225#include "llvm/TargetParser/PPCTargetParser.def"
3226#undef PPC_TGT_PARSER_UNDEF_MACROS
3227 }
3228 case PPC::DFLOADf32:
3229 case PPC::DFLOADf64:
3230 case PPC::DFSTOREf32:
3231 case PPC::DFSTOREf64: {
3232 assert(Subtarget.hasP9Vector() &&
3233 "Invalid D-Form Pseudo-ops on Pre-P9 target.");
3234 assert(MI.getOperand(2).isReg() &&
3235 isAnImmediateOperand(MI.getOperand(1)) &&
3236 "D-form op must have register and immediate operands");
3237 return expandVSXMemPseudo(MI);
3238 }
3239 case PPC::XFLOADf32:
3240 case PPC::XFSTOREf32:
3241 case PPC::LIWAX:
3242 case PPC::LIWZX:
3243 case PPC::STIWX: {
3244 assert(Subtarget.hasP8Vector() &&
3245 "Invalid X-Form Pseudo-ops on Pre-P8 target.");
3246 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
3247 "X-form op must have register and register operands");
3248 return expandVSXMemPseudo(MI);
3249 }
3250 case PPC::XFLOADf64:
3251 case PPC::XFSTOREf64: {
3252 assert(Subtarget.hasVSX() &&
3253 "Invalid X-Form Pseudo-ops on target that has no VSX.");
3254 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
3255 "X-form op must have register and register operands");
3256 return expandVSXMemPseudo(MI);
3257 }
3258 case PPC::SPILLTOVSR_LD: {
3259 Register TargetReg = MI.getOperand(0).getReg();
3260 if (PPC::VSFRCRegClass.contains(TargetReg)) {
3261 MI.setDesc(get(PPC::DFLOADf64));
3262 return expandPostRAPseudo(MI);
3263 }
3264 else
3265 MI.setDesc(get(PPC::LD));
3266 return true;
3267 }
3268 case PPC::SPILLTOVSR_ST: {
3269 Register SrcReg = MI.getOperand(0).getReg();
3270 if (PPC::VSFRCRegClass.contains(SrcReg)) {
3271 NumStoreSPILLVSRRCAsVec++;
3272 MI.setDesc(get(PPC::DFSTOREf64));
3273 return expandPostRAPseudo(MI);
3274 } else {
3275 NumStoreSPILLVSRRCAsGpr++;
3276 MI.setDesc(get(PPC::STD));
3277 }
3278 return true;
3279 }
3280 case PPC::SPILLTOVSR_LDX: {
3281 Register TargetReg = MI.getOperand(0).getReg();
3282 if (PPC::VSFRCRegClass.contains(TargetReg))
3283 MI.setDesc(get(PPC::LXSDX));
3284 else
3285 MI.setDesc(get(PPC::LDX));
3286 return true;
3287 }
3288 case PPC::SPILLTOVSR_STX: {
3289 Register SrcReg = MI.getOperand(0).getReg();
3290 if (PPC::VSFRCRegClass.contains(SrcReg)) {
3291 NumStoreSPILLVSRRCAsVec++;
3292 MI.setDesc(get(PPC::STXSDX));
3293 } else {
3294 NumStoreSPILLVSRRCAsGpr++;
3295 MI.setDesc(get(PPC::STDX));
3296 }
3297 return true;
3298 }
3299
3300 // FIXME: Maybe we can expand it in 'PowerPC Expand Atomic' pass.
3301 case PPC::CFENCE:
3302 case PPC::CFENCE8: {
3303 auto Val = MI.getOperand(0).getReg();
3304 unsigned CmpOp = Subtarget.isPPC64() ? PPC::CMPD : PPC::CMPW;
3305 BuildMI(MBB, MI, DL, get(CmpOp), PPC::CR7).addReg(Val).addReg(Val);
3306 BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
3308 .addReg(PPC::CR7)
3309 .addImm(1);
3310 MI.setDesc(get(PPC::ISYNC));
3311 MI.removeOperand(1);
3312 MI.removeOperand(0);
3313 return true;
3314 }
3315 case PPC::LWAT_CSNE_PSEUDO:
3316 case PPC::LDAT_CSNE_PSEUDO:
3317 return expandAMOCSNEPseudo(MI);
3318 }
3319 return false;
3320}
3321
3322// Essentially a compile-time implementation of a compare->isel sequence.
3323// It takes two constants to compare, along with the true/false registers
3324// and the comparison type (as a subreg to a CR field) and returns one
3325// of the true/false registers, depending on the comparison results.
3326static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
3327 unsigned TrueReg, unsigned FalseReg,
3328 unsigned CRSubReg) {
3329 // Signed comparisons. The immediates are assumed to be sign-extended.
3330 if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
3331 switch (CRSubReg) {
3332 default: llvm_unreachable("Unknown integer comparison type.");
3333 case PPC::sub_lt:
3334 return Imm1 < Imm2 ? TrueReg : FalseReg;
3335 case PPC::sub_gt:
3336 return Imm1 > Imm2 ? TrueReg : FalseReg;
3337 case PPC::sub_eq:
3338 return Imm1 == Imm2 ? TrueReg : FalseReg;
3339 }
3340 }
3341 // Unsigned comparisons.
3342 else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
3343 switch (CRSubReg) {
3344 default: llvm_unreachable("Unknown integer comparison type.");
3345 case PPC::sub_lt:
3346 return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
3347 case PPC::sub_gt:
3348 return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
3349 case PPC::sub_eq:
3350 return Imm1 == Imm2 ? TrueReg : FalseReg;
3351 }
3352 }
3353 return PPC::NoRegister;
3354}
3355
3357 unsigned OpNo,
3358 int64_t Imm) const {
3359 assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
3360 // Replace the REG with the Immediate.
3361 Register InUseReg = MI.getOperand(OpNo).getReg();
3362 MI.getOperand(OpNo).ChangeToImmediate(Imm);
3363
3364 // We need to make sure that the MI didn't have any implicit use
3365 // of this REG any more. We don't call MI.implicit_operands().empty() to
3366 // return early, since MI's MCID might be changed in calling context, as a
3367 // result its number of explicit operands may be changed, thus the begin of
3368 // implicit operand is changed.
3369 int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, &RI, false);
3370 if (UseOpIdx >= 0) {
3371 MachineOperand &MO = MI.getOperand(UseOpIdx);
3372 if (MO.isImplicit())
3373 // The operands must always be in the following order:
3374 // - explicit reg defs,
3375 // - other explicit operands (reg uses, immediates, etc.),
3376 // - implicit reg defs
3377 // - implicit reg uses
3378 // Therefore, removing the implicit operand won't change the explicit
3379 // operands layout.
3380 MI.removeOperand(UseOpIdx);
3381 }
3382}
3383
3384// Replace an instruction with one that materializes a constant (and sets
3385// CR0 if the original instruction was a record-form instruction).
3387 const LoadImmediateInfo &LII) const {
3388 // Remove existing operands.
3389 int OperandToKeep = LII.SetCR ? 1 : 0;
3390 for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
3391 MI.removeOperand(i);
3392
3393 // Replace the instruction.
3394 if (LII.SetCR) {
3395 MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3396 // Set the immediate.
3397 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3398 .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
3399 return;
3400 }
3401 else
3402 MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
3403
3404 // Set the immediate.
3405 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3406 .addImm(LII.Imm);
3407}
3408
3410 bool &SeenIntermediateUse) const {
3411 assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
3412 "Should be called after register allocation.");
3413 MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
3414 It++;
3415 SeenIntermediateUse = false;
3416 for (; It != E; ++It) {
3417 if (It->modifiesRegister(Reg, &RI))
3418 return &*It;
3419 if (It->readsRegister(Reg, &RI))
3420 SeenIntermediateUse = true;
3421 }
3422 return nullptr;
3423}
3424
3427 const DebugLoc &DL, Register Reg,
3428 int64_t Imm) const {
3429 assert(!MBB.getParent()->getRegInfo().isSSA() &&
3430 "Register should be in non-SSA form after RA");
3431 bool isPPC64 = Subtarget.isPPC64();
3432 // FIXME: Materialization here is not optimal.
3433 // For some special bit patterns we can use less instructions.
3434 // See `selectI64ImmDirect` in PPCISelDAGToDAG.cpp.
3435 if (isInt<16>(Imm)) {
3436 BuildMI(MBB, MBBI, DL, get(isPPC64 ? PPC::LI8 : PPC::LI), Reg).addImm(Imm);
3437 } else if (isInt<32>(Imm)) {
3438 BuildMI(MBB, MBBI, DL, get(isPPC64 ? PPC::LIS8 : PPC::LIS), Reg)
3439 .addImm(Imm >> 16);
3440 if (Imm & 0xFFFF)
3441 BuildMI(MBB, MBBI, DL, get(isPPC64 ? PPC::ORI8 : PPC::ORI), Reg)
3442 .addReg(Reg, RegState::Kill)
3443 .addImm(Imm & 0xFFFF);
3444 } else {
3445 assert(isPPC64 && "Materializing 64-bit immediate to single register is "
3446 "only supported in PPC64");
3447 BuildMI(MBB, MBBI, DL, get(PPC::LIS8), Reg).addImm(Imm >> 48);
3448 if ((Imm >> 32) & 0xFFFF)
3449 BuildMI(MBB, MBBI, DL, get(PPC::ORI8), Reg)
3450 .addReg(Reg, RegState::Kill)
3451 .addImm((Imm >> 32) & 0xFFFF);
3452 BuildMI(MBB, MBBI, DL, get(PPC::RLDICR), Reg)
3453 .addReg(Reg, RegState::Kill)
3454 .addImm(32)
3455 .addImm(31);
3456 BuildMI(MBB, MBBI, DL, get(PPC::ORIS8), Reg)
3457 .addReg(Reg, RegState::Kill)
3458 .addImm((Imm >> 16) & 0xFFFF);
3459 if (Imm & 0xFFFF)
3460 BuildMI(MBB, MBBI, DL, get(PPC::ORI8), Reg)
3461 .addReg(Reg, RegState::Kill)
3462 .addImm(Imm & 0xFFFF);
3463 }
3464}
3465
3466MachineInstr *PPCInstrInfo::getForwardingDefMI(
3468 unsigned &OpNoForForwarding,
3469 bool &SeenIntermediateUse) const {
3470 OpNoForForwarding = ~0U;
3471 MachineInstr *DefMI = nullptr;
3472 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3473 // If we're in SSA, get the defs through the MRI. Otherwise, only look
3474 // within the basic block to see if the register is defined using an
3475 // LI/LI8/ADDI/ADDI8.
3476 if (MRI->isSSA()) {
3477 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3478 if (!MI.getOperand(i).isReg())
3479 continue;
3480 Register Reg = MI.getOperand(i).getReg();
3481 if (!Reg.isVirtual())
3482 continue;
3483 Register TrueReg = RI.lookThruCopyLike(Reg, MRI);
3484 if (TrueReg.isVirtual()) {
3485 MachineInstr *DefMIForTrueReg = MRI->getVRegDef(TrueReg);
3486 if (!DefMIForTrueReg)
3487 continue;
3488 if (DefMIForTrueReg->getOpcode() == PPC::LI ||
3489 DefMIForTrueReg->getOpcode() == PPC::LI8 ||
3490 DefMIForTrueReg->getOpcode() == PPC::ADDI ||
3491 DefMIForTrueReg->getOpcode() == PPC::ADDI8) {
3492 OpNoForForwarding = i;
3493 DefMI = DefMIForTrueReg;
3494 // The ADDI and LI operand maybe exist in one instruction at same
3495 // time. we prefer to fold LI operand as LI only has one Imm operand
3496 // and is more possible to be converted. So if current DefMI is
3497 // ADDI/ADDI8, we continue to find possible LI/LI8.
3498 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
3499 break;
3500 }
3501 }
3502 }
3503 } else {
3504 // Looking back through the definition for each operand could be expensive,
3505 // so exit early if this isn't an instruction that either has an immediate
3506 // form or is already an immediate form that we can handle.
3507 ImmInstrInfo III;
3508 unsigned Opc = MI.getOpcode();
3509 bool ConvertibleImmForm =
3510 Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
3511 Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
3512 Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
3513 Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
3514 Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
3515 Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
3516 Opc == PPC::RLWINM8_rec;
3517 bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
3518 ? PPC::isVFRegister(MI.getOperand(0).getReg())
3519 : false;
3520 if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
3521 return nullptr;
3522
3523 // Don't convert or %X, %Y, %Y since that's just a register move.
3524 if ((Opc == PPC::OR || Opc == PPC::OR8) &&
3525 MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
3526 return nullptr;
3527 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3528 MachineOperand &MO = MI.getOperand(i);
3529 SeenIntermediateUse = false;
3530 if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
3531 Register Reg = MI.getOperand(i).getReg();
3532 // If we see another use of this reg between the def and the MI,
3533 // we want to flag it so the def isn't deleted.
3534 MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
3535 if (DefMI) {
3536 // Is this register defined by some form of add-immediate (including
3537 // load-immediate) within this basic block?
3538 switch (DefMI->getOpcode()) {
3539 default:
3540 break;
3541 case PPC::LI:
3542 case PPC::LI8:
3543 case PPC::ADDItocL8:
3544 case PPC::ADDI:
3545 case PPC::ADDI8:
3546 OpNoForForwarding = i;
3547 return DefMI;
3548 }
3549 }
3550 }
3551 }
3552 }
3553 return OpNoForForwarding == ~0U ? nullptr : DefMI;
3554}
3555
3556unsigned PPCInstrInfo::getSpillTarget() const {
3557 // With P10, we may need to spill paired vector registers or accumulator
3558 // registers. MMA implies paired vectors, so we can just check that.
3559 bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
3560 // P11 uses the P10 target.
3561 return Subtarget.isISAFuture() ? 3 : IsP10Variant ?
3562 2 : Subtarget.hasP9Vector() ?
3563 1 : 0;
3564}
3565
3566ArrayRef<unsigned> PPCInstrInfo::getStoreOpcodesForSpillArray() const {
3567 return {StoreSpillOpcodesArray[getSpillTarget()], SOK_LastOpcodeSpill};
3568}
3569
3570ArrayRef<unsigned> PPCInstrInfo::getLoadOpcodesForSpillArray() const {
3571 return {LoadSpillOpcodesArray[getSpillTarget()], SOK_LastOpcodeSpill};
3572}
3573
3574// This opt tries to convert the following imm form to an index form to save an
3575// add for stack variables.
3576// Return false if no such pattern found.
3577//
3578// ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3579// ADD instr: ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
3580// Imm instr: Reg = op OffsetImm, ToBeDeletedReg(killed)
3581//
3582// can be converted to:
3583//
3584// new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
3585// Index instr: Reg = opx ScaleReg, ToBeChangedReg(killed)
3586//
3587// In order to eliminate ADD instr, make sure that:
3588// 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
3589// new ADDI instr and ADDI can only take int16 Imm.
3590// 2: ToBeChangedReg must be killed in ADD instr and there is no other use
3591// between ADDI and ADD instr since its original def in ADDI will be changed
3592// in new ADDI instr. And also there should be no new def for it between
3593// ADD and Imm instr as ToBeChangedReg will be used in Index instr.
3594// 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
3595// between ADD and Imm instr since ADD instr will be eliminated.
3596// 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
3597// moved to Index instr.
3599 MachineFunction *MF = MI.getParent()->getParent();
3601 bool PostRA = !MRI->isSSA();
3602 // Do this opt after PEI which is after RA. The reason is stack slot expansion
3603 // in PEI may expose such opportunities since in PEI, stack slot offsets to
3604 // frame base(OffsetAddi) are determined.
3605 if (!PostRA)
3606 return false;
3607 unsigned ToBeDeletedReg = 0;
3608 int64_t OffsetImm = 0;
3609 unsigned XFormOpcode = 0;
3610 ImmInstrInfo III;
3611
3612 // Check if Imm instr meets requirement.
3613 if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
3614 III))
3615 return false;
3616
3617 bool OtherIntermediateUse = false;
3618 MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
3619
3620 // Exit if there is other use between ADD and Imm instr or no def found.
3621 if (OtherIntermediateUse || !ADDMI)
3622 return false;
3623
3624 // Check if ADD instr meets requirement.
3625 if (!isADDInstrEligibleForFolding(*ADDMI))
3626 return false;
3627
3628 unsigned ScaleRegIdx = 0;
3629 int64_t OffsetAddi = 0;
3630 MachineInstr *ADDIMI = nullptr;
3631
3632 // Check if there is a valid ToBeChangedReg in ADDMI.
3633 // 1: It must be killed.
3634 // 2: Its definition must be a valid ADDIMI.
3635 // 3: It must satify int16 offset requirement.
3636 if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
3637 ScaleRegIdx = 2;
3638 else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
3639 ScaleRegIdx = 1;
3640 else
3641 return false;
3642
3643 assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
3644 Register ToBeChangedReg = ADDIMI->getOperand(0).getReg();
3645 Register ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
3646 auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
3648 for (auto It = ++Start; It != End; It++)
3649 if (It->modifiesRegister(Reg, &getRegisterInfo()))
3650 return true;
3651 return false;
3652 };
3653
3654 // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
3655 // treated as special zero when ScaleReg is R0/X0 register.
3656 if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
3657 (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
3658 return false;
3659
3660 // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
3661 // and Imm Instr.
3662 if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
3663 return false;
3664
3665 // Now start to do the transformation.
3666 LLVM_DEBUG(dbgs() << "Replace instruction: "
3667 << "\n");
3668 LLVM_DEBUG(ADDIMI->dump());
3669 LLVM_DEBUG(ADDMI->dump());
3670 LLVM_DEBUG(MI.dump());
3671 LLVM_DEBUG(dbgs() << "with: "
3672 << "\n");
3673
3674 // Update ADDI instr.
3675 ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
3676
3677 // Update Imm instr.
3678 MI.setDesc(get(XFormOpcode));
3679 MI.getOperand(III.ImmOpNo)
3680 .ChangeToRegister(ScaleReg, false, false,
3681 ADDMI->getOperand(ScaleRegIdx).isKill());
3682
3683 MI.getOperand(III.OpNoForForwarding)
3684 .ChangeToRegister(ToBeChangedReg, false, false, true);
3685
3686 // Eliminate ADD instr.
3687 ADDMI->eraseFromParent();
3688
3689 LLVM_DEBUG(ADDIMI->dump());
3690 LLVM_DEBUG(MI.dump());
3691
3692 return true;
3693}
3694
3696 int64_t &Imm) const {
3697 unsigned Opc = ADDIMI.getOpcode();
3698
3699 // Exit if the instruction is not ADDI.
3700 if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
3701 return false;
3702
3703 // The operand may not necessarily be an immediate - it could be a relocation.
3704 if (!ADDIMI.getOperand(2).isImm())
3705 return false;
3706
3707 Imm = ADDIMI.getOperand(2).getImm();
3708
3709 return true;
3710}
3711
3713 unsigned Opc = ADDMI.getOpcode();
3714
3715 // Exit if the instruction is not ADD.
3716 return Opc == PPC::ADD4 || Opc == PPC::ADD8;
3717}
3718
3720 unsigned &ToBeDeletedReg,
3721 unsigned &XFormOpcode,
3722 int64_t &OffsetImm,
3723 ImmInstrInfo &III) const {
3724 // Only handle load/store.
3725 if (!MI.mayLoadOrStore())
3726 return false;
3727
3728 unsigned Opc = MI.getOpcode();
3729
3730 XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
3731
3732 // Exit if instruction has no index form.
3733 if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
3734 return false;
3735
3736 // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
3737 if (!instrHasImmForm(XFormOpcode,
3738 PPC::isVFRegister(MI.getOperand(0).getReg()), III, true))
3739 return false;
3740
3741 if (!III.IsSummingOperands)
3742 return false;
3743
3744 MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
3745 MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
3746 // Only support imm operands, not relocation slots or others.
3747 if (!ImmOperand.isImm())
3748 return false;
3749
3750 assert(RegOperand.isReg() && "Instruction format is not right");
3751
3752 // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
3753 if (!RegOperand.isKill())
3754 return false;
3755
3756 ToBeDeletedReg = RegOperand.getReg();
3757 OffsetImm = ImmOperand.getImm();
3758
3759 return true;
3760}
3761
3763 MachineInstr *&ADDIMI,
3764 int64_t &OffsetAddi,
3765 int64_t OffsetImm) const {
3766 assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
3767 MachineOperand &MO = ADDMI->getOperand(Index);
3768
3769 if (!MO.isKill())
3770 return false;
3771
3772 bool OtherIntermediateUse = false;
3773
3774 ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
3775 // Currently handle only one "add + Imminstr" pair case, exit if other
3776 // intermediate use for ToBeChangedReg found.
3777 // TODO: handle the cases where there are other "add + Imminstr" pairs
3778 // with same offset in Imminstr which is like:
3779 //
3780 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3781 // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
3782 // Imm instr1: Reg1 = op1 OffsetImm, ToBeDeletedReg1(killed)
3783 // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
3784 // Imm instr2: Reg2 = op2 OffsetImm, ToBeDeletedReg2(killed)
3785 //
3786 // can be converted to:
3787 //
3788 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
3789 // (OffsetAddi + OffsetImm)
3790 // Index instr1: Reg1 = opx1 ScaleReg1, ToBeChangedReg
3791 // Index instr2: Reg2 = opx2 ScaleReg2, ToBeChangedReg(killed)
3792
3793 if (OtherIntermediateUse || !ADDIMI)
3794 return false;
3795 // Check if ADDI instr meets requirement.
3796 if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
3797 return false;
3798
3799 if (isInt<16>(OffsetAddi + OffsetImm))
3800 return true;
3801 return false;
3802}
3803
3804// If this instruction has an immediate form and one of its operands is a
3805// result of a load-immediate or an add-immediate, convert it to
3806// the immediate form if the constant is in range.
3808 SmallSet<Register, 4> &RegsToUpdate,
3809 MachineInstr **KilledDef) const {
3810 MachineFunction *MF = MI.getParent()->getParent();
3812 bool PostRA = !MRI->isSSA();
3813 bool SeenIntermediateUse = true;
3814 unsigned ForwardingOperand = ~0U;
3815 MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
3816 SeenIntermediateUse);
3817 if (!DefMI)
3818 return false;
3819 assert(ForwardingOperand < MI.getNumOperands() &&
3820 "The forwarding operand needs to be valid at this point");
3821 bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
3822 bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
3823 if (KilledDef && KillFwdDefMI)
3824 *KilledDef = DefMI;
3825
3826 // Conservatively add defs from DefMI and defs/uses from MI to the set of
3827 // registers that need their kill flags updated.
3828 for (const MachineOperand &MO : DefMI->operands())
3829 if (MO.isReg() && MO.isDef())
3830 RegsToUpdate.insert(MO.getReg());
3831 for (const MachineOperand &MO : MI.operands())
3832 if (MO.isReg())
3833 RegsToUpdate.insert(MO.getReg());
3834
3835 // If this is a imm instruction and its register operands is produced by ADDI,
3836 // put the imm into imm inst directly.
3837 if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) !=
3838 PPC::INSTRUCTION_LIST_END &&
3839 transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand))
3840 return true;
3841
3842 ImmInstrInfo III;
3843 bool IsVFReg = MI.getOperand(0).isReg() &&
3844 MI.getOperand(0).getReg().isPhysical() &&
3845 PPC::isVFRegister(MI.getOperand(0).getReg());
3846 bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
3847 // If this is a reg+reg instruction that has a reg+imm form,
3848 // and one of the operands is produced by an add-immediate,
3849 // try to convert it.
3850 if (HasImmForm &&
3851 transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
3852 KillFwdDefMI))
3853 return true;
3854
3855 // If this is a reg+reg instruction that has a reg+imm form,
3856 // and one of the operands is produced by LI, convert it now.
3857 if (HasImmForm &&
3858 transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI))
3859 return true;
3860
3861 // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
3862 // can be simpified to LI.
3863 if (!HasImmForm &&
3864 simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef, &RegsToUpdate))
3865 return true;
3866
3867 return false;
3868}
3869
3871 MachineInstr **ToErase) const {
3872 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3873 Register FoldingReg = MI.getOperand(1).getReg();
3874 if (!FoldingReg.isVirtual())
3875 return false;
3876 MachineInstr *SrcMI = MRI->getVRegDef(FoldingReg);
3877 if (!SrcMI)
3878 return false;
3879 if (SrcMI->getOpcode() != PPC::RLWINM &&
3880 SrcMI->getOpcode() != PPC::RLWINM_rec &&
3881 SrcMI->getOpcode() != PPC::RLWINM8 &&
3882 SrcMI->getOpcode() != PPC::RLWINM8_rec)
3883 return false;
3884 assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
3885 MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
3886 SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
3887 "Invalid PPC::RLWINM Instruction!");
3888 uint64_t SHSrc = SrcMI->getOperand(2).getImm();
3889 uint64_t SHMI = MI.getOperand(2).getImm();
3890 uint64_t MBSrc = SrcMI->getOperand(3).getImm();
3891 uint64_t MBMI = MI.getOperand(3).getImm();
3892 uint64_t MESrc = SrcMI->getOperand(4).getImm();
3893 uint64_t MEMI = MI.getOperand(4).getImm();
3894
3895 assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
3896 "Invalid PPC::RLWINM Instruction!");
3897 // If MBMI is bigger than MEMI, we always can not get run of ones.
3898 // RotatedSrcMask non-wrap:
3899 // 0........31|32........63
3900 // RotatedSrcMask: B---E B---E
3901 // MaskMI: -----------|--E B------
3902 // Result: ----- --- (Bad candidate)
3903 //
3904 // RotatedSrcMask wrap:
3905 // 0........31|32........63
3906 // RotatedSrcMask: --E B----|--E B----
3907 // MaskMI: -----------|--E B------
3908 // Result: --- -----|--- ----- (Bad candidate)
3909 //
3910 // One special case is RotatedSrcMask is a full set mask.
3911 // RotatedSrcMask full:
3912 // 0........31|32........63
3913 // RotatedSrcMask: ------EB---|-------EB---
3914 // MaskMI: -----------|--E B------
3915 // Result: -----------|--- ------- (Good candidate)
3916
3917 // Mark special case.
3918 bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
3919
3920 // For other MBMI > MEMI cases, just return.
3921 if ((MBMI > MEMI) && !SrcMaskFull)
3922 return false;
3923
3924 // Handle MBMI <= MEMI cases.
3925 APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI);
3926 // In MI, we only need low 32 bits of SrcMI, just consider about low 32
3927 // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
3928 // while in PowerPC ISA, lowerest bit is at index 63.
3929 APInt MaskSrc = APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc);
3930
3931 APInt RotatedSrcMask = MaskSrc.rotl(SHMI);
3932 APInt FinalMask = RotatedSrcMask & MaskMI;
3933 uint32_t NewMB, NewME;
3934 bool Simplified = false;
3935
3936 // If final mask is 0, MI result should be 0 too.
3937 if (FinalMask.isZero()) {
3938 bool Is64Bit =
3939 (MI.getOpcode() == PPC::RLWINM8 || MI.getOpcode() == PPC::RLWINM8_rec);
3940 Simplified = true;
3941 LLVM_DEBUG(dbgs() << "Replace Instr: ");
3942 LLVM_DEBUG(MI.dump());
3943
3944 if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
3945 // Replace MI with "LI 0"
3946 MI.removeOperand(4);
3947 MI.removeOperand(3);
3948 MI.removeOperand(2);
3949 MI.getOperand(1).ChangeToImmediate(0);
3950 MI.setDesc(get(Is64Bit ? PPC::LI8 : PPC::LI));
3951 } else {
3952 // Replace MI with "ANDI_rec reg, 0"
3953 MI.removeOperand(4);
3954 MI.removeOperand(3);
3955 MI.getOperand(2).setImm(0);
3956 MI.setDesc(get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3957 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3958 if (SrcMI->getOperand(1).isKill()) {
3959 MI.getOperand(1).setIsKill(true);
3960 SrcMI->getOperand(1).setIsKill(false);
3961 } else
3962 // About to replace MI.getOperand(1), clear its kill flag.
3963 MI.getOperand(1).setIsKill(false);
3964 }
3965
3966 LLVM_DEBUG(dbgs() << "With: ");
3967 LLVM_DEBUG(MI.dump());
3968
3969 } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, NewME) &&
3970 NewMB <= NewME) ||
3971 SrcMaskFull) {
3972 // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
3973 // than NewME. Otherwise we get a 64 bit value after folding, but MI
3974 // return a 32 bit value.
3975 Simplified = true;
3976 LLVM_DEBUG(dbgs() << "Converting Instr: ");
3977 LLVM_DEBUG(MI.dump());
3978
3979 uint16_t NewSH = (SHSrc + SHMI) % 32;
3980 MI.getOperand(2).setImm(NewSH);
3981 // If SrcMI mask is full, no need to update MBMI and MEMI.
3982 if (!SrcMaskFull) {
3983 MI.getOperand(3).setImm(NewMB);
3984 MI.getOperand(4).setImm(NewME);
3985 }
3986 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3987 if (SrcMI->getOperand(1).isKill()) {
3988 MI.getOperand(1).setIsKill(true);
3989 SrcMI->getOperand(1).setIsKill(false);
3990 } else
3991 // About to replace MI.getOperand(1), clear its kill flag.
3992 MI.getOperand(1).setIsKill(false);
3993
3994 LLVM_DEBUG(dbgs() << "To: ");
3995 LLVM_DEBUG(MI.dump());
3996 }
3997 if (Simplified & MRI->use_nodbg_empty(FoldingReg) &&
3998 !SrcMI->hasImplicitDef()) {
3999 // If FoldingReg has no non-debug use and it has no implicit def (it
4000 // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI.
4001 // Otherwise keep it.
4002 *ToErase = SrcMI;
4003 LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
4004 LLVM_DEBUG(SrcMI->dump());
4005 }
4006 return Simplified;
4007}
4008
4009bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
4010 ImmInstrInfo &III, bool PostRA) const {
4011 // The vast majority of the instructions would need their operand 2 replaced
4012 // with an immediate when switching to the reg+imm form. A marked exception
4013 // are the update form loads/stores for which a constant operand 2 would need
4014 // to turn into a displacement and move operand 1 to the operand 2 position.
4015 III.ImmOpNo = 2;
4016 III.OpNoForForwarding = 2;
4017 III.ImmWidth = 16;
4018 III.ImmMustBeMultipleOf = 1;
4019 III.TruncateImmTo = 0;
4020 III.IsSummingOperands = false;
4021 switch (Opc) {
4022 default: return false;
4023 case PPC::ADD4:
4024 case PPC::ADD8:
4025 III.SignedImm = true;
4026 III.ZeroIsSpecialOrig = 0;
4027 III.ZeroIsSpecialNew = 1;
4028 III.IsCommutative = true;
4029 III.IsSummingOperands = true;
4030 III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
4031 break;
4032 case PPC::ADDC:
4033 case PPC::ADDC8:
4034 III.SignedImm = true;
4035 III.ZeroIsSpecialOrig = 0;
4036 III.ZeroIsSpecialNew = 0;
4037 III.IsCommutative = true;
4038 III.IsSummingOperands = true;
4039 III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
4040 break;
4041 case PPC::ADDC_rec:
4042 III.SignedImm = true;
4043 III.ZeroIsSpecialOrig = 0;
4044 III.ZeroIsSpecialNew = 0;
4045 III.IsCommutative = true;
4046 III.IsSummingOperands = true;
4047 III.ImmOpcode = PPC::ADDIC_rec;
4048 break;
4049 case PPC::SUBFC:
4050 case PPC::SUBFC8:
4051 III.SignedImm = true;
4052 III.ZeroIsSpecialOrig = 0;
4053 III.ZeroIsSpecialNew = 0;
4054 III.IsCommutative = false;
4055 III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
4056 break;
4057 case PPC::CMPW:
4058 case PPC::CMPD:
4059 III.SignedImm = true;
4060 III.ZeroIsSpecialOrig = 0;
4061 III.ZeroIsSpecialNew = 0;
4062 III.IsCommutative = false;
4063 III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
4064 break;
4065 case PPC::CMPLW:
4066 case PPC::CMPLD:
4067 III.SignedImm = false;
4068 III.ZeroIsSpecialOrig = 0;
4069 III.ZeroIsSpecialNew = 0;
4070 III.IsCommutative = false;
4071 III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
4072 break;
4073 case PPC::AND_rec:
4074 case PPC::AND8_rec:
4075 case PPC::OR:
4076 case PPC::OR8:
4077 case PPC::XOR:
4078 case PPC::XOR8:
4079 III.SignedImm = false;
4080 III.ZeroIsSpecialOrig = 0;
4081 III.ZeroIsSpecialNew = 0;
4082 III.IsCommutative = true;
4083 switch(Opc) {
4084 default: llvm_unreachable("Unknown opcode");
4085 case PPC::AND_rec:
4086 III.ImmOpcode = PPC::ANDI_rec;
4087 break;
4088 case PPC::AND8_rec:
4089 III.ImmOpcode = PPC::ANDI8_rec;
4090 break;
4091 case PPC::OR: III.ImmOpcode = PPC::ORI; break;
4092 case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
4093 case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
4094 case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
4095 }
4096 break;
4097 case PPC::RLWNM:
4098 case PPC::RLWNM8:
4099 case PPC::RLWNM_rec:
4100 case PPC::RLWNM8_rec:
4101 case PPC::SLW:
4102 case PPC::SLW8:
4103 case PPC::SLW_rec:
4104 case PPC::SLW8_rec:
4105 case PPC::SRW:
4106 case PPC::SRW8:
4107 case PPC::SRW_rec:
4108 case PPC::SRW8_rec:
4109 case PPC::SRAW:
4110 case PPC::SRAW_rec:
4111 III.SignedImm = false;
4112 III.ZeroIsSpecialOrig = 0;
4113 III.ZeroIsSpecialNew = 0;
4114 III.IsCommutative = false;
4115 // This isn't actually true, but the instructions ignore any of the
4116 // upper bits, so any immediate loaded with an LI is acceptable.
4117 // This does not apply to shift right algebraic because a value
4118 // out of range will produce a -1/0.
4119 III.ImmWidth = 16;
4120 if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
4121 Opc == PPC::RLWNM8_rec)
4122 III.TruncateImmTo = 5;
4123 else
4124 III.TruncateImmTo = 6;
4125 switch(Opc) {
4126 default: llvm_unreachable("Unknown opcode");
4127 case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
4128 case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
4129 case PPC::RLWNM_rec:
4130 III.ImmOpcode = PPC::RLWINM_rec;
4131 break;
4132 case PPC::RLWNM8_rec:
4133 III.ImmOpcode = PPC::RLWINM8_rec;
4134 break;
4135 case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
4136 case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
4137 case PPC::SLW_rec:
4138 III.ImmOpcode = PPC::RLWINM_rec;
4139 break;
4140 case PPC::SLW8_rec:
4141 III.ImmOpcode = PPC::RLWINM8_rec;
4142 break;
4143 case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
4144 case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
4145 case PPC::SRW_rec:
4146 III.ImmOpcode = PPC::RLWINM_rec;
4147 break;
4148 case PPC::SRW8_rec:
4149 III.ImmOpcode = PPC::RLWINM8_rec;
4150 break;
4151 case PPC::SRAW:
4152 III.ImmWidth = 5;
4153 III.TruncateImmTo = 0;
4154 III.ImmOpcode = PPC::SRAWI;
4155 break;
4156 case PPC::SRAW_rec:
4157 III.ImmWidth = 5;
4158 III.TruncateImmTo = 0;
4159 III.ImmOpcode = PPC::SRAWI_rec;
4160 break;
4161 }
4162 break;
4163 case PPC::RLDCL:
4164 case PPC::RLDCL_rec:
4165 case PPC::RLDCR:
4166 case PPC::RLDCR_rec:
4167 case PPC::SLD:
4168 case PPC::SLD_rec:
4169 case PPC::SRD:
4170 case PPC::SRD_rec:
4171 case PPC::SRAD:
4172 case PPC::SRAD_rec:
4173 III.SignedImm = false;
4174 III.ZeroIsSpecialOrig = 0;
4175 III.ZeroIsSpecialNew = 0;
4176 III.IsCommutative = false;
4177 // This isn't actually true, but the instructions ignore any of the
4178 // upper bits, so any immediate loaded with an LI is acceptable.
4179 // This does not apply to shift right algebraic because a value
4180 // out of range will produce a -1/0.
4181 III.ImmWidth = 16;
4182 if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
4183 Opc == PPC::RLDCR_rec)
4184 III.TruncateImmTo = 6;
4185 else
4186 III.TruncateImmTo = 7;
4187 switch(Opc) {
4188 default: llvm_unreachable("Unknown opcode");
4189 case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
4190 case PPC::RLDCL_rec:
4191 III.ImmOpcode = PPC::RLDICL_rec;
4192 break;
4193 case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
4194 case PPC::RLDCR_rec:
4195 III.ImmOpcode = PPC::RLDICR_rec;
4196 break;
4197 case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
4198 case PPC::SLD_rec:
4199 III.ImmOpcode = PPC::RLDICR_rec;
4200 break;
4201 case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
4202 case PPC::SRD_rec:
4203 III.ImmOpcode = PPC::RLDICL_rec;
4204 break;
4205 case PPC::SRAD:
4206 III.ImmWidth = 6;
4207 III.TruncateImmTo = 0;
4208 III.ImmOpcode = PPC::SRADI;
4209 break;
4210 case PPC::SRAD_rec:
4211 III.ImmWidth = 6;
4212 III.TruncateImmTo = 0;
4213 III.ImmOpcode = PPC::SRADI_rec;
4214 break;
4215 }
4216 break;
4217 // Loads and stores:
4218 case PPC::LBZX:
4219 case PPC::LBZX8:
4220 case PPC::LHZX:
4221 case PPC::LHZX8:
4222 case PPC::LHAX:
4223 case PPC::LHAX8:
4224 case PPC::LWZX:
4225 case PPC::LWZX8:
4226 case PPC::LWAX:
4227 case PPC::LDX:
4228 case PPC::LFSX:
4229 case PPC::LFDX:
4230 case PPC::STBX:
4231 case PPC::STBX8:
4232 case PPC::STHX:
4233 case PPC::STHX8:
4234 case PPC::STWX:
4235 case PPC::STWX8:
4236 case PPC::STDX:
4237 case PPC::STFSX:
4238 case PPC::STFDX:
4239 III.SignedImm = true;
4240 III.ZeroIsSpecialOrig = 1;
4241 III.ZeroIsSpecialNew = 2;
4242 III.IsCommutative = true;
4243 III.IsSummingOperands = true;
4244 III.ImmOpNo = 1;
4245 III.OpNoForForwarding = 2;
4246 switch(Opc) {
4247 default: llvm_unreachable("Unknown opcode");
4248 case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
4249 case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
4250 case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
4251 case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
4252 case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
4253 case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
4254 case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
4255 case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
4256 case PPC::LWAX:
4257 III.ImmOpcode = PPC::LWA;
4258 III.ImmMustBeMultipleOf = 4;
4259 break;
4260 case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
4261 case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
4262 case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
4263 case PPC::STBX: III.ImmOpcode = PPC::STB; break;
4264 case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
4265 case PPC::STHX: III.ImmOpcode = PPC::STH; break;
4266 case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
4267 case PPC::STWX: III.ImmOpcode = PPC::STW; break;
4268 case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
4269 case PPC::STDX:
4270 III.ImmOpcode = PPC::STD;
4271 III.ImmMustBeMultipleOf = 4;
4272 break;
4273 case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
4274 case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
4275 }
4276 break;
4277 case PPC::LBZUX:
4278 case PPC::LBZUX8:
4279 case PPC::LHZUX:
4280 case PPC::LHZUX8:
4281 case PPC::LHAUX:
4282 case PPC::LHAUX8:
4283 case PPC::LWZUX:
4284 case PPC::LWZUX8:
4285 case PPC::LDUX:
4286 case PPC::LFSUX:
4287 case PPC::LFDUX:
4288 case PPC::STBUX:
4289 case PPC::STBUX8:
4290 case PPC::STHUX:
4291 case PPC::STHUX8:
4292 case PPC::STWUX:
4293 case PPC::STWUX8:
4294 case PPC::STDUX:
4295 case PPC::STFSUX:
4296 case PPC::STFDUX:
4297 III.SignedImm = true;
4298 III.ZeroIsSpecialOrig = 2;
4299 III.ZeroIsSpecialNew = 3;
4300 III.IsCommutative = false;
4301 III.IsSummingOperands = true;
4302 III.ImmOpNo = 2;
4303 III.OpNoForForwarding = 3;
4304 switch(Opc) {
4305 default: llvm_unreachable("Unknown opcode");
4306 case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
4307 case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
4308 case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
4309 case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
4310 case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
4311 case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
4312 case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
4313 case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
4314 case PPC::LDUX:
4315 III.ImmOpcode = PPC::LDU;
4316 III.ImmMustBeMultipleOf = 4;
4317 break;
4318 case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
4319 case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
4320 case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
4321 case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
4322 case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
4323 case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
4324 case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
4325 case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
4326 case PPC::STDUX:
4327 III.ImmOpcode = PPC::STDU;
4328 III.ImmMustBeMultipleOf = 4;
4329 break;
4330 case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
4331 case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
4332 }
4333 break;
4334 // Power9 and up only. For some of these, the X-Form version has access to all
4335 // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
4336 // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
4337 // into or stored from is one of the VR registers.
4338 case PPC::LXVX:
4339 case PPC::LXSSPX:
4340 case PPC::LXSDX:
4341 case PPC::STXVX:
4342 case PPC::STXSSPX:
4343 case PPC::STXSDX:
4344 case PPC::XFLOADf32:
4345 case PPC::XFLOADf64:
4346 case PPC::XFSTOREf32:
4347 case PPC::XFSTOREf64:
4348 if (!Subtarget.hasP9Vector())
4349 return false;
4350 III.SignedImm = true;
4351 III.ZeroIsSpecialOrig = 1;
4352 III.ZeroIsSpecialNew = 2;
4353 III.IsCommutative = true;
4354 III.IsSummingOperands = true;
4355 III.ImmOpNo = 1;
4356 III.OpNoForForwarding = 2;
4357 III.ImmMustBeMultipleOf = 4;
4358 switch(Opc) {
4359 default: llvm_unreachable("Unknown opcode");
4360 case PPC::LXVX:
4361 III.ImmOpcode = PPC::LXV;
4362 III.ImmMustBeMultipleOf = 16;
4363 break;
4364 case PPC::LXSSPX:
4365 if (PostRA) {
4366 if (IsVFReg)
4367 III.ImmOpcode = PPC::LXSSP;
4368 else {
4369 III.ImmOpcode = PPC::LFS;
4370 III.ImmMustBeMultipleOf = 1;
4371 }
4372 break;
4373 }
4374 [[fallthrough]];
4375 case PPC::XFLOADf32:
4376 III.ImmOpcode = PPC::DFLOADf32;
4377 break;
4378 case PPC::LXSDX:
4379 if (PostRA) {
4380 if (IsVFReg)
4381 III.ImmOpcode = PPC::LXSD;
4382 else {
4383 III.ImmOpcode = PPC::LFD;
4384 III.ImmMustBeMultipleOf = 1;
4385 }
4386 break;
4387 }
4388 [[fallthrough]];
4389 case PPC::XFLOADf64:
4390 III.ImmOpcode = PPC::DFLOADf64;
4391 break;
4392 case PPC::STXVX:
4393 III.ImmOpcode = PPC::STXV;
4394 III.ImmMustBeMultipleOf = 16;
4395 break;
4396 case PPC::STXSSPX:
4397 if (PostRA) {
4398 if (IsVFReg)
4399 III.ImmOpcode = PPC::STXSSP;
4400 else {
4401 III.ImmOpcode = PPC::STFS;
4402 III.ImmMustBeMultipleOf = 1;
4403 }
4404 break;
4405 }
4406 [[fallthrough]];
4407 case PPC::XFSTOREf32:
4408 III.ImmOpcode = PPC::DFSTOREf32;
4409 break;
4410 case PPC::STXSDX:
4411 if (PostRA) {
4412 if (IsVFReg)
4413 III.ImmOpcode = PPC::STXSD;
4414 else {
4415 III.ImmOpcode = PPC::STFD;
4416 III.ImmMustBeMultipleOf = 1;
4417 }
4418 break;
4419 }
4420 [[fallthrough]];
4421 case PPC::XFSTOREf64:
4422 III.ImmOpcode = PPC::DFSTOREf64;
4423 break;
4424 }
4425 break;
4426 }
4427 return true;
4428}
4429
4430// Utility function for swaping two arbitrary operands of an instruction.
4431static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
4432 assert(Op1 != Op2 && "Cannot swap operand with itself.");
4433
4434 unsigned MaxOp = std::max(Op1, Op2);
4435 unsigned MinOp = std::min(Op1, Op2);
4436 MachineOperand MOp1 = MI.getOperand(MinOp);
4437 MachineOperand MOp2 = MI.getOperand(MaxOp);
4438 MI.removeOperand(std::max(Op1, Op2));
4439 MI.removeOperand(std::min(Op1, Op2));
4440
4441 // If the operands we are swapping are the two at the end (the common case)
4442 // we can just remove both and add them in the opposite order.
4443 if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
4444 MI.addOperand(MOp2);
4445 MI.addOperand(MOp1);
4446 } else {
4447 // Store all operands in a temporary vector, remove them and re-add in the
4448 // right order.
4450 unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
4451 for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
4452 MOps.push_back(MI.getOperand(i));
4453 MI.removeOperand(i);
4454 }
4455 // MOp2 needs to be added next.
4456 MI.addOperand(MOp2);
4457 // Now add the rest.
4458 for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
4459 if (i == MaxOp)
4460 MI.addOperand(MOp1);
4461 else {
4462 MI.addOperand(MOps.back());
4463 MOps.pop_back();
4464 }
4465 }
4466 }
4467}
4468
4469// Check if the 'MI' that has the index OpNoForForwarding
4470// meets the requirement described in the ImmInstrInfo.
4471bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
4472 const ImmInstrInfo &III,
4473 unsigned OpNoForForwarding
4474 ) const {
4475 // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
4476 // would not work pre-RA, we can only do the check post RA.
4477 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4478 if (MRI.isSSA())
4479 return false;
4480
4481 // Cannot do the transform if MI isn't summing the operands.
4482 if (!III.IsSummingOperands)
4483 return false;
4484
4485 // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
4486 if (!III.ZeroIsSpecialOrig)
4487 return false;
4488
4489 // We cannot do the transform if the operand we are trying to replace
4490 // isn't the same as the operand the instruction allows.
4491 if (OpNoForForwarding != III.OpNoForForwarding)
4492 return false;
4493
4494 // Check if the instruction we are trying to transform really has
4495 // the special zero register as its operand.
4496 if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
4497 MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
4498 return false;
4499
4500 // This machine instruction is convertible if it is,
4501 // 1. summing the operands.
4502 // 2. one of the operands is special zero register.
4503 // 3. the operand we are trying to replace is allowed by the MI.
4504 return true;
4505}
4506
4507// Check if the DefMI is the add inst and set the ImmMO and RegMO
4508// accordingly.
4509bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
4510 const ImmInstrInfo &III,
4511 MachineOperand *&ImmMO,
4512 MachineOperand *&RegMO) const {
4513 unsigned Opc = DefMI.getOpcode();
4514 if (Opc != PPC::ADDItocL8 && Opc != PPC::ADDI && Opc != PPC::ADDI8)
4515 return false;
4516
4517 // Skip the optimization of transformTo[NewImm|Imm]FormFedByAdd for ADDItocL8
4518 // on AIX which is used for toc-data access. TODO: Follow up to see if it can
4519 // apply for AIX toc-data as well.
4520 if (Opc == PPC::ADDItocL8 && Subtarget.isAIX())
4521 return false;
4522
4523 assert(DefMI.getNumOperands() >= 3 &&
4524 "Add inst must have at least three operands");
4525 RegMO = &DefMI.getOperand(1);
4526 ImmMO = &DefMI.getOperand(2);
4527
4528 // Before RA, ADDI first operand could be a frame index.
4529 if (!RegMO->isReg())
4530 return false;
4531
4532 // This DefMI is elgible for forwarding if it is:
4533 // 1. add inst
4534 // 2. one of the operands is Imm/CPI/Global.
4535 return isAnImmediateOperand(*ImmMO);
4536}
4537
4538bool PPCInstrInfo::isRegElgibleForForwarding(
4539 const MachineOperand &RegMO, const MachineInstr &DefMI,
4540 const MachineInstr &MI, bool KillDefMI,
4541 bool &IsFwdFeederRegKilled, bool &SeenIntermediateUse) const {
4542 // x = addi y, imm
4543 // ...
4544 // z = lfdx 0, x -> z = lfd imm(y)
4545 // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
4546 // of "y" between the DEF of "x" and "z".
4547 // The query is only valid post RA.
4548 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4549 if (MRI.isSSA())
4550 return false;
4551
4552 Register Reg = RegMO.getReg();
4553
4554 // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
4556 MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
4557 It++;
4558 for (; It != E; ++It) {
4559 if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4560 return false;
4561 else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4562 IsFwdFeederRegKilled = true;
4563 if (It->readsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4564 SeenIntermediateUse = true;
4565 // Made it to DefMI without encountering a clobber.
4566 if ((&*It) == &DefMI)
4567 break;
4568 }
4569 assert((&*It) == &DefMI && "DefMI is missing");
4570
4571 // If DefMI also defines the register to be forwarded, we can only forward it
4572 // if DefMI is being erased.
4573 if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
4574 return KillDefMI;
4575
4576 return true;
4577}
4578
4579bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
4580 const MachineInstr &DefMI,
4581 const ImmInstrInfo &III,
4582 int64_t &Imm,
4583 int64_t BaseImm) const {
4584 assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
4585 if (DefMI.getOpcode() == PPC::ADDItocL8) {
4586 // The operand for ADDItocL8 is CPI, which isn't imm at compiling time,
4587 // However, we know that, it is 16-bit width, and has the alignment of 4.
4588 // Check if the instruction met the requirement.
4589 if (III.ImmMustBeMultipleOf > 4 ||
4590 III.TruncateImmTo || III.ImmWidth != 16)
4591 return false;
4592
4593 // Going from XForm to DForm loads means that the displacement needs to be
4594 // not just an immediate but also a multiple of 4, or 16 depending on the
4595 // load. A DForm load cannot be represented if it is a multiple of say 2.
4596 // XForm loads do not have this restriction.
4597 if (ImmMO.isGlobal()) {
4598 const DataLayout &DL = ImmMO.getGlobal()->getDataLayout();
4600 return false;
4601 }
4602
4603 return true;
4604 }
4605
4606 if (ImmMO.isImm()) {
4607 // It is Imm, we need to check if the Imm fit the range.
4608 // Sign-extend to 64-bits.
4609 // DefMI may be folded with another imm form instruction, the result Imm is
4610 // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
4611 APInt ActualValue(64, ImmMO.getImm() + BaseImm, true);
4612 if (III.SignedImm && !ActualValue.isSignedIntN(III.ImmWidth))
4613 return false;
4614 if (!III.SignedImm && !ActualValue.isIntN(III.ImmWidth))
4615 return false;
4616 Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm);
4617
4618 if (Imm % III.ImmMustBeMultipleOf)
4619 return false;
4620 if (III.TruncateImmTo)
4621 Imm &= ((1 << III.TruncateImmTo) - 1);
4622 }
4623 else
4624 return false;
4625
4626 // This ImmMO is forwarded if it meets the requriement describle
4627 // in ImmInstrInfo
4628 return true;
4629}
4630
4631bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
4632 unsigned OpNoForForwarding,
4633 MachineInstr **KilledDef,
4634 SmallSet<Register, 4> *RegsToUpdate) const {
4635 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4636 !DefMI.getOperand(1).isImm())
4637 return false;
4638
4639 MachineFunction *MF = MI.getParent()->getParent();
4640 MachineRegisterInfo *MRI = &MF->getRegInfo();
4641 bool PostRA = !MRI->isSSA();
4642
4643 int64_t Immediate = DefMI.getOperand(1).getImm();
4644 // Sign-extend to 64-bits.
4645 int64_t SExtImm = SignExtend64<16>(Immediate);
4646
4647 bool ReplaceWithLI = false;
4648 bool Is64BitLI = false;
4649 int64_t NewImm = 0;
4650 bool SetCR = false;
4651 unsigned Opc = MI.getOpcode();
4652 switch (Opc) {
4653 default:
4654 return false;
4655
4656 // FIXME: Any branches conditional on such a comparison can be made
4657 // unconditional. At this time, this happens too infrequently to be worth
4658 // the implementation effort, but if that ever changes, we could convert
4659 // such a pattern here.
4660 case PPC::CMPWI:
4661 case PPC::CMPLWI:
4662 case PPC::CMPDI:
4663 case PPC::CMPLDI: {
4664 // Doing this post-RA would require dataflow analysis to reliably find uses
4665 // of the CR register set by the compare.
4666 // No need to fixup killed/dead flag since this transformation is only valid
4667 // before RA.
4668 if (PostRA)
4669 return false;
4670 // If a compare-immediate is fed by an immediate and is itself an input of
4671 // an ISEL (the most common case) into a COPY of the correct register.
4672 bool Changed = false;
4673 Register DefReg = MI.getOperand(0).getReg();
4674 int64_t Comparand = MI.getOperand(2).getImm();
4675 int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
4676 ? (Comparand | 0xFFFFFFFFFFFF0000)
4677 : Comparand;
4678
4679 for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
4680 unsigned UseOpc = CompareUseMI.getOpcode();
4681 if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
4682 continue;
4683 unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
4684 Register TrueReg = CompareUseMI.getOperand(1).getReg();
4685 Register FalseReg = CompareUseMI.getOperand(2).getReg();
4686 unsigned RegToCopy =
4687 selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg);
4688 if (RegToCopy == PPC::NoRegister)
4689 continue;
4690 // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
4691 if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
4692 CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
4693 replaceInstrOperandWithImm(CompareUseMI, 1, 0);
4694 CompareUseMI.removeOperand(3);
4695 CompareUseMI.removeOperand(2);
4696 continue;
4697 }
4698 LLVM_DEBUG(
4699 dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
4700 LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
4701 LLVM_DEBUG(dbgs() << "Is converted to:\n");
4702 if (RegsToUpdate) {
4703 for (const MachineOperand &MO : CompareUseMI.operands())
4704 if (MO.isReg())
4705 RegsToUpdate->insert(MO.getReg());
4706 }
4707 // Convert to copy and remove unneeded operands.
4708 CompareUseMI.setDesc(get(PPC::COPY));
4709 CompareUseMI.removeOperand(3);
4710 CompareUseMI.removeOperand(RegToCopy == TrueReg ? 2 : 1);
4711 CmpIselsConverted++;
4712 Changed = true;
4713 LLVM_DEBUG(CompareUseMI.dump());
4714 }
4715 if (Changed)
4716 return true;
4717 // This may end up incremented multiple times since this function is called
4718 // during a fixed-point transformation, but it is only meant to indicate the
4719 // presence of this opportunity.
4720 MissedConvertibleImmediateInstrs++;
4721 return false;
4722 }
4723
4724 // Immediate forms - may simply be convertable to an LI.
4725 case PPC::ADDI:
4726 case PPC::ADDI8: {
4727 // Does the sum fit in a 16-bit signed field?
4728 int64_t Addend = MI.getOperand(2).getImm();
4729 if (isInt<16>(Addend + SExtImm)) {
4730 ReplaceWithLI = true;
4731 Is64BitLI = Opc == PPC::ADDI8;
4732 NewImm = Addend + SExtImm;
4733 break;
4734 }
4735 return false;
4736 }
4737 case PPC::SUBFIC:
4738 case PPC::SUBFIC8: {
4739 // Only transform this if the CARRY implicit operand is dead.
4740 if (MI.getNumOperands() > 3 && !MI.getOperand(3).isDead())
4741 return false;
4742 int64_t Minuend = MI.getOperand(2).getImm();
4743 if (isInt<16>(Minuend - SExtImm)) {
4744 ReplaceWithLI = true;
4745 Is64BitLI = Opc == PPC::SUBFIC8;
4746 NewImm = Minuend - SExtImm;
4747 break;
4748 }
4749 return false;
4750 }
4751 case PPC::RLDICL:
4752 case PPC::RLDICL_rec:
4753 case PPC::RLDICL_32:
4754 case PPC::RLDICL_32_64: {
4755 // Use APInt's rotate function.
4756 int64_t SH = MI.getOperand(2).getImm();
4757 int64_t MB = MI.getOperand(3).getImm();
4758 APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
4759 SExtImm, true);
4760 InVal = InVal.rotl(SH);
4761 uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
4762 InVal &= Mask;
4763 // Can't replace negative values with an LI as that will sign-extend
4764 // and not clear the left bits. If we're setting the CR bit, we will use
4765 // ANDI_rec which won't sign extend, so that's safe.
4766 if (isUInt<15>(InVal.getSExtValue()) ||
4767 (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
4768 ReplaceWithLI = true;
4769 Is64BitLI = Opc != PPC::RLDICL_32;
4770 NewImm = InVal.getSExtValue();
4771 SetCR = Opc == PPC::RLDICL_rec;
4772 break;
4773 }
4774 return false;
4775 }
4776 case PPC::RLWINM:
4777 case PPC::RLWINM8:
4778 case PPC::RLWINM_rec:
4779 case PPC::RLWINM8_rec: {
4780 int64_t SH = MI.getOperand(2).getImm();
4781 int64_t MB = MI.getOperand(3).getImm();
4782 int64_t ME = MI.getOperand(4).getImm();
4783 APInt InVal(32, SExtImm, true);
4784 InVal = InVal.rotl(SH);
4785 APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB);
4786 InVal &= Mask;
4787 // Can't replace negative values with an LI as that will sign-extend
4788 // and not clear the left bits. If we're setting the CR bit, we will use
4789 // ANDI_rec which won't sign extend, so that's safe.
4790 bool ValueFits = isUInt<15>(InVal.getSExtValue());
4791 ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
4792 isUInt<16>(InVal.getSExtValue()));
4793 if (ValueFits) {
4794 ReplaceWithLI = true;
4795 Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
4796 NewImm = InVal.getSExtValue();
4797 SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
4798 break;
4799 }
4800 return false;
4801 }
4802 case PPC::ORI:
4803 case PPC::ORI8:
4804 case PPC::XORI:
4805 case PPC::XORI8: {
4806 int64_t LogicalImm = MI.getOperand(2).getImm();
4807 int64_t Result = 0;
4808 if (Opc == PPC::ORI || Opc == PPC::ORI8)
4809 Result = LogicalImm | SExtImm;
4810 else
4811 Result = LogicalImm ^ SExtImm;
4812 if (isInt<16>(Result)) {
4813 ReplaceWithLI = true;
4814 Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
4815 NewImm = Result;
4816 break;
4817 }
4818 return false;
4819 }
4820 }
4821
4822 if (ReplaceWithLI) {
4823 // We need to be careful with CR-setting instructions we're replacing.
4824 if (SetCR) {
4825 // We don't know anything about uses when we're out of SSA, so only
4826 // replace if the new immediate will be reproduced.
4827 bool ImmChanged = (SExtImm & NewImm) != NewImm;
4828 if (PostRA && ImmChanged)
4829 return false;
4830
4831 if (!PostRA) {
4832 // If the defining load-immediate has no other uses, we can just replace
4833 // the immediate with the new immediate.
4834 if (MRI->hasOneUse(DefMI.getOperand(0).getReg()))
4835 DefMI.getOperand(1).setImm(NewImm);
4836
4837 // If we're not using the GPR result of the CR-setting instruction, we
4838 // just need to and with zero/non-zero depending on the new immediate.
4839 else if (MRI->use_empty(MI.getOperand(0).getReg())) {
4840 if (NewImm) {
4841 assert(Immediate && "Transformation converted zero to non-zero?");
4842 NewImm = Immediate;
4843 }
4844 } else if (ImmChanged)
4845 return false;
4846 }
4847 }
4848
4849 LLVM_DEBUG(dbgs() << "Replacing constant instruction:\n");
4850 LLVM_DEBUG(MI.dump());
4851 LLVM_DEBUG(dbgs() << "Fed by:\n");
4852 LLVM_DEBUG(DefMI.dump());
4853 LoadImmediateInfo LII;
4854 LII.Imm = NewImm;
4855 LII.Is64Bit = Is64BitLI;
4856 LII.SetCR = SetCR;
4857 // If we're setting the CR, the original load-immediate must be kept (as an
4858 // operand to ANDI_rec/ANDI8_rec).
4859 if (KilledDef && SetCR)
4860 *KilledDef = nullptr;
4861 replaceInstrWithLI(MI, LII);
4862
4863 if (PostRA)
4864 recomputeLivenessFlags(*MI.getParent());
4865
4866 LLVM_DEBUG(dbgs() << "With:\n");
4867 LLVM_DEBUG(MI.dump());
4868 return true;
4869 }
4870 return false;
4871}
4872
4873bool PPCInstrInfo::transformToNewImmFormFedByAdd(
4874 MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
4875 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
4876 bool PostRA = !MRI->isSSA();
4877 // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
4878 // for post-ra.
4879 if (PostRA)
4880 return false;
4881
4882 // Only handle load/store.
4883 if (!MI.mayLoadOrStore())
4884 return false;
4885
4886 unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode());
4887
4888 assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
4889 "MI must have x-form opcode");
4890
4891 // get Imm Form info.
4892 ImmInstrInfo III;
4893 bool IsVFReg = MI.getOperand(0).isReg() &&
4894 MI.getOperand(0).getReg().isPhysical() &&
4895 PPC::isVFRegister(MI.getOperand(0).getReg());
4896
4897 if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA))
4898 return false;
4899
4900 if (!III.IsSummingOperands)
4901 return false;
4902
4903 if (OpNoForForwarding != III.OpNoForForwarding)
4904 return false;
4905
4906 MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo);
4907 if (!ImmOperandMI.isImm())
4908 return false;
4909
4910 // Check DefMI.
4911 MachineOperand *ImmMO = nullptr;
4912 MachineOperand *RegMO = nullptr;
4913 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4914 return false;
4915 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4916
4917 // Check Imm.
4918 // Set ImmBase from imm instruction as base and get new Imm inside
4919 // isImmElgibleForForwarding.
4920 int64_t ImmBase = ImmOperandMI.getImm();
4921 int64_t Imm = 0;
4922 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase))
4923 return false;
4924
4925 // Do the transform
4926 LLVM_DEBUG(dbgs() << "Replacing existing reg+imm instruction:\n");
4927 LLVM_DEBUG(MI.dump());
4928 LLVM_DEBUG(dbgs() << "Fed by:\n");
4929 LLVM_DEBUG(DefMI.dump());
4930
4931 MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg());
4932 MI.getOperand(III.ImmOpNo).setImm(Imm);
4933
4934 LLVM_DEBUG(dbgs() << "With:\n");
4935 LLVM_DEBUG(MI.dump());
4936 return true;
4937}
4938
4939// If an X-Form instruction is fed by an add-immediate and one of its operands
4940// is the literal zero, attempt to forward the source of the add-immediate to
4941// the corresponding D-Form instruction with the displacement coming from
4942// the immediate being added.
4943bool PPCInstrInfo::transformToImmFormFedByAdd(
4944 MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
4945 MachineInstr &DefMI, bool KillDefMI) const {
4946 // RegMO ImmMO
4947 // | |
4948 // x = addi reg, imm <----- DefMI
4949 // y = op 0 , x <----- MI
4950 // |
4951 // OpNoForForwarding
4952 // Check if the MI meet the requirement described in the III.
4953 if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
4954 return false;
4955
4956 // Check if the DefMI meet the requirement
4957 // described in the III. If yes, set the ImmMO and RegMO accordingly.
4958 MachineOperand *ImmMO = nullptr;
4959 MachineOperand *RegMO = nullptr;
4960 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4961 return false;
4962 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4963
4964 // As we get the Imm operand now, we need to check if the ImmMO meet
4965 // the requirement described in the III. If yes set the Imm.
4966 int64_t Imm = 0;
4967 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
4968 return false;
4969
4970 bool IsFwdFeederRegKilled = false;
4971 bool SeenIntermediateUse = false;
4972 // Check if the RegMO can be forwarded to MI.
4973 if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
4974 IsFwdFeederRegKilled, SeenIntermediateUse))
4975 return false;
4976
4977 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4978 bool PostRA = !MRI.isSSA();
4979
4980 // We know that, the MI and DefMI both meet the pattern, and
4981 // the Imm also meet the requirement with the new Imm-form.
4982 // It is safe to do the transformation now.
4983 LLVM_DEBUG(dbgs() << "Replacing indexed instruction:\n");
4984 LLVM_DEBUG(MI.dump());
4985 LLVM_DEBUG(dbgs() << "Fed by:\n");
4986 LLVM_DEBUG(DefMI.dump());
4987
4988 // Update the base reg first.
4989 MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
4990 false, false,
4991 RegMO->isKill());
4992
4993 // Then, update the imm.
4994 if (ImmMO->isImm()) {
4995 // If the ImmMO is Imm, change the operand that has ZERO to that Imm
4996 // directly.
4998 }
4999 else {
5000 // Otherwise, it is Constant Pool Index(CPI) or Global,
5001 // which is relocation in fact. We need to replace the special zero
5002 // register with ImmMO.
5003 // Before that, we need to fixup the target flags for imm.
5004 // For some reason, we miss to set the flag for the ImmMO if it is CPI.
5005 if (DefMI.getOpcode() == PPC::ADDItocL8)
5007
5008 // MI didn't have the interface such as MI.setOperand(i) though
5009 // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
5010 // ImmMO, we need to remove ZERO operand and all the operands behind it,
5011 // and, add the ImmMO, then, move back all the operands behind ZERO.
5013 for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
5014 MOps.push_back(MI.getOperand(i));
5015 MI.removeOperand(i);
5016 }
5017
5018 // Remove the last MO in the list, which is ZERO operand in fact.
5019 MOps.pop_back();
5020 // Add the imm operand.
5021 MI.addOperand(*ImmMO);
5022 // Now add the rest back.
5023 for (auto &MO : MOps)
5024 MI.addOperand(MO);
5025 }
5026
5027 // Update the opcode.
5028 MI.setDesc(get(III.ImmOpcode));
5029
5030 if (PostRA)
5031 recomputeLivenessFlags(*MI.getParent());
5032 LLVM_DEBUG(dbgs() << "With:\n");
5033 LLVM_DEBUG(MI.dump());
5034
5035 return true;
5036}
5037
5038bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
5039 const ImmInstrInfo &III,
5040 unsigned ConstantOpNo,
5041 MachineInstr &DefMI) const {
5042 // DefMI must be LI or LI8.
5043 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
5044 !DefMI.getOperand(1).isImm())
5045 return false;
5046
5047 // Get Imm operand and Sign-extend to 64-bits.
5048 int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm());
5049
5050 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5051 bool PostRA = !MRI.isSSA();
5052 // Exit early if we can't convert this.
5053 if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
5054 return false;
5055 if (Imm % III.ImmMustBeMultipleOf)
5056 return false;
5057 if (III.TruncateImmTo)
5058 Imm &= ((1 << III.TruncateImmTo) - 1);
5059 if (III.SignedImm) {
5060 APInt ActualValue(64, Imm, true);
5061 if (!ActualValue.isSignedIntN(III.ImmWidth))
5062 return false;
5063 } else {
5064 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
5065 if ((uint64_t)Imm > UnsignedMax)
5066 return false;
5067 }
5068
5069 // If we're post-RA, the instructions don't agree on whether register zero is
5070 // special, we can transform this as long as the register operand that will
5071 // end up in the location where zero is special isn't R0.
5072 if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5073 unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
5074 III.ZeroIsSpecialNew + 1;
5075 Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
5076 Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
5077 // If R0 is in the operand where zero is special for the new instruction,
5078 // it is unsafe to transform if the constant operand isn't that operand.
5079 if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
5080 ConstantOpNo != III.ZeroIsSpecialNew)
5081 return false;
5082 if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
5083 ConstantOpNo != PosForOrigZero)
5084 return false;
5085 }
5086
5087 unsigned Opc = MI.getOpcode();
5088 bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
5089 Opc == PPC::SRW || Opc == PPC::SRW_rec ||
5090 Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
5091 Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
5092 bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
5093 Opc == PPC::SRD || Opc == PPC::SRD_rec;
5094 bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
5095 Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
5096 bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
5097 Opc == PPC::SRD_rec;
5098
5099 LLVM_DEBUG(dbgs() << "Replacing reg+reg instruction: ");
5100 LLVM_DEBUG(MI.dump());
5101 LLVM_DEBUG(dbgs() << "Fed by load-immediate: ");
5102 LLVM_DEBUG(DefMI.dump());
5103 MI.setDesc(get(III.ImmOpcode));
5104 if (ConstantOpNo == III.OpNoForForwarding) {
5105 // Converting shifts to immediate form is a bit tricky since they may do
5106 // one of three things:
5107 // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
5108 // 2. If the shift amount is zero, the result is unchanged (save for maybe
5109 // setting CR0)
5110 // 3. If the shift amount is in [1, OpSize), it's just a shift
5111 if (SpecialShift32 || SpecialShift64) {
5112 LoadImmediateInfo LII;
5113 LII.Imm = 0;
5114 LII.SetCR = SetCR;
5115 LII.Is64Bit = SpecialShift64;
5116 uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
5117 if (Imm & (SpecialShift32 ? 0x20 : 0x40))
5118 replaceInstrWithLI(MI, LII);
5119 // Shifts by zero don't change the value. If we don't need to set CR0,
5120 // just convert this to a COPY. Can't do this post-RA since we've already
5121 // cleaned up the copies.
5122 else if (!SetCR && ShAmt == 0 && !PostRA) {
5123 MI.removeOperand(2);
5124 MI.setDesc(get(PPC::COPY));
5125 } else {
5126 // The 32 bit and 64 bit instructions are quite different.
5127 if (SpecialShift32) {
5128 // Left shifts use (N, 0, 31-N).
5129 // Right shifts use (32-N, N, 31) if 0 < N < 32.
5130 // use (0, 0, 31) if N == 0.
5131 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
5132 uint64_t MB = RightShift ? ShAmt : 0;
5133 uint64_t ME = RightShift ? 31 : 31 - ShAmt;
5135 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
5136 .addImm(ME);
5137 } else {
5138 // Left shifts use (N, 63-N).
5139 // Right shifts use (64-N, N) if 0 < N < 64.
5140 // use (0, 0) if N == 0.
5141 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
5142 uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
5144 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
5145 }
5146 }
5147 } else
5148 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
5149 }
5150 // Convert commutative instructions (switch the operands and convert the
5151 // desired one to an immediate.
5152 else if (III.IsCommutative) {
5153 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
5154 swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
5155 } else
5156 llvm_unreachable("Should have exited early!");
5157
5158 // For instructions for which the constant register replaces a different
5159 // operand than where the immediate goes, we need to swap them.
5160 if (III.OpNoForForwarding != III.ImmOpNo)
5162
5163 // If the special R0/X0 register index are different for original instruction
5164 // and new instruction, we need to fix up the register class in new
5165 // instruction.
5166 if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5167 if (III.ZeroIsSpecialNew) {
5168 // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
5169 // need to fix up register class.
5170 Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
5171 if (RegToModify.isVirtual()) {
5172 const TargetRegisterClass *NewRC =
5173 MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
5174 &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
5175 MRI.setRegClass(RegToModify, NewRC);
5176 }
5177 }
5178 }
5179
5180 if (PostRA)
5181 recomputeLivenessFlags(*MI.getParent());
5182
5183 LLVM_DEBUG(dbgs() << "With: ");
5184 LLVM_DEBUG(MI.dump());
5185 LLVM_DEBUG(dbgs() << "\n");
5186 return true;
5187}
5188
5189const TargetRegisterClass *
5191 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
5192 return &PPC::VSRCRegClass;
5193 return RC;
5194}
5195
5197 return PPC::getRecordFormOpcode(Opcode);
5198}
5199
5200static bool isOpZeroOfSubwordPreincLoad(int Opcode) {
5201 return (Opcode == PPC::LBZU || Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 ||
5202 Opcode == PPC::LBZUX8 || Opcode == PPC::LHZU ||
5203 Opcode == PPC::LHZUX || Opcode == PPC::LHZU8 ||
5204 Opcode == PPC::LHZUX8);
5205}
5206
5207// This function checks for sign extension from 32 bits to 64 bits.
5209 const unsigned Reg,
5210 const MachineRegisterInfo *MRI) {
5212 return false;
5213
5214 MachineInstr *MI = MRI->getVRegDef(Reg);
5215 if (!MI)
5216 return false;
5217
5218 int Opcode = MI->getOpcode();
5219 if (TII.isSExt32To64(Opcode))
5220 return true;
5221
5222 // The first def of LBZU/LHZU is sign extended.
5223 if (isOpZeroOfSubwordPreincLoad(Opcode) && MI->getOperand(0).getReg() == Reg)
5224 return true;
5225
5226 // RLDICL generates sign-extended output if it clears at least
5227 // 33 bits from the left (MSB).
5228 if (Opcode == PPC::RLDICL && MI->getOperand(3).getImm() >= 33)
5229 return true;
5230
5231 // If at least one bit from left in a lower word is masked out,
5232 // all of 0 to 32-th bits of the output are cleared.
5233 // Hence the output is already sign extended.
5234 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5235 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
5236 MI->getOperand(3).getImm() > 0 &&
5237 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
5238 return true;
5239
5240 // If the most significant bit of immediate in ANDIS is zero,
5241 // all of 0 to 32-th bits are cleared.
5242 if (Opcode == PPC::ANDIS_rec || Opcode == PPC::ANDIS8_rec) {
5243 uint16_t Imm = MI->getOperand(2).getImm();
5244 if ((Imm & 0x8000) == 0)
5245 return true;
5246 }
5247
5248 return false;
5249}
5250
5251// This function checks the machine instruction that defines the input register
5252// Reg. If that machine instruction always outputs a value that has only zeros
5253// in the higher 32 bits then this function will return true.
5255 const unsigned Reg,
5256 const MachineRegisterInfo *MRI) {
5258 return false;
5259
5260 MachineInstr *MI = MRI->getVRegDef(Reg);
5261 if (!MI)
5262 return false;
5263
5264 int Opcode = MI->getOpcode();
5265 if (TII.isZExt32To64(Opcode))
5266 return true;
5267
5268 // The first def of LBZU/LHZU/LWZU are zero extended.
5269 if ((isOpZeroOfSubwordPreincLoad(Opcode) || Opcode == PPC::LWZU ||
5270 Opcode == PPC::LWZUX || Opcode == PPC::LWZU8 || Opcode == PPC::LWZUX8) &&
5271 MI->getOperand(0).getReg() == Reg)
5272 return true;
5273
5274 // The 16-bit immediate is sign-extended in li/lis.
5275 // If the most significant bit is zero, all higher bits are zero.
5276 if (Opcode == PPC::LI || Opcode == PPC::LI8 ||
5277 Opcode == PPC::LIS || Opcode == PPC::LIS8) {
5278 int64_t Imm = MI->getOperand(1).getImm();
5279 if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
5280 return true;
5281 }
5282
5283 // We have some variations of rotate-and-mask instructions
5284 // that clear higher 32-bits.
5285 if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
5286 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
5287 Opcode == PPC::RLDICL_32_64) &&
5288 MI->getOperand(3).getImm() >= 32)
5289 return true;
5290
5291 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
5292 MI->getOperand(3).getImm() >= 32 &&
5293 MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
5294 return true;
5295
5296 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5297 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
5298 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
5299 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
5300 return true;
5301
5302 return false;
5303}
5304
5305// This function returns true if the input MachineInstr is a TOC save
5306// instruction.
5308 if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
5309 return false;
5310 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5311 unsigned StackOffset = MI.getOperand(1).getImm();
5312 Register StackReg = MI.getOperand(2).getReg();
5313 Register SPReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
5314 if (StackReg == SPReg && StackOffset == TOCSaveOffset)
5315 return true;
5316
5317 return false;
5318}
5319
5320// We limit the max depth to track incoming values of PHIs or binary ops
5321// (e.g. AND) to avoid excessive cost.
5322const unsigned MAX_BINOP_DEPTH = 1;
5323
5324// This function will promote the instruction which defines the register `Reg`
5325// in the parameter from a 32-bit to a 64-bit instruction if needed. The logic
5326// used to check whether an instruction needs to be promoted or not is similar
5327// to the logic used to check whether or not a defined register is sign or zero
5328// extended within the function PPCInstrInfo::isSignOrZeroExtended.
5329// Additionally, the `promoteInstr32To64ForElimEXTSW` function is recursive.
5330// BinOpDepth does not count all of the recursions. The parameter BinOpDepth is
5331// incremented only when `promoteInstr32To64ForElimEXTSW` calls itself more
5332// than once. This is done to prevent exponential recursion.
5335 unsigned BinOpDepth) const {
5336 if (!Reg.isVirtual())
5337 return;
5338
5339 MachineInstr *MI = MRI->getVRegDef(Reg);
5340 if (!MI)
5341 return;
5342
5343 unsigned Opcode = MI->getOpcode();
5344
5345 switch (Opcode) {
5346 case PPC::OR:
5347 case PPC::ISEL:
5348 case PPC::OR8:
5349 case PPC::PHI: {
5350 if (BinOpDepth >= MAX_BINOP_DEPTH)
5351 break;
5352 unsigned OperandEnd = 3, OperandStride = 1;
5353 if (Opcode == PPC::PHI) {
5354 OperandEnd = MI->getNumOperands();
5355 OperandStride = 2;
5356 }
5357
5358 for (unsigned I = 1; I < OperandEnd; I += OperandStride) {
5359 assert(MI->getOperand(I).isReg() && "Operand must be register");
5360 promoteInstr32To64ForElimEXTSW(MI->getOperand(I).getReg(), MRI,
5361 BinOpDepth + 1);
5362 }
5363
5364 break;
5365 }
5366 case PPC::COPY: {
5367 // Refers to the logic of the `case PPC::COPY` statement in the function
5368 // PPCInstrInfo::isSignOrZeroExtended().
5369
5370 Register SrcReg = MI->getOperand(1).getReg();
5371 // In both ELFv1 and v2 ABI, method parameters and the return value
5372 // are sign- or zero-extended.
5373 const MachineFunction *MF = MI->getMF();
5374 if (!MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5375 // If this is a copy from another register, we recursively promote the
5376 // source.
5377 promoteInstr32To64ForElimEXTSW(SrcReg, MRI, BinOpDepth);
5378 return;
5379 }
5380
5381 // From here on everything is SVR4ABI. COPY will be eliminated in the other
5382 // pass, we do not need promote the COPY pseudo opcode.
5383
5384 if (SrcReg != PPC::X3)
5385 // If this is a copy from another register, we recursively promote the
5386 // source.
5387 promoteInstr32To64ForElimEXTSW(SrcReg, MRI, BinOpDepth);
5388 return;
5389 }
5390 case PPC::ORI:
5391 case PPC::XORI:
5392 case PPC::ORIS:
5393 case PPC::XORIS:
5394 case PPC::ORI8:
5395 case PPC::XORI8:
5396 case PPC::ORIS8:
5397 case PPC::XORIS8:
5398 promoteInstr32To64ForElimEXTSW(MI->getOperand(1).getReg(), MRI, BinOpDepth);
5399 break;
5400 case PPC::AND:
5401 case PPC::AND8:
5402 if (BinOpDepth >= MAX_BINOP_DEPTH)
5403 break;
5404
5405 promoteInstr32To64ForElimEXTSW(MI->getOperand(1).getReg(), MRI,
5406 BinOpDepth + 1);
5407 promoteInstr32To64ForElimEXTSW(MI->getOperand(2).getReg(), MRI,
5408 BinOpDepth + 1);
5409 break;
5410 }
5411
5412 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
5413 if (RC == &PPC::G8RCRegClass || RC == &PPC::G8RC_and_G8RC_NOX0RegClass)
5414 return;
5415
5416 // Map the 32bit to 64bit opcodes for instructions that are not signed or zero
5417 // extended themselves, but may have operands who's destination registers of
5418 // signed or zero extended instructions.
5419 DenseMap<unsigned, unsigned> OpcodeMap = {
5420 {PPC::OR, PPC::OR8}, {PPC::ISEL, PPC::ISEL8},
5421 {PPC::ORI, PPC::ORI8}, {PPC::XORI, PPC::XORI8},
5422 {PPC::ORIS, PPC::ORIS8}, {PPC::XORIS, PPC::XORIS8},
5423 {PPC::AND, PPC::AND8}};
5424
5425 int NewOpcode = -1;
5426 auto It = OpcodeMap.find(Opcode);
5427 if (It != OpcodeMap.end()) {
5428 // Set the new opcode to the mapped 64-bit version.
5429 NewOpcode = It->second;
5430 } else {
5431 if (!isSExt32To64(Opcode))
5432 return;
5433
5434 // The TableGen function `get64BitInstrFromSignedExt32BitInstr` is used to
5435 // map the 32-bit instruction with the `SExt32To64` flag to the 64-bit
5436 // instruction with the same opcode.
5437 NewOpcode = PPC::get64BitInstrFromSignedExt32BitInstr(Opcode);
5438 }
5439
5440 assert(NewOpcode != -1 &&
5441 "Must have a 64-bit opcode to map the 32-bit opcode!");
5442
5443 const MCInstrDesc &MCID = get(NewOpcode);
5444 const TargetRegisterClass *NewRC =
5445 RI.getRegClass(MCID.operands()[0].RegClass);
5446
5447 Register SrcReg = MI->getOperand(0).getReg();
5448 const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
5449
5450 // If the register class of the defined register in the 32-bit instruction
5451 // is the same as the register class of the defined register in the promoted
5452 // 64-bit instruction, we do not need to promote the instruction.
5453 if (NewRC == SrcRC)
5454 return;
5455
5456 DebugLoc DL = MI->getDebugLoc();
5457 auto MBB = MI->getParent();
5458
5459 // Since the pseudo-opcode of the instruction is promoted from 32-bit to
5460 // 64-bit, if the source reg class of the original instruction belongs to
5461 // PPC::GRCRegClass or PPC::GPRC_and_GPRC_NOR0RegClass, we need to promote
5462 // the operand to PPC::G8CRegClass or PPC::G8RC_and_G8RC_NOR0RegClass,
5463 // respectively.
5464 for (unsigned i = 1; i < MI->getNumOperands(); i++) {
5465 MachineOperand &Operand = MI->getOperand(i);
5466 if (!Operand.isReg())
5467 continue;
5468
5469 Register OperandReg = Operand.getReg();
5470 if (!OperandReg.isVirtual())
5471 continue;
5472
5473 const TargetRegisterClass *NewUsedRegRC =
5474 RI.getRegClass(MCID.operands()[i].RegClass);
5475 const TargetRegisterClass *OrgRC = MRI->getRegClass(OperandReg);
5476
5477 // An operand that reads the sub_32 subregister of a 64-bit register already
5478 // holds the value in a full 64-bit register, so it can be used directly by
5479 // the promoted instruction.
5480 if (Operand.getSubReg() == PPC::sub_32) {
5481 assert(NewUsedRegRC->hasSubClassEq(OrgRC) &&
5482 "sub_32 source register class is incompatible with the promoted "
5483 "operand register class");
5484 Operand.setSubReg(PPC::NoSubRegister);
5485 continue;
5486 }
5487
5488 if (NewUsedRegRC != OrgRC && (OrgRC == &PPC::GPRCRegClass ||
5489 OrgRC == &PPC::GPRC_and_GPRC_NOR0RegClass)) {
5490 // Promote the used 32-bit register to 64-bit register.
5491 Register TmpReg = MRI->createVirtualRegister(NewUsedRegRC);
5492 Register DstTmpReg = MRI->createVirtualRegister(NewUsedRegRC);
5493 BuildMI(*MBB, MI, DL, get(PPC::IMPLICIT_DEF), TmpReg);
5494 BuildMI(*MBB, MI, DL, get(PPC::INSERT_SUBREG), DstTmpReg)
5495 .addReg(TmpReg)
5496 .addReg(OperandReg)
5497 .addImm(PPC::sub_32);
5498 Operand.setReg(DstTmpReg);
5499 }
5500 }
5501
5502 Register NewDefinedReg = MRI->createVirtualRegister(NewRC);
5503 MI->setDesc(MCID);
5504 MI->getOperand(0).setReg(NewDefinedReg);
5505
5506 // A defined register may be used by other instructions that are 32-bit.
5507 // After the defined register is promoted to 64-bit for the promoted
5508 // instruction, we need to demote the 64-bit defined register back to a
5509 // 32-bit register
5510 BuildMI(*MBB, std::next(MI->getIterator()), DL, get(PPC::COPY), SrcReg)
5511 .addReg(NewDefinedReg, {}, PPC::sub_32);
5512}
5513
5514// The isSignOrZeroExtended function is recursive. The parameter BinOpDepth
5515// does not count all of the recursions. The parameter BinOpDepth is incremented
5516// only when isSignOrZeroExtended calls itself more than once. This is done to
5517// prevent expontential recursion. There is no parameter to track linear
5518// recursion.
5519std::pair<bool, bool>
5521 const unsigned BinOpDepth,
5522 const MachineRegisterInfo *MRI) const {
5524 return std::pair<bool, bool>(false, false);
5525
5526 MachineInstr *MI = MRI->getVRegDef(Reg);
5527 if (!MI)
5528 return std::pair<bool, bool>(false, false);
5529
5530 bool IsSExt = definedBySignExtendingOp(*this, Reg, MRI);
5531 bool IsZExt = definedByZeroExtendingOp(*this, Reg, MRI);
5532
5533 // If we know the instruction always returns sign- and zero-extended result,
5534 // return here.
5535 if (IsSExt && IsZExt)
5536 return std::pair<bool, bool>(IsSExt, IsZExt);
5537
5538 switch (MI->getOpcode()) {
5539 case PPC::COPY: {
5540 Register SrcReg = MI->getOperand(1).getReg();
5541
5542 // In both ELFv1 and v2 ABI, method parameters and the return value
5543 // are sign- or zero-extended.
5544 const MachineFunction *MF = MI->getMF();
5545
5546 if (!MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5547 // If this is a copy from another register, we recursively check source.
5548 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5549 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5550 SrcExt.second || IsZExt);
5551 }
5552
5553 // From here on everything is SVR4ABI
5554 const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
5555 // We check the ZExt/SExt flags for a method parameter.
5556 if (MI->getParent()->getBasicBlock() ==
5557 &MF->getFunction().getEntryBlock()) {
5558 Register VReg = MI->getOperand(0).getReg();
5559 if (MF->getRegInfo().isLiveIn(VReg)) {
5560 IsSExt |= FuncInfo->isLiveInSExt(VReg);
5561 IsZExt |= FuncInfo->isLiveInZExt(VReg);
5562 return std::pair<bool, bool>(IsSExt, IsZExt);
5563 }
5564 }
5565
5566 if (SrcReg != PPC::X3) {
5567 // If this is a copy from another register, we recursively check source.
5568 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5569 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5570 SrcExt.second || IsZExt);
5571 }
5572
5573 // For a method return value, we check the ZExt/SExt flags in attribute.
5574 // We assume the following code sequence for method call.
5575 // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
5576 // BL8_NOP @func,...
5577 // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
5578 // %5 = COPY %x3; G8RC:%5
5579 const MachineBasicBlock *MBB = MI->getParent();
5580 std::pair<bool, bool> IsExtendPair = std::pair<bool, bool>(IsSExt, IsZExt);
5583 if (II == MBB->instr_begin() || (--II)->getOpcode() != PPC::ADJCALLSTACKUP)
5584 return IsExtendPair;
5585
5586 const MachineInstr &CallMI = *(--II);
5587 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
5588 return IsExtendPair;
5589
5590 const Function *CalleeFn =
5592 if (!CalleeFn)
5593 return IsExtendPair;
5594 const IntegerType *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
5595 if (IntTy && IntTy->getBitWidth() <= 32) {
5596 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
5597 IsSExt |= Attrs.hasAttribute(Attribute::SExt);
5598 IsZExt |= Attrs.hasAttribute(Attribute::ZExt);
5599 return std::pair<bool, bool>(IsSExt, IsZExt);
5600 }
5601
5602 return IsExtendPair;
5603 }
5604
5605 // OR, XOR with 16-bit immediate does not change the upper 48 bits.
5606 // So, we track the operand register as we do for register copy.
5607 case PPC::ORI:
5608 case PPC::XORI:
5609 case PPC::ORI8:
5610 case PPC::XORI8: {
5611 Register SrcReg = MI->getOperand(1).getReg();
5612 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5613 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5614 SrcExt.second || IsZExt);
5615 }
5616
5617 // OR, XOR with shifted 16-bit immediate does not change the upper
5618 // 32 bits. So, we track the operand register for zero extension.
5619 // For sign extension when the MSB of the immediate is zero, we also
5620 // track the operand register since the upper 33 bits are unchanged.
5621 case PPC::ORIS:
5622 case PPC::XORIS:
5623 case PPC::ORIS8:
5624 case PPC::XORIS8: {
5625 Register SrcReg = MI->getOperand(1).getReg();
5626 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5627 uint16_t Imm = MI->getOperand(2).getImm();
5628 if (Imm & 0x8000)
5629 return std::pair<bool, bool>(false, SrcExt.second || IsZExt);
5630 else
5631 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5632 SrcExt.second || IsZExt);
5633 }
5634
5635 // If all incoming values are sign-/zero-extended,
5636 // the output of OR, ISEL or PHI is also sign-/zero-extended.
5637 case PPC::OR:
5638 case PPC::OR8:
5639 case PPC::ISEL:
5640 case PPC::PHI: {
5641 if (BinOpDepth >= MAX_BINOP_DEPTH)
5642 return std::pair<bool, bool>(false, false);
5643
5644 // The input registers for PHI are operand 1, 3, ...
5645 // The input registers for others are operand 1 and 2.
5646 unsigned OperandEnd = 3, OperandStride = 1;
5647 if (MI->getOpcode() == PPC::PHI) {
5648 OperandEnd = MI->getNumOperands();
5649 OperandStride = 2;
5650 }
5651
5652 IsSExt = true;
5653 IsZExt = true;
5654 for (unsigned I = 1; I != OperandEnd; I += OperandStride) {
5655 if (!MI->getOperand(I).isReg())
5656 return std::pair<bool, bool>(false, false);
5657
5658 Register SrcReg = MI->getOperand(I).getReg();
5659 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth + 1, MRI);
5660 IsSExt &= SrcExt.first;
5661 IsZExt &= SrcExt.second;
5662 }
5663 return std::pair<bool, bool>(IsSExt, IsZExt);
5664 }
5665
5666 // If at least one of the incoming values of an AND is zero extended
5667 // then the output is also zero-extended. If both of the incoming values
5668 // are sign-extended then the output is also sign extended.
5669 case PPC::AND:
5670 case PPC::AND8: {
5671 if (BinOpDepth >= MAX_BINOP_DEPTH)
5672 return std::pair<bool, bool>(false, false);
5673
5674 Register SrcReg1 = MI->getOperand(1).getReg();
5675 Register SrcReg2 = MI->getOperand(2).getReg();
5676 auto Src1Ext = isSignOrZeroExtended(SrcReg1, BinOpDepth + 1, MRI);
5677 auto Src2Ext = isSignOrZeroExtended(SrcReg2, BinOpDepth + 1, MRI);
5678 return std::pair<bool, bool>(Src1Ext.first && Src2Ext.first,
5679 Src1Ext.second || Src2Ext.second);
5680 }
5681
5682 default:
5683 break;
5684 }
5685 return std::pair<bool, bool>(IsSExt, IsZExt);
5686}
5687
5688bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
5689 return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
5690}
5691
5692namespace {
5693class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
5694 MachineInstr *Loop, *EndLoop, *LoopCount;
5695 MachineFunction *MF;
5696 int64_t TripCount;
5697
5698public:
5699 PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
5700 MachineInstr *LoopCount)
5701 : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
5702 MF(Loop->getParent()->getParent()) {
5703 // Inspect the Loop instruction up-front, as it may be deleted when we call
5704 // createTripCountGreaterCondition.
5705 if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
5706 TripCount = LoopCount->getOperand(1).getImm();
5707 else
5708 TripCount = -1;
5709 }
5710
5711 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
5712 // Only ignore the terminator.
5713 return MI == EndLoop;
5714 }
5715
5716 std::optional<bool> createTripCountGreaterCondition(
5717 int TC, MachineBasicBlock &MBB,
5718 SmallVectorImpl<MachineOperand> &Cond) override {
5719 if (TripCount == -1) {
5720 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5721 // so we don't need to generate any thing here.
5724 MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
5725 true));
5726 return {};
5727 }
5728
5729 return TripCount > TC;
5730 }
5731
5732 void setPreheader(MachineBasicBlock *NewPreheader) override {
5733 // Do nothing. We want the LOOP setup instruction to stay in the *old*
5734 // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
5735 }
5736
5737 void adjustTripCount(int TripCountAdjust) override {
5738 // If the loop trip count is a compile-time value, then just change the
5739 // value.
5740 if (LoopCount->getOpcode() == PPC::LI8 ||
5741 LoopCount->getOpcode() == PPC::LI) {
5742 int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
5743 LoopCount->getOperand(1).setImm(TripCount);
5744 return;
5745 }
5746
5747 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5748 // so we don't need to generate any thing here.
5749 }
5750
5751 void disposed(LiveIntervals *LIS) override {
5752 if (LIS) {
5754 LIS->RemoveMachineInstrFromMaps(*LoopCount);
5755 }
5756 Loop->eraseFromParent();
5757 // Ensure the loop setup instruction is deleted too.
5758 LoopCount->eraseFromParent();
5759 }
5760};
5761} // namespace
5762
5763std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
5765 // We really "analyze" only hardware loops right now.
5767 MachineBasicBlock *Preheader = *LoopBB->pred_begin();
5768 if (Preheader == LoopBB)
5769 Preheader = *std::next(LoopBB->pred_begin());
5770 MachineFunction *MF = Preheader->getParent();
5771
5772 if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
5774 if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
5775 Register LoopCountReg = LoopInst->getOperand(0).getReg();
5777 MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
5778 return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
5779 }
5780 }
5781 return nullptr;
5782}
5783
5785 MachineBasicBlock &PreHeader,
5786 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
5787
5788 unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
5789
5790 // The loop set-up instruction should be in preheader
5791 for (auto &I : PreHeader.instrs())
5792 if (I.getOpcode() == LOOPi)
5793 return &I;
5794 return nullptr;
5795}
5796
5797// Return true if get the base operand, byte offset of an instruction and the
5798// memory width. Width is the size of memory that is being loaded/stored.
5800 const MachineOperand *&BaseReg,
5801 int64_t &Offset,
5802 LocationSize &Width) const {
5803 if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
5804 return false;
5805
5806 // Handle only loads/stores with base register followed by immediate offset.
5807 if (!LdSt.getOperand(1).isImm() ||
5808 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5809 return false;
5810
5811 if (!LdSt.hasOneMemOperand())
5812 return false;
5813
5814 Width = (*LdSt.memoperands_begin())->getSize();
5815 Offset = LdSt.getOperand(1).getImm();
5816 BaseReg = &LdSt.getOperand(2);
5817 return true;
5818}
5819
5821 const MachineInstr &MIa, const MachineInstr &MIb) const {
5822 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
5823 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
5824
5827 return false;
5828
5829 // Retrieve the base register, offset from the base register and width. Width
5830 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If
5831 // base registers are identical, and the offset of a lower memory access +
5832 // the width doesn't overlap the offset of a higher memory access,
5833 // then the memory accesses are different.
5834 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
5835 int64_t OffsetA = 0, OffsetB = 0;
5837 WidthB = LocationSize::precise(0);
5838 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA) &&
5839 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB)) {
5840 if (BaseOpA->isIdenticalTo(*BaseOpB)) {
5841 int LowOffset = std::min(OffsetA, OffsetB);
5842 int HighOffset = std::max(OffsetA, OffsetB);
5843 LocationSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
5844 if (LowWidth.hasValue() &&
5845 LowOffset + (int)LowWidth.getValue() <= HighOffset)
5846 return true;
5847 }
5848 }
5849 return false;
5850}
5851
5852// Expands LWAT_CSNE_PSEUDO/LDAT_CSNE_PSEUDO post register allocation.
5853// lwat/ldat FC=16 requires 3 consecutive registers. X8/X9/X10 are
5854// hardcoded post-RA to satisfy this constraint without a dedicated
5855// register class.
5857 MachineBasicBlock &MBB = *MI.getParent();
5858 DebugLoc DL = MI.getDebugLoc();
5859 bool IsLDAT = MI.getOpcode() == PPC::LDAT_CSNE_PSEUDO;
5860
5861 Register DstReg = MI.getOperand(0).getReg();
5862 Register PtrReg = MI.getOperand(1).getReg();
5863
5864 Register ScratchReg = PtrReg;
5865 if (PtrReg == PPC::X8 || PtrReg == PPC::X9 || PtrReg == PPC::X10) {
5866 // If ptr is in X8/X9/X10, use $dst as scratch to move ptr away from
5867 // X8/X9/X10 since lwat FC=16 always writes its result to X8. After lwat
5868 // copy X8 into $dst.
5869 Register DstReg64 = IsLDAT ? DstReg
5870 : Register(RI.getMatchingSuperReg(
5871 DstReg, PPC::sub_32, &PPC::G8RCRegClass));
5872 BuildMI(MBB, MI, DL, get(PPC::OR8), DstReg64).addReg(PtrReg).addReg(PtrReg);
5873 ScratchReg = DstReg64;
5874 }
5875
5876 BuildMI(MBB, MI, DL, get(IsLDAT ? PPC::LDAT_CSNE : PPC::LWAT_CSNE), PPC::X8)
5877 .addReg(ScratchReg)
5878 .addReg(PPC::X9, RegState::Implicit)
5879 .addReg(PPC::X10, RegState::Implicit);
5880
5881 if (DstReg != (IsLDAT ? PPC::X8 : PPC::R8)) {
5882 BuildMI(MBB, MI, DL, get(IsLDAT ? PPC::OR8 : PPC::OR), DstReg)
5883 .addReg(IsLDAT ? PPC::X8 : PPC::R8)
5884 .addReg(IsLDAT ? PPC::X8 : PPC::R8);
5885 }
5886 MI.eraseFromParent();
5887 return true;
5888}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis false
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t IntrinsicInst * II
static bool isOpZeroOfSubwordPreincLoad(int Opcode)
static bool MBBDefinesCTR(MachineBasicBlock &MBB)
#define InfoArrayIdxMULOpIdx
static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc, unsigned TrueReg, unsigned FalseReg, unsigned CRSubReg)
static unsigned getCRBitValue(unsigned CRBit)
static bool isAnImmediateOperand(const MachineOperand &MO)
static const uint16_t FMAOpIdxInfo[][6]
#define InfoArrayIdxAddOpIdx
static bool definedBySignExtendingOp(const PPCInstrInfo &TII, const unsigned Reg, const MachineRegisterInfo *MRI)
#define InfoArrayIdxFMAInst
static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc, const PPCSubtarget &Subtarget)
static bool isLdStSafeToCluster(const MachineInstr &LdSt, const TargetRegisterInfo *TRI)
const unsigned MAX_BINOP_DEPTH
#define InfoArrayIdxFSubInst
#define InfoArrayIdxFAddInst
static bool definedByZeroExtendingOp(const PPCInstrInfo &TII, const unsigned Reg, const MachineRegisterInfo *MRI)
#define InfoArrayIdxFMULInst
static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2)
static constexpr MCPhysReg SPReg
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
static bool isPhysical(const MachineOperand &MO)
This file declares the machine register scavenger class.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
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
void changeSign()
Definition APFloat.h:1434
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1186
static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit, unsigned hiBit)
Wrap version of getBitsSet.
Definition APInt.h:266
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
const BasicBlock & getEntryBlock() const
Definition Function.h:803
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Itinerary data supplied by a subtarget to be used by a target.
std::optional< unsigned > getOperandCycle(unsigned ItinClassIndx, unsigned OperandIdx) const
Return the cycle for the given class and operand.
Class to represent integer types.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
bool hasValue() const
static LocationSize precise(uint64_t Value)
TypeSize getValue() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
void setOpcode(unsigned Op)
Definition MCInst.h:200
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
ArrayRef< MCPhysReg > implicit_defs() const
Return a list of registers that are potentially written by any instance of this machine instruction.
ArrayRef< MCPhysReg > implicit_uses() const
Return a list of registers that are potentially read by any instance of this machine instruction.
bool isPseudo() const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:88
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Dead
Register is known to be fully dead.
MachineInstrBundleIterator< const MachineInstr, true > const_reverse_iterator
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
const std::vector< MachineConstantPoolEntry > & getConstants() const
LLVM_ABI unsigned getConstantPoolIndex(const Constant *C, Align Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
bool hasImplicitDef() const
Returns true if the instruction has implicit definition.
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void dump() const
LLVM_ABI void clearRegisterDeads(Register Reg)
Clear all dead flags on operands defining register Reg.
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
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
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static MachineOperand CreateImm(int64_t Val)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
void setTargetFlags(unsigned F)
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
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)
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the specified register,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual 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...
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
LLVM_ABI bool isLiveIn(Register Reg) const
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
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 use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
PPCDispatchGroupSBHazardRecognizer - This class implements a scoreboard-based hazard recognizer for P...
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
bool isLiveInSExt(Register VReg) const
This function returns true if the specified vreg is a live-in register and sign-extended.
bool isLiveInZExt(Register VReg) const
This function returns true if the specified vreg is a live-in register and zero-extended.
PPCHazardRecognizer970 - This class defines a finite state automata that models the dispatch logic on...
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
bool getFMAPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce) const
Return true when there is potentially a faster code sequence for a fma chain ending in Root.
bool combineRLWINM(MachineInstr &MI, MachineInstr **ToErase=nullptr) const
bool isReMaterializableImpl(const MachineInstr &MI) const override
PPCInstrInfo(const PPCSubtarget &STI)
const TargetRegisterClass * updatedRC(const TargetRegisterClass *RC) const
bool isPredicated(const MachineInstr &MI) const override
bool expandVSXMemPseudo(MachineInstr &MI) const
bool onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg) const
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const override
void finalizeInsInstrs(MachineInstr &Root, unsigned &Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs) const override
Fixup the placeholders we put in genAlternativeCodeSequence() for MachineCombiner.
MCInst getNop() const override
Return the noop instruction to use for a noop.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
static int getRecordFormOpcode(unsigned Opcode)
MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const override
Commutes the operands in the given instruction.
bool isXFormMemOp(unsigned Opcode) const
const PPCRegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
CombinerObjective getCombinerObjective(unsigned Pattern) const override
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
unsigned getStoreOpcodeForSpill(const TargetRegisterClass *RC) const
unsigned getLoadOpcodeForSpill(const TargetRegisterClass *RC) const
bool expandAMOCSNEPseudo(MachineInstr &MI) const
bool isTOCSaveMI(const MachineInstr &MI) const
ScheduleHazardRecognizer * CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *DAG) const override
CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer to use for this target when ...
bool isSExt32To64(unsigned Opcode) const
bool foldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg, MachineRegisterInfo *MRI) const override
bool isBDNZ(unsigned Opcode) const
Check Opcode is BDNZ (Decrement CTR and branch if it is still nonzero).
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
bool isZeroExtended(const unsigned Reg, const MachineRegisterInfo *MRI) const
std::pair< unsigned, unsigned > decomposeMachineOperandsTargetFlags(unsigned TF) const override
std::pair< bool, bool > isSignOrZeroExtended(const unsigned Reg, const unsigned BinOpDepth, const MachineRegisterInfo *MRI) const
bool expandPostRAPseudo(MachineInstr &MI) const override
bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const override
void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
bool isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index, MachineInstr *&ADDIMI, int64_t &OffsetAddi, int64_t OffsetImm) const
bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t Mask, int64_t Value, const MachineRegisterInfo *MRI) const override
ArrayRef< std::pair< unsigned, const char * > > getSerializableDirectMachineOperandTargetFlags() const override
std::optional< unsigned > getOperandLatency(const InstrItineraryData *ItinData, const MachineInstr &DefMI, unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const override
void materializeImmPostRA(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, Register Reg, int64_t Imm) const
bool isADDInstrEligibleForFolding(MachineInstr &ADDMI) const
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
Return true if two MIs access different memory addresses and false otherwise.
bool SubsumesPredicate(ArrayRef< MachineOperand > Pred1, ArrayRef< MachineOperand > Pred2) const override
ScheduleHazardRecognizer * CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, const ScheduleDAG *DAG) const override
CreateTargetHazardRecognizer - Return the hazard recognizer to use for this target when scheduling th...
void setSpecialOperandAttr(MachineInstr &MI, uint32_t Flags) const
bool isADDIInstrEligibleForFolding(MachineInstr &ADDIMI, int64_t &Imm) const
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const override
Get the base operand and byte offset of an instruction that reads/writes memory.
void loadRegFromStackSlotNoUpd(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC) const
bool foldFrameOffset(MachineInstr &MI) const
bool isLoadFromConstantPool(MachineInstr *I) const
MachineInstr * findLoopInstr(MachineBasicBlock &PreHeader, SmallPtrSet< MachineBasicBlock *, 8 > &Visited) const
Find the hardware loop instruction used to set-up the specified loop.
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const override
void storeRegToStackSlotNoUpd(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC) const
static bool isPredicatedBLR8(unsigned Opcode)
Return true if Opcode is a conditional return that PredicateInstruction makes from BLR8.
bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg, Register &DstReg, unsigned &SubIdx) const override
bool convertToImmediateForm(MachineInstr &MI, SmallSet< Register, 4 > &RegsToUpdate, MachineInstr **KilledDef=nullptr) const
bool isAssociativeAndCommutative(const MachineInstr &Inst, bool Invert) const override
bool getMemOperandWithOffsetWidth(const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset, LocationSize &Width) const
Return true if get the base operand, byte offset of an instruction and the memory width.
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &Mask, int64_t &Value) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
bool shouldReduceRegisterPressure(const MachineBasicBlock *MBB, const RegisterClassInfo *RegClassInfo) const override
On PowerPC, we leverage machine combiner pass to reduce register pressure when the register pressure ...
const TargetRegisterClass * getInlineAsmMemoryOperandRegClass(InlineAsm::ConstraintCode C) const override
void genAlternativeCodeSequence(MachineInstr &Root, unsigned Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg) const override
When getMachineCombinerPatterns() finds patterns, this function generates the instructions that could...
InstSizeVerifyMode getInstSizeVerifyMode(const MachineInstr &MI) const override
bool isSignExtended(const unsigned Reg, const MachineRegisterInfo *MRI) const
void replaceInstrOperandWithImm(MachineInstr &MI, unsigned OpNo, int64_t Imm) const
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const override
Analyze loop L, which must be a single-basic-block loop, and if the conditions can be understood enou...
bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const override
Returns true if the two given memory operations should be scheduled adjacent.
void replaceInstrWithLI(MachineInstr &MI, const LoadImmediateInfo &LII) const
bool isImmInstrEligibleForFolding(MachineInstr &MI, unsigned &BaseReg, unsigned &XFormOpcode, int64_t &OffsetOfImmInstr, ImmInstrInfo &III) const
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Pred) const override
bool getMachineCombinerPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce) const override
Return true when there is potentially a faster code sequence for an instruction chain ending in <Root...
bool optimizeCmpPostRA(MachineInstr &MI) const
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
const Constant * getConstantFromConstantPool(MachineInstr *I) const
bool ClobbersPredicate(MachineInstr &MI, std::vector< MachineOperand > &Pred, bool SkipDead) const override
bool canInsertSelect(const MachineBasicBlock &, ArrayRef< MachineOperand > Cond, Register, Register, Register, SelectExpansion &) const override
void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const override
void promoteInstr32To64ForElimEXTSW(const Register &Reg, MachineRegisterInfo *MRI, unsigned BinOpDepth) const
bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const override
bool instrHasImmForm(unsigned Opc, bool IsVFReg, ImmInstrInfo &III, bool PostRA) const
MachineInstr * getDefMIPostRA(unsigned Reg, MachineInstr &MI, bool &SeenIntermediateUse) const
static void emitAccCopyInfo(MachineBasicBlock &MBB, MCRegister DestReg, MCRegister SrcReg)
bool isSVR4ABI() const
MI-level patchpoint operands.
Definition StackMaps.h:77
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given patchpoint should emit.
Definition StackMaps.h:105
Track the current register pressure at some position in the instruction stream, and remember the high...
LLVM_ABI void init(const MachineFunction *mf, const RegisterClassInfo *rci, LiveIntervals *lis, const MachineBasicBlock *mbb, MachineBasicBlock::const_iterator pos, bool TrackLaneMasks, bool TrackUntiedDefs)
Setup the RegPressureTracker.
LLVM_ABI void closeRegion()
Finalize the region boundaries and recored live ins and live outs.
LLVM_ABI void recede(SmallVectorImpl< VRegMaskOrUnit > *LiveUses=nullptr)
Recede across the previous instruction.
RegisterPressure & getPressure()
Get the resulting register pressure over the traversed region.
LLVM_ABI void recedeSkipDebugValues()
Recede until we find an instruction which is not a DebugValue.
MachineBasicBlock::const_iterator getPos() const
Get the MI position corresponding to this register pressure.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
List of registers defined and used by a machine instruction.
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
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
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
const TargetInstrInfo * TII
Target instruction information.
MachineFunction & MF
Machine function.
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
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
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
MI-level stackmap operands.
Definition StackMaps.h:36
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given stackmap should emit.
Definition StackMaps.h:51
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
Object returned by analyzeLoopForPipelining.
virtual bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction.
virtual void genAlternativeCodeSequence(MachineInstr &Root, unsigned Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstIdxForVirtReg) const
When getMachineCombinerPatterns() finds patterns, this function generates the instructions that could...
virtual ScheduleHazardRecognizer * CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, const ScheduleDAG *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
virtual bool getMachineCombinerPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce) const
Return true when there is potentially a faster code sequence for an instruction chain ending in Root.
virtual bool isReMaterializableImpl(const MachineInstr &MI) const
For instructions with opcodes for which the M_REMATERIALIZABLE flag is set, this hook lets the target...
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
virtual CombinerObjective getCombinerObjective(unsigned Pattern) const
Return the objective of a combiner pattern.
virtual MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const
This method commutes the operands of the given machine instruction MI.
const Triple & getTargetTriple() const
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
LLVM_ABI bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition Triple.cpp:2240
bool isOSAIX() const
Tests whether the OS is AIX.
Definition Triple.h:859
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
PPCII - This namespace holds all of the PowerPC target-specific per-instruction flags.
@ MO_TOC_LO
Definition PPC.h:196
Define some predicates that are used for node matching.
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.
Predicate InvertPredicate(Predicate Opcode)
Invert the specified predicate. != -> ==, < -> >=.
int32_t getNonRecordFormOpcode(uint32_t)
int32_t getAltVSXFMAOpcode(uint32_t Opcode)
static bool isVFRegister(MCRegister Reg)
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Kill
The last use of a register.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
static const MachineInstrBuilder & addFrameReference(const MachineInstrBuilder &MIB, int FI, int Offset=0, bool mem=true)
addFrameReference - This function is used to add a reference to the base of an abstract object on the...
static unsigned getCRFromCRBit(unsigned SrcReg)
constexpr RegState getDeadRegState(bool B)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
@ REASSOC_XY_BCA
@ REASSOC_XY_BAC
@ REASSOC_XY_AMM_BMM
@ REASSOC_XMM_AMM_BMM
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void recomputeLivenessFlags(MachineBasicBlock &MBB)
Recomputes dead and kill flags in MBB.
@ Sub
Subtraction of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ SOK_CRBitSpill
@ SOK_VSXVectorSpill
@ SOK_SpillToVSR
@ SOK_Int4Spill
@ SOK_PairedVecSpill
@ SOK_VectorFloat8Spill
@ SOK_UAccumulatorSpill
@ SOK_PairedG8Spill
@ SOK_DMRSpill
@ SOK_VectorFloat4Spill
@ SOK_Float8Spill
@ SOK_Float4Spill
@ SOK_VRVectorSpill
@ SOK_WAccumulatorSpill
@ SOK_SPESpill
@ SOK_CRSpill
@ SOK_AccumulatorSpill
@ SOK_Int8Spill
@ SOK_LastOpcodeSpill
@ SOK_DMRpSpill
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME)
Returns true iff Val consists of one contiguous run of 1s with any number of 0s on either side.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
uint64_t IsSummingOperands
uint64_t OpNoForForwarding
uint64_t ImmMustBeMultipleOf
uint64_t ZeroIsSpecialNew
uint64_t ZeroIsSpecialOrig
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
RegisterPressure computed within a region of instructions delimited by TopPos and BottomPos.
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.