66#define DEBUG_TYPE "hwloops"
68STATISTIC(NumHWLoops,
"Number of loops converted to hardware loops");
81 const HexagonOptions *CLOpts =
nullptr;
93 StringRef getPassName()
const override {
return "Hexagon Hardware Loops"; }
95 void getAnalysisUsage(AnalysisUsage &AU)
const override {
98 AU.
addRequired<MachineOptimizationRemarkEmitterPass>();
103 using LoopFeederMap = std::map<Register, MachineInstr *>;
123 static Kind getSwappedComparison(Kind Cmp) {
124 assert ((!((Cmp & L) && (Cmp & G))) &&
"Malformed comparison operator");
125 if ((Cmp & L) || (Cmp & G))
126 return (Kind)(
Cmp ^ (L|G));
130 static Kind getNegatedComparison(Kind Cmp) {
131 if ((Cmp & L) || (Cmp & G))
132 return (Kind)((
Cmp ^ (L | G)) ^ EQ);
133 if ((Cmp & NE) || (Cmp & EQ))
134 return (Kind)(
Cmp ^ (EQ | NE));
139 return (Cmp & (L | G) && !(Cmp & U));
142 static bool isUnsigned(Kind Cmp) {
159 bool findInductionRegister(MachineLoop *L,
Register &
Reg,
160 int64_t &IVBump, MachineInstr *&IVOp)
const;
163 Comparison::Kind getComparisonKind(
unsigned CondOpc,
164 MachineOperand *InitialValue,
165 const MachineOperand *Endvalue,
166 int64_t IVBump)
const;
172 SmallVectorImpl<MachineInstr *> &OldInsts);
181 CountValue *computeCount(MachineLoop *
Loop,
const MachineOperand *Start,
183 int64_t IVBump, Comparison::Kind Cmp)
const;
187 bool isInvalidLoopOperation(
const MachineInstr *
MI,
188 bool IsInnerHWLoop)
const;
192 bool containsInvalidInstruction(MachineLoop *L,
bool IsInnerHWLoop)
const;
196 bool convertToHardwareLoop(MachineLoop *L,
bool &L0used,
bool &L1used);
200 SmallVectorImpl<MachineInstr *> &DeadPhis)
const;
203 void removeIfDead(MachineInstr *
MI);
209 bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
214 bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *
A, MachineInstr *
MI,
215 const MachineOperand *MO,
216 LoopFeederMap &LoopFeederPhi)
const;
220 bool phiMayWrapOrUnderflow(MachineInstr *Phi,
const MachineOperand *EndVal,
221 MachineBasicBlock *
MBB, MachineLoop *L,
222 LoopFeederMap &LoopFeederPhi)
const;
226 bool loopCountMayWrapOrUnderFlow(
const MachineOperand *InitVal,
227 const MachineOperand *EndVal,
228 MachineBasicBlock *
MBB, MachineLoop *L,
229 LoopFeederMap &LoopFeederPhi)
const;
234 bool checkForImmediate(
const MachineOperand &MO, int64_t &Val)
const;
237 bool isImmediate(
const MachineOperand &MO)
const {
239 return checkForImmediate(MO,
V);
243 int64_t getImmediate(
const MachineOperand &MO)
const {
245 if (!checkForImmediate(MO,
V))
253 void setImmediate(MachineOperand &MO, int64_t Val);
259 bool tryExtractPostIncInduction(MachineInstr *DI, MachineInstr *Phi,
261 int64_t &IVBump)
const;
282 bool fixupInductionVariable(MachineLoop *L);
286 MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
289 char HexagonHardwareLoops::ID = 0;
291 int HexagonHardwareLoops::Counter = 0;
299 enum CountValueType {
317 explicit CountValue(CountValueType t,
Register v,
unsigned u = 0) {
319 if (Kind == CV_Register) {
327 bool isReg()
const {
return Kind == CV_Register; }
328 bool isImm()
const {
return Kind == CV_Immediate; }
332 return Contents.R.Reg;
335 unsigned getSubReg()
const {
337 return Contents.R.Sub;
341 assert(isImm() &&
"Wrong CountValue accessor");
342 return Contents.ImmVal;
345 void print(raw_ostream &OS,
const TargetRegisterInfo *
TRI =
nullptr)
const {
347 if (isImm()) { OS << Contents.ImmVal; }
354 "Hexagon Hardware Loops",
false,
false)
361 return new HexagonHardwareLoops();
365 LLVM_DEBUG(
dbgs() <<
"********* Hexagon Hardware Loops *********\n");
371 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
373 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
379 MORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
382 if (L->isOutermost()) {
385 Changed |= convertToHardwareLoop(L, L0Used, L1Used);
391bool HexagonHardwareLoops::tryExtractPostIncInduction(MachineInstr *DI,
395 int64_t &IVBump)
const {
396 if (!
TII->isPostIncWithImmOffset(*DI))
399 unsigned BasePos, OffsetPos;
400 if (!
TII->getBaseAndOffsetPosition(*DI, BasePos, OffsetPos))
409 const MachineOperand &BaseOp = DI->
getOperand(BasePos);
420bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
425 MachineBasicBlock *Header =
L->getHeader();
426 MachineBasicBlock *Preheader =
427 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader);
428 MachineBasicBlock *Latch =
L->getLoopLatch();
429 MachineBasicBlock *ExitingBlock =
L->findLoopControlBlock();
430 if (!Header || !Preheader || !Latch || !ExitingBlock)
435 using RegisterBump = std::pair<Register, int64_t>;
441 using InductionMap = std::map<Register, RegisterBump>;
447 for (instr_iterator
I = Header->instr_begin(),
E = Header->instr_end();
448 I !=
E &&
I->isPHI(); ++
I) {
449 MachineInstr *
Phi = &*
I;
454 for (
unsigned i = 1, n =
Phi->getNumOperands(); i < n; i += 2) {
455 if (
Phi->getOperand(i+1).getMBB() != Latch)
467 if (
MRI->
getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2,
V)) {
469 IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg,
V)));
474 if (tryExtractPostIncInduction(DI, Phi, PhiOpReg, IndReg,
V))
475 IndMap.insert(std::make_pair(PhiOpReg, std::make_pair(IndReg,
V)));
481 MachineBasicBlock *
TB =
nullptr, *FB =
nullptr;
489 if (!
TII->getPredReg(
Cond, PredR, PredPos, PredRegFlags))
497 int64_t CmpImm = 0, CmpMask = 0;
508 InductionMap::iterator IndMapEnd = IndMap.end();
509 InductionMap::iterator
F = IndMapEnd;
511 InductionMap::iterator F1 = IndMap.find(CmpReg1);
516 InductionMap::iterator F2 = IndMap.find(CmpReg2);
517 if (F2 != IndMapEnd) {
526 Reg =
F->second.first;
527 IVBump =
F->second.second;
533HexagonHardwareLoops::Comparison::Kind
534HexagonHardwareLoops::getComparisonKind(
unsigned CondOpc,
535 MachineOperand *InitialValue,
536 const MachineOperand *EndValue,
537 int64_t IVBump)
const {
538 Comparison::Kind
Cmp = (Comparison::Kind)0;
540 case Hexagon::C2_cmpeq:
541 case Hexagon::C2_cmpeqi:
542 case Hexagon::C2_cmpeqp:
543 Cmp = Comparison::EQ;
545 case Hexagon::C4_cmpneq:
546 case Hexagon::C4_cmpneqi:
547 Cmp = Comparison::NE;
549 case Hexagon::C2_cmplt:
550 Cmp = Comparison::LTs;
552 case Hexagon::C2_cmpltu:
553 Cmp = Comparison::LTu;
555 case Hexagon::C4_cmplte:
556 case Hexagon::C4_cmpltei:
557 Cmp = Comparison::LEs;
559 case Hexagon::C4_cmplteu:
560 case Hexagon::C4_cmplteui:
561 Cmp = Comparison::LEu;
563 case Hexagon::C2_cmpgt:
564 case Hexagon::C2_cmpgti:
565 case Hexagon::C2_cmpgtp:
566 Cmp = Comparison::GTs;
568 case Hexagon::C2_cmpgtu:
569 case Hexagon::C2_cmpgtui:
570 case Hexagon::C2_cmpgtup:
571 Cmp = Comparison::GTu;
573 case Hexagon::C2_cmpgei:
574 Cmp = Comparison::GEs;
576 case Hexagon::C2_cmpgeui:
577 Cmp = Comparison::GEs;
580 return (Comparison::Kind)0;
592CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
593 SmallVectorImpl<MachineInstr *> &OldInsts) {
594 MachineBasicBlock *TopMBB =
L->getTopBlock();
597 "Loop must have more than one incoming edge!");
598 MachineBasicBlock *Backedge = *PI++;
601 MachineBasicBlock *Incoming = *PI++;
607 if (
L->contains(Incoming)) {
608 if (
L->contains(Backedge))
611 }
else if (!
L->contains(Backedge))
617 MachineBasicBlock *ExitingBlock =
L->findLoopControlBlock();
624 bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
628 MachineBasicBlock *Preheader =
629 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader);
631 MachineOperand *InitialValue =
nullptr;
633 MachineBasicBlock *Latch =
L->getLoopLatch();
634 for (
unsigned i = 1, n = IV_Phi->
getNumOperands(); i < n; i += 2) {
636 if (
MBB == Preheader)
638 else if (
MBB == Latch)
645 MachineBasicBlock *
TB =
nullptr, *FB =
nullptr;
650 MachineBasicBlock *Header =
L->getHeader();
654 assert (TB &&
"Exit block without a branch?");
655 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
656 MachineBasicBlock *LTB =
nullptr, *LFB =
nullptr;
662 TB = (LTB == Header) ? LTB : LFB;
664 FB = (LTB == Header) ? LTB: LFB;
666 assert ((!FB || TB == Header || FB == Header) &&
"Branches not to header?");
667 if (!TB || (FB && TB != Header && FB != Header))
674 bool Negated =
TII->predOpcodeHasNot(
Cond) ^ (
TB != Header);
678 if (!
TII->getPredReg(
Cond, PredReg, PredPos, PredRegFlags))
684 int64_t
Mask = 0, ImmValue = 0;
700 Comparison::Kind
Cmp;
701 bool isSwapped =
false;
702 const MachineOperand &Op1 = CondI->
getOperand(1);
703 const MachineOperand &Op2 = CondI->
getOperand(2);
704 const MachineOperand *EndValue =
nullptr;
718 Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
722 Cmp = Comparison::getNegatedComparison(Cmp);
724 Cmp = Comparison::getSwappedComparison(Cmp);
726 if (InitialValue->
isReg()) {
731 if (!checkForImmediate(*InitialValue,
V))
736 if (EndValue->
isReg()) {
741 if (!checkForImmediate(*EndValue,
V))
747 return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
754CountValue *HexagonHardwareLoops::computeCount(MachineLoop *
Loop,
755 const MachineOperand *Start,
756 const MachineOperand *
End,
759 Comparison::Kind Cmp)
const {
766 if (Cmp == Comparison::EQ)
771 if (
Start->isReg()) {
773 if (StartValInstr && (StartValInstr->
getOpcode() == Hexagon::A2_tfrsi ||
774 StartValInstr->
getOpcode() == Hexagon::A2_tfrpi))
779 if (EndValInstr && (EndValInstr->
getOpcode() == Hexagon::A2_tfrsi ||
780 EndValInstr->
getOpcode() == Hexagon::A2_tfrpi))
786 if (!
End->isReg() && !
End->isImm())
789 bool CmpLess =
Cmp & Comparison::L;
790 bool CmpGreater =
Cmp & Comparison::G;
791 bool CmpHasEqual =
Cmp & Comparison::EQ;
794 if (CmpLess && IVBump < 0)
798 if (CmpGreater && IVBump > 0)
803 LoopFeederMap LoopFeederPhi;
808 if (loopCountMayWrapOrUnderFlow(Start,
End,
Loop->getLoopPreheader(),
Loop,
812 if (
Start->isImm() &&
End->isImm()) {
814 int64_t StartV =
Start->getImm();
815 int64_t EndV =
End->getImm();
816 int64_t Dist = EndV - StartV;
820 bool Exact = (Dist % IVBump) == 0;
822 if (Cmp == Comparison::NE) {
825 if ((Dist < 0) ^ (IVBump < 0))
832 Dist = Dist > 0 ? Dist+1 : Dist-1;
838 if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
842 int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump - 1)) / IVBump
843 : (-Dist + (-IVBump - 1)) / (-IVBump);
844 assert (Dist1 > 0 &&
"Fishy thing. Both operands have the same sign.");
848 if (
Count > 0xFFFFFFFFULL)
851 return new CountValue(CountValue::CV_Immediate,
Count);
863 MachineBasicBlock *PH =
864 MLI->findLoopPreheader(
Loop, CLOpts->hwloop_spec_preheader);
865 assert (PH &&
"Should have a preheader by now");
868 if (InsertPos != PH->
end())
869 DL = InsertPos->getDebugLoc();
886 bool RegToImm =
Start->isReg() &&
End->isImm();
887 bool RegToReg =
Start->isReg() &&
End->isReg();
889 int64_t StartV = 0, EndV = 0;
891 StartV =
Start->getImm();
893 EndV =
End->getImm();
908 else if (
End->isImm())
914 if (Cmp != Comparison::NE) {
916 StartV -= (IVBump-1);
917 else if (
End->isImm())
925 if (
Start->isReg()) {
927 SR =
Start->getSubReg();
930 SR =
End->getSubReg();
935 if (!SR && RC == &Hexagon::DoubleRegsRegClass)
944 if (
Start->isImm() && StartV == 0) {
945 DistR =
End->getReg();
946 DistSR =
End->getSubReg();
948 const MCInstrDesc &SubD = RegToReg ?
TII->get(Hexagon::A2_sub) :
949 (RegToImm ?
TII->get(Hexagon::A2_subri) :
950 TII->get(Hexagon::A2_addi));
951 if (RegToReg || RegToImm) {
953 MachineInstrBuilder SubIB =
967 if (EndValInstr->
getOpcode() == Hexagon::A2_addi &&
973 MachineInstrBuilder SubIB =
992 MCInstrDesc
const &AddD =
TII->get(Hexagon::A2_addi);
994 .
addReg(DistR, {}, DistSR)
1010 unsigned Shift =
Log2_32(IVBump);
1014 const MCInstrDesc &LsrD =
TII->get(Hexagon::S2_lsr_i_r);
1025 unsigned MuxSR = CountSR;
1029 if (!(
Start->isImm() && StartV == 0 && Comparison::isUnsigned(Cmp) &&
1031 (CmpLess || CmpGreater)) {
1036 unsigned DistCheckOpc = (CmpLess && Comparison::isUnsigned(Cmp))
1037 ? Hexagon::C2_cmpgtui
1038 : Hexagon::C2_cmpgti;
1039 const MCInstrDesc &DistCheckD =
TII->get(DistCheckOpc);
1040 BuildMI(*PH, InsertPos,
DL, DistCheckD, DistCheckR)
1041 .
addReg(DistR, {}, DistSR)
1042 .addImm((CmpLess) ? 0 : -1);
1049 const MCInstrDesc &MuxD =
TII->get(Hexagon::C2_muxir);
1052 .
addReg(CountR, {}, CountSR)
1055 const MCInstrDesc &MuxD =
TII->get(Hexagon::C2_muxri);
1059 .
addReg(CountR, {}, CountSR);
1064 return new CountValue(CountValue::CV_Register, MuxR, MuxSR);
1068bool HexagonHardwareLoops::isInvalidLoopOperation(
const MachineInstr *
MI,
1069 bool IsInnerHWLoop)
const {
1072 if (
MI->getDesc().isCall())
1073 return !
TII->doesNotReturn(*
MI);
1076 using namespace Hexagon;
1078 static const Register Regs01[] = { LC0, SA0, LC1, SA1 };
1079 static const Register Regs1[] = { LC1, SA1 };
1082 if (
MI->modifiesRegister(R,
TRI))
1090bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
1091 bool IsInnerHWLoop)
const {
1094 for (MachineBasicBlock *
MBB :
L->getBlocks()) {
1095 for (
const MachineInstr &
MI : *
MBB) {
1096 if (isInvalidLoopOperation(&
MI, IsInnerHWLoop)) {
1110bool HexagonHardwareLoops::isDead(
const MachineInstr *
MI,
1111 SmallVectorImpl<MachineInstr *> &DeadPhis)
const {
1113 for (
const MachineOperand &MO :
MI->operands()) {
1128 if (std::next(
I) !=
End || !
I->getParent()->isPHI())
1132 for (
const MachineOperand &OPO : OnePhi->
operands()) {
1133 if (!OPO.isReg() || !OPO.isDef())
1137 use_nodbg_iterator nextJ;
1139 J !=
End; J = nextJ) {
1140 nextJ = std::next(J);
1141 MachineOperand &
Use = *J;
1142 MachineInstr *
UseMI =
Use.getParent();
1156void HexagonHardwareLoops::removeIfDead(MachineInstr *
MI) {
1166 for (
const MachineOperand &MO :
MI->operands()) {
1172 for (MachineOperand &MO :
1182 MI->eraseFromParent();
1183 for (
unsigned i = 0; i < DeadPhis.
size(); ++i)
1184 DeadPhis[i]->eraseFromParent();
1196bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
1200 assert(
L->getHeader() &&
"Loop without a header?");
1203 bool L0Used =
false;
1204 bool L1Used =
false;
1207 for (MachineLoop *
I : *L) {
1208 Changed |= convertToHardwareLoop(
I, RecL0used, RecL1used);
1209 L0Used |= RecL0used;
1210 L1Used |= RecL1used;
1214 if (
Changed && L0Used && L1Used)
1224 unsigned IsInnerHWLoop = 1;
1227 LOOP_i = Hexagon::J2_loop1i;
1228 LOOP_r = Hexagon::J2_loop1r;
1229 ENDLOOP = Hexagon::ENDLOOP1;
1232 LOOP_i = Hexagon::J2_loop0i;
1233 LOOP_r = Hexagon::J2_loop0r;
1234 ENDLOOP = Hexagon::ENDLOOP0;
1239 int Limit = CLOpts->max_hwloop;
1241 if (Counter >= CLOpts->max_hwloop)
1248 if (containsInvalidInstruction(L, IsInnerHWLoop)) {
1250 return MachineOptimizationRemarkMissed(
DEBUG_TYPE,
"InvalidInstruction",
1251 L->getStartLoc(),
L->getHeader())
1252 <<
"loop contains an instruction that prevents hardware loop "
1253 "generation (e.g. a call or hardware loop register definition)";
1258 MachineBasicBlock *LastMBB =
L->findLoopControlBlock();
1262 SmallVector<MachineBasicBlock *, 2> ExitingBlocks;
1263 L->getExitingBlocks(ExitingBlocks);
1264 bool HasUnreachableExit =
false;
1265 if (LastMBB && ExitingBlocks.
size() > 1) {
1266 for (MachineBasicBlock *Succ : LastMBB->
successors()) {
1267 if (!
L->contains(Succ) && !Succ->empty() && Succ->succ_empty() &&
1268 !Succ->isReturnBlock()) {
1269 HasUnreachableExit =
true;
1274 if (!LastMBB || HasUnreachableExit) {
1276 return MachineOptimizationRemarkMissed(
DEBUG_TYPE,
"MultipleExits",
1277 L->getStartLoc(),
L->getHeader())
1278 <<
"loop has multiple exits and cannot be converted to a "
1285 if (LastI == LastMBB->
end())
1289 if (!fixupInductionVariable(L)) {
1291 return MachineOptimizationRemarkMissed(
DEBUG_TYPE,
"InductionVariable",
1292 L->getStartLoc(),
L->getHeader())
1293 <<
"could not identify or fix up the induction variable";
1300 MachineBasicBlock *Preheader =
1301 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader);
1303 Preheader = createPreheaderForLoop(L);
1310 SmallVector<MachineInstr*, 2> OldInsts;
1315 return MachineOptimizationRemarkMissed(
DEBUG_TYPE,
"TripCount",
1316 L->getStartLoc(),
L->getHeader())
1317 <<
"trip count of the loop could not be computed";
1323 if (TripCount->isReg()) {
1327 MachineBasicBlock *BBDef = TCDef->
getParent();
1328 if (!MDT->
dominates(BBDef, Preheader)) {
1330 return MachineOptimizationRemarkMissed(
DEBUG_TYPE,
1331 "TripCountNotDominating",
1332 L->getStartLoc(),
L->getHeader())
1333 <<
"trip count register is not available in the loop preheader";
1340 MachineBasicBlock *TopBlock =
L->getTopBlock();
1341 MachineBasicBlock *ExitingBlock =
L->findLoopControlBlock();
1342 MachineBasicBlock *LoopStart =
nullptr;
1343 if (ExitingBlock !=
L->getLoopLatch()) {
1344 MachineBasicBlock *
TB =
nullptr, *FB =
nullptr;
1350 if (
L->contains(TB))
1352 else if (
L->contains(FB))
1358 LoopStart = TopBlock;
1363 if (InsertPos != Preheader->
end())
1364 DL = InsertPos->getDebugLoc();
1366 if (TripCount->isReg()) {
1369 BuildMI(*Preheader, InsertPos,
DL,
TII->get(TargetOpcode::COPY), CountReg)
1370 .
addReg(TripCount->getReg(), {}, TripCount->getSubReg());
1375 assert(TripCount->isImm() &&
"Expecting immediate value for trip count");
1379 int64_t CountImm = TripCount->getImm();
1380 if (!
TII->isValidOffset(LOOP_i, CountImm)) {
1382 BuildMI(*Preheader, InsertPos,
DL,
TII->get(Hexagon::A2_tfrsi), CountReg)
1395 DebugLoc LastIDL = LastI->getDebugLoc();
1401 if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1402 LastI->getOpcode() == Hexagon::J2_jumpf) {
1404 MachineBasicBlock *
BranchTarget = LastI->getOperand(1).getMBB();
1405 LastI = LastMBB->
erase(LastI);
1406 if (!
L->contains(BranchTarget)) {
1407 if (LastI != LastMBB->
end())
1408 LastI = LastMBB->
erase(LastI);
1414 LastMBB->
erase(LastI);
1420 for (
unsigned i = 0; i < OldInsts.
size(); ++i)
1421 removeIfDead(OldInsts[i]);
1426 return MachineOptimizationRemark(
DEBUG_TYPE,
"HardwareLoop",
1427 L->getStartLoc(),
L->getHeader())
1428 <<
"converted loop to hardware loop";
1442bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1443 MachineInstr *CmpI) {
1444 assert (BumpI != CmpI &&
"Bump and compare in the same instruction?");
1446 MachineBasicBlock *BB = BumpI->
getParent();
1459 bool FoundBump =
false;
1460 instr_iterator CmpIt = CmpI->
getIterator(), NextIt = std::next(CmpIt);
1461 for (instr_iterator
I = NextIt,
E = BB->
instr_end();
I !=
E; ++
I) {
1462 MachineInstr *
In = &*
I;
1463 for (
unsigned i = 0, n =
In->getNumOperands(); i < n; ++i) {
1464 MachineOperand &MO =
In->getOperand(i);
1466 if (MO.
getReg() == PredR)
1477 assert (FoundBump &&
"Cannot determine instruction order");
1486bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *
A,
1488 const MachineOperand *MO,
1489 LoopFeederMap &LoopFeederPhi)
const {
1490 if (LoopFeederPhi.find(MO->
getReg()) == LoopFeederPhi.end()) {
1497 LoopFeederPhi.
insert(std::make_pair(MO->
getReg(), Def));
1506bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1507 MachineInstr *Phi,
const MachineOperand *EndVal, MachineBasicBlock *
MBB,
1508 MachineLoop *L, LoopFeederMap &LoopFeederPhi)
const {
1509 assert(
Phi->isPHI() &&
"Expecting a Phi.");
1512 for (
int i = 1, n =
Phi->getNumOperands(); i < n; i += 2)
1513 if (isLoopFeeder(L,
MBB, Phi, &(
Phi->getOperand(i)), LoopFeederPhi))
1514 if (loopCountMayWrapOrUnderFlow(&(
Phi->getOperand(i)), EndVal,
1515 Phi->getParent(), L, LoopFeederPhi))
1534bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1535 const MachineOperand *InitVal,
const MachineOperand *EndVal,
1536 MachineBasicBlock *
MBB, MachineLoop *L,
1537 LoopFeederMap &LoopFeederPhi)
const {
1539 if (!InitVal->
isReg())
1542 if (!EndVal->
isImm())
1548 if (checkForImmediate(*InitVal,
Imm))
1563 if (
Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal,
Def->getParent(),
1566 if (
Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(
Def->getOperand(1)),
1567 EndVal,
Def->getParent(),
1576 MachineInstr *
MI = &*
I;
1578 int64_t CmpMask = 0, CmpValue = 0;
1583 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
1588 Comparison::Kind
Cmp =
1589 getComparisonKind(
MI->getOpcode(),
nullptr,
nullptr, 0);
1593 Cmp = Comparison::getNegatedComparison(Cmp);
1594 if (CmpReg2 != 0 && CmpReg2 ==
Reg)
1595 Cmp = Comparison::getSwappedComparison(Cmp);
1598 if (Comparison::isSigned(Cmp))
1604 if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1611 if (!
Def->isCopy() && !
Def->isPHI())
1617bool HexagonHardwareLoops::checkForImmediate(
const MachineOperand &MO,
1618 int64_t &Val)
const {
1637 case TargetOpcode::COPY:
1638 case Hexagon::A2_tfrsi:
1639 case Hexagon::A2_tfrpi:
1640 case Hexagon::CONST32:
1641 case Hexagon::CONST64:
1645 if (!checkForImmediate(DI->
getOperand(1), TV))
1648 case Hexagon::A2_combineii:
1649 case Hexagon::A4_combineir:
1650 case Hexagon::A4_combineii:
1651 case Hexagon::A4_combineri:
1652 case Hexagon::A2_combinew: {
1654 const MachineOperand &S2 = DI->
getOperand(2);
1656 if (!checkForImmediate(
S1,
V1) || !checkForImmediate(S2, V2))
1661 case TargetOpcode::REG_SEQUENCE: {
1663 const MachineOperand &S3 = DI->
getOperand(3);
1665 if (!checkForImmediate(
S1,
V1) || !checkForImmediate(S3,
V3))
1669 if (Sub2 == Hexagon::isub_lo && Sub4 == Hexagon::isub_hi)
1670 TV =
V1 | (
V3 << 32);
1671 else if (Sub2 == Hexagon::isub_hi && Sub4 == Hexagon::isub_lo)
1672 TV =
V3 | (
V1 << 32);
1685 case Hexagon::isub_lo:
1686 Val = TV & 0xFFFFFFFFULL;
1688 case Hexagon::isub_hi:
1689 Val = (TV >> 32) & 0xFFFFFFFFULL;
1698void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1716bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1717 MachineBasicBlock *Header =
L->getHeader();
1718 MachineBasicBlock *Latch =
L->getLoopLatch();
1719 MachineBasicBlock *ExitingBlock =
L->findLoopControlBlock();
1721 if (!(Header && Latch && ExitingBlock))
1726 using RegisterBump = std::pair<Register, int64_t>;
1727 using RegisterInduction = std::pair<Register, RegisterBump>;
1728 using RegisterInductionSet = std::set<RegisterInduction>;
1731 RegisterInductionSet IndRegs;
1738 for (instr_iterator
I = Header->instr_begin(),
E = Header->instr_end();
1739 I !=
E &&
I->isPHI(); ++
I) {
1740 MachineInstr *
Phi = &*
I;
1743 for (
unsigned i = 1, n =
Phi->getNumOperands(); i < n; i += 2) {
1744 if (
Phi->getOperand(i+1).getMBB() != Latch)
1756 if (
MRI->
getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2,
V)) {
1758 IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg,
V)));
1763 if (tryExtractPostIncInduction(DI, Phi, PhiReg, IndReg,
V))
1764 IndRegs.insert(std::make_pair(PhiReg, std::make_pair(IndReg,
V)));
1769 if (IndRegs.empty())
1772 MachineBasicBlock *
TB =
nullptr, *FB =
nullptr;
1779 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
1780 MachineBasicBlock *LTB =
nullptr, *LFB =
nullptr;
1789 TB = (LTB == Header) ? LTB : LFB;
1791 FB = (LTB == Header) ? LTB : LFB;
1814 if (CSz != 1 && CSz != 2)
1826 SmallSet<Register,2> CmpRegs;
1827 MachineOperand *CmpImmOp =
nullptr;
1833 for (MachineOperand &MO : PredDef->
operands()) {
1840 if (!isImmediate(MO)) {
1849 }
else if (MO.
isImm()) {
1856 if (CmpRegs.
empty())
1860 for (RegisterInductionSet::iterator
I = IndRegs.begin(),
E = IndRegs.end();
1865 if (CmpRegs.
count(
I->first))
1871 const RegisterBump &RB =
I->second;
1872 if (CmpRegs.
count(RB.first)) {
1876 MachineInstr *IndI =
nullptr;
1877 MachineInstr *nonIndI =
nullptr;
1878 MachineOperand *IndMO =
nullptr;
1879 MachineOperand *nonIndMO =
nullptr;
1881 for (
unsigned i = 1, n = PredDef->
getNumOperands(); i < n; ++i) {
1891 }
else if (MO.
isReg()) {
1901 if (IndI && nonIndI &&
1902 nonIndI->
getOpcode() == Hexagon::A2_addi &&
1905 bool Order = orderBumpCompare(IndI, PredDef);
1917 Comparison::Kind
Cmp =
1918 getComparisonKind(PredDef->
getOpcode(),
nullptr,
nullptr, 0);
1919 if (!Cmp || Comparison::isUnsigned(Cmp))
1925 int64_t CmpImm = getImmediate(*CmpImmOp);
1926 int64_t
V = RB.second;
1935 if (CmpImmOp->
isImm() && !
TII->isExtendable(*PredDef) &&
1936 !
TII->isValidOffset(PredDef->
getOpcode(), CmpImm,
false))
1942 bool Order = orderBumpCompare(BumpI, PredDef);
1947 setImmediate(*CmpImmOp, CmpImm);
1948 for (MachineOperand &MO : PredDef->
operands()) {
1961MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1963 if (MachineBasicBlock *TmpPH =
1964 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader))
1966 if (!CLOpts->hwloop_preheader)
1969 MachineBasicBlock *Header =
L->getHeader();
1970 MachineBasicBlock *Latch =
L->getLoopLatch();
1971 MachineBasicBlock *ExitingBlock =
L->findLoopControlBlock();
1976 if (!CLOpts->hwloop_phfn.empty() && CLOpts->hwloop_phfn != MF->
getName())
1980 if (!Latch || !ExitingBlock || Header->hasAddressTaken())
1987 using MBBVector = std::vector<MachineBasicBlock *>;
1989 MBBVector Preds(Header->pred_begin(), Header->pred_end());
1991 MachineBasicBlock *
TB =
nullptr, *FB =
nullptr;
1996 for (MachineBasicBlock *
PB : Preds) {
2003 MF->
insert(Header->getIterator(), NewPH);
2005 if (Header->pred_size() > 2) {
2011 for (instr_iterator
I = Header->instr_begin(),
E = Header->instr_end();
2012 I !=
E &&
I->isPHI(); ++
I) {
2013 MachineInstr *PN = &*
I;
2015 const MCInstrDesc &
PD =
TII->get(TargetOpcode::PHI);
2016 MachineInstr *NewPN = MF->CreateMachineInstr(PD,
DL);
2043 if (PredB != Latch) {
2052 assert(Header->pred_size() == 2);
2059 for (instr_iterator
I = Header->instr_begin(),
E = Header->instr_end();
2060 I !=
E &&
I->isPHI(); ++
I) {
2061 MachineInstr *PN = &*
I;
2064 if (MO.
getMBB() != Latch)
2078 for (MachineBasicBlock *
PB : Preds) {
2083 assert (!NotAnalyzed &&
"Should be analyzable!");
2084 if (TB != Header && (Tmp2.
empty() || FB != Header))
2086 PB->ReplaceUsesOfBlockWith(Header, NewPH);
2094 (void)LatchNotAnalyzed;
2095 assert (!LatchNotAnalyzed &&
"Should be analyzable!");
2103 MachineLoop *ParentLoop =
L->getParentLoop();
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool isSigned(unsigned Opcode)
SmallVector< MachineOperand, 4 > Cond
Register const TargetRegisterInfo * TRI
Promote Memory to Register
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
SmallVector< MachineBasicBlock *, 4 > MBBVector
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &CmpMask, int64_t &CmpValue) const override
analyzeCompare - For a comparison instruction, return the source registers in SrcReg and SrcReg2,...
AnalysisUsage & addRequired()
DomTreeNodeBase * getIDom() const
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
FunctionPass class - This class is used to implement most global optimizations.
const HexagonInstrInfo * getInstrInfo() const override
const HexagonRegisterInfo * getRegisterInfo() const override
const HexagonOptions & getCLOpts() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
bool isAdd() const
Return true if the instruction is an add instruction.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
Instructions::iterator instr_iterator
pred_iterator pred_begin()
instr_iterator instr_end()
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
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 & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool isCompare(QueryType Type=IgnoreBundle) const
Return true if this instruction is a comparison.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI void insert(mop_iterator InsertBefore, ArrayRef< MachineOperand > Ops)
Inserts Ops BEFORE It. Can untie/retie tied operands.
LLVM_ABI unsigned findTiedOperandIdx(unsigned OpIdx) const
Given the index of a tied register operand, find the operand it is tied to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setImm(int64_t immVal)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
use_nodbg_iterator use_nodbg_begin(Register RegNo) const
defusechain_instr_iterator< true, false, true, true > use_instr_nodbg_iterator
use_instr_nodbg_iterator/use_instr_nodbg_begin/use_instr_nodbg_end - Walk all uses of the specified r...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
static use_nodbg_iterator use_nodbg_end()
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
defusechain_iterator< true, false, true, true, false > use_nodbg_iterator
use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the specified register,...
iterator_range< use_iterator > use_operands(Register Reg) const
static use_instr_nodbg_iterator use_instr_nodbg_end()
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void push_back(const T &Elt)
self_iterator getIterator()
#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.
@ TB
TB - TwoByte - Set if this instruction has a two byte opcode, which starts with a 0x0F byte before th...
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
NodeAddr< DefNode * > Def
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
unsigned getLoopTripCount(const Loop *L, ScalarEvolution &SE, unsigned LoopAwareTripCount)
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
RelativeUniformCounterPtr Values
RegState
Flags to represent properties of register accesses.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionPass * createHexagonHardwareLoops()
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.