ExecutionDepsFix.cpp 26 KB

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