PPCMIPeephole.cpp 68 KB

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