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 = RetOpcode == PPC::BCCLR;
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(0);
3312 return true;
3313 }
3314 case PPC::LWAT_CSNE_PSEUDO:
3315 case PPC::LDAT_CSNE_PSEUDO:
3316 return expandAMOCSNEPseudo(MI);
3317 }
3318 return false;
3319}
3320
3321// Essentially a compile-time implementation of a compare->isel sequence.
3322// It takes two constants to compare, along with the true/false registers
3323// and the comparison type (as a subreg to a CR field) and returns one
3324// of the true/false registers, depending on the comparison results.
3325static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
3326 unsigned TrueReg, unsigned FalseReg,
3327 unsigned CRSubReg) {
3328 // Signed comparisons. The immediates are assumed to be sign-extended.
3329 if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
3330 switch (CRSubReg) {
3331 default: llvm_unreachable("Unknown integer comparison type.");
3332 case PPC::sub_lt:
3333 return Imm1 < Imm2 ? TrueReg : FalseReg;
3334 case PPC::sub_gt:
3335 return Imm1 > Imm2 ? TrueReg : FalseReg;
3336 case PPC::sub_eq:
3337 return Imm1 == Imm2 ? TrueReg : FalseReg;
3338 }
3339 }
3340 // Unsigned comparisons.
3341 else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
3342 switch (CRSubReg) {
3343 default: llvm_unreachable("Unknown integer comparison type.");
3344 case PPC::sub_lt:
3345 return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
3346 case PPC::sub_gt:
3347 return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
3348 case PPC::sub_eq:
3349 return Imm1 == Imm2 ? TrueReg : FalseReg;
3350 }
3351 }
3352 return PPC::NoRegister;
3353}
3354
3356 unsigned OpNo,
3357 int64_t Imm) const {
3358 assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
3359 // Replace the REG with the Immediate.
3360 Register InUseReg = MI.getOperand(OpNo).getReg();
3361 MI.getOperand(OpNo).ChangeToImmediate(Imm);
3362
3363 // We need to make sure that the MI didn't have any implicit use
3364 // of this REG any more. We don't call MI.implicit_operands().empty() to
3365 // return early, since MI's MCID might be changed in calling context, as a
3366 // result its number of explicit operands may be changed, thus the begin of
3367 // implicit operand is changed.
3368 int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, &RI, false);
3369 if (UseOpIdx >= 0) {
3370 MachineOperand &MO = MI.getOperand(UseOpIdx);
3371 if (MO.isImplicit())
3372 // The operands must always be in the following order:
3373 // - explicit reg defs,
3374 // - other explicit operands (reg uses, immediates, etc.),
3375 // - implicit reg defs
3376 // - implicit reg uses
3377 // Therefore, removing the implicit operand won't change the explicit
3378 // operands layout.
3379 MI.removeOperand(UseOpIdx);
3380 }
3381}
3382
3383// Replace an instruction with one that materializes a constant (and sets
3384// CR0 if the original instruction was a record-form instruction).
3386 const LoadImmediateInfo &LII) const {
3387 // Remove existing operands.
3388 int OperandToKeep = LII.SetCR ? 1 : 0;
3389 for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
3390 MI.removeOperand(i);
3391
3392 // Replace the instruction.
3393 if (LII.SetCR) {
3394 MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3395 // Set the immediate.
3396 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3397 .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
3398 return;
3399 }
3400 else
3401 MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
3402
3403 // Set the immediate.
3404 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3405 .addImm(LII.Imm);
3406}
3407
3409 bool &SeenIntermediateUse) const {
3410 assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
3411 "Should be called after register allocation.");
3412 MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
3413 It++;
3414 SeenIntermediateUse = false;
3415 for (; It != E; ++It) {
3416 if (It->modifiesRegister(Reg, &RI))
3417 return &*It;
3418 if (It->readsRegister(Reg, &RI))
3419 SeenIntermediateUse = true;
3420 }
3421 return nullptr;
3422}
3423
3426 const DebugLoc &DL, Register Reg,
3427 int64_t Imm) const {
3428 assert(!MBB.getParent()->getRegInfo().isSSA() &&
3429 "Register should be in non-SSA form after RA");
3430 bool isPPC64 = Subtarget.isPPC64();
3431 // FIXME: Materialization here is not optimal.
3432 // For some special bit patterns we can use less instructions.
3433 // See `selectI64ImmDirect` in PPCISelDAGToDAG.cpp.
3434 if (isInt<16>(Imm)) {
3435 BuildMI(MBB, MBBI, DL, get(isPPC64 ? PPC::LI8 : PPC::LI), Reg).addImm(Imm);
3436 } else if (isInt<32>(Imm)) {
3437 BuildMI(MBB, MBBI, DL, get(isPPC64 ? PPC::LIS8 : PPC::LIS), Reg)
3438 .addImm(Imm >> 16);
3439 if (Imm & 0xFFFF)
3440 BuildMI(MBB, MBBI, DL, get(isPPC64 ? PPC::ORI8 : PPC::ORI), Reg)
3441 .addReg(Reg, RegState::Kill)
3442 .addImm(Imm & 0xFFFF);
3443 } else {
3444 assert(isPPC64 && "Materializing 64-bit immediate to single register is "
3445 "only supported in PPC64");
3446 BuildMI(MBB, MBBI, DL, get(PPC::LIS8), Reg).addImm(Imm >> 48);
3447 if ((Imm >> 32) & 0xFFFF)
3448 BuildMI(MBB, MBBI, DL, get(PPC::ORI8), Reg)
3449 .addReg(Reg, RegState::Kill)
3450 .addImm((Imm >> 32) & 0xFFFF);
3451 BuildMI(MBB, MBBI, DL, get(PPC::RLDICR), Reg)
3452 .addReg(Reg, RegState::Kill)
3453 .addImm(32)
3454 .addImm(31);
3455 BuildMI(MBB, MBBI, DL, get(PPC::ORIS8), Reg)
3456 .addReg(Reg, RegState::Kill)
3457 .addImm((Imm >> 16) & 0xFFFF);
3458 if (Imm & 0xFFFF)
3459 BuildMI(MBB, MBBI, DL, get(PPC::ORI8), Reg)
3460 .addReg(Reg, RegState::Kill)
3461 .addImm(Imm & 0xFFFF);
3462 }
3463}
3464
3465MachineInstr *PPCInstrInfo::getForwardingDefMI(
3467 unsigned &OpNoForForwarding,
3468 bool &SeenIntermediateUse) const {
3469 OpNoForForwarding = ~0U;
3470 MachineInstr *DefMI = nullptr;
3471 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3472 // If we're in SSA, get the defs through the MRI. Otherwise, only look
3473 // within the basic block to see if the register is defined using an
3474 // LI/LI8/ADDI/ADDI8.
3475 if (MRI->isSSA()) {
3476 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3477 if (!MI.getOperand(i).isReg())
3478 continue;
3479 Register Reg = MI.getOperand(i).getReg();
3480 if (!Reg.isVirtual())
3481 continue;
3482 Register TrueReg = RI.lookThruCopyLike(Reg, MRI);
3483 if (TrueReg.isVirtual()) {
3484 MachineInstr *DefMIForTrueReg = MRI->getVRegDef(TrueReg);
3485 if (!DefMIForTrueReg)
3486 continue;
3487 if (DefMIForTrueReg->getOpcode() == PPC::LI ||
3488 DefMIForTrueReg->getOpcode() == PPC::LI8 ||
3489 DefMIForTrueReg->getOpcode() == PPC::ADDI ||
3490 DefMIForTrueReg->getOpcode() == PPC::ADDI8) {
3491 OpNoForForwarding = i;
3492 DefMI = DefMIForTrueReg;
3493 // The ADDI and LI operand maybe exist in one instruction at same
3494 // time. we prefer to fold LI operand as LI only has one Imm operand
3495 // and is more possible to be converted. So if current DefMI is
3496 // ADDI/ADDI8, we continue to find possible LI/LI8.
3497 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
3498 break;
3499 }
3500 }
3501 }
3502 } else {
3503 // Looking back through the definition for each operand could be expensive,
3504 // so exit early if this isn't an instruction that either has an immediate
3505 // form or is already an immediate form that we can handle.
3506 ImmInstrInfo III;
3507 unsigned Opc = MI.getOpcode();
3508 bool ConvertibleImmForm =
3509 Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
3510 Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
3511 Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
3512 Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
3513 Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
3514 Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
3515 Opc == PPC::RLWINM8_rec;
3516 bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
3517 ? PPC::isVFRegister(MI.getOperand(0).getReg())
3518 : false;
3519 if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
3520 return nullptr;
3521
3522 // Don't convert or %X, %Y, %Y since that's just a register move.
3523 if ((Opc == PPC::OR || Opc == PPC::OR8) &&
3524 MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
3525 return nullptr;
3526 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3527 MachineOperand &MO = MI.getOperand(i);
3528 SeenIntermediateUse = false;
3529 if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
3530 Register Reg = MI.getOperand(i).getReg();
3531 // If we see another use of this reg between the def and the MI,
3532 // we want to flag it so the def isn't deleted.
3533 MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
3534 if (DefMI) {
3535 // Is this register defined by some form of add-immediate (including
3536 // load-immediate) within this basic block?
3537 switch (DefMI->getOpcode()) {
3538 default:
3539 break;
3540 case PPC::LI:
3541 case PPC::LI8:
3542 case PPC::ADDItocL8:
3543 case PPC::ADDI:
3544 case PPC::ADDI8:
3545 OpNoForForwarding = i;
3546 return DefMI;
3547 }
3548 }
3549 }
3550 }
3551 }
3552 return OpNoForForwarding == ~0U ? nullptr : DefMI;
3553}
3554
3555unsigned PPCInstrInfo::getSpillTarget() const {
3556 // With P10, we may need to spill paired vector registers or accumulator
3557 // registers. MMA implies paired vectors, so we can just check that.
3558 bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
3559 // P11 uses the P10 target.
3560 return Subtarget.isISAFuture() ? 3 : IsP10Variant ?
3561 2 : Subtarget.hasP9Vector() ?
3562 1 : 0;
3563}
3564
3565ArrayRef<unsigned> PPCInstrInfo::getStoreOpcodesForSpillArray() const {
3566 return {StoreSpillOpcodesArray[getSpillTarget()], SOK_LastOpcodeSpill};
3567}
3568
3569ArrayRef<unsigned> PPCInstrInfo::getLoadOpcodesForSpillArray() const {
3570 return {LoadSpillOpcodesArray[getSpillTarget()], SOK_LastOpcodeSpill};
3571}
3572
3573// This opt tries to convert the following imm form to an index form to save an
3574// add for stack variables.
3575// Return false if no such pattern found.
3576//
3577// ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3578// ADD instr: ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
3579// Imm instr: Reg = op OffsetImm, ToBeDeletedReg(killed)
3580//
3581// can be converted to:
3582//
3583// new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
3584// Index instr: Reg = opx ScaleReg, ToBeChangedReg(killed)
3585//
3586// In order to eliminate ADD instr, make sure that:
3587// 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
3588// new ADDI instr and ADDI can only take int16 Imm.
3589// 2: ToBeChangedReg must be killed in ADD instr and there is no other use
3590// between ADDI and ADD instr since its original def in ADDI will be changed
3591// in new ADDI instr. And also there should be no new def for it between
3592// ADD and Imm instr as ToBeChangedReg will be used in Index instr.
3593// 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
3594// between ADD and Imm instr since ADD instr will be eliminated.
3595// 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
3596// moved to Index instr.
3598 MachineFunction *MF = MI.getParent()->getParent();
3600 bool PostRA = !MRI->isSSA();
3601 // Do this opt after PEI which is after RA. The reason is stack slot expansion
3602 // in PEI may expose such opportunities since in PEI, stack slot offsets to
3603 // frame base(OffsetAddi) are determined.
3604 if (!PostRA)
3605 return false;
3606 unsigned ToBeDeletedReg = 0;
3607 int64_t OffsetImm = 0;
3608 unsigned XFormOpcode = 0;
3609 ImmInstrInfo III;
3610
3611 // Check if Imm instr meets requirement.
3612 if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
3613 III))
3614 return false;
3615
3616 bool OtherIntermediateUse = false;
3617 MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
3618
3619 // Exit if there is other use between ADD and Imm instr or no def found.
3620 if (OtherIntermediateUse || !ADDMI)
3621 return false;
3622
3623 // Check if ADD instr meets requirement.
3624 if (!isADDInstrEligibleForFolding(*ADDMI))
3625 return false;
3626
3627 unsigned ScaleRegIdx = 0;
3628 int64_t OffsetAddi = 0;
3629 MachineInstr *ADDIMI = nullptr;
3630
3631 // Check if there is a valid ToBeChangedReg in ADDMI.
3632 // 1: It must be killed.
3633 // 2: Its definition must be a valid ADDIMI.
3634 // 3: It must satify int16 offset requirement.
3635 if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
3636 ScaleRegIdx = 2;
3637 else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
3638 ScaleRegIdx = 1;
3639 else
3640 return false;
3641
3642 assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
3643 Register ToBeChangedReg = ADDIMI->getOperand(0).getReg();
3644 Register ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
3645 auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
3647 for (auto It = ++Start; It != End; It++)
3648 if (It->modifiesRegister(Reg, &getRegisterInfo()))
3649 return true;
3650 return false;
3651 };
3652
3653 // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
3654 // treated as special zero when ScaleReg is R0/X0 register.
3655 if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
3656 (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
3657 return false;
3658
3659 // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
3660 // and Imm Instr.
3661 if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
3662 return false;
3663
3664 // Now start to do the transformation.
3665 LLVM_DEBUG(dbgs() << "Replace instruction: "
3666 << "\n");
3667 LLVM_DEBUG(ADDIMI->dump());
3668 LLVM_DEBUG(ADDMI->dump());
3669 LLVM_DEBUG(MI.dump());
3670 LLVM_DEBUG(dbgs() << "with: "
3671 << "\n");
3672
3673 // Update ADDI instr.
3674 ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
3675
3676 // Update Imm instr.
3677 MI.setDesc(get(XFormOpcode));
3678 MI.getOperand(III.ImmOpNo)
3679 .ChangeToRegister(ScaleReg, false, false,
3680 ADDMI->getOperand(ScaleRegIdx).isKill());
3681
3682 MI.getOperand(III.OpNoForForwarding)
3683 .ChangeToRegister(ToBeChangedReg, false, false, true);
3684
3685 // Eliminate ADD instr.
3686 ADDMI->eraseFromParent();
3687
3688 LLVM_DEBUG(ADDIMI->dump());
3689 LLVM_DEBUG(MI.dump());
3690
3691 return true;
3692}
3693
3695 int64_t &Imm) const {
3696 unsigned Opc = ADDIMI.getOpcode();
3697
3698 // Exit if the instruction is not ADDI.
3699 if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
3700 return false;
3701
3702 // The operand may not necessarily be an immediate - it could be a relocation.
3703 if (!ADDIMI.getOperand(2).isImm())
3704 return false;
3705
3706 Imm = ADDIMI.getOperand(2).getImm();
3707
3708 return true;
3709}
3710
3712 unsigned Opc = ADDMI.getOpcode();
3713
3714 // Exit if the instruction is not ADD.
3715 return Opc == PPC::ADD4 || Opc == PPC::ADD8;
3716}
3717
3719 unsigned &ToBeDeletedReg,
3720 unsigned &XFormOpcode,
3721 int64_t &OffsetImm,
3722 ImmInstrInfo &III) const {
3723 // Only handle load/store.
3724 if (!MI.mayLoadOrStore())
3725 return false;
3726
3727 unsigned Opc = MI.getOpcode();
3728
3729 XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
3730
3731 // Exit if instruction has no index form.
3732 if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
3733 return false;
3734
3735 // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
3736 if (!instrHasImmForm(XFormOpcode,
3737 PPC::isVFRegister(MI.getOperand(0).getReg()), III, true))
3738 return false;
3739
3740 if (!III.IsSummingOperands)
3741 return false;
3742
3743 MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
3744 MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
3745 // Only support imm operands, not relocation slots or others.
3746 if (!ImmOperand.isImm())
3747 return false;
3748
3749 assert(RegOperand.isReg() && "Instruction format is not right");
3750
3751 // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
3752 if (!RegOperand.isKill())
3753 return false;
3754
3755 ToBeDeletedReg = RegOperand.getReg();
3756 OffsetImm = ImmOperand.getImm();
3757
3758 return true;
3759}
3760
3762 MachineInstr *&ADDIMI,
3763 int64_t &OffsetAddi,
3764 int64_t OffsetImm) const {
3765 assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
3766 MachineOperand &MO = ADDMI->getOperand(Index);
3767
3768 if (!MO.isKill())
3769 return false;
3770
3771 bool OtherIntermediateUse = false;
3772
3773 ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
3774 // Currently handle only one "add + Imminstr" pair case, exit if other
3775 // intermediate use for ToBeChangedReg found.
3776 // TODO: handle the cases where there are other "add + Imminstr" pairs
3777 // with same offset in Imminstr which is like:
3778 //
3779 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3780 // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
3781 // Imm instr1: Reg1 = op1 OffsetImm, ToBeDeletedReg1(killed)
3782 // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
3783 // Imm instr2: Reg2 = op2 OffsetImm, ToBeDeletedReg2(killed)
3784 //
3785 // can be converted to:
3786 //
3787 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
3788 // (OffsetAddi + OffsetImm)
3789 // Index instr1: Reg1 = opx1 ScaleReg1, ToBeChangedReg
3790 // Index instr2: Reg2 = opx2 ScaleReg2, ToBeChangedReg(killed)
3791
3792 if (OtherIntermediateUse || !ADDIMI)
3793 return false;
3794 // Check if ADDI instr meets requirement.
3795 if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
3796 return false;
3797
3798 if (isInt<16>(OffsetAddi + OffsetImm))
3799 return true;
3800 return false;
3801}
3802
3803// If this instruction has an immediate form and one of its operands is a
3804// result of a load-immediate or an add-immediate, convert it to
3805// the immediate form if the constant is in range.
3807 SmallSet<Register, 4> &RegsToUpdate,
3808 MachineInstr **KilledDef) const {
3809 MachineFunction *MF = MI.getParent()->getParent();
3811 bool PostRA = !MRI->isSSA();
3812 bool SeenIntermediateUse = true;
3813 unsigned ForwardingOperand = ~0U;
3814 MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
3815 SeenIntermediateUse);
3816 if (!DefMI)
3817 return false;
3818 assert(ForwardingOperand < MI.getNumOperands() &&
3819 "The forwarding operand needs to be valid at this point");
3820 bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
3821 bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
3822 if (KilledDef && KillFwdDefMI)
3823 *KilledDef = DefMI;
3824
3825 // Conservatively add defs from DefMI and defs/uses from MI to the set of
3826 // registers that need their kill flags updated.
3827 for (const MachineOperand &MO : DefMI->operands())
3828 if (MO.isReg() && MO.isDef())
3829 RegsToUpdate.insert(MO.getReg());
3830 for (const MachineOperand &MO : MI.operands())
3831 if (MO.isReg())
3832 RegsToUpdate.insert(MO.getReg());
3833
3834 // If this is a imm instruction and its register operands is produced by ADDI,
3835 // put the imm into imm inst directly.
3836 if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) !=
3837 PPC::INSTRUCTION_LIST_END &&
3838 transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand))
3839 return true;
3840
3841 ImmInstrInfo III;
3842 bool IsVFReg = MI.getOperand(0).isReg() &&
3843 MI.getOperand(0).getReg().isPhysical() &&
3844 PPC::isVFRegister(MI.getOperand(0).getReg());
3845 bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
3846 // If this is a reg+reg instruction that has a reg+imm form,
3847 // and one of the operands is produced by an add-immediate,
3848 // try to convert it.
3849 if (HasImmForm &&
3850 transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
3851 KillFwdDefMI))
3852 return true;
3853
3854 // If this is a reg+reg instruction that has a reg+imm form,
3855 // and one of the operands is produced by LI, convert it now.
3856 if (HasImmForm &&
3857 transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI))
3858 return true;
3859
3860 // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
3861 // can be simpified to LI.
3862 if (!HasImmForm &&
3863 simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef, &RegsToUpdate))
3864 return true;
3865
3866 return false;
3867}
3868
3870 MachineInstr **ToErase) const {
3871 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3872 Register FoldingReg = MI.getOperand(1).getReg();
3873 if (!FoldingReg.isVirtual())
3874 return false;
3875 MachineInstr *SrcMI = MRI->getVRegDef(FoldingReg);
3876 if (!SrcMI)
3877 return false;
3878 if (SrcMI->getOpcode() != PPC::RLWINM &&
3879 SrcMI->getOpcode() != PPC::RLWINM_rec &&
3880 SrcMI->getOpcode() != PPC::RLWINM8 &&
3881 SrcMI->getOpcode() != PPC::RLWINM8_rec)
3882 return false;
3883 assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
3884 MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
3885 SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
3886 "Invalid PPC::RLWINM Instruction!");
3887 uint64_t SHSrc = SrcMI->getOperand(2).getImm();
3888 uint64_t SHMI = MI.getOperand(2).getImm();
3889 uint64_t MBSrc = SrcMI->getOperand(3).getImm();
3890 uint64_t MBMI = MI.getOperand(3).getImm();
3891 uint64_t MESrc = SrcMI->getOperand(4).getImm();
3892 uint64_t MEMI = MI.getOperand(4).getImm();
3893
3894 assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
3895 "Invalid PPC::RLWINM Instruction!");
3896 // If MBMI is bigger than MEMI, we always can not get run of ones.
3897 // RotatedSrcMask non-wrap:
3898 // 0........31|32........63
3899 // RotatedSrcMask: B---E B---E
3900 // MaskMI: -----------|--E B------
3901 // Result: ----- --- (Bad candidate)
3902 //
3903 // RotatedSrcMask wrap:
3904 // 0........31|32........63
3905 // RotatedSrcMask: --E B----|--E B----
3906 // MaskMI: -----------|--E B------
3907 // Result: --- -----|--- ----- (Bad candidate)
3908 //
3909 // One special case is RotatedSrcMask is a full set mask.
3910 // RotatedSrcMask full:
3911 // 0........31|32........63
3912 // RotatedSrcMask: ------EB---|-------EB---
3913 // MaskMI: -----------|--E B------
3914 // Result: -----------|--- ------- (Good candidate)
3915
3916 // Mark special case.
3917 bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
3918
3919 // For other MBMI > MEMI cases, just return.
3920 if ((MBMI > MEMI) && !SrcMaskFull)
3921 return false;
3922
3923 // Handle MBMI <= MEMI cases.
3924 APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI);
3925 // In MI, we only need low 32 bits of SrcMI, just consider about low 32
3926 // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
3927 // while in PowerPC ISA, lowerest bit is at index 63.
3928 APInt MaskSrc = APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc);
3929
3930 APInt RotatedSrcMask = MaskSrc.rotl(SHMI);
3931 APInt FinalMask = RotatedSrcMask & MaskMI;
3932 uint32_t NewMB, NewME;
3933 bool Simplified = false;
3934
3935 // If final mask is 0, MI result should be 0 too.
3936 if (FinalMask.isZero()) {
3937 bool Is64Bit =
3938 (MI.getOpcode() == PPC::RLWINM8 || MI.getOpcode() == PPC::RLWINM8_rec);
3939 Simplified = true;
3940 LLVM_DEBUG(dbgs() << "Replace Instr: ");
3941 LLVM_DEBUG(MI.dump());
3942
3943 if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
3944 // Replace MI with "LI 0"
3945 MI.removeOperand(4);
3946 MI.removeOperand(3);
3947 MI.removeOperand(2);
3948 MI.getOperand(1).ChangeToImmediate(0);
3949 MI.setDesc(get(Is64Bit ? PPC::LI8 : PPC::LI));
3950 } else {
3951 // Replace MI with "ANDI_rec reg, 0"
3952 MI.removeOperand(4);
3953 MI.removeOperand(3);
3954 MI.getOperand(2).setImm(0);
3955 MI.setDesc(get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3956 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3957 if (SrcMI->getOperand(1).isKill()) {
3958 MI.getOperand(1).setIsKill(true);
3959 SrcMI->getOperand(1).setIsKill(false);
3960 } else
3961 // About to replace MI.getOperand(1), clear its kill flag.
3962 MI.getOperand(1).setIsKill(false);
3963 }
3964
3965 LLVM_DEBUG(dbgs() << "With: ");
3966 LLVM_DEBUG(MI.dump());
3967
3968 } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, NewME) &&
3969 NewMB <= NewME) ||
3970 SrcMaskFull) {
3971 // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
3972 // than NewME. Otherwise we get a 64 bit value after folding, but MI
3973 // return a 32 bit value.
3974 Simplified = true;
3975 LLVM_DEBUG(dbgs() << "Converting Instr: ");
3976 LLVM_DEBUG(MI.dump());
3977
3978 uint16_t NewSH = (SHSrc + SHMI) % 32;
3979 MI.getOperand(2).setImm(NewSH);
3980 // If SrcMI mask is full, no need to update MBMI and MEMI.
3981 if (!SrcMaskFull) {
3982 MI.getOperand(3).setImm(NewMB);
3983 MI.getOperand(4).setImm(NewME);
3984 }
3985 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
3986 if (SrcMI->getOperand(1).isKill()) {
3987 MI.getOperand(1).setIsKill(true);
3988 SrcMI->getOperand(1).setIsKill(false);
3989 } else
3990 // About to replace MI.getOperand(1), clear its kill flag.
3991 MI.getOperand(1).setIsKill(false);
3992
3993 LLVM_DEBUG(dbgs() << "To: ");
3994 LLVM_DEBUG(MI.dump());
3995 }
3996 if (Simplified & MRI->use_nodbg_empty(FoldingReg) &&
3997 !SrcMI->hasImplicitDef()) {
3998 // If FoldingReg has no non-debug use and it has no implicit def (it
3999 // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI.
4000 // Otherwise keep it.
4001 *ToErase = SrcMI;
4002 LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
4003 LLVM_DEBUG(SrcMI->dump());
4004 }
4005 return Simplified;
4006}
4007
4008bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
4009 ImmInstrInfo &III, bool PostRA) const {
4010 // The vast majority of the instructions would need their operand 2 replaced
4011 // with an immediate when switching to the reg+imm form. A marked exception
4012 // are the update form loads/stores for which a constant operand 2 would need
4013 // to turn into a displacement and move operand 1 to the operand 2 position.
4014 III.ImmOpNo = 2;
4015 III.OpNoForForwarding = 2;
4016 III.ImmWidth = 16;
4017 III.ImmMustBeMultipleOf = 1;
4018 III.TruncateImmTo = 0;
4019 III.IsSummingOperands = false;
4020 switch (Opc) {
4021 default: return false;
4022 case PPC::ADD4:
4023 case PPC::ADD8:
4024 III.SignedImm = true;
4025 III.ZeroIsSpecialOrig = 0;
4026 III.ZeroIsSpecialNew = 1;
4027 III.IsCommutative = true;
4028 III.IsSummingOperands = true;
4029 III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
4030 break;
4031 case PPC::ADDC:
4032 case PPC::ADDC8:
4033 III.SignedImm = true;
4034 III.ZeroIsSpecialOrig = 0;
4035 III.ZeroIsSpecialNew = 0;
4036 III.IsCommutative = true;
4037 III.IsSummingOperands = true;
4038 III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
4039 break;
4040 case PPC::ADDC_rec:
4041 III.SignedImm = true;
4042 III.ZeroIsSpecialOrig = 0;
4043 III.ZeroIsSpecialNew = 0;
4044 III.IsCommutative = true;
4045 III.IsSummingOperands = true;
4046 III.ImmOpcode = PPC::ADDIC_rec;
4047 break;
4048 case PPC::SUBFC:
4049 case PPC::SUBFC8:
4050 III.SignedImm = true;
4051 III.ZeroIsSpecialOrig = 0;
4052 III.ZeroIsSpecialNew = 0;
4053 III.IsCommutative = false;
4054 III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
4055 break;
4056 case PPC::CMPW:
4057 case PPC::CMPD:
4058 III.SignedImm = true;
4059 III.ZeroIsSpecialOrig = 0;
4060 III.ZeroIsSpecialNew = 0;
4061 III.IsCommutative = false;
4062 III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
4063 break;
4064 case PPC::CMPLW:
4065 case PPC::CMPLD:
4066 III.SignedImm = false;
4067 III.ZeroIsSpecialOrig = 0;
4068 III.ZeroIsSpecialNew = 0;
4069 III.IsCommutative = false;
4070 III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
4071 break;
4072 case PPC::AND_rec:
4073 case PPC::AND8_rec:
4074 case PPC::OR:
4075 case PPC::OR8:
4076 case PPC::XOR:
4077 case PPC::XOR8:
4078 III.SignedImm = false;
4079 III.ZeroIsSpecialOrig = 0;
4080 III.ZeroIsSpecialNew = 0;
4081 III.IsCommutative = true;
4082 switch(Opc) {
4083 default: llvm_unreachable("Unknown opcode");
4084 case PPC::AND_rec:
4085 III.ImmOpcode = PPC::ANDI_rec;
4086 break;
4087 case PPC::AND8_rec:
4088 III.ImmOpcode = PPC::ANDI8_rec;
4089 break;
4090 case PPC::OR: III.ImmOpcode = PPC::ORI; break;
4091 case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
4092 case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
4093 case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
4094 }
4095 break;
4096 case PPC::RLWNM:
4097 case PPC::RLWNM8:
4098 case PPC::RLWNM_rec:
4099 case PPC::RLWNM8_rec:
4100 case PPC::SLW:
4101 case PPC::SLW8:
4102 case PPC::SLW_rec:
4103 case PPC::SLW8_rec:
4104 case PPC::SRW:
4105 case PPC::SRW8:
4106 case PPC::SRW_rec:
4107 case PPC::SRW8_rec:
4108 case PPC::SRAW:
4109 case PPC::SRAW_rec:
4110 III.SignedImm = false;
4111 III.ZeroIsSpecialOrig = 0;
4112 III.ZeroIsSpecialNew = 0;
4113 III.IsCommutative = false;
4114 // This isn't actually true, but the instructions ignore any of the
4115 // upper bits, so any immediate loaded with an LI is acceptable.
4116 // This does not apply to shift right algebraic because a value
4117 // out of range will produce a -1/0.
4118 III.ImmWidth = 16;
4119 if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
4120 Opc == PPC::RLWNM8_rec)
4121 III.TruncateImmTo = 5;
4122 else
4123 III.TruncateImmTo = 6;
4124 switch(Opc) {
4125 default: llvm_unreachable("Unknown opcode");
4126 case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
4127 case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
4128 case PPC::RLWNM_rec:
4129 III.ImmOpcode = PPC::RLWINM_rec;
4130 break;
4131 case PPC::RLWNM8_rec:
4132 III.ImmOpcode = PPC::RLWINM8_rec;
4133 break;
4134 case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
4135 case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
4136 case PPC::SLW_rec:
4137 III.ImmOpcode = PPC::RLWINM_rec;
4138 break;
4139 case PPC::SLW8_rec:
4140 III.ImmOpcode = PPC::RLWINM8_rec;
4141 break;
4142 case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
4143 case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
4144 case PPC::SRW_rec:
4145 III.ImmOpcode = PPC::RLWINM_rec;
4146 break;
4147 case PPC::SRW8_rec:
4148 III.ImmOpcode = PPC::RLWINM8_rec;
4149 break;
4150 case PPC::SRAW:
4151 III.ImmWidth = 5;
4152 III.TruncateImmTo = 0;
4153 III.ImmOpcode = PPC::SRAWI;
4154 break;
4155 case PPC::SRAW_rec:
4156 III.ImmWidth = 5;
4157 III.TruncateImmTo = 0;
4158 III.ImmOpcode = PPC::SRAWI_rec;
4159 break;
4160 }
4161 break;
4162 case PPC::RLDCL:
4163 case PPC::RLDCL_rec:
4164 case PPC::RLDCR:
4165 case PPC::RLDCR_rec:
4166 case PPC::SLD:
4167 case PPC::SLD_rec:
4168 case PPC::SRD:
4169 case PPC::SRD_rec:
4170 case PPC::SRAD:
4171 case PPC::SRAD_rec:
4172 III.SignedImm = false;
4173 III.ZeroIsSpecialOrig = 0;
4174 III.ZeroIsSpecialNew = 0;
4175 III.IsCommutative = false;
4176 // This isn't actually true, but the instructions ignore any of the
4177 // upper bits, so any immediate loaded with an LI is acceptable.
4178 // This does not apply to shift right algebraic because a value
4179 // out of range will produce a -1/0.
4180 III.ImmWidth = 16;
4181 if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
4182 Opc == PPC::RLDCR_rec)
4183 III.TruncateImmTo = 6;
4184 else
4185 III.TruncateImmTo = 7;
4186 switch(Opc) {
4187 default: llvm_unreachable("Unknown opcode");
4188 case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
4189 case PPC::RLDCL_rec:
4190 III.ImmOpcode = PPC::RLDICL_rec;
4191 break;
4192 case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
4193 case PPC::RLDCR_rec:
4194 III.ImmOpcode = PPC::RLDICR_rec;
4195 break;
4196 case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
4197 case PPC::SLD_rec:
4198 III.ImmOpcode = PPC::RLDICR_rec;
4199 break;
4200 case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
4201 case PPC::SRD_rec:
4202 III.ImmOpcode = PPC::RLDICL_rec;
4203 break;
4204 case PPC::SRAD:
4205 III.ImmWidth = 6;
4206 III.TruncateImmTo = 0;
4207 III.ImmOpcode = PPC::SRADI;
4208 break;
4209 case PPC::SRAD_rec:
4210 III.ImmWidth = 6;
4211 III.TruncateImmTo = 0;
4212 III.ImmOpcode = PPC::SRADI_rec;
4213 break;
4214 }
4215 break;
4216 // Loads and stores:
4217 case PPC::LBZX:
4218 case PPC::LBZX8:
4219 case PPC::LHZX:
4220 case PPC::LHZX8:
4221 case PPC::LHAX:
4222 case PPC::LHAX8:
4223 case PPC::LWZX:
4224 case PPC::LWZX8:
4225 case PPC::LWAX:
4226 case PPC::LDX:
4227 case PPC::LFSX:
4228 case PPC::LFDX:
4229 case PPC::STBX:
4230 case PPC::STBX8:
4231 case PPC::STHX:
4232 case PPC::STHX8:
4233 case PPC::STWX:
4234 case PPC::STWX8:
4235 case PPC::STDX:
4236 case PPC::STFSX:
4237 case PPC::STFDX:
4238 III.SignedImm = true;
4239 III.ZeroIsSpecialOrig = 1;
4240 III.ZeroIsSpecialNew = 2;
4241 III.IsCommutative = true;
4242 III.IsSummingOperands = true;
4243 III.ImmOpNo = 1;
4244 III.OpNoForForwarding = 2;
4245 switch(Opc) {
4246 default: llvm_unreachable("Unknown opcode");
4247 case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
4248 case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
4249 case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
4250 case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
4251 case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
4252 case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
4253 case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
4254 case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
4255 case PPC::LWAX:
4256 III.ImmOpcode = PPC::LWA;
4257 III.ImmMustBeMultipleOf = 4;
4258 break;
4259 case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
4260 case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
4261 case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
4262 case PPC::STBX: III.ImmOpcode = PPC::STB; break;
4263 case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
4264 case PPC::STHX: III.ImmOpcode = PPC::STH; break;
4265 case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
4266 case PPC::STWX: III.ImmOpcode = PPC::STW; break;
4267 case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
4268 case PPC::STDX:
4269 III.ImmOpcode = PPC::STD;
4270 III.ImmMustBeMultipleOf = 4;
4271 break;
4272 case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
4273 case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
4274 }
4275 break;
4276 case PPC::LBZUX:
4277 case PPC::LBZUX8:
4278 case PPC::LHZUX:
4279 case PPC::LHZUX8:
4280 case PPC::LHAUX:
4281 case PPC::LHAUX8:
4282 case PPC::LWZUX:
4283 case PPC::LWZUX8:
4284 case PPC::LDUX:
4285 case PPC::LFSUX:
4286 case PPC::LFDUX:
4287 case PPC::STBUX:
4288 case PPC::STBUX8:
4289 case PPC::STHUX:
4290 case PPC::STHUX8:
4291 case PPC::STWUX:
4292 case PPC::STWUX8:
4293 case PPC::STDUX:
4294 case PPC::STFSUX:
4295 case PPC::STFDUX:
4296 III.SignedImm = true;
4297 III.ZeroIsSpecialOrig = 2;
4298 III.ZeroIsSpecialNew = 3;
4299 III.IsCommutative = false;
4300 III.IsSummingOperands = true;
4301 III.ImmOpNo = 2;
4302 III.OpNoForForwarding = 3;
4303 switch(Opc) {
4304 default: llvm_unreachable("Unknown opcode");
4305 case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
4306 case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
4307 case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
4308 case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
4309 case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
4310 case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
4311 case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
4312 case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
4313 case PPC::LDUX:
4314 III.ImmOpcode = PPC::LDU;
4315 III.ImmMustBeMultipleOf = 4;
4316 break;
4317 case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
4318 case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
4319 case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
4320 case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
4321 case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
4322 case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
4323 case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
4324 case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
4325 case PPC::STDUX:
4326 III.ImmOpcode = PPC::STDU;
4327 III.ImmMustBeMultipleOf = 4;
4328 break;
4329 case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
4330 case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
4331 }
4332 break;
4333 // Power9 and up only. For some of these, the X-Form version has access to all
4334 // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
4335 // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
4336 // into or stored from is one of the VR registers.
4337 case PPC::LXVX:
4338 case PPC::LXSSPX:
4339 case PPC::LXSDX:
4340 case PPC::STXVX:
4341 case PPC::STXSSPX:
4342 case PPC::STXSDX:
4343 case PPC::XFLOADf32:
4344 case PPC::XFLOADf64:
4345 case PPC::XFSTOREf32:
4346 case PPC::XFSTOREf64:
4347 if (!Subtarget.hasP9Vector())
4348 return false;
4349 III.SignedImm = true;
4350 III.ZeroIsSpecialOrig = 1;
4351 III.ZeroIsSpecialNew = 2;
4352 III.IsCommutative = true;
4353 III.IsSummingOperands = true;
4354 III.ImmOpNo = 1;
4355 III.OpNoForForwarding = 2;
4356 III.ImmMustBeMultipleOf = 4;
4357 switch(Opc) {
4358 default: llvm_unreachable("Unknown opcode");
4359 case PPC::LXVX:
4360 III.ImmOpcode = PPC::LXV;
4361 III.ImmMustBeMultipleOf = 16;
4362 break;
4363 case PPC::LXSSPX:
4364 if (PostRA) {
4365 if (IsVFReg)
4366 III.ImmOpcode = PPC::LXSSP;
4367 else {
4368 III.ImmOpcode = PPC::LFS;
4369 III.ImmMustBeMultipleOf = 1;
4370 }
4371 break;
4372 }
4373 [[fallthrough]];
4374 case PPC::XFLOADf32:
4375 III.ImmOpcode = PPC::DFLOADf32;
4376 break;
4377 case PPC::LXSDX:
4378 if (PostRA) {
4379 if (IsVFReg)
4380 III.ImmOpcode = PPC::LXSD;
4381 else {
4382 III.ImmOpcode = PPC::LFD;
4383 III.ImmMustBeMultipleOf = 1;
4384 }
4385 break;
4386 }
4387 [[fallthrough]];
4388 case PPC::XFLOADf64:
4389 III.ImmOpcode = PPC::DFLOADf64;
4390 break;
4391 case PPC::STXVX:
4392 III.ImmOpcode = PPC::STXV;
4393 III.ImmMustBeMultipleOf = 16;
4394 break;
4395 case PPC::STXSSPX:
4396 if (PostRA) {
4397 if (IsVFReg)
4398 III.ImmOpcode = PPC::STXSSP;
4399 else {
4400 III.ImmOpcode = PPC::STFS;
4401 III.ImmMustBeMultipleOf = 1;
4402 }
4403 break;
4404 }
4405 [[fallthrough]];
4406 case PPC::XFSTOREf32:
4407 III.ImmOpcode = PPC::DFSTOREf32;
4408 break;
4409 case PPC::STXSDX:
4410 if (PostRA) {
4411 if (IsVFReg)
4412 III.ImmOpcode = PPC::STXSD;
4413 else {
4414 III.ImmOpcode = PPC::STFD;
4415 III.ImmMustBeMultipleOf = 1;
4416 }
4417 break;
4418 }
4419 [[fallthrough]];
4420 case PPC::XFSTOREf64:
4421 III.ImmOpcode = PPC::DFSTOREf64;
4422 break;
4423 }
4424 break;
4425 }
4426 return true;
4427}
4428
4429// Utility function for swaping two arbitrary operands of an instruction.
4430static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
4431 assert(Op1 != Op2 && "Cannot swap operand with itself.");
4432
4433 unsigned MaxOp = std::max(Op1, Op2);
4434 unsigned MinOp = std::min(Op1, Op2);
4435 MachineOperand MOp1 = MI.getOperand(MinOp);
4436 MachineOperand MOp2 = MI.getOperand(MaxOp);
4437 MI.removeOperand(std::max(Op1, Op2));
4438 MI.removeOperand(std::min(Op1, Op2));
4439
4440 // If the operands we are swapping are the two at the end (the common case)
4441 // we can just remove both and add them in the opposite order.
4442 if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
4443 MI.addOperand(MOp2);
4444 MI.addOperand(MOp1);
4445 } else {
4446 // Store all operands in a temporary vector, remove them and re-add in the
4447 // right order.
4449 unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
4450 for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
4451 MOps.push_back(MI.getOperand(i));
4452 MI.removeOperand(i);
4453 }
4454 // MOp2 needs to be added next.
4455 MI.addOperand(MOp2);
4456 // Now add the rest.
4457 for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
4458 if (i == MaxOp)
4459 MI.addOperand(MOp1);
4460 else {
4461 MI.addOperand(MOps.back());
4462 MOps.pop_back();
4463 }
4464 }
4465 }
4466}
4467
4468// Check if the 'MI' that has the index OpNoForForwarding
4469// meets the requirement described in the ImmInstrInfo.
4470bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
4471 const ImmInstrInfo &III,
4472 unsigned OpNoForForwarding
4473 ) const {
4474 // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
4475 // would not work pre-RA, we can only do the check post RA.
4476 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4477 if (MRI.isSSA())
4478 return false;
4479
4480 // Cannot do the transform if MI isn't summing the operands.
4481 if (!III.IsSummingOperands)
4482 return false;
4483
4484 // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
4485 if (!III.ZeroIsSpecialOrig)
4486 return false;
4487
4488 // We cannot do the transform if the operand we are trying to replace
4489 // isn't the same as the operand the instruction allows.
4490 if (OpNoForForwarding != III.OpNoForForwarding)
4491 return false;
4492
4493 // Check if the instruction we are trying to transform really has
4494 // the special zero register as its operand.
4495 if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
4496 MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
4497 return false;
4498
4499 // This machine instruction is convertible if it is,
4500 // 1. summing the operands.
4501 // 2. one of the operands is special zero register.
4502 // 3. the operand we are trying to replace is allowed by the MI.
4503 return true;
4504}
4505
4506// Check if the DefMI is the add inst and set the ImmMO and RegMO
4507// accordingly.
4508bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
4509 const ImmInstrInfo &III,
4510 MachineOperand *&ImmMO,
4511 MachineOperand *&RegMO) const {
4512 unsigned Opc = DefMI.getOpcode();
4513 if (Opc != PPC::ADDItocL8 && Opc != PPC::ADDI && Opc != PPC::ADDI8)
4514 return false;
4515
4516 // Skip the optimization of transformTo[NewImm|Imm]FormFedByAdd for ADDItocL8
4517 // on AIX which is used for toc-data access. TODO: Follow up to see if it can
4518 // apply for AIX toc-data as well.
4519 if (Opc == PPC::ADDItocL8 && Subtarget.isAIX())
4520 return false;
4521
4522 assert(DefMI.getNumOperands() >= 3 &&
4523 "Add inst must have at least three operands");
4524 RegMO = &DefMI.getOperand(1);
4525 ImmMO = &DefMI.getOperand(2);
4526
4527 // Before RA, ADDI first operand could be a frame index.
4528 if (!RegMO->isReg())
4529 return false;
4530
4531 // This DefMI is elgible for forwarding if it is:
4532 // 1. add inst
4533 // 2. one of the operands is Imm/CPI/Global.
4534 return isAnImmediateOperand(*ImmMO);
4535}
4536
4537bool PPCInstrInfo::isRegElgibleForForwarding(
4538 const MachineOperand &RegMO, const MachineInstr &DefMI,
4539 const MachineInstr &MI, bool KillDefMI,
4540 bool &IsFwdFeederRegKilled, bool &SeenIntermediateUse) const {
4541 // x = addi y, imm
4542 // ...
4543 // z = lfdx 0, x -> z = lfd imm(y)
4544 // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
4545 // of "y" between the DEF of "x" and "z".
4546 // The query is only valid post RA.
4547 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4548 if (MRI.isSSA())
4549 return false;
4550
4551 Register Reg = RegMO.getReg();
4552
4553 // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
4555 MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
4556 It++;
4557 for (; It != E; ++It) {
4558 if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4559 return false;
4560 else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4561 IsFwdFeederRegKilled = true;
4562 if (It->readsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
4563 SeenIntermediateUse = true;
4564 // Made it to DefMI without encountering a clobber.
4565 if ((&*It) == &DefMI)
4566 break;
4567 }
4568 assert((&*It) == &DefMI && "DefMI is missing");
4569
4570 // If DefMI also defines the register to be forwarded, we can only forward it
4571 // if DefMI is being erased.
4572 if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
4573 return KillDefMI;
4574
4575 return true;
4576}
4577
4578bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
4579 const MachineInstr &DefMI,
4580 const ImmInstrInfo &III,
4581 int64_t &Imm,
4582 int64_t BaseImm) const {
4583 assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
4584 if (DefMI.getOpcode() == PPC::ADDItocL8) {
4585 // The operand for ADDItocL8 is CPI, which isn't imm at compiling time,
4586 // However, we know that, it is 16-bit width, and has the alignment of 4.
4587 // Check if the instruction met the requirement.
4588 if (III.ImmMustBeMultipleOf > 4 ||
4589 III.TruncateImmTo || III.ImmWidth != 16)
4590 return false;
4591
4592 // Going from XForm to DForm loads means that the displacement needs to be
4593 // not just an immediate but also a multiple of 4, or 16 depending on the
4594 // load. A DForm load cannot be represented if it is a multiple of say 2.
4595 // XForm loads do not have this restriction.
4596 if (ImmMO.isGlobal()) {
4597 const DataLayout &DL = ImmMO.getGlobal()->getDataLayout();
4599 return false;
4600 }
4601
4602 return true;
4603 }
4604
4605 if (ImmMO.isImm()) {
4606 // It is Imm, we need to check if the Imm fit the range.
4607 // Sign-extend to 64-bits.
4608 // DefMI may be folded with another imm form instruction, the result Imm is
4609 // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
4610 APInt ActualValue(64, ImmMO.getImm() + BaseImm, true);
4611 if (III.SignedImm && !ActualValue.isSignedIntN(III.ImmWidth))
4612 return false;
4613 if (!III.SignedImm && !ActualValue.isIntN(III.ImmWidth))
4614 return false;
4615 Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm);
4616
4617 if (Imm % III.ImmMustBeMultipleOf)
4618 return false;
4619 if (III.TruncateImmTo)
4620 Imm &= ((1 << III.TruncateImmTo) - 1);
4621 }
4622 else
4623 return false;
4624
4625 // This ImmMO is forwarded if it meets the requriement describle
4626 // in ImmInstrInfo
4627 return true;
4628}
4629
4630bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
4631 unsigned OpNoForForwarding,
4632 MachineInstr **KilledDef,
4633 SmallSet<Register, 4> *RegsToUpdate) const {
4634 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4635 !DefMI.getOperand(1).isImm())
4636 return false;
4637
4638 MachineFunction *MF = MI.getParent()->getParent();
4639 MachineRegisterInfo *MRI = &MF->getRegInfo();
4640 bool PostRA = !MRI->isSSA();
4641
4642 int64_t Immediate = DefMI.getOperand(1).getImm();
4643 // Sign-extend to 64-bits.
4644 int64_t SExtImm = SignExtend64<16>(Immediate);
4645
4646 bool ReplaceWithLI = false;
4647 bool Is64BitLI = false;
4648 int64_t NewImm = 0;
4649 bool SetCR = false;
4650 unsigned Opc = MI.getOpcode();
4651 switch (Opc) {
4652 default:
4653 return false;
4654
4655 // FIXME: Any branches conditional on such a comparison can be made
4656 // unconditional. At this time, this happens too infrequently to be worth
4657 // the implementation effort, but if that ever changes, we could convert
4658 // such a pattern here.
4659 case PPC::CMPWI:
4660 case PPC::CMPLWI:
4661 case PPC::CMPDI:
4662 case PPC::CMPLDI: {
4663 // Doing this post-RA would require dataflow analysis to reliably find uses
4664 // of the CR register set by the compare.
4665 // No need to fixup killed/dead flag since this transformation is only valid
4666 // before RA.
4667 if (PostRA)
4668 return false;
4669 // If a compare-immediate is fed by an immediate and is itself an input of
4670 // an ISEL (the most common case) into a COPY of the correct register.
4671 bool Changed = false;
4672 Register DefReg = MI.getOperand(0).getReg();
4673 int64_t Comparand = MI.getOperand(2).getImm();
4674 int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
4675 ? (Comparand | 0xFFFFFFFFFFFF0000)
4676 : Comparand;
4677
4678 for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
4679 unsigned UseOpc = CompareUseMI.getOpcode();
4680 if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
4681 continue;
4682 unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
4683 Register TrueReg = CompareUseMI.getOperand(1).getReg();
4684 Register FalseReg = CompareUseMI.getOperand(2).getReg();
4685 unsigned RegToCopy =
4686 selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg);
4687 if (RegToCopy == PPC::NoRegister)
4688 continue;
4689 // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
4690 if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
4691 CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
4692 replaceInstrOperandWithImm(CompareUseMI, 1, 0);
4693 CompareUseMI.removeOperand(3);
4694 CompareUseMI.removeOperand(2);
4695 continue;
4696 }
4697 LLVM_DEBUG(
4698 dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
4699 LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
4700 LLVM_DEBUG(dbgs() << "Is converted to:\n");
4701 if (RegsToUpdate) {
4702 for (const MachineOperand &MO : CompareUseMI.operands())
4703 if (MO.isReg())
4704 RegsToUpdate->insert(MO.getReg());
4705 }
4706 // Convert to copy and remove unneeded operands.
4707 CompareUseMI.setDesc(get(PPC::COPY));
4708 CompareUseMI.removeOperand(3);
4709 CompareUseMI.removeOperand(RegToCopy == TrueReg ? 2 : 1);
4710 CmpIselsConverted++;
4711 Changed = true;
4712 LLVM_DEBUG(CompareUseMI.dump());
4713 }
4714 if (Changed)
4715 return true;
4716 // This may end up incremented multiple times since this function is called
4717 // during a fixed-point transformation, but it is only meant to indicate the
4718 // presence of this opportunity.
4719 MissedConvertibleImmediateInstrs++;
4720 return false;
4721 }
4722
4723 // Immediate forms - may simply be convertable to an LI.
4724 case PPC::ADDI:
4725 case PPC::ADDI8: {
4726 // Does the sum fit in a 16-bit signed field?
4727 int64_t Addend = MI.getOperand(2).getImm();
4728 if (isInt<16>(Addend + SExtImm)) {
4729 ReplaceWithLI = true;
4730 Is64BitLI = Opc == PPC::ADDI8;
4731 NewImm = Addend + SExtImm;
4732 break;
4733 }
4734 return false;
4735 }
4736 case PPC::SUBFIC:
4737 case PPC::SUBFIC8: {
4738 // Only transform this if the CARRY implicit operand is dead.
4739 if (MI.getNumOperands() > 3 && !MI.getOperand(3).isDead())
4740 return false;
4741 int64_t Minuend = MI.getOperand(2).getImm();
4742 if (isInt<16>(Minuend - SExtImm)) {
4743 ReplaceWithLI = true;
4744 Is64BitLI = Opc == PPC::SUBFIC8;
4745 NewImm = Minuend - SExtImm;
4746 break;
4747 }
4748 return false;
4749 }
4750 case PPC::RLDICL:
4751 case PPC::RLDICL_rec:
4752 case PPC::RLDICL_32:
4753 case PPC::RLDICL_32_64: {
4754 // Use APInt's rotate function.
4755 int64_t SH = MI.getOperand(2).getImm();
4756 int64_t MB = MI.getOperand(3).getImm();
4757 APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
4758 SExtImm, true);
4759 InVal = InVal.rotl(SH);
4760 uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
4761 InVal &= Mask;
4762 // Can't replace negative values with an LI as that will sign-extend
4763 // and not clear the left bits. If we're setting the CR bit, we will use
4764 // ANDI_rec which won't sign extend, so that's safe.
4765 if (isUInt<15>(InVal.getSExtValue()) ||
4766 (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
4767 ReplaceWithLI = true;
4768 Is64BitLI = Opc != PPC::RLDICL_32;
4769 NewImm = InVal.getSExtValue();
4770 SetCR = Opc == PPC::RLDICL_rec;
4771 break;
4772 }
4773 return false;
4774 }
4775 case PPC::RLWINM:
4776 case PPC::RLWINM8:
4777 case PPC::RLWINM_rec:
4778 case PPC::RLWINM8_rec: {
4779 int64_t SH = MI.getOperand(2).getImm();
4780 int64_t MB = MI.getOperand(3).getImm();
4781 int64_t ME = MI.getOperand(4).getImm();
4782 APInt InVal(32, SExtImm, true);
4783 InVal = InVal.rotl(SH);
4784 APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB);
4785 InVal &= Mask;
4786 // Can't replace negative values with an LI as that will sign-extend
4787 // and not clear the left bits. If we're setting the CR bit, we will use
4788 // ANDI_rec which won't sign extend, so that's safe.
4789 bool ValueFits = isUInt<15>(InVal.getSExtValue());
4790 ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
4791 isUInt<16>(InVal.getSExtValue()));
4792 if (ValueFits) {
4793 ReplaceWithLI = true;
4794 Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
4795 NewImm = InVal.getSExtValue();
4796 SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
4797 break;
4798 }
4799 return false;
4800 }
4801 case PPC::ORI:
4802 case PPC::ORI8:
4803 case PPC::XORI:
4804 case PPC::XORI8: {
4805 int64_t LogicalImm = MI.getOperand(2).getImm();
4806 int64_t Result = 0;
4807 if (Opc == PPC::ORI || Opc == PPC::ORI8)
4808 Result = LogicalImm | SExtImm;
4809 else
4810 Result = LogicalImm ^ SExtImm;
4811 if (isInt<16>(Result)) {
4812 ReplaceWithLI = true;
4813 Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
4814 NewImm = Result;
4815 break;
4816 }
4817 return false;
4818 }
4819 }
4820
4821 if (ReplaceWithLI) {
4822 // We need to be careful with CR-setting instructions we're replacing.
4823 if (SetCR) {
4824 // We don't know anything about uses when we're out of SSA, so only
4825 // replace if the new immediate will be reproduced.
4826 bool ImmChanged = (SExtImm & NewImm) != NewImm;
4827 if (PostRA && ImmChanged)
4828 return false;
4829
4830 if (!PostRA) {
4831 // If the defining load-immediate has no other uses, we can just replace
4832 // the immediate with the new immediate.
4833 if (MRI->hasOneUse(DefMI.getOperand(0).getReg()))
4834 DefMI.getOperand(1).setImm(NewImm);
4835
4836 // If we're not using the GPR result of the CR-setting instruction, we
4837 // just need to and with zero/non-zero depending on the new immediate.
4838 else if (MRI->use_empty(MI.getOperand(0).getReg())) {
4839 if (NewImm) {
4840 assert(Immediate && "Transformation converted zero to non-zero?");
4841 NewImm = Immediate;
4842 }
4843 } else if (ImmChanged)
4844 return false;
4845 }
4846 }
4847
4848 LLVM_DEBUG(dbgs() << "Replacing constant instruction:\n");
4849 LLVM_DEBUG(MI.dump());
4850 LLVM_DEBUG(dbgs() << "Fed by:\n");
4851 LLVM_DEBUG(DefMI.dump());
4852 LoadImmediateInfo LII;
4853 LII.Imm = NewImm;
4854 LII.Is64Bit = Is64BitLI;
4855 LII.SetCR = SetCR;
4856 // If we're setting the CR, the original load-immediate must be kept (as an
4857 // operand to ANDI_rec/ANDI8_rec).
4858 if (KilledDef && SetCR)
4859 *KilledDef = nullptr;
4860 replaceInstrWithLI(MI, LII);
4861
4862 if (PostRA)
4863 recomputeLivenessFlags(*MI.getParent());
4864
4865 LLVM_DEBUG(dbgs() << "With:\n");
4866 LLVM_DEBUG(MI.dump());
4867 return true;
4868 }
4869 return false;
4870}
4871
4872bool PPCInstrInfo::transformToNewImmFormFedByAdd(
4873 MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
4874 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
4875 bool PostRA = !MRI->isSSA();
4876 // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
4877 // for post-ra.
4878 if (PostRA)
4879 return false;
4880
4881 // Only handle load/store.
4882 if (!MI.mayLoadOrStore())
4883 return false;
4884
4885 unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode());
4886
4887 assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
4888 "MI must have x-form opcode");
4889
4890 // get Imm Form info.
4891 ImmInstrInfo III;
4892 bool IsVFReg = MI.getOperand(0).isReg() &&
4893 MI.getOperand(0).getReg().isPhysical() &&
4894 PPC::isVFRegister(MI.getOperand(0).getReg());
4895
4896 if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA))
4897 return false;
4898
4899 if (!III.IsSummingOperands)
4900 return false;
4901
4902 if (OpNoForForwarding != III.OpNoForForwarding)
4903 return false;
4904
4905 MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo);
4906 if (!ImmOperandMI.isImm())
4907 return false;
4908
4909 // Check DefMI.
4910 MachineOperand *ImmMO = nullptr;
4911 MachineOperand *RegMO = nullptr;
4912 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4913 return false;
4914 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4915
4916 // Check Imm.
4917 // Set ImmBase from imm instruction as base and get new Imm inside
4918 // isImmElgibleForForwarding.
4919 int64_t ImmBase = ImmOperandMI.getImm();
4920 int64_t Imm = 0;
4921 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase))
4922 return false;
4923
4924 // Do the transform
4925 LLVM_DEBUG(dbgs() << "Replacing existing reg+imm instruction:\n");
4926 LLVM_DEBUG(MI.dump());
4927 LLVM_DEBUG(dbgs() << "Fed by:\n");
4928 LLVM_DEBUG(DefMI.dump());
4929
4930 MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg());
4931 MI.getOperand(III.ImmOpNo).setImm(Imm);
4932
4933 LLVM_DEBUG(dbgs() << "With:\n");
4934 LLVM_DEBUG(MI.dump());
4935 return true;
4936}
4937
4938// If an X-Form instruction is fed by an add-immediate and one of its operands
4939// is the literal zero, attempt to forward the source of the add-immediate to
4940// the corresponding D-Form instruction with the displacement coming from
4941// the immediate being added.
4942bool PPCInstrInfo::transformToImmFormFedByAdd(
4943 MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
4944 MachineInstr &DefMI, bool KillDefMI) const {
4945 // RegMO ImmMO
4946 // | |
4947 // x = addi reg, imm <----- DefMI
4948 // y = op 0 , x <----- MI
4949 // |
4950 // OpNoForForwarding
4951 // Check if the MI meet the requirement described in the III.
4952 if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
4953 return false;
4954
4955 // Check if the DefMI meet the requirement
4956 // described in the III. If yes, set the ImmMO and RegMO accordingly.
4957 MachineOperand *ImmMO = nullptr;
4958 MachineOperand *RegMO = nullptr;
4959 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4960 return false;
4961 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4962
4963 // As we get the Imm operand now, we need to check if the ImmMO meet
4964 // the requirement described in the III. If yes set the Imm.
4965 int64_t Imm = 0;
4966 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
4967 return false;
4968
4969 bool IsFwdFeederRegKilled = false;
4970 bool SeenIntermediateUse = false;
4971 // Check if the RegMO can be forwarded to MI.
4972 if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
4973 IsFwdFeederRegKilled, SeenIntermediateUse))
4974 return false;
4975
4976 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4977 bool PostRA = !MRI.isSSA();
4978
4979 // We know that, the MI and DefMI both meet the pattern, and
4980 // the Imm also meet the requirement with the new Imm-form.
4981 // It is safe to do the transformation now.
4982 LLVM_DEBUG(dbgs() << "Replacing indexed instruction:\n");
4983 LLVM_DEBUG(MI.dump());
4984 LLVM_DEBUG(dbgs() << "Fed by:\n");
4985 LLVM_DEBUG(DefMI.dump());
4986
4987 // Update the base reg first.
4988 MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
4989 false, false,
4990 RegMO->isKill());
4991
4992 // Then, update the imm.
4993 if (ImmMO->isImm()) {
4994 // If the ImmMO is Imm, change the operand that has ZERO to that Imm
4995 // directly.
4997 }
4998 else {
4999 // Otherwise, it is Constant Pool Index(CPI) or Global,
5000 // which is relocation in fact. We need to replace the special zero
5001 // register with ImmMO.
5002 // Before that, we need to fixup the target flags for imm.
5003 // For some reason, we miss to set the flag for the ImmMO if it is CPI.
5004 if (DefMI.getOpcode() == PPC::ADDItocL8)
5006
5007 // MI didn't have the interface such as MI.setOperand(i) though
5008 // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
5009 // ImmMO, we need to remove ZERO operand and all the operands behind it,
5010 // and, add the ImmMO, then, move back all the operands behind ZERO.
5012 for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
5013 MOps.push_back(MI.getOperand(i));
5014 MI.removeOperand(i);
5015 }
5016
5017 // Remove the last MO in the list, which is ZERO operand in fact.
5018 MOps.pop_back();
5019 // Add the imm operand.
5020 MI.addOperand(*ImmMO);
5021 // Now add the rest back.
5022 for (auto &MO : MOps)
5023 MI.addOperand(MO);
5024 }
5025
5026 // Update the opcode.
5027 MI.setDesc(get(III.ImmOpcode));
5028
5029 if (PostRA)
5030 recomputeLivenessFlags(*MI.getParent());
5031 LLVM_DEBUG(dbgs() << "With:\n");
5032 LLVM_DEBUG(MI.dump());
5033
5034 return true;
5035}
5036
5037bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
5038 const ImmInstrInfo &III,
5039 unsigned ConstantOpNo,
5040 MachineInstr &DefMI) const {
5041 // DefMI must be LI or LI8.
5042 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
5043 !DefMI.getOperand(1).isImm())
5044 return false;
5045
5046 // Get Imm operand and Sign-extend to 64-bits.
5047 int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm());
5048
5049 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5050 bool PostRA = !MRI.isSSA();
5051 // Exit early if we can't convert this.
5052 if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
5053 return false;
5054 if (Imm % III.ImmMustBeMultipleOf)
5055 return false;
5056 if (III.TruncateImmTo)
5057 Imm &= ((1 << III.TruncateImmTo) - 1);
5058 if (III.SignedImm) {
5059 APInt ActualValue(64, Imm, true);
5060 if (!ActualValue.isSignedIntN(III.ImmWidth))
5061 return false;
5062 } else {
5063 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
5064 if ((uint64_t)Imm > UnsignedMax)
5065 return false;
5066 }
5067
5068 // If we're post-RA, the instructions don't agree on whether register zero is
5069 // special, we can transform this as long as the register operand that will
5070 // end up in the location where zero is special isn't R0.
5071 if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5072 unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
5073 III.ZeroIsSpecialNew + 1;
5074 Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
5075 Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
5076 // If R0 is in the operand where zero is special for the new instruction,
5077 // it is unsafe to transform if the constant operand isn't that operand.
5078 if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
5079 ConstantOpNo != III.ZeroIsSpecialNew)
5080 return false;
5081 if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
5082 ConstantOpNo != PosForOrigZero)
5083 return false;
5084 }
5085
5086 unsigned Opc = MI.getOpcode();
5087 bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
5088 Opc == PPC::SRW || Opc == PPC::SRW_rec ||
5089 Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
5090 Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
5091 bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
5092 Opc == PPC::SRD || Opc == PPC::SRD_rec;
5093 bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
5094 Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
5095 bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
5096 Opc == PPC::SRD_rec;
5097
5098 LLVM_DEBUG(dbgs() << "Replacing reg+reg instruction: ");
5099 LLVM_DEBUG(MI.dump());
5100 LLVM_DEBUG(dbgs() << "Fed by load-immediate: ");
5101 LLVM_DEBUG(DefMI.dump());
5102 MI.setDesc(get(III.ImmOpcode));
5103 if (ConstantOpNo == III.OpNoForForwarding) {
5104 // Converting shifts to immediate form is a bit tricky since they may do
5105 // one of three things:
5106 // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
5107 // 2. If the shift amount is zero, the result is unchanged (save for maybe
5108 // setting CR0)
5109 // 3. If the shift amount is in [1, OpSize), it's just a shift
5110 if (SpecialShift32 || SpecialShift64) {
5111 LoadImmediateInfo LII;
5112 LII.Imm = 0;
5113 LII.SetCR = SetCR;
5114 LII.Is64Bit = SpecialShift64;
5115 uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
5116 if (Imm & (SpecialShift32 ? 0x20 : 0x40))
5117 replaceInstrWithLI(MI, LII);
5118 // Shifts by zero don't change the value. If we don't need to set CR0,
5119 // just convert this to a COPY. Can't do this post-RA since we've already
5120 // cleaned up the copies.
5121 else if (!SetCR && ShAmt == 0 && !PostRA) {
5122 MI.removeOperand(2);
5123 MI.setDesc(get(PPC::COPY));
5124 } else {
5125 // The 32 bit and 64 bit instructions are quite different.
5126 if (SpecialShift32) {
5127 // Left shifts use (N, 0, 31-N).
5128 // Right shifts use (32-N, N, 31) if 0 < N < 32.
5129 // use (0, 0, 31) if N == 0.
5130 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
5131 uint64_t MB = RightShift ? ShAmt : 0;
5132 uint64_t ME = RightShift ? 31 : 31 - ShAmt;
5134 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
5135 .addImm(ME);
5136 } else {
5137 // Left shifts use (N, 63-N).
5138 // Right shifts use (64-N, N) if 0 < N < 64.
5139 // use (0, 0) if N == 0.
5140 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
5141 uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
5143 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
5144 }
5145 }
5146 } else
5147 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
5148 }
5149 // Convert commutative instructions (switch the operands and convert the
5150 // desired one to an immediate.
5151 else if (III.IsCommutative) {
5152 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
5153 swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
5154 } else
5155 llvm_unreachable("Should have exited early!");
5156
5157 // For instructions for which the constant register replaces a different
5158 // operand than where the immediate goes, we need to swap them.
5159 if (III.OpNoForForwarding != III.ImmOpNo)
5161
5162 // If the special R0/X0 register index are different for original instruction
5163 // and new instruction, we need to fix up the register class in new
5164 // instruction.
5165 if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5166 if (III.ZeroIsSpecialNew) {
5167 // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
5168 // need to fix up register class.
5169 Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
5170 if (RegToModify.isVirtual()) {
5171 const TargetRegisterClass *NewRC =
5172 MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
5173 &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
5174 MRI.setRegClass(RegToModify, NewRC);
5175 }
5176 }
5177 }
5178
5179 if (PostRA)
5180 recomputeLivenessFlags(*MI.getParent());
5181
5182 LLVM_DEBUG(dbgs() << "With: ");
5183 LLVM_DEBUG(MI.dump());
5184 LLVM_DEBUG(dbgs() << "\n");
5185 return true;
5186}
5187
5188const TargetRegisterClass *
5190 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
5191 return &PPC::VSRCRegClass;
5192 return RC;
5193}
5194
5196 return PPC::getRecordFormOpcode(Opcode);
5197}
5198
5199static bool isOpZeroOfSubwordPreincLoad(int Opcode) {
5200 return (Opcode == PPC::LBZU || Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 ||
5201 Opcode == PPC::LBZUX8 || Opcode == PPC::LHZU ||
5202 Opcode == PPC::LHZUX || Opcode == PPC::LHZU8 ||
5203 Opcode == PPC::LHZUX8);
5204}
5205
5206// This function checks for sign extension from 32 bits to 64 bits.
5208 const unsigned Reg,
5209 const MachineRegisterInfo *MRI) {
5211 return false;
5212
5213 MachineInstr *MI = MRI->getVRegDef(Reg);
5214 if (!MI)
5215 return false;
5216
5217 int Opcode = MI->getOpcode();
5218 if (TII.isSExt32To64(Opcode))
5219 return true;
5220
5221 // The first def of LBZU/LHZU is sign extended.
5222 if (isOpZeroOfSubwordPreincLoad(Opcode) && MI->getOperand(0).getReg() == Reg)
5223 return true;
5224
5225 // RLDICL generates sign-extended output if it clears at least
5226 // 33 bits from the left (MSB).
5227 if (Opcode == PPC::RLDICL && MI->getOperand(3).getImm() >= 33)
5228 return true;
5229
5230 // If at least one bit from left in a lower word is masked out,
5231 // all of 0 to 32-th bits of the output are cleared.
5232 // Hence the output is already sign extended.
5233 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5234 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
5235 MI->getOperand(3).getImm() > 0 &&
5236 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
5237 return true;
5238
5239 // If the most significant bit of immediate in ANDIS is zero,
5240 // all of 0 to 32-th bits are cleared.
5241 if (Opcode == PPC::ANDIS_rec || Opcode == PPC::ANDIS8_rec) {
5242 uint16_t Imm = MI->getOperand(2).getImm();
5243 if ((Imm & 0x8000) == 0)
5244 return true;
5245 }
5246
5247 return false;
5248}
5249
5250// This function checks the machine instruction that defines the input register
5251// Reg. If that machine instruction always outputs a value that has only zeros
5252// in the higher 32 bits then this function will return true.
5254 const unsigned Reg,
5255 const MachineRegisterInfo *MRI) {
5257 return false;
5258
5259 MachineInstr *MI = MRI->getVRegDef(Reg);
5260 if (!MI)
5261 return false;
5262
5263 int Opcode = MI->getOpcode();
5264 if (TII.isZExt32To64(Opcode))
5265 return true;
5266
5267 // The first def of LBZU/LHZU/LWZU are zero extended.
5268 if ((isOpZeroOfSubwordPreincLoad(Opcode) || Opcode == PPC::LWZU ||
5269 Opcode == PPC::LWZUX || Opcode == PPC::LWZU8 || Opcode == PPC::LWZUX8) &&
5270 MI->getOperand(0).getReg() == Reg)
5271 return true;
5272
5273 // The 16-bit immediate is sign-extended in li/lis.
5274 // If the most significant bit is zero, all higher bits are zero.
5275 if (Opcode == PPC::LI || Opcode == PPC::LI8 ||
5276 Opcode == PPC::LIS || Opcode == PPC::LIS8) {
5277 int64_t Imm = MI->getOperand(1).getImm();
5278 if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
5279 return true;
5280 }
5281
5282 // We have some variations of rotate-and-mask instructions
5283 // that clear higher 32-bits.
5284 if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
5285 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
5286 Opcode == PPC::RLDICL_32_64) &&
5287 MI->getOperand(3).getImm() >= 32)
5288 return true;
5289
5290 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
5291 MI->getOperand(3).getImm() >= 32 &&
5292 MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
5293 return true;
5294
5295 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5296 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
5297 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
5298 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
5299 return true;
5300
5301 return false;
5302}
5303
5304// This function returns true if the input MachineInstr is a TOC save
5305// instruction.
5307 if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
5308 return false;
5309 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5310 unsigned StackOffset = MI.getOperand(1).getImm();
5311 Register StackReg = MI.getOperand(2).getReg();
5312 Register SPReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
5313 if (StackReg == SPReg && StackOffset == TOCSaveOffset)
5314 return true;
5315
5316 return false;
5317}
5318
5319// We limit the max depth to track incoming values of PHIs or binary ops
5320// (e.g. AND) to avoid excessive cost.
5321const unsigned MAX_BINOP_DEPTH = 1;
5322
5323// This function will promote the instruction which defines the register `Reg`
5324// in the parameter from a 32-bit to a 64-bit instruction if needed. The logic
5325// used to check whether an instruction needs to be promoted or not is similar
5326// to the logic used to check whether or not a defined register is sign or zero
5327// extended within the function PPCInstrInfo::isSignOrZeroExtended.
5328// Additionally, the `promoteInstr32To64ForElimEXTSW` function is recursive.
5329// BinOpDepth does not count all of the recursions. The parameter BinOpDepth is
5330// incremented only when `promoteInstr32To64ForElimEXTSW` calls itself more
5331// than once. This is done to prevent exponential recursion.
5334 unsigned BinOpDepth) const {
5335 if (!Reg.isVirtual())
5336 return;
5337
5338 MachineInstr *MI = MRI->getVRegDef(Reg);
5339 if (!MI)
5340 return;
5341
5342 unsigned Opcode = MI->getOpcode();
5343
5344 switch (Opcode) {
5345 case PPC::OR:
5346 case PPC::ISEL:
5347 case PPC::OR8:
5348 case PPC::PHI: {
5349 if (BinOpDepth >= MAX_BINOP_DEPTH)
5350 break;
5351 unsigned OperandEnd = 3, OperandStride = 1;
5352 if (Opcode == PPC::PHI) {
5353 OperandEnd = MI->getNumOperands();
5354 OperandStride = 2;
5355 }
5356
5357 for (unsigned I = 1; I < OperandEnd; I += OperandStride) {
5358 assert(MI->getOperand(I).isReg() && "Operand must be register");
5359 promoteInstr32To64ForElimEXTSW(MI->getOperand(I).getReg(), MRI,
5360 BinOpDepth + 1);
5361 }
5362
5363 break;
5364 }
5365 case PPC::COPY: {
5366 // Refers to the logic of the `case PPC::COPY` statement in the function
5367 // PPCInstrInfo::isSignOrZeroExtended().
5368
5369 Register SrcReg = MI->getOperand(1).getReg();
5370 // In both ELFv1 and v2 ABI, method parameters and the return value
5371 // are sign- or zero-extended.
5372 const MachineFunction *MF = MI->getMF();
5373 if (!MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5374 // If this is a copy from another register, we recursively promote the
5375 // source.
5376 promoteInstr32To64ForElimEXTSW(SrcReg, MRI, BinOpDepth);
5377 return;
5378 }
5379
5380 // From here on everything is SVR4ABI. COPY will be eliminated in the other
5381 // pass, we do not need promote the COPY pseudo opcode.
5382
5383 if (SrcReg != PPC::X3)
5384 // If this is a copy from another register, we recursively promote the
5385 // source.
5386 promoteInstr32To64ForElimEXTSW(SrcReg, MRI, BinOpDepth);
5387 return;
5388 }
5389 case PPC::ORI:
5390 case PPC::XORI:
5391 case PPC::ORIS:
5392 case PPC::XORIS:
5393 case PPC::ORI8:
5394 case PPC::XORI8:
5395 case PPC::ORIS8:
5396 case PPC::XORIS8:
5397 promoteInstr32To64ForElimEXTSW(MI->getOperand(1).getReg(), MRI, BinOpDepth);
5398 break;
5399 case PPC::AND:
5400 case PPC::AND8:
5401 if (BinOpDepth >= MAX_BINOP_DEPTH)
5402 break;
5403
5404 promoteInstr32To64ForElimEXTSW(MI->getOperand(1).getReg(), MRI,
5405 BinOpDepth + 1);
5406 promoteInstr32To64ForElimEXTSW(MI->getOperand(2).getReg(), MRI,
5407 BinOpDepth + 1);
5408 break;
5409 }
5410
5411 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
5412 if (RC == &PPC::G8RCRegClass || RC == &PPC::G8RC_and_G8RC_NOX0RegClass)
5413 return;
5414
5415 // Map the 32bit to 64bit opcodes for instructions that are not signed or zero
5416 // extended themselves, but may have operands who's destination registers of
5417 // signed or zero extended instructions.
5418 DenseMap<unsigned, unsigned> OpcodeMap = {
5419 {PPC::OR, PPC::OR8}, {PPC::ISEL, PPC::ISEL8},
5420 {PPC::ORI, PPC::ORI8}, {PPC::XORI, PPC::XORI8},
5421 {PPC::ORIS, PPC::ORIS8}, {PPC::XORIS, PPC::XORIS8},
5422 {PPC::AND, PPC::AND8}};
5423
5424 int NewOpcode = -1;
5425 auto It = OpcodeMap.find(Opcode);
5426 if (It != OpcodeMap.end()) {
5427 // Set the new opcode to the mapped 64-bit version.
5428 NewOpcode = It->second;
5429 } else {
5430 if (!isSExt32To64(Opcode))
5431 return;
5432
5433 // The TableGen function `get64BitInstrFromSignedExt32BitInstr` is used to
5434 // map the 32-bit instruction with the `SExt32To64` flag to the 64-bit
5435 // instruction with the same opcode.
5436 NewOpcode = PPC::get64BitInstrFromSignedExt32BitInstr(Opcode);
5437 }
5438
5439 assert(NewOpcode != -1 &&
5440 "Must have a 64-bit opcode to map the 32-bit opcode!");
5441
5442 const MCInstrDesc &MCID = get(NewOpcode);
5443 const TargetRegisterClass *NewRC =
5444 RI.getRegClass(MCID.operands()[0].RegClass);
5445
5446 Register SrcReg = MI->getOperand(0).getReg();
5447 const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
5448
5449 // If the register class of the defined register in the 32-bit instruction
5450 // is the same as the register class of the defined register in the promoted
5451 // 64-bit instruction, we do not need to promote the instruction.
5452 if (NewRC == SrcRC)
5453 return;
5454
5455 DebugLoc DL = MI->getDebugLoc();
5456 auto MBB = MI->getParent();
5457
5458 // Since the pseudo-opcode of the instruction is promoted from 32-bit to
5459 // 64-bit, if the source reg class of the original instruction belongs to
5460 // PPC::GRCRegClass or PPC::GPRC_and_GPRC_NOR0RegClass, we need to promote
5461 // the operand to PPC::G8CRegClass or PPC::G8RC_and_G8RC_NOR0RegClass,
5462 // respectively.
5463 for (unsigned i = 1; i < MI->getNumOperands(); i++) {
5464 MachineOperand &Operand = MI->getOperand(i);
5465 if (!Operand.isReg())
5466 continue;
5467
5468 Register OperandReg = Operand.getReg();
5469 if (!OperandReg.isVirtual())
5470 continue;
5471
5472 const TargetRegisterClass *NewUsedRegRC =
5473 RI.getRegClass(MCID.operands()[i].RegClass);
5474 const TargetRegisterClass *OrgRC = MRI->getRegClass(OperandReg);
5475
5476 // An operand that reads the sub_32 subregister of a 64-bit register already
5477 // holds the value in a full 64-bit register, so it can be used directly by
5478 // the promoted instruction.
5479 if (Operand.getSubReg() == PPC::sub_32) {
5480 assert(NewUsedRegRC->hasSubClassEq(OrgRC) &&
5481 "sub_32 source register class is incompatible with the promoted "
5482 "operand register class");
5483 Operand.setSubReg(PPC::NoSubRegister);
5484 continue;
5485 }
5486
5487 if (NewUsedRegRC != OrgRC && (OrgRC == &PPC::GPRCRegClass ||
5488 OrgRC == &PPC::GPRC_and_GPRC_NOR0RegClass)) {
5489 // Promote the used 32-bit register to 64-bit register.
5490 Register TmpReg = MRI->createVirtualRegister(NewUsedRegRC);
5491 Register DstTmpReg = MRI->createVirtualRegister(NewUsedRegRC);
5492 BuildMI(*MBB, MI, DL, get(PPC::IMPLICIT_DEF), TmpReg);
5493 BuildMI(*MBB, MI, DL, get(PPC::INSERT_SUBREG), DstTmpReg)
5494 .addReg(TmpReg)
5495 .addReg(OperandReg)
5496 .addImm(PPC::sub_32);
5497 Operand.setReg(DstTmpReg);
5498 }
5499 }
5500
5501 Register NewDefinedReg = MRI->createVirtualRegister(NewRC);
5502 MI->setDesc(MCID);
5503 MI->getOperand(0).setReg(NewDefinedReg);
5504
5505 // A defined register may be used by other instructions that are 32-bit.
5506 // After the defined register is promoted to 64-bit for the promoted
5507 // instruction, we need to demote the 64-bit defined register back to a
5508 // 32-bit register
5509 BuildMI(*MBB, std::next(MI->getIterator()), DL, get(PPC::COPY), SrcReg)
5510 .addReg(NewDefinedReg, {}, PPC::sub_32);
5511}
5512
5513// The isSignOrZeroExtended function is recursive. The parameter BinOpDepth
5514// does not count all of the recursions. The parameter BinOpDepth is incremented
5515// only when isSignOrZeroExtended calls itself more than once. This is done to
5516// prevent expontential recursion. There is no parameter to track linear
5517// recursion.
5518std::pair<bool, bool>
5520 const unsigned BinOpDepth,
5521 const MachineRegisterInfo *MRI) const {
5523 return std::pair<bool, bool>(false, false);
5524
5525 MachineInstr *MI = MRI->getVRegDef(Reg);
5526 if (!MI)
5527 return std::pair<bool, bool>(false, false);
5528
5529 bool IsSExt = definedBySignExtendingOp(*this, Reg, MRI);
5530 bool IsZExt = definedByZeroExtendingOp(*this, Reg, MRI);
5531
5532 // If we know the instruction always returns sign- and zero-extended result,
5533 // return here.
5534 if (IsSExt && IsZExt)
5535 return std::pair<bool, bool>(IsSExt, IsZExt);
5536
5537 switch (MI->getOpcode()) {
5538 case PPC::COPY: {
5539 Register SrcReg = MI->getOperand(1).getReg();
5540
5541 // In both ELFv1 and v2 ABI, method parameters and the return value
5542 // are sign- or zero-extended.
5543 const MachineFunction *MF = MI->getMF();
5544
5545 if (!MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5546 // If this is a copy from another register, we recursively check source.
5547 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5548 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5549 SrcExt.second || IsZExt);
5550 }
5551
5552 // From here on everything is SVR4ABI
5553 const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
5554 // We check the ZExt/SExt flags for a method parameter.
5555 if (MI->getParent()->getBasicBlock() ==
5556 &MF->getFunction().getEntryBlock()) {
5557 Register VReg = MI->getOperand(0).getReg();
5558 if (MF->getRegInfo().isLiveIn(VReg)) {
5559 IsSExt |= FuncInfo->isLiveInSExt(VReg);
5560 IsZExt |= FuncInfo->isLiveInZExt(VReg);
5561 return std::pair<bool, bool>(IsSExt, IsZExt);
5562 }
5563 }
5564
5565 if (SrcReg != PPC::X3) {
5566 // If this is a copy from another register, we recursively check source.
5567 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5568 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5569 SrcExt.second || IsZExt);
5570 }
5571
5572 // For a method return value, we check the ZExt/SExt flags in attribute.
5573 // We assume the following code sequence for method call.
5574 // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
5575 // BL8_NOP @func,...
5576 // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
5577 // %5 = COPY %x3; G8RC:%5
5578 const MachineBasicBlock *MBB = MI->getParent();
5579 std::pair<bool, bool> IsExtendPair = std::pair<bool, bool>(IsSExt, IsZExt);
5582 if (II == MBB->instr_begin() || (--II)->getOpcode() != PPC::ADJCALLSTACKUP)
5583 return IsExtendPair;
5584
5585 const MachineInstr &CallMI = *(--II);
5586 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
5587 return IsExtendPair;
5588
5589 const Function *CalleeFn =
5591 if (!CalleeFn)
5592 return IsExtendPair;
5593 const IntegerType *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
5594 if (IntTy && IntTy->getBitWidth() <= 32) {
5595 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
5596 IsSExt |= Attrs.hasAttribute(Attribute::SExt);
5597 IsZExt |= Attrs.hasAttribute(Attribute::ZExt);
5598 return std::pair<bool, bool>(IsSExt, IsZExt);
5599 }
5600
5601 return IsExtendPair;
5602 }
5603
5604 // OR, XOR with 16-bit immediate does not change the upper 48 bits.
5605 // So, we track the operand register as we do for register copy.
5606 case PPC::ORI:
5607 case PPC::XORI:
5608 case PPC::ORI8:
5609 case PPC::XORI8: {
5610 Register SrcReg = MI->getOperand(1).getReg();
5611 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5612 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5613 SrcExt.second || IsZExt);
5614 }
5615
5616 // OR, XOR with shifted 16-bit immediate does not change the upper
5617 // 32 bits. So, we track the operand register for zero extension.
5618 // For sign extension when the MSB of the immediate is zero, we also
5619 // track the operand register since the upper 33 bits are unchanged.
5620 case PPC::ORIS:
5621 case PPC::XORIS:
5622 case PPC::ORIS8:
5623 case PPC::XORIS8: {
5624 Register SrcReg = MI->getOperand(1).getReg();
5625 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth, MRI);
5626 uint16_t Imm = MI->getOperand(2).getImm();
5627 if (Imm & 0x8000)
5628 return std::pair<bool, bool>(false, SrcExt.second || IsZExt);
5629 else
5630 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5631 SrcExt.second || IsZExt);
5632 }
5633
5634 // If all incoming values are sign-/zero-extended,
5635 // the output of OR, ISEL or PHI is also sign-/zero-extended.
5636 case PPC::OR:
5637 case PPC::OR8:
5638 case PPC::ISEL:
5639 case PPC::PHI: {
5640 if (BinOpDepth >= MAX_BINOP_DEPTH)
5641 return std::pair<bool, bool>(false, false);
5642
5643 // The input registers for PHI are operand 1, 3, ...
5644 // The input registers for others are operand 1 and 2.
5645 unsigned OperandEnd = 3, OperandStride = 1;
5646 if (MI->getOpcode() == PPC::PHI) {
5647 OperandEnd = MI->getNumOperands();
5648 OperandStride = 2;
5649 }
5650
5651 IsSExt = true;
5652 IsZExt = true;
5653 for (unsigned I = 1; I != OperandEnd; I += OperandStride) {
5654 if (!MI->getOperand(I).isReg())
5655 return std::pair<bool, bool>(false, false);
5656
5657 Register SrcReg = MI->getOperand(I).getReg();
5658 auto SrcExt = isSignOrZeroExtended(SrcReg, BinOpDepth + 1, MRI);
5659 IsSExt &= SrcExt.first;
5660 IsZExt &= SrcExt.second;
5661 }
5662 return std::pair<bool, bool>(IsSExt, IsZExt);
5663 }
5664
5665 // If at least one of the incoming values of an AND is zero extended
5666 // then the output is also zero-extended. If both of the incoming values
5667 // are sign-extended then the output is also sign extended.
5668 case PPC::AND:
5669 case PPC::AND8: {
5670 if (BinOpDepth >= MAX_BINOP_DEPTH)
5671 return std::pair<bool, bool>(false, false);
5672
5673 Register SrcReg1 = MI->getOperand(1).getReg();
5674 Register SrcReg2 = MI->getOperand(2).getReg();
5675 auto Src1Ext = isSignOrZeroExtended(SrcReg1, BinOpDepth + 1, MRI);
5676 auto Src2Ext = isSignOrZeroExtended(SrcReg2, BinOpDepth + 1, MRI);
5677 return std::pair<bool, bool>(Src1Ext.first && Src2Ext.first,
5678 Src1Ext.second || Src2Ext.second);
5679 }
5680
5681 default:
5682 break;
5683 }
5684 return std::pair<bool, bool>(IsSExt, IsZExt);
5685}
5686
5687bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
5688 return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
5689}
5690
5691namespace {
5692class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
5693 MachineInstr *Loop, *EndLoop, *LoopCount;
5694 MachineFunction *MF;
5695 const TargetInstrInfo *TII;
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 TII(MF->getSubtarget().getInstrInfo()) {
5704 // Inspect the Loop instruction up-front, as it may be deleted when we call
5705 // createTripCountGreaterCondition.
5706 if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
5707 TripCount = LoopCount->getOperand(1).getImm();
5708 else
5709 TripCount = -1;
5710 }
5711
5712 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
5713 // Only ignore the terminator.
5714 return MI == EndLoop;
5715 }
5716
5717 std::optional<bool> createTripCountGreaterCondition(
5718 int TC, MachineBasicBlock &MBB,
5719 SmallVectorImpl<MachineOperand> &Cond) override {
5720 if (TripCount == -1) {
5721 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5722 // so we don't need to generate any thing here.
5725 MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
5726 true));
5727 return {};
5728 }
5729
5730 return TripCount > TC;
5731 }
5732
5733 void setPreheader(MachineBasicBlock *NewPreheader) override {
5734 // Do nothing. We want the LOOP setup instruction to stay in the *old*
5735 // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
5736 }
5737
5738 void adjustTripCount(int TripCountAdjust) override {
5739 // If the loop trip count is a compile-time value, then just change the
5740 // value.
5741 if (LoopCount->getOpcode() == PPC::LI8 ||
5742 LoopCount->getOpcode() == PPC::LI) {
5743 int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
5744 LoopCount->getOperand(1).setImm(TripCount);
5745 return;
5746 }
5747
5748 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5749 // so we don't need to generate any thing here.
5750 }
5751
5752 void disposed(LiveIntervals *LIS) override {
5753 if (LIS) {
5755 LIS->RemoveMachineInstrFromMaps(*LoopCount);
5756 }
5757 Loop->eraseFromParent();
5758 // Ensure the loop setup instruction is deleted too.
5759 LoopCount->eraseFromParent();
5760 }
5761};
5762} // namespace
5763
5764std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
5766 // We really "analyze" only hardware loops right now.
5768 MachineBasicBlock *Preheader = *LoopBB->pred_begin();
5769 if (Preheader == LoopBB)
5770 Preheader = *std::next(LoopBB->pred_begin());
5771 MachineFunction *MF = Preheader->getParent();
5772
5773 if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
5775 if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
5776 Register LoopCountReg = LoopInst->getOperand(0).getReg();
5778 MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
5779 return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
5780 }
5781 }
5782 return nullptr;
5783}
5784
5786 MachineBasicBlock &PreHeader,
5787 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
5788
5789 unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
5790
5791 // The loop set-up instruction should be in preheader
5792 for (auto &I : PreHeader.instrs())
5793 if (I.getOpcode() == LOOPi)
5794 return &I;
5795 return nullptr;
5796}
5797
5798// Return true if get the base operand, byte offset of an instruction and the
5799// memory width. Width is the size of memory that is being loaded/stored.
5801 const MachineOperand *&BaseReg,
5802 int64_t &Offset,
5803 LocationSize &Width) const {
5804 if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
5805 return false;
5806
5807 // Handle only loads/stores with base register followed by immediate offset.
5808 if (!LdSt.getOperand(1).isImm() ||
5809 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
5810 return false;
5811
5812 if (!LdSt.hasOneMemOperand())
5813 return false;
5814
5815 Width = (*LdSt.memoperands_begin())->getSize();
5816 Offset = LdSt.getOperand(1).getImm();
5817 BaseReg = &LdSt.getOperand(2);
5818 return true;
5819}
5820
5822 const MachineInstr &MIa, const MachineInstr &MIb) const {
5823 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
5824 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
5825
5828 return false;
5829
5830 // Retrieve the base register, offset from the base register and width. Width
5831 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If
5832 // base registers are identical, and the offset of a lower memory access +
5833 // the width doesn't overlap the offset of a higher memory access,
5834 // then the memory accesses are different.
5835 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
5836 int64_t OffsetA = 0, OffsetB = 0;
5838 WidthB = LocationSize::precise(0);
5839 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA) &&
5840 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB)) {
5841 if (BaseOpA->isIdenticalTo(*BaseOpB)) {
5842 int LowOffset = std::min(OffsetA, OffsetB);
5843 int HighOffset = std::max(OffsetA, OffsetB);
5844 LocationSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
5845 if (LowWidth.hasValue() &&
5846 LowOffset + (int)LowWidth.getValue() <= HighOffset)
5847 return true;
5848 }
5849 }
5850 return false;
5851}
5852
5853// Expands LWAT_CSNE_PSEUDO/LDAT_CSNE_PSEUDO post register allocation.
5854// lwat/ldat FC=16 requires 3 consecutive registers. X8/X9/X10 are
5855// hardcoded post-RA to satisfy this constraint without a dedicated
5856// register class.
5858 MachineBasicBlock &MBB = *MI.getParent();
5859 DebugLoc DL = MI.getDebugLoc();
5860 bool IsLDAT = MI.getOpcode() == PPC::LDAT_CSNE_PSEUDO;
5861
5862 Register DstReg = MI.getOperand(0).getReg();
5863 Register PtrReg = MI.getOperand(1).getReg();
5864
5865 Register ScratchReg = PtrReg;
5866 if (PtrReg == PPC::X8 || PtrReg == PPC::X9 || PtrReg == PPC::X10) {
5867 // If ptr is in X8/X9/X10, use $dst as scratch to move ptr away from
5868 // X8/X9/X10 since lwat FC=16 always writes its result to X8. After lwat
5869 // copy X8 into $dst.
5870 Register DstReg64 = IsLDAT ? DstReg
5871 : Register(RI.getMatchingSuperReg(
5872 DstReg, PPC::sub_32, &PPC::G8RCRegClass));
5873 BuildMI(MBB, MI, DL, get(PPC::OR8), DstReg64).addReg(PtrReg).addReg(PtrReg);
5874 ScratchReg = DstReg64;
5875 }
5876
5877 BuildMI(MBB, MI, DL, get(IsLDAT ? PPC::LDAT_CSNE : PPC::LWAT_CSNE), PPC::X8)
5878 .addReg(ScratchReg)
5879 .addReg(PPC::X9, RegState::Implicit)
5880 .addReg(PPC::X10, RegState::Implicit);
5881
5882 if (DstReg != (IsLDAT ? PPC::X8 : PPC::R8)) {
5883 BuildMI(MBB, MI, DL, get(IsLDAT ? PPC::OR8 : PPC::OR), DstReg)
5884 .addReg(IsLDAT ? PPC::X8 : PPC::R8)
5885 .addReg(IsLDAT ? PPC::X8 : PPC::R8);
5886 }
5887 MI.eraseFromParent();
5888 return true;
5889}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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")
const HexagonInstrInfo * TII
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.
#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
SmallVector< MachineOperand, 4 > Cond
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
void changeSign()
Definition APFloat.h:1429
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:448
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:127
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:188
void setOpcode(unsigned Op)
Definition MCInst.h:201
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. Should be passed by value.
Definition MCRegister.h:41
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
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.
TargetInstrInfo - Interface to description of machine instruction set.
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:2228
bool isOSAIX() const
Tests whether the OS is AIX.
Definition Triple.h:858
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.