PPCMIPeephole.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. //===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===---------------------------------------------------------------------===//
  8. //
  9. // This pass performs peephole optimizations to clean up ugly code
  10. // sequences at the MachineInstruction layer. It runs at the end of
  11. // the SSA phases, following VSX swap removal. A pass of dead code
  12. // elimination follows this one for quick clean-up of any dead
  13. // instructions introduced here. Although we could do this as callbacks
  14. // from the generic peephole pass, this would have a couple of bad
  15. // effects: it might remove optimization opportunities for VSX swap
  16. // removal, and it would miss cleanups made possible following VSX
  17. // swap removal.
  18. //
  19. //===---------------------------------------------------------------------===//
  20. #include "MCTargetDesc/PPCMCTargetDesc.h"
  21. #include "MCTargetDesc/PPCPredicates.h"
  22. #include "PPC.h"
  23. #include "PPCInstrBuilder.h"
  24. #include "PPCInstrInfo.h"
  25. #include "PPCMachineFunctionInfo.h"
  26. #include "PPCTargetMachine.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  29. #include "llvm/CodeGen/MachineDominators.h"
  30. #include "llvm/CodeGen/MachineFunctionPass.h"
  31. #include "llvm/CodeGen/MachineInstrBuilder.h"
  32. #include "llvm/CodeGen/MachinePostDominators.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/InitializePasses.h"
  35. #include "llvm/Support/Debug.h"
  36. using namespace llvm;
  37. #define DEBUG_TYPE "ppc-mi-peepholes"
  38. STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
  39. STATISTIC(MultiTOCSaves,
  40. "Number of functions with multiple TOC saves that must be kept");
  41. STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue");
  42. STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
  43. STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
  44. STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
  45. STATISTIC(NumConvertedToImmediateForm,
  46. "Number of instructions converted to their immediate form");
  47. STATISTIC(NumFunctionsEnteredInMIPeephole,
  48. "Number of functions entered in PPC MI Peepholes");
  49. STATISTIC(NumFixedPointIterations,
  50. "Number of fixed-point iterations converting reg-reg instructions "
  51. "to reg-imm ones");
  52. STATISTIC(NumRotatesCollapsed,
  53. "Number of pairs of rotate left, clear left/right collapsed");
  54. STATISTIC(NumEXTSWAndSLDICombined,
  55. "Number of pairs of EXTSW and SLDI combined as EXTSWSLI");
  56. STATISTIC(NumLoadImmZeroFoldedAndRemoved,
  57. "Number of LI(8) reg, 0 that are folded to r0 and removed");
  58. static cl::opt<bool>
  59. FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
  60. cl::desc("Iterate to a fixed point when attempting to "
  61. "convert reg-reg instructions to reg-imm"));
  62. static cl::opt<bool>
  63. ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
  64. cl::desc("Convert eligible reg+reg instructions to reg+imm"));
  65. static cl::opt<bool>
  66. EnableSExtElimination("ppc-eliminate-signext",
  67. cl::desc("enable elimination of sign-extensions"),
  68. cl::init(false), cl::Hidden);
  69. static cl::opt<bool>
  70. EnableZExtElimination("ppc-eliminate-zeroext",
  71. cl::desc("enable elimination of zero-extensions"),
  72. cl::init(false), cl::Hidden);
  73. static cl::opt<bool>
  74. EnableTrapOptimization("ppc-opt-conditional-trap",
  75. cl::desc("enable optimization of conditional traps"),
  76. cl::init(false), cl::Hidden);
  77. namespace {
  78. struct PPCMIPeephole : public MachineFunctionPass {
  79. static char ID;
  80. const PPCInstrInfo *TII;
  81. MachineFunction *MF;
  82. MachineRegisterInfo *MRI;
  83. PPCMIPeephole() : MachineFunctionPass(ID) {
  84. initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
  85. }
  86. private:
  87. MachineDominatorTree *MDT;
  88. MachinePostDominatorTree *MPDT;
  89. MachineBlockFrequencyInfo *MBFI;
  90. uint64_t EntryFreq;
  91. // Initialize class variables.
  92. void initialize(MachineFunction &MFParm);
  93. // Perform peepholes.
  94. bool simplifyCode();
  95. // Perform peepholes.
  96. bool eliminateRedundantCompare();
  97. bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
  98. bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase);
  99. bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI);
  100. void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
  101. MachineInstr *MI);
  102. public:
  103. void getAnalysisUsage(AnalysisUsage &AU) const override {
  104. AU.addRequired<MachineDominatorTree>();
  105. AU.addRequired<MachinePostDominatorTree>();
  106. AU.addRequired<MachineBlockFrequencyInfo>();
  107. AU.addPreserved<MachineDominatorTree>();
  108. AU.addPreserved<MachinePostDominatorTree>();
  109. AU.addPreserved<MachineBlockFrequencyInfo>();
  110. MachineFunctionPass::getAnalysisUsage(AU);
  111. }
  112. // Main entry point for this pass.
  113. bool runOnMachineFunction(MachineFunction &MF) override {
  114. initialize(MF);
  115. // At this point, TOC pointer should not be used in a function that uses
  116. // PC-Relative addressing.
  117. assert((MF.getRegInfo().use_empty(PPC::X2) ||
  118. !MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) &&
  119. "TOC pointer used in a function using PC-Relative addressing!");
  120. if (skipFunction(MF.getFunction()))
  121. return false;
  122. return simplifyCode();
  123. }
  124. };
  125. // Initialize class variables.
  126. void PPCMIPeephole::initialize(MachineFunction &MFParm) {
  127. MF = &MFParm;
  128. MRI = &MF->getRegInfo();
  129. MDT = &getAnalysis<MachineDominatorTree>();
  130. MPDT = &getAnalysis<MachinePostDominatorTree>();
  131. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  132. EntryFreq = MBFI->getEntryFreq();
  133. TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
  134. LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
  135. LLVM_DEBUG(MF->dump());
  136. }
  137. static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
  138. MachineRegisterInfo *MRI) {
  139. assert(Op && "Invalid Operand!");
  140. if (!Op->isReg())
  141. return nullptr;
  142. Register Reg = Op->getReg();
  143. if (!Register::isVirtualRegister(Reg))
  144. return nullptr;
  145. return MRI->getVRegDef(Reg);
  146. }
  147. // This function returns number of known zero bits in output of MI
  148. // starting from the most significant bit.
  149. static unsigned
  150. getKnownLeadingZeroCount(MachineInstr *MI, const PPCInstrInfo *TII) {
  151. unsigned Opcode = MI->getOpcode();
  152. if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
  153. Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec)
  154. return MI->getOperand(3).getImm();
  155. if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
  156. MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
  157. return MI->getOperand(3).getImm();
  158. if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
  159. Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
  160. Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
  161. MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
  162. return 32 + MI->getOperand(3).getImm();
  163. if (Opcode == PPC::ANDI_rec) {
  164. uint16_t Imm = MI->getOperand(2).getImm();
  165. return 48 + countLeadingZeros(Imm);
  166. }
  167. if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
  168. Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
  169. Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
  170. // The result ranges from 0 to 32.
  171. return 58;
  172. if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
  173. Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec)
  174. // The result ranges from 0 to 64.
  175. return 57;
  176. if (Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
  177. Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 ||
  178. Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
  179. Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
  180. return 48;
  181. if (Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
  182. Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
  183. Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
  184. Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
  185. return 56;
  186. if (TII->isZeroExtended(*MI))
  187. return 32;
  188. return 0;
  189. }
  190. // This function maintains a map for the pairs <TOC Save Instr, Keep>
  191. // Each time a new TOC save is encountered, it checks if any of the existing
  192. // ones are dominated by the new one. If so, it marks the existing one as
  193. // redundant by setting it's entry in the map as false. It then adds the new
  194. // instruction to the map with either true or false depending on if any
  195. // existing instructions dominated the new one.
  196. void PPCMIPeephole::UpdateTOCSaves(
  197. std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
  198. assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
  199. // FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part,
  200. // here only support it under ELFv2.
  201. if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) {
  202. PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
  203. MachineBasicBlock *Entry = &MF->front();
  204. uint64_t CurrBlockFreq = MBFI->getBlockFreq(MI->getParent()).getFrequency();
  205. // If the block in which the TOC save resides is in a block that
  206. // post-dominates Entry, or a block that is hotter than entry (keep in mind
  207. // that early MachineLICM has already run so the TOC save won't be hoisted)
  208. // we can just do the save in the prologue.
  209. if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry))
  210. FI->setMustSaveTOC(true);
  211. // If we are saving the TOC in the prologue, all the TOC saves can be
  212. // removed from the code.
  213. if (FI->mustSaveTOC()) {
  214. for (auto &TOCSave : TOCSaves)
  215. TOCSave.second = false;
  216. // Add new instruction to map.
  217. TOCSaves[MI] = false;
  218. return;
  219. }
  220. }
  221. bool Keep = true;
  222. for (auto &I : TOCSaves) {
  223. MachineInstr *CurrInst = I.first;
  224. // If new instruction dominates an existing one, mark existing one as
  225. // redundant.
  226. if (I.second && MDT->dominates(MI, CurrInst))
  227. I.second = false;
  228. // Check if the new instruction is redundant.
  229. if (MDT->dominates(CurrInst, MI)) {
  230. Keep = false;
  231. break;
  232. }
  233. }
  234. // Add new instruction to map.
  235. TOCSaves[MI] = Keep;
  236. }
  237. // This function returns a list of all PHI nodes in the tree starting from
  238. // the RootPHI node. We perform a BFS traversal to get an ordered list of nodes.
  239. // The list initially only contains the root PHI. When we visit a PHI node, we
  240. // add it to the list. We continue to look for other PHI node operands while
  241. // there are nodes to visit in the list. The function returns false if the
  242. // optimization cannot be applied on this tree.
  243. static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI,
  244. MachineInstr *RootPHI,
  245. SmallVectorImpl<MachineInstr *> &PHIs) {
  246. PHIs.push_back(RootPHI);
  247. unsigned VisitedIndex = 0;
  248. while (VisitedIndex < PHIs.size()) {
  249. MachineInstr *VisitedPHI = PHIs[VisitedIndex];
  250. for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands();
  251. PHIOp != NumOps; PHIOp += 2) {
  252. Register RegOp = VisitedPHI->getOperand(PHIOp).getReg();
  253. if (!Register::isVirtualRegister(RegOp))
  254. return false;
  255. MachineInstr *Instr = MRI->getVRegDef(RegOp);
  256. // While collecting the PHI nodes, we check if they can be converted (i.e.
  257. // all the operands are either copies, implicit defs or PHI nodes).
  258. unsigned Opcode = Instr->getOpcode();
  259. if (Opcode == PPC::COPY) {
  260. Register Reg = Instr->getOperand(1).getReg();
  261. if (!Register::isVirtualRegister(Reg) ||
  262. MRI->getRegClass(Reg) != &PPC::ACCRCRegClass)
  263. return false;
  264. } else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI)
  265. return false;
  266. // If we detect a cycle in the PHI nodes, we exit. It would be
  267. // possible to change cycles as well, but that would add a lot
  268. // of complexity for a case that is unlikely to occur with MMA
  269. // code.
  270. if (Opcode != PPC::PHI)
  271. continue;
  272. if (llvm::is_contained(PHIs, Instr))
  273. return false;
  274. PHIs.push_back(Instr);
  275. }
  276. VisitedIndex++;
  277. }
  278. return true;
  279. }
  280. // This function changes the unprimed accumulator PHI nodes in the PHIs list to
  281. // primed accumulator PHI nodes. The list is traversed in reverse order to
  282. // change all the PHI operands of a PHI node before changing the node itself.
  283. // We keep a map to associate each changed PHI node to its non-changed form.
  284. static void convertUnprimedAccPHIs(const PPCInstrInfo *TII,
  285. MachineRegisterInfo *MRI,
  286. SmallVectorImpl<MachineInstr *> &PHIs,
  287. Register Dst) {
  288. DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap;
  289. for (MachineInstr *PHI : llvm::reverse(PHIs)) {
  290. SmallVector<std::pair<MachineOperand, MachineOperand>, 4> PHIOps;
  291. // We check if the current PHI node can be changed by looking at its
  292. // operands. If all the operands are either copies from primed
  293. // accumulators, implicit definitions or other unprimed accumulator
  294. // PHI nodes, we change it.
  295. for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
  296. PHIOp += 2) {
  297. Register RegOp = PHI->getOperand(PHIOp).getReg();
  298. MachineInstr *PHIInput = MRI->getVRegDef(RegOp);
  299. unsigned Opcode = PHIInput->getOpcode();
  300. assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF ||
  301. Opcode == PPC::PHI) &&
  302. "Unexpected instruction");
  303. if (Opcode == PPC::COPY) {
  304. assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) ==
  305. &PPC::ACCRCRegClass &&
  306. "Unexpected register class");
  307. PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)});
  308. } else if (Opcode == PPC::IMPLICIT_DEF) {
  309. Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
  310. BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(),
  311. TII->get(PPC::IMPLICIT_DEF), AccReg);
  312. PHIOps.push_back({MachineOperand::CreateReg(AccReg, false),
  313. PHI->getOperand(PHIOp + 1)});
  314. } else if (Opcode == PPC::PHI) {
  315. // We found a PHI operand. At this point we know this operand
  316. // has already been changed so we get its associated changed form
  317. // from the map.
  318. assert(ChangedPHIMap.count(PHIInput) == 1 &&
  319. "This PHI node should have already been changed.");
  320. MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput);
  321. PHIOps.push_back({MachineOperand::CreateReg(
  322. PrimedAccPHI->getOperand(0).getReg(), false),
  323. PHI->getOperand(PHIOp + 1)});
  324. }
  325. }
  326. Register AccReg = Dst;
  327. // If the PHI node we are changing is the root node, the register it defines
  328. // will be the destination register of the original copy (of the PHI def).
  329. // For all other PHI's in the list, we need to create another primed
  330. // accumulator virtual register as the PHI will no longer define the
  331. // unprimed accumulator.
  332. if (PHI != PHIs[0])
  333. AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
  334. MachineInstrBuilder NewPHI = BuildMI(
  335. *PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg);
  336. for (auto RegMBB : PHIOps)
  337. NewPHI.add(RegMBB.first).add(RegMBB.second);
  338. ChangedPHIMap[PHI] = NewPHI.getInstr();
  339. }
  340. }
  341. // Perform peephole optimizations.
  342. bool PPCMIPeephole::simplifyCode() {
  343. bool Simplified = false;
  344. bool TrapOpt = false;
  345. MachineInstr* ToErase = nullptr;
  346. std::map<MachineInstr *, bool> TOCSaves;
  347. const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
  348. NumFunctionsEnteredInMIPeephole++;
  349. if (ConvertRegReg) {
  350. // Fixed-point conversion of reg/reg instructions fed by load-immediate
  351. // into reg/imm instructions. FIXME: This is expensive, control it with
  352. // an option.
  353. bool SomethingChanged = false;
  354. do {
  355. NumFixedPointIterations++;
  356. SomethingChanged = false;
  357. for (MachineBasicBlock &MBB : *MF) {
  358. for (MachineInstr &MI : MBB) {
  359. if (MI.isDebugInstr())
  360. continue;
  361. if (TII->convertToImmediateForm(MI)) {
  362. // We don't erase anything in case the def has other uses. Let DCE
  363. // remove it if it can be removed.
  364. LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
  365. LLVM_DEBUG(MI.dump());
  366. NumConvertedToImmediateForm++;
  367. SomethingChanged = true;
  368. Simplified = true;
  369. continue;
  370. }
  371. }
  372. }
  373. } while (SomethingChanged && FixedPointRegToImm);
  374. }
  375. for (MachineBasicBlock &MBB : *MF) {
  376. for (MachineInstr &MI : MBB) {
  377. // If the previous instruction was marked for elimination,
  378. // remove it now.
  379. if (ToErase) {
  380. ToErase->eraseFromParent();
  381. ToErase = nullptr;
  382. }
  383. // If a conditional trap instruction got optimized to an
  384. // unconditional trap, eliminate all the instructions after
  385. // the trap.
  386. if (EnableTrapOptimization && TrapOpt) {
  387. ToErase = &MI;
  388. continue;
  389. }
  390. // Ignore debug instructions.
  391. if (MI.isDebugInstr())
  392. continue;
  393. // Per-opcode peepholes.
  394. switch (MI.getOpcode()) {
  395. default:
  396. break;
  397. case PPC::COPY: {
  398. Register Src = MI.getOperand(1).getReg();
  399. Register Dst = MI.getOperand(0).getReg();
  400. if (!Register::isVirtualRegister(Src) ||
  401. !Register::isVirtualRegister(Dst))
  402. break;
  403. if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
  404. MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
  405. break;
  406. // We are copying an unprimed accumulator to a primed accumulator.
  407. // If the input to the copy is a PHI that is fed only by (i) copies in
  408. // the other direction (ii) implicitly defined unprimed accumulators or
  409. // (iii) other PHI nodes satisfying (i) and (ii), we can change
  410. // the PHI to a PHI on primed accumulators (as long as we also change
  411. // its operands). To detect and change such copies, we first get a list
  412. // of all the PHI nodes starting from the root PHI node in BFS order.
  413. // We then visit all these PHI nodes to check if they can be changed to
  414. // primed accumulator PHI nodes and if so, we change them.
  415. MachineInstr *RootPHI = MRI->getVRegDef(Src);
  416. if (RootPHI->getOpcode() != PPC::PHI)
  417. break;
  418. SmallVector<MachineInstr *, 4> PHIs;
  419. if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
  420. break;
  421. convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
  422. ToErase = &MI;
  423. break;
  424. }
  425. case PPC::LI:
  426. case PPC::LI8: {
  427. // If we are materializing a zero, look for any use operands for which
  428. // zero means immediate zero. All such operands can be replaced with
  429. // PPC::ZERO.
  430. if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
  431. break;
  432. Register MIDestReg = MI.getOperand(0).getReg();
  433. for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
  434. Simplified |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
  435. if (MRI->use_nodbg_empty(MIDestReg)) {
  436. ++NumLoadImmZeroFoldedAndRemoved;
  437. ToErase = &MI;
  438. }
  439. break;
  440. }
  441. case PPC::STW:
  442. case PPC::STD: {
  443. MachineFrameInfo &MFI = MF->getFrameInfo();
  444. if (MFI.hasVarSizedObjects() ||
  445. (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
  446. !MF->getSubtarget<PPCSubtarget>().isAIXABI()))
  447. break;
  448. // When encountering a TOC save instruction, call UpdateTOCSaves
  449. // to add it to the TOCSaves map and mark any existing TOC saves
  450. // it dominates as redundant.
  451. if (TII->isTOCSaveMI(MI))
  452. UpdateTOCSaves(TOCSaves, &MI);
  453. break;
  454. }
  455. case PPC::XXPERMDI: {
  456. // Perform simplifications of 2x64 vector swaps and splats.
  457. // A swap is identified by an immediate value of 2, and a splat
  458. // is identified by an immediate value of 0 or 3.
  459. int Immed = MI.getOperand(3).getImm();
  460. if (Immed == 1)
  461. break;
  462. // For each of these simplifications, we need the two source
  463. // regs to match. Unfortunately, MachineCSE ignores COPY and
  464. // SUBREG_TO_REG, so for example we can see
  465. // XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
  466. // We have to look through chains of COPY and SUBREG_TO_REG
  467. // to find the real source values for comparison.
  468. Register TrueReg1 =
  469. TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
  470. Register TrueReg2 =
  471. TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
  472. if (!(TrueReg1 == TrueReg2 && Register::isVirtualRegister(TrueReg1)))
  473. break;
  474. MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
  475. if (!DefMI)
  476. break;
  477. unsigned DefOpc = DefMI->getOpcode();
  478. // If this is a splat fed by a splatting load, the splat is
  479. // redundant. Replace with a copy. This doesn't happen directly due
  480. // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
  481. // a load of a double to a vector of 64-bit integers.
  482. auto isConversionOfLoadAndSplat = [=]() -> bool {
  483. if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
  484. return false;
  485. Register FeedReg1 =
  486. TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
  487. if (Register::isVirtualRegister(FeedReg1)) {
  488. MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
  489. if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
  490. return true;
  491. }
  492. return false;
  493. };
  494. if ((Immed == 0 || Immed == 3) &&
  495. (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
  496. LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
  497. "to load-and-splat/copy: ");
  498. LLVM_DEBUG(MI.dump());
  499. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  500. MI.getOperand(0).getReg())
  501. .add(MI.getOperand(1));
  502. ToErase = &MI;
  503. Simplified = true;
  504. }
  505. // If this is a splat or a swap fed by another splat, we
  506. // can replace it with a copy.
  507. if (DefOpc == PPC::XXPERMDI) {
  508. Register DefReg1 = DefMI->getOperand(1).getReg();
  509. Register DefReg2 = DefMI->getOperand(2).getReg();
  510. unsigned DefImmed = DefMI->getOperand(3).getImm();
  511. // If the two inputs are not the same register, check to see if
  512. // they originate from the same virtual register after only
  513. // copy-like instructions.
  514. if (DefReg1 != DefReg2) {
  515. Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
  516. Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
  517. if (!(FeedReg1 == FeedReg2 &&
  518. Register::isVirtualRegister(FeedReg1)))
  519. break;
  520. }
  521. if (DefImmed == 0 || DefImmed == 3) {
  522. LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
  523. "to splat/copy: ");
  524. LLVM_DEBUG(MI.dump());
  525. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  526. MI.getOperand(0).getReg())
  527. .add(MI.getOperand(1));
  528. ToErase = &MI;
  529. Simplified = true;
  530. }
  531. // If this is a splat fed by a swap, we can simplify modify
  532. // the splat to splat the other value from the swap's input
  533. // parameter.
  534. else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
  535. LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
  536. LLVM_DEBUG(MI.dump());
  537. MI.getOperand(1).setReg(DefReg1);
  538. MI.getOperand(2).setReg(DefReg2);
  539. MI.getOperand(3).setImm(3 - Immed);
  540. Simplified = true;
  541. }
  542. // If this is a swap fed by a swap, we can replace it
  543. // with a copy from the first swap's input.
  544. else if (Immed == 2 && DefImmed == 2) {
  545. LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
  546. LLVM_DEBUG(MI.dump());
  547. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  548. MI.getOperand(0).getReg())
  549. .add(DefMI->getOperand(1));
  550. ToErase = &MI;
  551. Simplified = true;
  552. }
  553. } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
  554. DefOpc == PPC::XXPERMDIs &&
  555. (DefMI->getOperand(2).getImm() == 0 ||
  556. DefMI->getOperand(2).getImm() == 3)) {
  557. ToErase = &MI;
  558. Simplified = true;
  559. // Swap of a splat, convert to copy.
  560. if (Immed == 2) {
  561. LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
  562. LLVM_DEBUG(MI.dump());
  563. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  564. MI.getOperand(0).getReg())
  565. .add(MI.getOperand(1));
  566. break;
  567. }
  568. // Splat fed by another splat - switch the output of the first
  569. // and remove the second.
  570. DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
  571. LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
  572. LLVM_DEBUG(MI.dump());
  573. }
  574. break;
  575. }
  576. case PPC::VSPLTB:
  577. case PPC::VSPLTH:
  578. case PPC::XXSPLTW: {
  579. unsigned MyOpcode = MI.getOpcode();
  580. unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
  581. Register TrueReg =
  582. TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
  583. if (!Register::isVirtualRegister(TrueReg))
  584. break;
  585. MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
  586. if (!DefMI)
  587. break;
  588. unsigned DefOpcode = DefMI->getOpcode();
  589. auto isConvertOfSplat = [=]() -> bool {
  590. if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
  591. return false;
  592. Register ConvReg = DefMI->getOperand(1).getReg();
  593. if (!Register::isVirtualRegister(ConvReg))
  594. return false;
  595. MachineInstr *Splt = MRI->getVRegDef(ConvReg);
  596. return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
  597. Splt->getOpcode() == PPC::XXSPLTW);
  598. };
  599. bool AlreadySplat = (MyOpcode == DefOpcode) ||
  600. (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
  601. (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
  602. (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
  603. (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
  604. (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
  605. (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
  606. // If the instruction[s] that feed this splat have already splat
  607. // the value, this splat is redundant.
  608. if (AlreadySplat) {
  609. LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
  610. LLVM_DEBUG(MI.dump());
  611. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  612. MI.getOperand(0).getReg())
  613. .add(MI.getOperand(OpNo));
  614. ToErase = &MI;
  615. Simplified = true;
  616. }
  617. // Splat fed by a shift. Usually when we align value to splat into
  618. // vector element zero.
  619. if (DefOpcode == PPC::XXSLDWI) {
  620. Register ShiftRes = DefMI->getOperand(0).getReg();
  621. Register ShiftOp1 = DefMI->getOperand(1).getReg();
  622. Register ShiftOp2 = DefMI->getOperand(2).getReg();
  623. unsigned ShiftImm = DefMI->getOperand(3).getImm();
  624. unsigned SplatImm =
  625. MI.getOperand(MyOpcode == PPC::XXSPLTW ? 2 : 1).getImm();
  626. if (ShiftOp1 == ShiftOp2) {
  627. unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
  628. if (MRI->hasOneNonDBGUse(ShiftRes)) {
  629. LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
  630. LLVM_DEBUG(DefMI->dump());
  631. ToErase = DefMI;
  632. }
  633. Simplified = true;
  634. LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
  635. << " to " << NewElem << " in instruction: ");
  636. LLVM_DEBUG(MI.dump());
  637. MI.getOperand(1).setReg(ShiftOp1);
  638. MI.getOperand(2).setImm(NewElem);
  639. }
  640. }
  641. break;
  642. }
  643. case PPC::XVCVDPSP: {
  644. // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
  645. Register TrueReg =
  646. TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
  647. if (!Register::isVirtualRegister(TrueReg))
  648. break;
  649. MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
  650. // This can occur when building a vector of single precision or integer
  651. // values.
  652. if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
  653. Register DefsReg1 =
  654. TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
  655. Register DefsReg2 =
  656. TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
  657. if (!Register::isVirtualRegister(DefsReg1) ||
  658. !Register::isVirtualRegister(DefsReg2))
  659. break;
  660. MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
  661. MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
  662. if (!P1 || !P2)
  663. break;
  664. // Remove the passed FRSP/XSRSP instruction if it only feeds this MI
  665. // and set any uses of that FRSP/XSRSP (in this MI) to the source of
  666. // the FRSP/XSRSP.
  667. auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
  668. unsigned Opc = RoundInstr->getOpcode();
  669. if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
  670. MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
  671. Simplified = true;
  672. Register ConvReg1 = RoundInstr->getOperand(1).getReg();
  673. Register FRSPDefines = RoundInstr->getOperand(0).getReg();
  674. MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
  675. for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
  676. if (Use.getOperand(i).isReg() &&
  677. Use.getOperand(i).getReg() == FRSPDefines)
  678. Use.getOperand(i).setReg(ConvReg1);
  679. LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
  680. LLVM_DEBUG(RoundInstr->dump());
  681. LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
  682. LLVM_DEBUG(MI.dump());
  683. LLVM_DEBUG(dbgs() << "Through instruction:\n");
  684. LLVM_DEBUG(DefMI->dump());
  685. RoundInstr->eraseFromParent();
  686. }
  687. };
  688. // If the input to XVCVDPSP is a vector that was built (even
  689. // partially) out of FRSP's, the FRSP(s) can safely be removed
  690. // since this instruction performs the same operation.
  691. if (P1 != P2) {
  692. removeFRSPIfPossible(P1);
  693. removeFRSPIfPossible(P2);
  694. break;
  695. }
  696. removeFRSPIfPossible(P1);
  697. }
  698. break;
  699. }
  700. case PPC::EXTSH:
  701. case PPC::EXTSH8:
  702. case PPC::EXTSH8_32_64: {
  703. if (!EnableSExtElimination) break;
  704. Register NarrowReg = MI.getOperand(1).getReg();
  705. if (!Register::isVirtualRegister(NarrowReg))
  706. break;
  707. MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
  708. // If we've used a zero-extending load that we will sign-extend,
  709. // just do a sign-extending load.
  710. if (SrcMI->getOpcode() == PPC::LHZ ||
  711. SrcMI->getOpcode() == PPC::LHZX) {
  712. if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
  713. break;
  714. auto is64Bit = [] (unsigned Opcode) {
  715. return Opcode == PPC::EXTSH8;
  716. };
  717. auto isXForm = [] (unsigned Opcode) {
  718. return Opcode == PPC::LHZX;
  719. };
  720. auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
  721. if (is64Bit)
  722. if (isXForm) return PPC::LHAX8;
  723. else return PPC::LHA8;
  724. else
  725. if (isXForm) return PPC::LHAX;
  726. else return PPC::LHA;
  727. };
  728. unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
  729. isXForm(SrcMI->getOpcode()));
  730. LLVM_DEBUG(dbgs() << "Zero-extending load\n");
  731. LLVM_DEBUG(SrcMI->dump());
  732. LLVM_DEBUG(dbgs() << "and sign-extension\n");
  733. LLVM_DEBUG(MI.dump());
  734. LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
  735. SrcMI->setDesc(TII->get(Opc));
  736. SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
  737. ToErase = &MI;
  738. Simplified = true;
  739. NumEliminatedSExt++;
  740. }
  741. break;
  742. }
  743. case PPC::EXTSW:
  744. case PPC::EXTSW_32:
  745. case PPC::EXTSW_32_64: {
  746. if (!EnableSExtElimination) break;
  747. Register NarrowReg = MI.getOperand(1).getReg();
  748. if (!Register::isVirtualRegister(NarrowReg))
  749. break;
  750. MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
  751. // If we've used a zero-extending load that we will sign-extend,
  752. // just do a sign-extending load.
  753. if (SrcMI->getOpcode() == PPC::LWZ ||
  754. SrcMI->getOpcode() == PPC::LWZX) {
  755. if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
  756. break;
  757. auto is64Bit = [] (unsigned Opcode) {
  758. return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64;
  759. };
  760. auto isXForm = [] (unsigned Opcode) {
  761. return Opcode == PPC::LWZX;
  762. };
  763. auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
  764. if (is64Bit)
  765. if (isXForm) return PPC::LWAX;
  766. else return PPC::LWA;
  767. else
  768. if (isXForm) return PPC::LWAX_32;
  769. else return PPC::LWA_32;
  770. };
  771. unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
  772. isXForm(SrcMI->getOpcode()));
  773. LLVM_DEBUG(dbgs() << "Zero-extending load\n");
  774. LLVM_DEBUG(SrcMI->dump());
  775. LLVM_DEBUG(dbgs() << "and sign-extension\n");
  776. LLVM_DEBUG(MI.dump());
  777. LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
  778. SrcMI->setDesc(TII->get(Opc));
  779. SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
  780. ToErase = &MI;
  781. Simplified = true;
  782. NumEliminatedSExt++;
  783. } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
  784. TII->isSignExtended(*SrcMI)) {
  785. // We can eliminate EXTSW if the input is known to be already
  786. // sign-extended.
  787. LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
  788. Register TmpReg =
  789. MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
  790. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
  791. TmpReg);
  792. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
  793. MI.getOperand(0).getReg())
  794. .addReg(TmpReg)
  795. .addReg(NarrowReg)
  796. .addImm(PPC::sub_32);
  797. ToErase = &MI;
  798. Simplified = true;
  799. NumEliminatedSExt++;
  800. }
  801. break;
  802. }
  803. case PPC::RLDICL: {
  804. // We can eliminate RLDICL (e.g. for zero-extension)
  805. // if all bits to clear are already zero in the input.
  806. // This code assume following code sequence for zero-extension.
  807. // %6 = COPY %5:sub_32; (optional)
  808. // %8 = IMPLICIT_DEF;
  809. // %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
  810. if (!EnableZExtElimination) break;
  811. if (MI.getOperand(2).getImm() != 0)
  812. break;
  813. Register SrcReg = MI.getOperand(1).getReg();
  814. if (!Register::isVirtualRegister(SrcReg))
  815. break;
  816. MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
  817. if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
  818. SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
  819. break;
  820. MachineInstr *ImpDefMI, *SubRegMI;
  821. ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
  822. SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
  823. if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
  824. SrcMI = SubRegMI;
  825. if (SubRegMI->getOpcode() == PPC::COPY) {
  826. Register CopyReg = SubRegMI->getOperand(1).getReg();
  827. if (Register::isVirtualRegister(CopyReg))
  828. SrcMI = MRI->getVRegDef(CopyReg);
  829. }
  830. unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII);
  831. if (MI.getOperand(3).getImm() <= KnownZeroCount) {
  832. LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
  833. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  834. MI.getOperand(0).getReg())
  835. .addReg(SrcReg);
  836. ToErase = &MI;
  837. Simplified = true;
  838. NumEliminatedZExt++;
  839. }
  840. break;
  841. }
  842. // TODO: Any instruction that has an immediate form fed only by a PHI
  843. // whose operands are all load immediate can be folded away. We currently
  844. // do this for ADD instructions, but should expand it to arithmetic and
  845. // binary instructions with immediate forms in the future.
  846. case PPC::ADD4:
  847. case PPC::ADD8: {
  848. auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
  849. assert(PhiOp && "Invalid Operand!");
  850. MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
  851. return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
  852. MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
  853. };
  854. auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
  855. MachineOperand *PhiOp) {
  856. assert(PhiOp && "Invalid Operand!");
  857. assert(DominatorOp && "Invalid Operand!");
  858. MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
  859. MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
  860. // Note: the vregs only show up at odd indices position of PHI Node,
  861. // the even indices position save the BB info.
  862. for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
  863. MachineInstr *LiMI =
  864. getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
  865. if (!LiMI ||
  866. (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
  867. || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
  868. !MDT->dominates(DefDomMI, LiMI))
  869. return false;
  870. }
  871. return true;
  872. };
  873. MachineOperand Op1 = MI.getOperand(1);
  874. MachineOperand Op2 = MI.getOperand(2);
  875. if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
  876. std::swap(Op1, Op2);
  877. else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
  878. break; // We don't have an ADD fed by LI's that can be transformed
  879. // Now we know that Op1 is the PHI node and Op2 is the dominator
  880. Register DominatorReg = Op2.getReg();
  881. const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
  882. ? &PPC::G8RC_and_G8RC_NOX0RegClass
  883. : &PPC::GPRC_and_GPRC_NOR0RegClass;
  884. MRI->setRegClass(DominatorReg, TRC);
  885. // replace LIs with ADDIs
  886. MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
  887. for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
  888. MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
  889. LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
  890. LLVM_DEBUG(LiMI->dump());
  891. // There could be repeated registers in the PHI, e.g: %1 =
  892. // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
  893. // already replaced the def instruction, skip.
  894. if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
  895. continue;
  896. assert((LiMI->getOpcode() == PPC::LI ||
  897. LiMI->getOpcode() == PPC::LI8) &&
  898. "Invalid Opcode!");
  899. auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
  900. LiMI->RemoveOperand(1); // remove the imm of LI
  901. LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
  902. : PPC::ADDI8));
  903. MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
  904. .addReg(DominatorReg)
  905. .addImm(LiImm); // restore the imm of LI
  906. LLVM_DEBUG(LiMI->dump());
  907. }
  908. // Replace ADD with COPY
  909. LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
  910. LLVM_DEBUG(MI.dump());
  911. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
  912. MI.getOperand(0).getReg())
  913. .add(Op1);
  914. ToErase = &MI;
  915. Simplified = true;
  916. NumOptADDLIs++;
  917. break;
  918. }
  919. case PPC::RLDICR: {
  920. Simplified |= emitRLDICWhenLoweringJumpTables(MI) ||
  921. combineSEXTAndSHL(MI, ToErase);
  922. break;
  923. }
  924. case PPC::RLWINM:
  925. case PPC::RLWINM_rec:
  926. case PPC::RLWINM8:
  927. case PPC::RLWINM8_rec: {
  928. Simplified = TII->combineRLWINM(MI, &ToErase);
  929. if (Simplified)
  930. ++NumRotatesCollapsed;
  931. break;
  932. }
  933. // We will replace TD/TW/TDI/TWI with an unconditional trap if it will
  934. // always trap, we will delete the node if it will never trap.
  935. case PPC::TDI:
  936. case PPC::TWI:
  937. case PPC::TD:
  938. case PPC::TW: {
  939. if (!EnableTrapOptimization) break;
  940. MachineInstr *LiMI1 = getVRegDefOrNull(&MI.getOperand(1), MRI);
  941. MachineInstr *LiMI2 = getVRegDefOrNull(&MI.getOperand(2), MRI);
  942. bool IsOperand2Immediate = MI.getOperand(2).isImm();
  943. // We can only do the optimization if we can get immediates
  944. // from both operands
  945. if (!(LiMI1 && (LiMI1->getOpcode() == PPC::LI ||
  946. LiMI1->getOpcode() == PPC::LI8)))
  947. break;
  948. if (!IsOperand2Immediate &&
  949. !(LiMI2 && (LiMI2->getOpcode() == PPC::LI ||
  950. LiMI2->getOpcode() == PPC::LI8)))
  951. break;
  952. auto ImmOperand0 = MI.getOperand(0).getImm();
  953. auto ImmOperand1 = LiMI1->getOperand(1).getImm();
  954. auto ImmOperand2 = IsOperand2Immediate ? MI.getOperand(2).getImm()
  955. : LiMI2->getOperand(1).getImm();
  956. // We will replace the MI with an unconditional trap if it will always
  957. // trap.
  958. if ((ImmOperand0 == 31) ||
  959. ((ImmOperand0 & 0x10) &&
  960. ((int64_t)ImmOperand1 < (int64_t)ImmOperand2)) ||
  961. ((ImmOperand0 & 0x8) &&
  962. ((int64_t)ImmOperand1 > (int64_t)ImmOperand2)) ||
  963. ((ImmOperand0 & 0x2) &&
  964. ((uint64_t)ImmOperand1 < (uint64_t)ImmOperand2)) ||
  965. ((ImmOperand0 & 0x1) &&
  966. ((uint64_t)ImmOperand1 > (uint64_t)ImmOperand2)) ||
  967. ((ImmOperand0 & 0x4) && (ImmOperand1 == ImmOperand2))) {
  968. BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::TRAP));
  969. TrapOpt = true;
  970. }
  971. // We will delete the MI if it will never trap.
  972. ToErase = &MI;
  973. Simplified = true;
  974. break;
  975. }
  976. }
  977. }
  978. // If the last instruction was marked for elimination,
  979. // remove it now.
  980. if (ToErase) {
  981. ToErase->eraseFromParent();
  982. ToErase = nullptr;
  983. }
  984. // Reset TrapOpt to false at the end of the basic block.
  985. if (EnableTrapOptimization)
  986. TrapOpt = false;
  987. }
  988. // Eliminate all the TOC save instructions which are redundant.
  989. Simplified |= eliminateRedundantTOCSaves(TOCSaves);
  990. PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
  991. if (FI->mustSaveTOC())
  992. NumTOCSavesInPrologue++;
  993. // We try to eliminate redundant compare instruction.
  994. Simplified |= eliminateRedundantCompare();
  995. return Simplified;
  996. }
  997. // helper functions for eliminateRedundantCompare
  998. static bool isEqOrNe(MachineInstr *BI) {
  999. PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
  1000. unsigned PredCond = PPC::getPredicateCondition(Pred);
  1001. return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
  1002. }
  1003. static bool isSupportedCmpOp(unsigned opCode) {
  1004. return (opCode == PPC::CMPLD || opCode == PPC::CMPD ||
  1005. opCode == PPC::CMPLW || opCode == PPC::CMPW ||
  1006. opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
  1007. opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
  1008. }
  1009. static bool is64bitCmpOp(unsigned opCode) {
  1010. return (opCode == PPC::CMPLD || opCode == PPC::CMPD ||
  1011. opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
  1012. }
  1013. static bool isSignedCmpOp(unsigned opCode) {
  1014. return (opCode == PPC::CMPD || opCode == PPC::CMPW ||
  1015. opCode == PPC::CMPDI || opCode == PPC::CMPWI);
  1016. }
  1017. static unsigned getSignedCmpOpCode(unsigned opCode) {
  1018. if (opCode == PPC::CMPLD) return PPC::CMPD;
  1019. if (opCode == PPC::CMPLW) return PPC::CMPW;
  1020. if (opCode == PPC::CMPLDI) return PPC::CMPDI;
  1021. if (opCode == PPC::CMPLWI) return PPC::CMPWI;
  1022. return opCode;
  1023. }
  1024. // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
  1025. // (LT x) to (LE x-1)
  1026. static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
  1027. uint64_t Imm = CMPI->getOperand(2).getImm();
  1028. bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
  1029. if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
  1030. return 0;
  1031. PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
  1032. unsigned PredCond = PPC::getPredicateCondition(Pred);
  1033. unsigned PredHint = PPC::getPredicateHint(Pred);
  1034. if (PredCond == PPC::PRED_GE)
  1035. return PPC::getPredicate(PPC::PRED_GT, PredHint);
  1036. if (PredCond == PPC::PRED_LT)
  1037. return PPC::getPredicate(PPC::PRED_LE, PredHint);
  1038. return 0;
  1039. }
  1040. // We can increment immediate x in (GT x) by changing it to (GE x+1) or
  1041. // (LE x) to (LT x+1)
  1042. static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
  1043. uint64_t Imm = CMPI->getOperand(2).getImm();
  1044. bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
  1045. if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
  1046. return 0;
  1047. PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
  1048. unsigned PredCond = PPC::getPredicateCondition(Pred);
  1049. unsigned PredHint = PPC::getPredicateHint(Pred);
  1050. if (PredCond == PPC::PRED_GT)
  1051. return PPC::getPredicate(PPC::PRED_GE, PredHint);
  1052. if (PredCond == PPC::PRED_LE)
  1053. return PPC::getPredicate(PPC::PRED_LT, PredHint);
  1054. return 0;
  1055. }
  1056. // This takes a Phi node and returns a register value for the specified BB.
  1057. static unsigned getIncomingRegForBlock(MachineInstr *Phi,
  1058. MachineBasicBlock *MBB) {
  1059. for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
  1060. MachineOperand &MO = Phi->getOperand(I);
  1061. if (MO.getMBB() == MBB)
  1062. return Phi->getOperand(I-1).getReg();
  1063. }
  1064. llvm_unreachable("invalid src basic block for this Phi node\n");
  1065. return 0;
  1066. }
  1067. // This function tracks the source of the register through register copy.
  1068. // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
  1069. // assuming that the control comes from BB1 into BB2.
  1070. static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
  1071. MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
  1072. unsigned SrcReg = Reg;
  1073. while (true) {
  1074. unsigned NextReg = SrcReg;
  1075. MachineInstr *Inst = MRI->getVRegDef(SrcReg);
  1076. if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
  1077. NextReg = getIncomingRegForBlock(Inst, BB1);
  1078. // We track through PHI only once to avoid infinite loop.
  1079. BB1 = nullptr;
  1080. }
  1081. else if (Inst->isFullCopy())
  1082. NextReg = Inst->getOperand(1).getReg();
  1083. if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg))
  1084. break;
  1085. SrcReg = NextReg;
  1086. }
  1087. return SrcReg;
  1088. }
  1089. static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
  1090. MachineBasicBlock *&PredMBB,
  1091. MachineBasicBlock *&MBBtoMoveCmp,
  1092. MachineRegisterInfo *MRI) {
  1093. auto isEligibleBB = [&](MachineBasicBlock &BB) {
  1094. auto BII = BB.getFirstInstrTerminator();
  1095. // We optimize BBs ending with a conditional branch.
  1096. // We check only for BCC here, not BCCLR, because BCCLR
  1097. // will be formed only later in the pipeline.
  1098. if (BB.succ_size() == 2 &&
  1099. BII != BB.instr_end() &&
  1100. (*BII).getOpcode() == PPC::BCC &&
  1101. (*BII).getOperand(1).isReg()) {
  1102. // We optimize only if the condition code is used only by one BCC.
  1103. Register CndReg = (*BII).getOperand(1).getReg();
  1104. if (!Register::isVirtualRegister(CndReg) || !MRI->hasOneNonDBGUse(CndReg))
  1105. return false;
  1106. MachineInstr *CMPI = MRI->getVRegDef(CndReg);
  1107. // We assume compare and branch are in the same BB for ease of analysis.
  1108. if (CMPI->getParent() != &BB)
  1109. return false;
  1110. // We skip this BB if a physical register is used in comparison.
  1111. for (MachineOperand &MO : CMPI->operands())
  1112. if (MO.isReg() && !Register::isVirtualRegister(MO.getReg()))
  1113. return false;
  1114. return true;
  1115. }
  1116. return false;
  1117. };
  1118. // If this BB has more than one successor, we can create a new BB and
  1119. // move the compare instruction in the new BB.
  1120. // So far, we do not move compare instruction to a BB having multiple
  1121. // successors to avoid potentially increasing code size.
  1122. auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
  1123. return BB.succ_size() == 1;
  1124. };
  1125. if (!isEligibleBB(MBB))
  1126. return false;
  1127. unsigned NumPredBBs = MBB.pred_size();
  1128. if (NumPredBBs == 1) {
  1129. MachineBasicBlock *TmpMBB = *MBB.pred_begin();
  1130. if (isEligibleBB(*TmpMBB)) {
  1131. PredMBB = TmpMBB;
  1132. MBBtoMoveCmp = nullptr;
  1133. return true;
  1134. }
  1135. }
  1136. else if (NumPredBBs == 2) {
  1137. // We check for partially redundant case.
  1138. // So far, we support cases with only two predecessors
  1139. // to avoid increasing the number of instructions.
  1140. MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
  1141. MachineBasicBlock *Pred1MBB = *PI;
  1142. MachineBasicBlock *Pred2MBB = *(PI+1);
  1143. if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
  1144. // We assume Pred1MBB is the BB containing the compare to be merged and
  1145. // Pred2MBB is the BB to which we will append a compare instruction.
  1146. // Hence we can proceed as is.
  1147. }
  1148. else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
  1149. // We need to swap Pred1MBB and Pred2MBB to canonicalize.
  1150. std::swap(Pred1MBB, Pred2MBB);
  1151. }
  1152. else return false;
  1153. // Here, Pred2MBB is the BB to which we need to append a compare inst.
  1154. // We cannot move the compare instruction if operands are not available
  1155. // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
  1156. MachineInstr *BI = &*MBB.getFirstInstrTerminator();
  1157. MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
  1158. for (int I = 1; I <= 2; I++)
  1159. if (CMPI->getOperand(I).isReg()) {
  1160. MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
  1161. if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
  1162. return false;
  1163. }
  1164. PredMBB = Pred1MBB;
  1165. MBBtoMoveCmp = Pred2MBB;
  1166. return true;
  1167. }
  1168. return false;
  1169. }
  1170. // This function will iterate over the input map containing a pair of TOC save
  1171. // instruction and a flag. The flag will be set to false if the TOC save is
  1172. // proven redundant. This function will erase from the basic block all the TOC
  1173. // saves marked as redundant.
  1174. bool PPCMIPeephole::eliminateRedundantTOCSaves(
  1175. std::map<MachineInstr *, bool> &TOCSaves) {
  1176. bool Simplified = false;
  1177. int NumKept = 0;
  1178. for (auto TOCSave : TOCSaves) {
  1179. if (!TOCSave.second) {
  1180. TOCSave.first->eraseFromParent();
  1181. RemoveTOCSave++;
  1182. Simplified = true;
  1183. } else {
  1184. NumKept++;
  1185. }
  1186. }
  1187. if (NumKept > 1)
  1188. MultiTOCSaves++;
  1189. return Simplified;
  1190. }
  1191. // If multiple conditional branches are executed based on the (essentially)
  1192. // same comparison, we merge compare instructions into one and make multiple
  1193. // conditional branches on this comparison.
  1194. // For example,
  1195. // if (a == 0) { ... }
  1196. // else if (a < 0) { ... }
  1197. // can be executed by one compare and two conditional branches instead of
  1198. // two pairs of a compare and a conditional branch.
  1199. //
  1200. // This method merges two compare instructions in two MBBs and modifies the
  1201. // compare and conditional branch instructions if needed.
  1202. // For the above example, the input for this pass looks like:
  1203. // cmplwi r3, 0
  1204. // beq 0, .LBB0_3
  1205. // cmpwi r3, -1
  1206. // bgt 0, .LBB0_4
  1207. // So, before merging two compares, we need to modify these instructions as
  1208. // cmpwi r3, 0 ; cmplwi and cmpwi yield same result for beq
  1209. // beq 0, .LBB0_3
  1210. // cmpwi r3, 0 ; greather than -1 means greater or equal to 0
  1211. // bge 0, .LBB0_4
  1212. bool PPCMIPeephole::eliminateRedundantCompare() {
  1213. bool Simplified = false;
  1214. for (MachineBasicBlock &MBB2 : *MF) {
  1215. MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
  1216. // For fully redundant case, we select two basic blocks MBB1 and MBB2
  1217. // as an optimization target if
  1218. // - both MBBs end with a conditional branch,
  1219. // - MBB1 is the only predecessor of MBB2, and
  1220. // - compare does not take a physical register as a operand in both MBBs.
  1221. // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
  1222. //
  1223. // As partially redundant case, we additionally handle if MBB2 has one
  1224. // additional predecessor, which has only one successor (MBB2).
  1225. // In this case, we move the compare instruction originally in MBB2 into
  1226. // MBBtoMoveCmp. This partially redundant case is typically appear by
  1227. // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
  1228. //
  1229. // Overview of CFG of related basic blocks
  1230. // Fully redundant case Partially redundant case
  1231. // -------- ---------------- --------
  1232. // | MBB1 | (w/ 2 succ) | MBBtoMoveCmp | | MBB1 | (w/ 2 succ)
  1233. // -------- ---------------- --------
  1234. // | \ (w/ 1 succ) \ | \
  1235. // | \ \ | \
  1236. // | \ |
  1237. // -------- --------
  1238. // | MBB2 | (w/ 1 pred | MBB2 | (w/ 2 pred
  1239. // -------- and 2 succ) -------- and 2 succ)
  1240. // | \ | \
  1241. // | \ | \
  1242. //
  1243. if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
  1244. continue;
  1245. MachineInstr *BI1 = &*MBB1->getFirstInstrTerminator();
  1246. MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
  1247. MachineInstr *BI2 = &*MBB2.getFirstInstrTerminator();
  1248. MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
  1249. bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
  1250. // We cannot optimize an unsupported compare opcode or
  1251. // a mix of 32-bit and 64-bit comaprisons
  1252. if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
  1253. !isSupportedCmpOp(CMPI2->getOpcode()) ||
  1254. is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
  1255. continue;
  1256. unsigned NewOpCode = 0;
  1257. unsigned NewPredicate1 = 0, NewPredicate2 = 0;
  1258. int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
  1259. bool SwapOperands = false;
  1260. if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
  1261. // Typically, unsigned comparison is used for equality check, but
  1262. // we replace it with a signed comparison if the comparison
  1263. // to be merged is a signed comparison.
  1264. // In other cases of opcode mismatch, we cannot optimize this.
  1265. // We cannot change opcode when comparing against an immediate
  1266. // if the most significant bit of the immediate is one
  1267. // due to the difference in sign extension.
  1268. auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
  1269. if (!I->getOperand(2).isImm())
  1270. return false;
  1271. int16_t Imm = (int16_t)I->getOperand(2).getImm();
  1272. return Imm < 0;
  1273. };
  1274. if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
  1275. CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
  1276. NewOpCode = CMPI1->getOpcode();
  1277. else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
  1278. getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
  1279. NewOpCode = CMPI2->getOpcode();
  1280. else continue;
  1281. }
  1282. if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
  1283. // In case of comparisons between two registers, these two registers
  1284. // must be same to merge two comparisons.
  1285. unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
  1286. nullptr, nullptr, MRI);
  1287. unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
  1288. nullptr, nullptr, MRI);
  1289. unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
  1290. MBB1, &MBB2, MRI);
  1291. unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
  1292. MBB1, &MBB2, MRI);
  1293. if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
  1294. // Same pair of registers in the same order; ready to merge as is.
  1295. }
  1296. else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
  1297. // Same pair of registers in different order.
  1298. // We reverse the predicate to merge compare instructions.
  1299. PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
  1300. NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
  1301. // In case of partial redundancy, we need to swap operands
  1302. // in another compare instruction.
  1303. SwapOperands = true;
  1304. }
  1305. else continue;
  1306. }
  1307. else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
  1308. // In case of comparisons between a register and an immediate,
  1309. // the operand register must be same for two compare instructions.
  1310. unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
  1311. nullptr, nullptr, MRI);
  1312. unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
  1313. MBB1, &MBB2, MRI);
  1314. if (Cmp1Operand1 != Cmp2Operand1)
  1315. continue;
  1316. NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
  1317. NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
  1318. // If immediate are not same, we try to adjust by changing predicate;
  1319. // e.g. GT imm means GE (imm+1).
  1320. if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
  1321. int Diff = Imm1 - Imm2;
  1322. if (Diff < -2 || Diff > 2)
  1323. continue;
  1324. unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
  1325. unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
  1326. unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
  1327. unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
  1328. if (Diff == 2) {
  1329. if (PredToInc2 && PredToDec1) {
  1330. NewPredicate2 = PredToInc2;
  1331. NewPredicate1 = PredToDec1;
  1332. NewImm2++;
  1333. NewImm1--;
  1334. }
  1335. }
  1336. else if (Diff == 1) {
  1337. if (PredToInc2) {
  1338. NewImm2++;
  1339. NewPredicate2 = PredToInc2;
  1340. }
  1341. else if (PredToDec1) {
  1342. NewImm1--;
  1343. NewPredicate1 = PredToDec1;
  1344. }
  1345. }
  1346. else if (Diff == -1) {
  1347. if (PredToDec2) {
  1348. NewImm2--;
  1349. NewPredicate2 = PredToDec2;
  1350. }
  1351. else if (PredToInc1) {
  1352. NewImm1++;
  1353. NewPredicate1 = PredToInc1;
  1354. }
  1355. }
  1356. else if (Diff == -2) {
  1357. if (PredToDec2 && PredToInc1) {
  1358. NewPredicate2 = PredToDec2;
  1359. NewPredicate1 = PredToInc1;
  1360. NewImm2--;
  1361. NewImm1++;
  1362. }
  1363. }
  1364. }
  1365. // We cannot merge two compares if the immediates are not same.
  1366. if (NewImm2 != NewImm1)
  1367. continue;
  1368. }
  1369. LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
  1370. LLVM_DEBUG(CMPI1->dump());
  1371. LLVM_DEBUG(BI1->dump());
  1372. LLVM_DEBUG(CMPI2->dump());
  1373. LLVM_DEBUG(BI2->dump());
  1374. // We adjust opcode, predicates and immediate as we determined above.
  1375. if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
  1376. CMPI1->setDesc(TII->get(NewOpCode));
  1377. }
  1378. if (NewPredicate1) {
  1379. BI1->getOperand(0).setImm(NewPredicate1);
  1380. }
  1381. if (NewPredicate2) {
  1382. BI2->getOperand(0).setImm(NewPredicate2);
  1383. }
  1384. if (NewImm1 != Imm1) {
  1385. CMPI1->getOperand(2).setImm(NewImm1);
  1386. }
  1387. if (IsPartiallyRedundant) {
  1388. // We touch up the compare instruction in MBB2 and move it to
  1389. // a previous BB to handle partially redundant case.
  1390. if (SwapOperands) {
  1391. Register Op1 = CMPI2->getOperand(1).getReg();
  1392. Register Op2 = CMPI2->getOperand(2).getReg();
  1393. CMPI2->getOperand(1).setReg(Op2);
  1394. CMPI2->getOperand(2).setReg(Op1);
  1395. }
  1396. if (NewImm2 != Imm2)
  1397. CMPI2->getOperand(2).setImm(NewImm2);
  1398. for (int I = 1; I <= 2; I++) {
  1399. if (CMPI2->getOperand(I).isReg()) {
  1400. MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
  1401. if (Inst->getParent() != &MBB2)
  1402. continue;
  1403. assert(Inst->getOpcode() == PPC::PHI &&
  1404. "We cannot support if an operand comes from this BB.");
  1405. unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
  1406. CMPI2->getOperand(I).setReg(SrcReg);
  1407. }
  1408. }
  1409. auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
  1410. MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
  1411. DebugLoc DL = CMPI2->getDebugLoc();
  1412. Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
  1413. BuildMI(MBB2, MBB2.begin(), DL,
  1414. TII->get(PPC::PHI), NewVReg)
  1415. .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
  1416. .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
  1417. BI2->getOperand(1).setReg(NewVReg);
  1418. }
  1419. else {
  1420. // We finally eliminate compare instruction in MBB2.
  1421. BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
  1422. CMPI2->eraseFromParent();
  1423. }
  1424. BI2->getOperand(1).setIsKill(true);
  1425. BI1->getOperand(1).setIsKill(false);
  1426. LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
  1427. LLVM_DEBUG(CMPI1->dump());
  1428. LLVM_DEBUG(BI1->dump());
  1429. LLVM_DEBUG(BI2->dump());
  1430. if (IsPartiallyRedundant) {
  1431. LLVM_DEBUG(dbgs() << "The following compare is moved into "
  1432. << printMBBReference(*MBBtoMoveCmp)
  1433. << " to handle partial redundancy.\n");
  1434. LLVM_DEBUG(CMPI2->dump());
  1435. }
  1436. Simplified = true;
  1437. }
  1438. return Simplified;
  1439. }
  1440. // We miss the opportunity to emit an RLDIC when lowering jump tables
  1441. // since ISEL sees only a single basic block. When selecting, the clear
  1442. // and shift left will be in different blocks.
  1443. bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI) {
  1444. if (MI.getOpcode() != PPC::RLDICR)
  1445. return false;
  1446. Register SrcReg = MI.getOperand(1).getReg();
  1447. if (!Register::isVirtualRegister(SrcReg))
  1448. return false;
  1449. MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
  1450. if (SrcMI->getOpcode() != PPC::RLDICL)
  1451. return false;
  1452. MachineOperand MOpSHSrc = SrcMI->getOperand(2);
  1453. MachineOperand MOpMBSrc = SrcMI->getOperand(3);
  1454. MachineOperand MOpSHMI = MI.getOperand(2);
  1455. MachineOperand MOpMEMI = MI.getOperand(3);
  1456. if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() &&
  1457. MOpMEMI.isImm()))
  1458. return false;
  1459. uint64_t SHSrc = MOpSHSrc.getImm();
  1460. uint64_t MBSrc = MOpMBSrc.getImm();
  1461. uint64_t SHMI = MOpSHMI.getImm();
  1462. uint64_t MEMI = MOpMEMI.getImm();
  1463. uint64_t NewSH = SHSrc + SHMI;
  1464. uint64_t NewMB = MBSrc - SHMI;
  1465. if (NewMB > 63 || NewSH > 63)
  1466. return false;
  1467. // The bits cleared with RLDICL are [0, MBSrc).
  1468. // The bits cleared with RLDICR are (MEMI, 63].
  1469. // After the sequence, the bits cleared are:
  1470. // [0, MBSrc-SHMI) and (MEMI, 63).
  1471. //
  1472. // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63].
  1473. if ((63 - NewSH) != MEMI)
  1474. return false;
  1475. LLVM_DEBUG(dbgs() << "Converting pair: ");
  1476. LLVM_DEBUG(SrcMI->dump());
  1477. LLVM_DEBUG(MI.dump());
  1478. MI.setDesc(TII->get(PPC::RLDIC));
  1479. MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
  1480. MI.getOperand(2).setImm(NewSH);
  1481. MI.getOperand(3).setImm(NewMB);
  1482. MI.getOperand(1).setIsKill(SrcMI->getOperand(1).isKill());
  1483. SrcMI->getOperand(1).setIsKill(false);
  1484. LLVM_DEBUG(dbgs() << "To: ");
  1485. LLVM_DEBUG(MI.dump());
  1486. NumRotatesCollapsed++;
  1487. // If SrcReg has no non-debug use it's safe to delete its def SrcMI.
  1488. if (MRI->use_nodbg_empty(SrcReg)) {
  1489. assert(!SrcMI->hasImplicitDef() &&
  1490. "Not expecting an implicit def with this instr.");
  1491. SrcMI->eraseFromParent();
  1492. }
  1493. return true;
  1494. }
  1495. // For case in LLVM IR
  1496. // entry:
  1497. // %iconv = sext i32 %index to i64
  1498. // br i1 undef label %true, label %false
  1499. // true:
  1500. // %ptr = getelementptr inbounds i32, i32* null, i64 %iconv
  1501. // ...
  1502. // PPCISelLowering::combineSHL fails to combine, because sext and shl are in
  1503. // different BBs when conducting instruction selection. We can do a peephole
  1504. // optimization to combine these two instructions into extswsli after
  1505. // instruction selection.
  1506. bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI,
  1507. MachineInstr *&ToErase) {
  1508. if (MI.getOpcode() != PPC::RLDICR)
  1509. return false;
  1510. if (!MF->getSubtarget<PPCSubtarget>().isISA3_0())
  1511. return false;
  1512. assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands");
  1513. MachineOperand MOpSHMI = MI.getOperand(2);
  1514. MachineOperand MOpMEMI = MI.getOperand(3);
  1515. if (!(MOpSHMI.isImm() && MOpMEMI.isImm()))
  1516. return false;
  1517. uint64_t SHMI = MOpSHMI.getImm();
  1518. uint64_t MEMI = MOpMEMI.getImm();
  1519. if (SHMI + MEMI != 63)
  1520. return false;
  1521. Register SrcReg = MI.getOperand(1).getReg();
  1522. if (!Register::isVirtualRegister(SrcReg))
  1523. return false;
  1524. MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
  1525. if (SrcMI->getOpcode() != PPC::EXTSW &&
  1526. SrcMI->getOpcode() != PPC::EXTSW_32_64)
  1527. return false;
  1528. // If the register defined by extsw has more than one use, combination is not
  1529. // needed.
  1530. if (!MRI->hasOneNonDBGUse(SrcReg))
  1531. return false;
  1532. assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands");
  1533. assert(SrcMI->getOperand(1).isReg() &&
  1534. "EXTSW's second operand should be a register");
  1535. if (!Register::isVirtualRegister(SrcMI->getOperand(1).getReg()))
  1536. return false;
  1537. LLVM_DEBUG(dbgs() << "Combining pair: ");
  1538. LLVM_DEBUG(SrcMI->dump());
  1539. LLVM_DEBUG(MI.dump());
  1540. MachineInstr *NewInstr =
  1541. BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
  1542. SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI)
  1543. : TII->get(PPC::EXTSWSLI_32_64),
  1544. MI.getOperand(0).getReg())
  1545. .add(SrcMI->getOperand(1))
  1546. .add(MOpSHMI);
  1547. (void)NewInstr;
  1548. LLVM_DEBUG(dbgs() << "TO: ");
  1549. LLVM_DEBUG(NewInstr->dump());
  1550. ++NumEXTSWAndSLDICombined;
  1551. ToErase = &MI;
  1552. // SrcMI, which is extsw, is of no use now, erase it.
  1553. SrcMI->eraseFromParent();
  1554. return true;
  1555. }
  1556. } // end default namespace
  1557. INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
  1558. "PowerPC MI Peephole Optimization", false, false)
  1559. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  1560. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  1561. INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
  1562. INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
  1563. "PowerPC MI Peephole Optimization", false, false)
  1564. char PPCMIPeephole::ID = 0;
  1565. FunctionPass*
  1566. llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }