ExecutionDepsFix.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. //===- ExecutionDepsFix.cpp - Fix execution dependecy issues ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the execution dependency fix pass.
  11. //
  12. // Some X86 SSE instructions like mov, and, or, xor are available in different
  13. // variants for different operand types. These variant instructions are
  14. // equivalent, but on Nehalem and newer cpus there is extra latency
  15. // transferring data between integer and floating point domains. ARM cores
  16. // have similar issues when they are configured with both VFP and NEON
  17. // pipelines.
  18. //
  19. // This pass changes the variant instructions to minimize domain crossings.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/CodeGen/Passes.h"
  23. #include "llvm/ADT/PostOrderIterator.h"
  24. #include "llvm/ADT/iterator_range.h"
  25. #include "llvm/CodeGen/LivePhysRegs.h"
  26. #include "llvm/CodeGen/MachineFunctionPass.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/Support/Allocator.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/Target/TargetInstrInfo.h"
  32. #include "llvm/Target/TargetSubtargetInfo.h"
  33. using namespace llvm;
  34. #define DEBUG_TYPE "execution-fix"
  35. /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
  36. /// of execution domains.
  37. ///
  38. /// An open DomainValue represents a set of instructions that can still switch
  39. /// execution domain. Multiple registers may refer to the same open
  40. /// DomainValue - they will eventually be collapsed to the same execution
  41. /// domain.
  42. ///
  43. /// A collapsed DomainValue represents a single register that has been forced
  44. /// into one of more execution domains. There is a separate collapsed
  45. /// DomainValue for each register, but it may contain multiple execution
  46. /// domains. A register value is initially created in a single execution
  47. /// domain, but if we were forced to pay the penalty of a domain crossing, we
  48. /// keep track of the fact that the register is now available in multiple
  49. /// domains.
  50. namespace {
  51. struct DomainValue {
  52. // Basic reference counting.
  53. unsigned Refs;
  54. // Bitmask of available domains. For an open DomainValue, it is the still
  55. // possible domains for collapsing. For a collapsed DomainValue it is the
  56. // domains where the register is available for free.
  57. unsigned AvailableDomains;
  58. // Pointer to the next DomainValue in a chain. When two DomainValues are
  59. // merged, Victim.Next is set to point to Victor, so old DomainValue
  60. // references can be updated by following the chain.
  61. DomainValue *Next;
  62. // Twiddleable instructions using or defining these registers.
  63. SmallVector<MachineInstr*, 8> Instrs;
  64. // A collapsed DomainValue has no instructions to twiddle - it simply keeps
  65. // track of the domains where the registers are already available.
  66. bool isCollapsed() const { return Instrs.empty(); }
  67. // Is domain available?
  68. bool hasDomain(unsigned domain) const {
  69. assert(domain <
  70. static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
  71. "undefined behavior");
  72. return AvailableDomains & (1u << domain);
  73. }
  74. // Mark domain as available.
  75. void addDomain(unsigned domain) {
  76. AvailableDomains |= 1u << domain;
  77. }
  78. // Restrict to a single domain available.
  79. void setSingleDomain(unsigned domain) {
  80. AvailableDomains = 1u << domain;
  81. }
  82. // Return bitmask of domains that are available and in mask.
  83. unsigned getCommonDomains(unsigned mask) const {
  84. return AvailableDomains & mask;
  85. }
  86. // First domain available.
  87. unsigned getFirstDomain() const {
  88. return countTrailingZeros(AvailableDomains);
  89. }
  90. DomainValue() : Refs(0) { clear(); }
  91. // Clear this DomainValue and point to next which has all its data.
  92. void clear() {
  93. AvailableDomains = 0;
  94. Next = nullptr;
  95. Instrs.clear();
  96. }
  97. };
  98. }
  99. namespace {
  100. /// Information about a live register.
  101. struct LiveReg {
  102. /// Value currently in this register, or NULL when no value is being tracked.
  103. /// This counts as a DomainValue reference.
  104. DomainValue *Value;
  105. /// Instruction that defined this register, relative to the beginning of the
  106. /// current basic block. When a LiveReg is used to represent a live-out
  107. /// register, this value is relative to the end of the basic block, so it
  108. /// will be a negative number.
  109. int Def;
  110. };
  111. } // anonymous namespace
  112. namespace {
  113. class ExeDepsFix : public MachineFunctionPass {
  114. static char ID;
  115. SpecificBumpPtrAllocator<DomainValue> Allocator;
  116. SmallVector<DomainValue*,16> Avail;
  117. const TargetRegisterClass *const RC;
  118. MachineFunction *MF;
  119. const TargetInstrInfo *TII;
  120. const TargetRegisterInfo *TRI;
  121. std::vector<SmallVector<int, 1>> AliasMap;
  122. const unsigned NumRegs;
  123. LiveReg *LiveRegs;
  124. typedef DenseMap<MachineBasicBlock*, LiveReg*> LiveOutMap;
  125. LiveOutMap LiveOuts;
  126. /// List of undefined register reads in this block in forward order.
  127. std::vector<std::pair<MachineInstr*, unsigned> > UndefReads;
  128. /// Storage for register unit liveness.
  129. LivePhysRegs LiveRegSet;
  130. /// Current instruction number.
  131. /// The first instruction in each basic block is 0.
  132. int CurInstr;
  133. /// True when the current block has a predecessor that hasn't been visited
  134. /// yet.
  135. bool SeenUnknownBackEdge;
  136. public:
  137. ExeDepsFix(const TargetRegisterClass *rc)
  138. : MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
  139. void getAnalysisUsage(AnalysisUsage &AU) const override {
  140. AU.setPreservesAll();
  141. MachineFunctionPass::getAnalysisUsage(AU);
  142. }
  143. bool runOnMachineFunction(MachineFunction &MF) override;
  144. const char *getPassName() const override {
  145. return "Execution dependency fix";
  146. }
  147. private:
  148. iterator_range<SmallVectorImpl<int>::const_iterator>
  149. regIndices(unsigned Reg) const;
  150. // DomainValue allocation.
  151. DomainValue *alloc(int domain = -1);
  152. DomainValue *retain(DomainValue *DV) {
  153. if (DV) ++DV->Refs;
  154. return DV;
  155. }
  156. void release(DomainValue*);
  157. DomainValue *resolve(DomainValue*&);
  158. // LiveRegs manipulations.
  159. void setLiveReg(int rx, DomainValue *DV);
  160. void kill(int rx);
  161. void force(int rx, unsigned domain);
  162. void collapse(DomainValue *dv, unsigned domain);
  163. bool merge(DomainValue *A, DomainValue *B);
  164. void enterBasicBlock(MachineBasicBlock*);
  165. void leaveBasicBlock(MachineBasicBlock*);
  166. void visitInstr(MachineInstr*);
  167. void processDefs(MachineInstr*, bool Kill);
  168. void visitSoftInstr(MachineInstr*, unsigned mask);
  169. void visitHardInstr(MachineInstr*, unsigned domain);
  170. bool shouldBreakDependence(MachineInstr*, unsigned OpIdx, unsigned Pref);
  171. void processUndefReads(MachineBasicBlock*);
  172. };
  173. }
  174. char ExeDepsFix::ID = 0;
  175. /// Translate TRI register number to a list of indices into our smaller tables
  176. /// of interesting registers.
  177. iterator_range<SmallVectorImpl<int>::const_iterator>
  178. ExeDepsFix::regIndices(unsigned Reg) const {
  179. assert(Reg < AliasMap.size() && "Invalid register");
  180. const auto &Entry = AliasMap[Reg];
  181. return make_range(Entry.begin(), Entry.end());
  182. }
  183. DomainValue *ExeDepsFix::alloc(int domain) {
  184. DomainValue *dv = Avail.empty() ?
  185. new(Allocator.Allocate()) DomainValue :
  186. Avail.pop_back_val();
  187. if (domain >= 0)
  188. dv->addDomain(domain);
  189. assert(dv->Refs == 0 && "Reference count wasn't cleared");
  190. assert(!dv->Next && "Chained DomainValue shouldn't have been recycled");
  191. return dv;
  192. }
  193. /// Release a reference to DV. When the last reference is released,
  194. /// collapse if needed.
  195. void ExeDepsFix::release(DomainValue *DV) {
  196. while (DV) {
  197. assert(DV->Refs && "Bad DomainValue");
  198. if (--DV->Refs)
  199. return;
  200. // There are no more DV references. Collapse any contained instructions.
  201. if (DV->AvailableDomains && !DV->isCollapsed())
  202. collapse(DV, DV->getFirstDomain());
  203. DomainValue *Next = DV->Next;
  204. DV->clear();
  205. Avail.push_back(DV);
  206. // Also release the next DomainValue in the chain.
  207. DV = Next;
  208. }
  209. }
  210. /// Follow the chain of dead DomainValues until a live DomainValue is reached.
  211. /// Update the referenced pointer when necessary.
  212. DomainValue *ExeDepsFix::resolve(DomainValue *&DVRef) {
  213. DomainValue *DV = DVRef;
  214. if (!DV || !DV->Next)
  215. return DV;
  216. // DV has a chain. Find the end.
  217. do DV = DV->Next;
  218. while (DV->Next);
  219. // Update DVRef to point to DV.
  220. retain(DV);
  221. release(DVRef);
  222. DVRef = DV;
  223. return DV;
  224. }
  225. /// Set LiveRegs[rx] = dv, updating reference counts.
  226. void ExeDepsFix::setLiveReg(int rx, DomainValue *dv) {
  227. assert(unsigned(rx) < NumRegs && "Invalid index");
  228. assert(LiveRegs && "Must enter basic block first.");
  229. if (LiveRegs[rx].Value == dv)
  230. return;
  231. if (LiveRegs[rx].Value)
  232. release(LiveRegs[rx].Value);
  233. LiveRegs[rx].Value = retain(dv);
  234. }
  235. // Kill register rx, recycle or collapse any DomainValue.
  236. void ExeDepsFix::kill(int rx) {
  237. assert(unsigned(rx) < NumRegs && "Invalid index");
  238. assert(LiveRegs && "Must enter basic block first.");
  239. if (!LiveRegs[rx].Value)
  240. return;
  241. release(LiveRegs[rx].Value);
  242. LiveRegs[rx].Value = nullptr;
  243. }
  244. /// Force register rx into domain.
  245. void ExeDepsFix::force(int rx, unsigned domain) {
  246. assert(unsigned(rx) < NumRegs && "Invalid index");
  247. assert(LiveRegs && "Must enter basic block first.");
  248. if (DomainValue *dv = LiveRegs[rx].Value) {
  249. if (dv->isCollapsed())
  250. dv->addDomain(domain);
  251. else if (dv->hasDomain(domain))
  252. collapse(dv, domain);
  253. else {
  254. // This is an incompatible open DomainValue. Collapse it to whatever and
  255. // force the new value into domain. This costs a domain crossing.
  256. collapse(dv, dv->getFirstDomain());
  257. assert(LiveRegs[rx].Value && "Not live after collapse?");
  258. LiveRegs[rx].Value->addDomain(domain);
  259. }
  260. } else {
  261. // Set up basic collapsed DomainValue.
  262. setLiveReg(rx, alloc(domain));
  263. }
  264. }
  265. /// Collapse open DomainValue into given domain. If there are multiple
  266. /// registers using dv, they each get a unique collapsed DomainValue.
  267. void ExeDepsFix::collapse(DomainValue *dv, unsigned domain) {
  268. assert(dv->hasDomain(domain) && "Cannot collapse");
  269. // Collapse all the instructions.
  270. while (!dv->Instrs.empty())
  271. TII->setExecutionDomain(dv->Instrs.pop_back_val(), domain);
  272. dv->setSingleDomain(domain);
  273. // If there are multiple users, give them new, unique DomainValues.
  274. if (LiveRegs && dv->Refs > 1)
  275. for (unsigned rx = 0; rx != NumRegs; ++rx)
  276. if (LiveRegs[rx].Value == dv)
  277. setLiveReg(rx, alloc(domain));
  278. }
  279. /// All instructions and registers in B are moved to A, and B is released.
  280. bool ExeDepsFix::merge(DomainValue *A, DomainValue *B) {
  281. assert(!A->isCollapsed() && "Cannot merge into collapsed");
  282. assert(!B->isCollapsed() && "Cannot merge from collapsed");
  283. if (A == B)
  284. return true;
  285. // Restrict to the domains that A and B have in common.
  286. unsigned common = A->getCommonDomains(B->AvailableDomains);
  287. if (!common)
  288. return false;
  289. A->AvailableDomains = common;
  290. A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
  291. // Clear the old DomainValue so we won't try to swizzle instructions twice.
  292. B->clear();
  293. // All uses of B are referred to A.
  294. B->Next = retain(A);
  295. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  296. assert(LiveRegs && "no space allocated for live registers");
  297. if (LiveRegs[rx].Value == B)
  298. setLiveReg(rx, A);
  299. }
  300. return true;
  301. }
  302. /// Set up LiveRegs by merging predecessor live-out values.
  303. void ExeDepsFix::enterBasicBlock(MachineBasicBlock *MBB) {
  304. // Detect back-edges from predecessors we haven't processed yet.
  305. SeenUnknownBackEdge = false;
  306. // Reset instruction counter in each basic block.
  307. CurInstr = 0;
  308. // Set up UndefReads to track undefined register reads.
  309. UndefReads.clear();
  310. LiveRegSet.clear();
  311. // Set up LiveRegs to represent registers entering MBB.
  312. if (!LiveRegs)
  313. LiveRegs = new LiveReg[NumRegs];
  314. // Default values are 'nothing happened a long time ago'.
  315. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  316. LiveRegs[rx].Value = nullptr;
  317. LiveRegs[rx].Def = -(1 << 20);
  318. }
  319. // This is the entry block.
  320. if (MBB->pred_empty()) {
  321. for (MachineBasicBlock::livein_iterator i = MBB->livein_begin(),
  322. e = MBB->livein_end(); i != e; ++i) {
  323. for (int rx : regIndices(*i)) {
  324. // Treat function live-ins as if they were defined just before the first
  325. // instruction. Usually, function arguments are set up immediately
  326. // before the call.
  327. LiveRegs[rx].Def = -1;
  328. }
  329. }
  330. DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": entry\n");
  331. return;
  332. }
  333. // Try to coalesce live-out registers from predecessors.
  334. for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
  335. pe = MBB->pred_end(); pi != pe; ++pi) {
  336. LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
  337. if (fi == LiveOuts.end()) {
  338. SeenUnknownBackEdge = true;
  339. continue;
  340. }
  341. assert(fi->second && "Can't have NULL entries");
  342. for (unsigned rx = 0; rx != NumRegs; ++rx) {
  343. // Use the most recent predecessor def for each register.
  344. LiveRegs[rx].Def = std::max(LiveRegs[rx].Def, fi->second[rx].Def);
  345. DomainValue *pdv = resolve(fi->second[rx].Value);
  346. if (!pdv)
  347. continue;
  348. if (!LiveRegs[rx].Value) {
  349. setLiveReg(rx, pdv);
  350. continue;
  351. }
  352. // We have a live DomainValue from more than one predecessor.
  353. if (LiveRegs[rx].Value->isCollapsed()) {
  354. // We are already collapsed, but predecessor is not. Force it.
  355. unsigned Domain = LiveRegs[rx].Value->getFirstDomain();
  356. if (!pdv->isCollapsed() && pdv->hasDomain(Domain))
  357. collapse(pdv, Domain);
  358. continue;
  359. }
  360. // Currently open, merge in predecessor.
  361. if (!pdv->isCollapsed())
  362. merge(LiveRegs[rx].Value, pdv);
  363. else
  364. force(rx, pdv->getFirstDomain());
  365. }
  366. }
  367. DEBUG(dbgs() << "BB#" << MBB->getNumber()
  368. << (SeenUnknownBackEdge ? ": incomplete\n" : ": all preds known\n"));
  369. }
  370. void ExeDepsFix::leaveBasicBlock(MachineBasicBlock *MBB) {
  371. assert(LiveRegs && "Must enter basic block first.");
  372. // Save live registers at end of MBB - used by enterBasicBlock().
  373. // Also use LiveOuts as a visited set to detect back-edges.
  374. bool First = LiveOuts.insert(std::make_pair(MBB, LiveRegs)).second;
  375. if (First) {
  376. // LiveRegs was inserted in LiveOuts. Adjust all defs to be relative to
  377. // the end of this block instead of the beginning.
  378. for (unsigned i = 0, e = NumRegs; i != e; ++i)
  379. LiveRegs[i].Def -= CurInstr;
  380. } else {
  381. // Insertion failed, this must be the second pass.
  382. // Release all the DomainValues instead of keeping them.
  383. for (unsigned i = 0, e = NumRegs; i != e; ++i)
  384. release(LiveRegs[i].Value);
  385. delete[] LiveRegs;
  386. }
  387. LiveRegs = nullptr;
  388. }
  389. void ExeDepsFix::visitInstr(MachineInstr *MI) {
  390. if (MI->isDebugValue())
  391. return;
  392. // Update instructions with explicit execution domains.
  393. std::pair<uint16_t, uint16_t> DomP = TII->getExecutionDomain(MI);
  394. if (DomP.first) {
  395. if (DomP.second)
  396. visitSoftInstr(MI, DomP.second);
  397. else
  398. visitHardInstr(MI, DomP.first);
  399. }
  400. // Process defs to track register ages, and kill values clobbered by generic
  401. // instructions.
  402. processDefs(MI, !DomP.first);
  403. }
  404. /// \brief Return true to if it makes sense to break dependence on a partial def
  405. /// or undef use.
  406. bool ExeDepsFix::shouldBreakDependence(MachineInstr *MI, unsigned OpIdx,
  407. unsigned Pref) {
  408. unsigned reg = MI->getOperand(OpIdx).getReg();
  409. for (int rx : regIndices(reg)) {
  410. unsigned Clearance = CurInstr - LiveRegs[rx].Def;
  411. DEBUG(dbgs() << "Clearance: " << Clearance << ", want " << Pref);
  412. if (Pref > Clearance) {
  413. DEBUG(dbgs() << ": Break dependency.\n");
  414. continue;
  415. }
  416. // The current clearance seems OK, but we may be ignoring a def from a
  417. // back-edge.
  418. if (!SeenUnknownBackEdge || Pref <= unsigned(CurInstr)) {
  419. DEBUG(dbgs() << ": OK .\n");
  420. return false;
  421. }
  422. // A def from an unprocessed back-edge may make us break this dependency.
  423. DEBUG(dbgs() << ": Wait for back-edge to resolve.\n");
  424. return false;
  425. }
  426. return true;
  427. }
  428. // Update def-ages for registers defined by MI.
  429. // If Kill is set, also kill off DomainValues clobbered by the defs.
  430. //
  431. // Also break dependencies on partial defs and undef uses.
  432. void ExeDepsFix::processDefs(MachineInstr *MI, bool Kill) {
  433. assert(!MI->isDebugValue() && "Won't process debug values");
  434. // Break dependence on undef uses. Do this before updating LiveRegs below.
  435. unsigned OpNum;
  436. unsigned Pref = TII->getUndefRegClearance(MI, OpNum, TRI);
  437. if (Pref) {
  438. if (shouldBreakDependence(MI, OpNum, Pref))
  439. UndefReads.push_back(std::make_pair(MI, OpNum));
  440. }
  441. const MCInstrDesc &MCID = MI->getDesc();
  442. for (unsigned i = 0,
  443. e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
  444. i != e; ++i) {
  445. MachineOperand &MO = MI->getOperand(i);
  446. if (!MO.isReg())
  447. continue;
  448. if (MO.isImplicit())
  449. break;
  450. if (MO.isUse())
  451. continue;
  452. for (int rx : regIndices(MO.getReg())) {
  453. // This instruction explicitly defines rx.
  454. DEBUG(dbgs() << TRI->getName(RC->getRegister(rx)) << ":\t" << CurInstr
  455. << '\t' << *MI);
  456. // Check clearance before partial register updates.
  457. // Call breakDependence before setting LiveRegs[rx].Def.
  458. unsigned Pref = TII->getPartialRegUpdateClearance(MI, i, TRI);
  459. if (Pref && shouldBreakDependence(MI, i, Pref))
  460. TII->breakPartialRegDependency(MI, i, TRI);
  461. // How many instructions since rx was last written?
  462. LiveRegs[rx].Def = CurInstr;
  463. // Kill off domains redefined by generic instructions.
  464. if (Kill)
  465. kill(rx);
  466. }
  467. }
  468. ++CurInstr;
  469. }
  470. /// \break Break false dependencies on undefined register reads.
  471. ///
  472. /// Walk the block backward computing precise liveness. This is expensive, so we
  473. /// only do it on demand. Note that the occurrence of undefined register reads
  474. /// that should be broken is very rare, but when they occur we may have many in
  475. /// a single block.
  476. void ExeDepsFix::processUndefReads(MachineBasicBlock *MBB) {
  477. if (UndefReads.empty())
  478. return;
  479. // Collect this block's live out register units.
  480. LiveRegSet.init(TRI);
  481. LiveRegSet.addLiveOuts(MBB);
  482. MachineInstr *UndefMI = UndefReads.back().first;
  483. unsigned OpIdx = UndefReads.back().second;
  484. for (MachineBasicBlock::reverse_iterator I = MBB->rbegin(), E = MBB->rend();
  485. I != E; ++I) {
  486. // Update liveness, including the current instruction's defs.
  487. LiveRegSet.stepBackward(*I);
  488. if (UndefMI == &*I) {
  489. if (!LiveRegSet.contains(UndefMI->getOperand(OpIdx).getReg()))
  490. TII->breakPartialRegDependency(UndefMI, OpIdx, TRI);
  491. UndefReads.pop_back();
  492. if (UndefReads.empty())
  493. return;
  494. UndefMI = UndefReads.back().first;
  495. OpIdx = UndefReads.back().second;
  496. }
  497. }
  498. }
  499. // A hard instruction only works in one domain. All input registers will be
  500. // forced into that domain.
  501. void ExeDepsFix::visitHardInstr(MachineInstr *mi, unsigned domain) {
  502. // Collapse all uses.
  503. for (unsigned i = mi->getDesc().getNumDefs(),
  504. e = mi->getDesc().getNumOperands(); i != e; ++i) {
  505. MachineOperand &mo = mi->getOperand(i);
  506. if (!mo.isReg()) continue;
  507. for (int rx : regIndices(mo.getReg())) {
  508. force(rx, domain);
  509. }
  510. }
  511. // Kill all defs and force them.
  512. for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
  513. MachineOperand &mo = mi->getOperand(i);
  514. if (!mo.isReg()) continue;
  515. for (int rx : regIndices(mo.getReg())) {
  516. kill(rx);
  517. force(rx, domain);
  518. }
  519. }
  520. }
  521. // A soft instruction can be changed to work in other domains given by mask.
  522. void ExeDepsFix::visitSoftInstr(MachineInstr *mi, unsigned mask) {
  523. // Bitmask of available domains for this instruction after taking collapsed
  524. // operands into account.
  525. unsigned available = mask;
  526. // Scan the explicit use operands for incoming domains.
  527. SmallVector<int, 4> used;
  528. if (LiveRegs)
  529. for (unsigned i = mi->getDesc().getNumDefs(),
  530. e = mi->getDesc().getNumOperands(); i != e; ++i) {
  531. MachineOperand &mo = mi->getOperand(i);
  532. if (!mo.isReg()) continue;
  533. for (int rx : regIndices(mo.getReg())) {
  534. DomainValue *dv = LiveRegs[rx].Value;
  535. if (dv == nullptr)
  536. continue;
  537. // Bitmask of domains that dv and available have in common.
  538. unsigned common = dv->getCommonDomains(available);
  539. // Is it possible to use this collapsed register for free?
  540. if (dv->isCollapsed()) {
  541. // Restrict available domains to the ones in common with the operand.
  542. // If there are no common domains, we must pay the cross-domain
  543. // penalty for this operand.
  544. if (common) available = common;
  545. } else if (common)
  546. // Open DomainValue is compatible, save it for merging.
  547. used.push_back(rx);
  548. else
  549. // Open DomainValue is not compatible with instruction. It is useless
  550. // now.
  551. kill(rx);
  552. }
  553. }
  554. // If the collapsed operands force a single domain, propagate the collapse.
  555. if (isPowerOf2_32(available)) {
  556. unsigned domain = countTrailingZeros(available);
  557. TII->setExecutionDomain(mi, domain);
  558. visitHardInstr(mi, domain);
  559. return;
  560. }
  561. // Kill off any remaining uses that don't match available, and build a list of
  562. // incoming DomainValues that we want to merge.
  563. SmallVector<LiveReg, 4> Regs;
  564. for (SmallVectorImpl<int>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
  565. int rx = *i;
  566. assert(LiveRegs && "no space allocated for live registers");
  567. const LiveReg &LR = LiveRegs[rx];
  568. // This useless DomainValue could have been missed above.
  569. if (!LR.Value->getCommonDomains(available)) {
  570. kill(rx);
  571. continue;
  572. }
  573. // Sorted insertion.
  574. bool Inserted = false;
  575. for (SmallVectorImpl<LiveReg>::iterator i = Regs.begin(), e = Regs.end();
  576. i != e && !Inserted; ++i) {
  577. if (LR.Def < i->Def) {
  578. Inserted = true;
  579. Regs.insert(i, LR);
  580. }
  581. }
  582. if (!Inserted)
  583. Regs.push_back(LR);
  584. }
  585. // doms are now sorted in order of appearance. Try to merge them all, giving
  586. // priority to the latest ones.
  587. DomainValue *dv = nullptr;
  588. while (!Regs.empty()) {
  589. if (!dv) {
  590. dv = Regs.pop_back_val().Value;
  591. // Force the first dv to match the current instruction.
  592. dv->AvailableDomains = dv->getCommonDomains(available);
  593. assert(dv->AvailableDomains && "Domain should have been filtered");
  594. continue;
  595. }
  596. DomainValue *Latest = Regs.pop_back_val().Value;
  597. // Skip already merged values.
  598. if (Latest == dv || Latest->Next)
  599. continue;
  600. if (merge(dv, Latest))
  601. continue;
  602. // If latest didn't merge, it is useless now. Kill all registers using it.
  603. for (int i : used) {
  604. assert(LiveRegs && "no space allocated for live registers");
  605. if (LiveRegs[i].Value == Latest)
  606. kill(i);
  607. }
  608. }
  609. // dv is the DomainValue we are going to use for this instruction.
  610. if (!dv) {
  611. dv = alloc();
  612. dv->AvailableDomains = available;
  613. }
  614. dv->Instrs.push_back(mi);
  615. // Finally set all defs and non-collapsed uses to dv. We must iterate through
  616. // all the operators, including imp-def ones.
  617. for (MachineInstr::mop_iterator ii = mi->operands_begin(),
  618. ee = mi->operands_end();
  619. ii != ee; ++ii) {
  620. MachineOperand &mo = *ii;
  621. if (!mo.isReg()) continue;
  622. for (int rx : regIndices(mo.getReg())) {
  623. if (!LiveRegs[rx].Value || (mo.isDef() && LiveRegs[rx].Value != dv)) {
  624. kill(rx);
  625. setLiveReg(rx, dv);
  626. }
  627. }
  628. }
  629. }
  630. bool ExeDepsFix::runOnMachineFunction(MachineFunction &mf) {
  631. MF = &mf;
  632. TII = MF->getSubtarget().getInstrInfo();
  633. TRI = MF->getSubtarget().getRegisterInfo();
  634. LiveRegs = nullptr;
  635. assert(NumRegs == RC->getNumRegs() && "Bad regclass");
  636. DEBUG(dbgs() << "********** FIX EXECUTION DEPENDENCIES: "
  637. << TRI->getRegClassName(RC) << " **********\n");
  638. // If no relevant registers are used in the function, we can skip it
  639. // completely.
  640. bool anyregs = false;
  641. for (TargetRegisterClass::const_iterator I = RC->begin(), E = RC->end();
  642. I != E; ++I)
  643. if (MF->getRegInfo().isPhysRegUsed(*I)) {
  644. anyregs = true;
  645. break;
  646. }
  647. if (!anyregs) return false;
  648. // Initialize the AliasMap on the first use.
  649. if (AliasMap.empty()) {
  650. // Given a PhysReg, AliasMap[PhysReg] returns a list of indices into RC and
  651. // therefore the LiveRegs array.
  652. AliasMap.resize(TRI->getNumRegs());
  653. for (unsigned i = 0, e = RC->getNumRegs(); i != e; ++i)
  654. for (MCRegAliasIterator AI(RC->getRegister(i), TRI, true);
  655. AI.isValid(); ++AI)
  656. AliasMap[*AI].push_back(i);
  657. }
  658. MachineBasicBlock *Entry = MF->begin();
  659. ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
  660. SmallVector<MachineBasicBlock*, 16> Loops;
  661. for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
  662. MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
  663. MachineBasicBlock *MBB = *MBBI;
  664. enterBasicBlock(MBB);
  665. if (SeenUnknownBackEdge)
  666. Loops.push_back(MBB);
  667. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
  668. ++I)
  669. visitInstr(I);
  670. processUndefReads(MBB);
  671. leaveBasicBlock(MBB);
  672. }
  673. // Visit all the loop blocks again in order to merge DomainValues from
  674. // back-edges.
  675. for (unsigned i = 0, e = Loops.size(); i != e; ++i) {
  676. MachineBasicBlock *MBB = Loops[i];
  677. enterBasicBlock(MBB);
  678. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
  679. ++I)
  680. if (!I->isDebugValue())
  681. processDefs(I, false);
  682. processUndefReads(MBB);
  683. leaveBasicBlock(MBB);
  684. }
  685. // Clear the LiveOuts vectors and collapse any remaining DomainValues.
  686. for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
  687. MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
  688. LiveOutMap::const_iterator FI = LiveOuts.find(*MBBI);
  689. if (FI == LiveOuts.end() || !FI->second)
  690. continue;
  691. for (unsigned i = 0, e = NumRegs; i != e; ++i)
  692. if (FI->second[i].Value)
  693. release(FI->second[i].Value);
  694. delete[] FI->second;
  695. }
  696. LiveOuts.clear();
  697. UndefReads.clear();
  698. Avail.clear();
  699. Allocator.DestroyAll();
  700. return false;
  701. }
  702. FunctionPass *
  703. llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
  704. return new ExeDepsFix(RC);
  705. }