RegisterBankInfo.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. //===- llvm/CodeGen/GlobalISel/RegisterBankInfo.cpp --------------*- C++ -*-==//
  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. /// \file
  9. /// This file implements the RegisterBankInfo class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/RegisterBankInfo.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/ADT/iterator_range.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/RegisterBank.h"
  18. #include "llvm/CodeGen/TargetOpcodes.h"
  19. #include "llvm/CodeGen/TargetRegisterInfo.h"
  20. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <algorithm> // For std::max.
  25. #define DEBUG_TYPE "registerbankinfo"
  26. using namespace llvm;
  27. STATISTIC(NumPartialMappingsCreated,
  28. "Number of partial mappings dynamically created");
  29. STATISTIC(NumPartialMappingsAccessed,
  30. "Number of partial mappings dynamically accessed");
  31. STATISTIC(NumValueMappingsCreated,
  32. "Number of value mappings dynamically created");
  33. STATISTIC(NumValueMappingsAccessed,
  34. "Number of value mappings dynamically accessed");
  35. STATISTIC(NumOperandsMappingsCreated,
  36. "Number of operands mappings dynamically created");
  37. STATISTIC(NumOperandsMappingsAccessed,
  38. "Number of operands mappings dynamically accessed");
  39. STATISTIC(NumInstructionMappingsCreated,
  40. "Number of instruction mappings dynamically created");
  41. STATISTIC(NumInstructionMappingsAccessed,
  42. "Number of instruction mappings dynamically accessed");
  43. const unsigned RegisterBankInfo::DefaultMappingID = UINT_MAX;
  44. const unsigned RegisterBankInfo::InvalidMappingID = UINT_MAX - 1;
  45. //------------------------------------------------------------------------------
  46. // RegisterBankInfo implementation.
  47. //------------------------------------------------------------------------------
  48. RegisterBankInfo::RegisterBankInfo(RegisterBank **RegBanks,
  49. unsigned NumRegBanks)
  50. : RegBanks(RegBanks), NumRegBanks(NumRegBanks) {
  51. #ifndef NDEBUG
  52. for (unsigned Idx = 0, End = getNumRegBanks(); Idx != End; ++Idx) {
  53. assert(RegBanks[Idx] != nullptr && "Invalid RegisterBank");
  54. assert(RegBanks[Idx]->isValid() && "RegisterBank should be valid");
  55. }
  56. #endif // NDEBUG
  57. }
  58. bool RegisterBankInfo::verify(const TargetRegisterInfo &TRI) const {
  59. #ifndef NDEBUG
  60. for (unsigned Idx = 0, End = getNumRegBanks(); Idx != End; ++Idx) {
  61. const RegisterBank &RegBank = getRegBank(Idx);
  62. assert(Idx == RegBank.getID() &&
  63. "ID does not match the index in the array");
  64. LLVM_DEBUG(dbgs() << "Verify " << RegBank << '\n');
  65. assert(RegBank.verify(TRI) && "RegBank is invalid");
  66. }
  67. #endif // NDEBUG
  68. return true;
  69. }
  70. const RegisterBank *
  71. RegisterBankInfo::getRegBank(Register Reg, const MachineRegisterInfo &MRI,
  72. const TargetRegisterInfo &TRI) const {
  73. if (Reg.isPhysical()) {
  74. // FIXME: This was probably a copy to a virtual register that does have a
  75. // type we could use.
  76. return &getRegBankFromRegClass(getMinimalPhysRegClass(Reg, TRI), LLT());
  77. }
  78. assert(Reg && "NoRegister does not have a register bank");
  79. const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
  80. if (auto *RB = RegClassOrBank.dyn_cast<const RegisterBank *>())
  81. return RB;
  82. if (auto *RC = RegClassOrBank.dyn_cast<const TargetRegisterClass *>())
  83. return &getRegBankFromRegClass(*RC, MRI.getType(Reg));
  84. return nullptr;
  85. }
  86. const TargetRegisterClass &
  87. RegisterBankInfo::getMinimalPhysRegClass(Register Reg,
  88. const TargetRegisterInfo &TRI) const {
  89. assert(Reg.isPhysical() && "Reg must be a physreg");
  90. const auto &RegRCIt = PhysRegMinimalRCs.find(Reg);
  91. if (RegRCIt != PhysRegMinimalRCs.end())
  92. return *RegRCIt->second;
  93. const TargetRegisterClass *PhysRC = TRI.getMinimalPhysRegClass(Reg);
  94. PhysRegMinimalRCs[Reg] = PhysRC;
  95. return *PhysRC;
  96. }
  97. const RegisterBank *RegisterBankInfo::getRegBankFromConstraints(
  98. const MachineInstr &MI, unsigned OpIdx, const TargetInstrInfo &TII,
  99. const MachineRegisterInfo &MRI) const {
  100. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  101. // The mapping of the registers may be available via the
  102. // register class constraints.
  103. const TargetRegisterClass *RC = MI.getRegClassConstraint(OpIdx, &TII, TRI);
  104. if (!RC)
  105. return nullptr;
  106. Register Reg = MI.getOperand(OpIdx).getReg();
  107. const RegisterBank &RegBank = getRegBankFromRegClass(*RC, MRI.getType(Reg));
  108. // Check that the target properly implemented getRegBankFromRegClass.
  109. assert(RegBank.covers(*RC) &&
  110. "The mapping of the register bank does not make sense");
  111. return &RegBank;
  112. }
  113. const TargetRegisterClass *RegisterBankInfo::constrainGenericRegister(
  114. Register Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI) {
  115. // If the register already has a class, fallback to MRI::constrainRegClass.
  116. auto &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
  117. if (RegClassOrBank.is<const TargetRegisterClass *>())
  118. return MRI.constrainRegClass(Reg, &RC);
  119. const RegisterBank *RB = RegClassOrBank.get<const RegisterBank *>();
  120. // Otherwise, all we can do is ensure the bank covers the class, and set it.
  121. if (RB && !RB->covers(RC))
  122. return nullptr;
  123. // If nothing was set or the class is simply compatible, set it.
  124. MRI.setRegClass(Reg, &RC);
  125. return &RC;
  126. }
  127. /// Check whether or not \p MI should be treated like a copy
  128. /// for the mappings.
  129. /// Copy like instruction are special for mapping because
  130. /// they don't have actual register constraints. Moreover,
  131. /// they sometimes have register classes assigned and we can
  132. /// just use that instead of failing to provide a generic mapping.
  133. static bool isCopyLike(const MachineInstr &MI) {
  134. return MI.isCopy() || MI.isPHI() ||
  135. MI.getOpcode() == TargetOpcode::REG_SEQUENCE;
  136. }
  137. const RegisterBankInfo::InstructionMapping &
  138. RegisterBankInfo::getInstrMappingImpl(const MachineInstr &MI) const {
  139. // For copies we want to walk over the operands and try to find one
  140. // that has a register bank since the instruction itself will not get
  141. // us any constraint.
  142. bool IsCopyLike = isCopyLike(MI);
  143. // For copy like instruction, only the mapping of the definition
  144. // is important. The rest is not constrained.
  145. unsigned NumOperandsForMapping = IsCopyLike ? 1 : MI.getNumOperands();
  146. const MachineFunction &MF = *MI.getMF();
  147. const TargetSubtargetInfo &STI = MF.getSubtarget();
  148. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  149. const MachineRegisterInfo &MRI = MF.getRegInfo();
  150. // We may need to query the instruction encoding to guess the mapping.
  151. const TargetInstrInfo &TII = *STI.getInstrInfo();
  152. // Before doing anything complicated check if the mapping is not
  153. // directly available.
  154. bool CompleteMapping = true;
  155. SmallVector<const ValueMapping *, 8> OperandsMapping(NumOperandsForMapping);
  156. for (unsigned OpIdx = 0, EndIdx = MI.getNumOperands(); OpIdx != EndIdx;
  157. ++OpIdx) {
  158. const MachineOperand &MO = MI.getOperand(OpIdx);
  159. if (!MO.isReg())
  160. continue;
  161. Register Reg = MO.getReg();
  162. if (!Reg)
  163. continue;
  164. // The register bank of Reg is just a side effect of the current
  165. // excution and in particular, there is no reason to believe this
  166. // is the best default mapping for the current instruction. Keep
  167. // it as an alternative register bank if we cannot figure out
  168. // something.
  169. const RegisterBank *AltRegBank = getRegBank(Reg, MRI, TRI);
  170. // For copy-like instruction, we want to reuse the register bank
  171. // that is already set on Reg, if any, since those instructions do
  172. // not have any constraints.
  173. const RegisterBank *CurRegBank = IsCopyLike ? AltRegBank : nullptr;
  174. if (!CurRegBank) {
  175. // If this is a target specific instruction, we can deduce
  176. // the register bank from the encoding constraints.
  177. CurRegBank = getRegBankFromConstraints(MI, OpIdx, TII, MRI);
  178. if (!CurRegBank) {
  179. // All our attempts failed, give up.
  180. CompleteMapping = false;
  181. if (!IsCopyLike)
  182. // MI does not carry enough information to guess the mapping.
  183. return getInvalidInstructionMapping();
  184. continue;
  185. }
  186. }
  187. unsigned Size = getSizeInBits(Reg, MRI, TRI);
  188. const ValueMapping *ValMapping = &getValueMapping(0, Size, *CurRegBank);
  189. if (IsCopyLike) {
  190. if (!OperandsMapping[0]) {
  191. if (MI.isRegSequence()) {
  192. // For reg_sequence, the result size does not match the input.
  193. unsigned ResultSize = getSizeInBits(MI.getOperand(0).getReg(),
  194. MRI, TRI);
  195. OperandsMapping[0] = &getValueMapping(0, ResultSize, *CurRegBank);
  196. } else {
  197. OperandsMapping[0] = ValMapping;
  198. }
  199. }
  200. // The default handling assumes any register bank can be copied to any
  201. // other. If this isn't the case, the target should specially deal with
  202. // reg_sequence/phi. There may also be unsatisfiable copies.
  203. for (; OpIdx != EndIdx; ++OpIdx) {
  204. const MachineOperand &MO = MI.getOperand(OpIdx);
  205. if (!MO.isReg())
  206. continue;
  207. Register Reg = MO.getReg();
  208. if (!Reg)
  209. continue;
  210. const RegisterBank *AltRegBank = getRegBank(Reg, MRI, TRI);
  211. if (AltRegBank &&
  212. cannotCopy(*CurRegBank, *AltRegBank, getSizeInBits(Reg, MRI, TRI)))
  213. return getInvalidInstructionMapping();
  214. }
  215. CompleteMapping = true;
  216. break;
  217. }
  218. OperandsMapping[OpIdx] = ValMapping;
  219. }
  220. if (IsCopyLike && !CompleteMapping) {
  221. // No way to deduce the type from what we have.
  222. return getInvalidInstructionMapping();
  223. }
  224. assert(CompleteMapping && "Setting an uncomplete mapping");
  225. return getInstructionMapping(
  226. DefaultMappingID, /*Cost*/ 1,
  227. /*OperandsMapping*/ getOperandsMapping(OperandsMapping),
  228. NumOperandsForMapping);
  229. }
  230. /// Hashing function for PartialMapping.
  231. static hash_code hashPartialMapping(unsigned StartIdx, unsigned Length,
  232. const RegisterBank *RegBank) {
  233. return hash_combine(StartIdx, Length, RegBank ? RegBank->getID() : 0);
  234. }
  235. /// Overloaded version of hash_value for a PartialMapping.
  236. hash_code
  237. llvm::hash_value(const RegisterBankInfo::PartialMapping &PartMapping) {
  238. return hashPartialMapping(PartMapping.StartIdx, PartMapping.Length,
  239. PartMapping.RegBank);
  240. }
  241. const RegisterBankInfo::PartialMapping &
  242. RegisterBankInfo::getPartialMapping(unsigned StartIdx, unsigned Length,
  243. const RegisterBank &RegBank) const {
  244. ++NumPartialMappingsAccessed;
  245. hash_code Hash = hashPartialMapping(StartIdx, Length, &RegBank);
  246. const auto &It = MapOfPartialMappings.find(Hash);
  247. if (It != MapOfPartialMappings.end())
  248. return *It->second;
  249. ++NumPartialMappingsCreated;
  250. auto &PartMapping = MapOfPartialMappings[Hash];
  251. PartMapping = std::make_unique<PartialMapping>(StartIdx, Length, RegBank);
  252. return *PartMapping;
  253. }
  254. const RegisterBankInfo::ValueMapping &
  255. RegisterBankInfo::getValueMapping(unsigned StartIdx, unsigned Length,
  256. const RegisterBank &RegBank) const {
  257. return getValueMapping(&getPartialMapping(StartIdx, Length, RegBank), 1);
  258. }
  259. static hash_code
  260. hashValueMapping(const RegisterBankInfo::PartialMapping *BreakDown,
  261. unsigned NumBreakDowns) {
  262. if (LLVM_LIKELY(NumBreakDowns == 1))
  263. return hash_value(*BreakDown);
  264. SmallVector<size_t, 8> Hashes(NumBreakDowns);
  265. for (unsigned Idx = 0; Idx != NumBreakDowns; ++Idx)
  266. Hashes.push_back(hash_value(BreakDown[Idx]));
  267. return hash_combine_range(Hashes.begin(), Hashes.end());
  268. }
  269. const RegisterBankInfo::ValueMapping &
  270. RegisterBankInfo::getValueMapping(const PartialMapping *BreakDown,
  271. unsigned NumBreakDowns) const {
  272. ++NumValueMappingsAccessed;
  273. hash_code Hash = hashValueMapping(BreakDown, NumBreakDowns);
  274. const auto &It = MapOfValueMappings.find(Hash);
  275. if (It != MapOfValueMappings.end())
  276. return *It->second;
  277. ++NumValueMappingsCreated;
  278. auto &ValMapping = MapOfValueMappings[Hash];
  279. ValMapping = std::make_unique<ValueMapping>(BreakDown, NumBreakDowns);
  280. return *ValMapping;
  281. }
  282. template <typename Iterator>
  283. const RegisterBankInfo::ValueMapping *
  284. RegisterBankInfo::getOperandsMapping(Iterator Begin, Iterator End) const {
  285. ++NumOperandsMappingsAccessed;
  286. // The addresses of the value mapping are unique.
  287. // Therefore, we can use them directly to hash the operand mapping.
  288. hash_code Hash = hash_combine_range(Begin, End);
  289. auto &Res = MapOfOperandsMappings[Hash];
  290. if (Res)
  291. return Res.get();
  292. ++NumOperandsMappingsCreated;
  293. // Create the array of ValueMapping.
  294. // Note: this array will not hash to this instance of operands
  295. // mapping, because we use the pointer of the ValueMapping
  296. // to hash and we expect them to uniquely identify an instance
  297. // of value mapping.
  298. Res = std::make_unique<ValueMapping[]>(std::distance(Begin, End));
  299. unsigned Idx = 0;
  300. for (Iterator It = Begin; It != End; ++It, ++Idx) {
  301. const ValueMapping *ValMap = *It;
  302. if (!ValMap)
  303. continue;
  304. Res[Idx] = *ValMap;
  305. }
  306. return Res.get();
  307. }
  308. const RegisterBankInfo::ValueMapping *RegisterBankInfo::getOperandsMapping(
  309. const SmallVectorImpl<const RegisterBankInfo::ValueMapping *> &OpdsMapping)
  310. const {
  311. return getOperandsMapping(OpdsMapping.begin(), OpdsMapping.end());
  312. }
  313. const RegisterBankInfo::ValueMapping *RegisterBankInfo::getOperandsMapping(
  314. std::initializer_list<const RegisterBankInfo::ValueMapping *> OpdsMapping)
  315. const {
  316. return getOperandsMapping(OpdsMapping.begin(), OpdsMapping.end());
  317. }
  318. static hash_code
  319. hashInstructionMapping(unsigned ID, unsigned Cost,
  320. const RegisterBankInfo::ValueMapping *OperandsMapping,
  321. unsigned NumOperands) {
  322. return hash_combine(ID, Cost, OperandsMapping, NumOperands);
  323. }
  324. const RegisterBankInfo::InstructionMapping &
  325. RegisterBankInfo::getInstructionMappingImpl(
  326. bool IsInvalid, unsigned ID, unsigned Cost,
  327. const RegisterBankInfo::ValueMapping *OperandsMapping,
  328. unsigned NumOperands) const {
  329. assert(((IsInvalid && ID == InvalidMappingID && Cost == 0 &&
  330. OperandsMapping == nullptr && NumOperands == 0) ||
  331. !IsInvalid) &&
  332. "Mismatch argument for invalid input");
  333. ++NumInstructionMappingsAccessed;
  334. hash_code Hash =
  335. hashInstructionMapping(ID, Cost, OperandsMapping, NumOperands);
  336. const auto &It = MapOfInstructionMappings.find(Hash);
  337. if (It != MapOfInstructionMappings.end())
  338. return *It->second;
  339. ++NumInstructionMappingsCreated;
  340. auto &InstrMapping = MapOfInstructionMappings[Hash];
  341. InstrMapping = std::make_unique<InstructionMapping>(
  342. ID, Cost, OperandsMapping, NumOperands);
  343. return *InstrMapping;
  344. }
  345. const RegisterBankInfo::InstructionMapping &
  346. RegisterBankInfo::getInstrMapping(const MachineInstr &MI) const {
  347. const RegisterBankInfo::InstructionMapping &Mapping = getInstrMappingImpl(MI);
  348. if (Mapping.isValid())
  349. return Mapping;
  350. llvm_unreachable("The target must implement this");
  351. }
  352. RegisterBankInfo::InstructionMappings
  353. RegisterBankInfo::getInstrPossibleMappings(const MachineInstr &MI) const {
  354. InstructionMappings PossibleMappings;
  355. const auto &Mapping = getInstrMapping(MI);
  356. if (Mapping.isValid()) {
  357. // Put the default mapping first.
  358. PossibleMappings.push_back(&Mapping);
  359. }
  360. // Then the alternative mapping, if any.
  361. InstructionMappings AltMappings = getInstrAlternativeMappings(MI);
  362. append_range(PossibleMappings, AltMappings);
  363. #ifndef NDEBUG
  364. for (const InstructionMapping *Mapping : PossibleMappings)
  365. assert(Mapping->verify(MI) && "Mapping is invalid");
  366. #endif
  367. return PossibleMappings;
  368. }
  369. RegisterBankInfo::InstructionMappings
  370. RegisterBankInfo::getInstrAlternativeMappings(const MachineInstr &MI) const {
  371. // No alternative for MI.
  372. return InstructionMappings();
  373. }
  374. void RegisterBankInfo::applyDefaultMapping(const OperandsMapper &OpdMapper) {
  375. MachineInstr &MI = OpdMapper.getMI();
  376. MachineRegisterInfo &MRI = OpdMapper.getMRI();
  377. LLVM_DEBUG(dbgs() << "Applying default-like mapping\n");
  378. for (unsigned OpIdx = 0,
  379. EndIdx = OpdMapper.getInstrMapping().getNumOperands();
  380. OpIdx != EndIdx; ++OpIdx) {
  381. LLVM_DEBUG(dbgs() << "OpIdx " << OpIdx);
  382. MachineOperand &MO = MI.getOperand(OpIdx);
  383. if (!MO.isReg()) {
  384. LLVM_DEBUG(dbgs() << " is not a register, nothing to be done\n");
  385. continue;
  386. }
  387. if (!MO.getReg()) {
  388. LLVM_DEBUG(dbgs() << " is $noreg, nothing to be done\n");
  389. continue;
  390. }
  391. LLT Ty = MRI.getType(MO.getReg());
  392. if (!Ty.isValid())
  393. continue;
  394. assert(OpdMapper.getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns !=
  395. 0 &&
  396. "Invalid mapping");
  397. assert(OpdMapper.getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns ==
  398. 1 &&
  399. "This mapping is too complex for this function");
  400. iterator_range<SmallVectorImpl<Register>::const_iterator> NewRegs =
  401. OpdMapper.getVRegs(OpIdx);
  402. if (NewRegs.empty()) {
  403. LLVM_DEBUG(dbgs() << " has not been repaired, nothing to be done\n");
  404. continue;
  405. }
  406. Register OrigReg = MO.getReg();
  407. Register NewReg = *NewRegs.begin();
  408. LLVM_DEBUG(dbgs() << " changed, replace " << printReg(OrigReg, nullptr));
  409. MO.setReg(NewReg);
  410. LLVM_DEBUG(dbgs() << " with " << printReg(NewReg, nullptr));
  411. // The OperandsMapper creates plain scalar, we may have to fix that.
  412. // Check if the types match and if not, fix that.
  413. LLT OrigTy = MRI.getType(OrigReg);
  414. LLT NewTy = MRI.getType(NewReg);
  415. if (OrigTy != NewTy) {
  416. // The default mapping is not supposed to change the size of
  417. // the storage. However, right now we don't necessarily bump all
  418. // the types to storage size. For instance, we can consider
  419. // s16 G_AND legal whereas the storage size is going to be 32.
  420. assert(OrigTy.getSizeInBits() <= NewTy.getSizeInBits() &&
  421. "Types with difference size cannot be handled by the default "
  422. "mapping");
  423. LLVM_DEBUG(dbgs() << "\nChange type of new opd from " << NewTy << " to "
  424. << OrigTy);
  425. MRI.setType(NewReg, OrigTy);
  426. }
  427. LLVM_DEBUG(dbgs() << '\n');
  428. }
  429. }
  430. unsigned RegisterBankInfo::getSizeInBits(Register Reg,
  431. const MachineRegisterInfo &MRI,
  432. const TargetRegisterInfo &TRI) const {
  433. if (Reg.isPhysical()) {
  434. // The size is not directly available for physical registers.
  435. // Instead, we need to access a register class that contains Reg and
  436. // get the size of that register class.
  437. // Because this is expensive, we'll cache the register class by calling
  438. auto *RC = &getMinimalPhysRegClass(Reg, TRI);
  439. assert(RC && "Expecting Register class");
  440. return TRI.getRegSizeInBits(*RC);
  441. }
  442. return TRI.getRegSizeInBits(Reg, MRI);
  443. }
  444. //------------------------------------------------------------------------------
  445. // Helper classes implementation.
  446. //------------------------------------------------------------------------------
  447. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  448. LLVM_DUMP_METHOD void RegisterBankInfo::PartialMapping::dump() const {
  449. print(dbgs());
  450. dbgs() << '\n';
  451. }
  452. #endif
  453. bool RegisterBankInfo::PartialMapping::verify() const {
  454. assert(RegBank && "Register bank not set");
  455. assert(Length && "Empty mapping");
  456. assert((StartIdx <= getHighBitIdx()) && "Overflow, switch to APInt?");
  457. // Check if the minimum width fits into RegBank.
  458. assert(RegBank->getSize() >= Length && "Register bank too small for Mask");
  459. return true;
  460. }
  461. void RegisterBankInfo::PartialMapping::print(raw_ostream &OS) const {
  462. OS << "[" << StartIdx << ", " << getHighBitIdx() << "], RegBank = ";
  463. if (RegBank)
  464. OS << *RegBank;
  465. else
  466. OS << "nullptr";
  467. }
  468. bool RegisterBankInfo::ValueMapping::partsAllUniform() const {
  469. if (NumBreakDowns < 2)
  470. return true;
  471. const PartialMapping *First = begin();
  472. for (const PartialMapping *Part = First + 1; Part != end(); ++Part) {
  473. if (Part->Length != First->Length || Part->RegBank != First->RegBank)
  474. return false;
  475. }
  476. return true;
  477. }
  478. bool RegisterBankInfo::ValueMapping::verify(unsigned MeaningfulBitWidth) const {
  479. assert(NumBreakDowns && "Value mapped nowhere?!");
  480. unsigned OrigValueBitWidth = 0;
  481. for (const RegisterBankInfo::PartialMapping &PartMap : *this) {
  482. // Check that each register bank is big enough to hold the partial value:
  483. // this check is done by PartialMapping::verify
  484. assert(PartMap.verify() && "Partial mapping is invalid");
  485. // The original value should completely be mapped.
  486. // Thus the maximum accessed index + 1 is the size of the original value.
  487. OrigValueBitWidth =
  488. std::max(OrigValueBitWidth, PartMap.getHighBitIdx() + 1);
  489. }
  490. assert(OrigValueBitWidth >= MeaningfulBitWidth &&
  491. "Meaningful bits not covered by the mapping");
  492. APInt ValueMask(OrigValueBitWidth, 0);
  493. for (const RegisterBankInfo::PartialMapping &PartMap : *this) {
  494. // Check that the union of the partial mappings covers the whole value,
  495. // without overlaps.
  496. // The high bit is exclusive in the APInt API, thus getHighBitIdx + 1.
  497. APInt PartMapMask = APInt::getBitsSet(OrigValueBitWidth, PartMap.StartIdx,
  498. PartMap.getHighBitIdx() + 1);
  499. ValueMask ^= PartMapMask;
  500. assert((ValueMask & PartMapMask) == PartMapMask &&
  501. "Some partial mappings overlap");
  502. }
  503. assert(ValueMask.isAllOnes() && "Value is not fully mapped");
  504. return true;
  505. }
  506. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  507. LLVM_DUMP_METHOD void RegisterBankInfo::ValueMapping::dump() const {
  508. print(dbgs());
  509. dbgs() << '\n';
  510. }
  511. #endif
  512. void RegisterBankInfo::ValueMapping::print(raw_ostream &OS) const {
  513. OS << "#BreakDown: " << NumBreakDowns << " ";
  514. bool IsFirst = true;
  515. for (const PartialMapping &PartMap : *this) {
  516. if (!IsFirst)
  517. OS << ", ";
  518. OS << '[' << PartMap << ']';
  519. IsFirst = false;
  520. }
  521. }
  522. bool RegisterBankInfo::InstructionMapping::verify(
  523. const MachineInstr &MI) const {
  524. // Check that all the register operands are properly mapped.
  525. // Check the constructor invariant.
  526. // For PHI, we only care about mapping the definition.
  527. assert(NumOperands == (isCopyLike(MI) ? 1 : MI.getNumOperands()) &&
  528. "NumOperands must match, see constructor");
  529. assert(MI.getParent() && MI.getMF() &&
  530. "MI must be connected to a MachineFunction");
  531. const MachineFunction &MF = *MI.getMF();
  532. const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
  533. (void)RBI;
  534. const MachineRegisterInfo &MRI = MF.getRegInfo();
  535. for (unsigned Idx = 0; Idx < NumOperands; ++Idx) {
  536. const MachineOperand &MO = MI.getOperand(Idx);
  537. if (!MO.isReg()) {
  538. assert(!getOperandMapping(Idx).isValid() &&
  539. "We should not care about non-reg mapping");
  540. continue;
  541. }
  542. Register Reg = MO.getReg();
  543. if (!Reg)
  544. continue;
  545. LLT Ty = MRI.getType(Reg);
  546. if (!Ty.isValid())
  547. continue;
  548. assert(getOperandMapping(Idx).isValid() &&
  549. "We must have a mapping for reg operands");
  550. const RegisterBankInfo::ValueMapping &MOMapping = getOperandMapping(Idx);
  551. (void)MOMapping;
  552. // Register size in bits.
  553. // This size must match what the mapping expects.
  554. assert(MOMapping.verify(RBI->getSizeInBits(
  555. Reg, MF.getRegInfo(), *MF.getSubtarget().getRegisterInfo())) &&
  556. "Value mapping is invalid");
  557. }
  558. return true;
  559. }
  560. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  561. LLVM_DUMP_METHOD void RegisterBankInfo::InstructionMapping::dump() const {
  562. print(dbgs());
  563. dbgs() << '\n';
  564. }
  565. #endif
  566. void RegisterBankInfo::InstructionMapping::print(raw_ostream &OS) const {
  567. OS << "ID: " << getID() << " Cost: " << getCost() << " Mapping: ";
  568. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  569. const ValueMapping &ValMapping = getOperandMapping(OpIdx);
  570. if (OpIdx)
  571. OS << ", ";
  572. OS << "{ Idx: " << OpIdx << " Map: " << ValMapping << '}';
  573. }
  574. }
  575. const int RegisterBankInfo::OperandsMapper::DontKnowIdx = -1;
  576. RegisterBankInfo::OperandsMapper::OperandsMapper(
  577. MachineInstr &MI, const InstructionMapping &InstrMapping,
  578. MachineRegisterInfo &MRI)
  579. : MRI(MRI), MI(MI), InstrMapping(InstrMapping) {
  580. unsigned NumOpds = InstrMapping.getNumOperands();
  581. OpToNewVRegIdx.resize(NumOpds, OperandsMapper::DontKnowIdx);
  582. assert(InstrMapping.verify(MI) && "Invalid mapping for MI");
  583. }
  584. iterator_range<SmallVectorImpl<Register>::iterator>
  585. RegisterBankInfo::OperandsMapper::getVRegsMem(unsigned OpIdx) {
  586. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  587. unsigned NumPartialVal =
  588. getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns;
  589. int StartIdx = OpToNewVRegIdx[OpIdx];
  590. if (StartIdx == OperandsMapper::DontKnowIdx) {
  591. // This is the first time we try to access OpIdx.
  592. // Create the cells that will hold all the partial values at the
  593. // end of the list of NewVReg.
  594. StartIdx = NewVRegs.size();
  595. OpToNewVRegIdx[OpIdx] = StartIdx;
  596. for (unsigned i = 0; i < NumPartialVal; ++i)
  597. NewVRegs.push_back(0);
  598. }
  599. SmallVectorImpl<Register>::iterator End =
  600. getNewVRegsEnd(StartIdx, NumPartialVal);
  601. return make_range(&NewVRegs[StartIdx], End);
  602. }
  603. SmallVectorImpl<Register>::const_iterator
  604. RegisterBankInfo::OperandsMapper::getNewVRegsEnd(unsigned StartIdx,
  605. unsigned NumVal) const {
  606. return const_cast<OperandsMapper *>(this)->getNewVRegsEnd(StartIdx, NumVal);
  607. }
  608. SmallVectorImpl<Register>::iterator
  609. RegisterBankInfo::OperandsMapper::getNewVRegsEnd(unsigned StartIdx,
  610. unsigned NumVal) {
  611. assert((NewVRegs.size() == StartIdx + NumVal ||
  612. NewVRegs.size() > StartIdx + NumVal) &&
  613. "NewVRegs too small to contain all the partial mapping");
  614. return NewVRegs.size() <= StartIdx + NumVal ? NewVRegs.end()
  615. : &NewVRegs[StartIdx + NumVal];
  616. }
  617. void RegisterBankInfo::OperandsMapper::createVRegs(unsigned OpIdx) {
  618. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  619. iterator_range<SmallVectorImpl<Register>::iterator> NewVRegsForOpIdx =
  620. getVRegsMem(OpIdx);
  621. const ValueMapping &ValMapping = getInstrMapping().getOperandMapping(OpIdx);
  622. const PartialMapping *PartMap = ValMapping.begin();
  623. for (Register &NewVReg : NewVRegsForOpIdx) {
  624. assert(PartMap != ValMapping.end() && "Out-of-bound access");
  625. assert(NewVReg == 0 && "Register has already been created");
  626. // The new registers are always bound to scalar with the right size.
  627. // The actual type has to be set when the target does the mapping
  628. // of the instruction.
  629. // The rationale is that this generic code cannot guess how the
  630. // target plans to split the input type.
  631. NewVReg = MRI.createGenericVirtualRegister(LLT::scalar(PartMap->Length));
  632. MRI.setRegBank(NewVReg, *PartMap->RegBank);
  633. ++PartMap;
  634. }
  635. }
  636. void RegisterBankInfo::OperandsMapper::setVRegs(unsigned OpIdx,
  637. unsigned PartialMapIdx,
  638. Register NewVReg) {
  639. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  640. assert(getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns >
  641. PartialMapIdx &&
  642. "Out-of-bound access for partial mapping");
  643. // Make sure the memory is initialized for that operand.
  644. (void)getVRegsMem(OpIdx);
  645. assert(NewVRegs[OpToNewVRegIdx[OpIdx] + PartialMapIdx] == 0 &&
  646. "This value is already set");
  647. NewVRegs[OpToNewVRegIdx[OpIdx] + PartialMapIdx] = NewVReg;
  648. }
  649. iterator_range<SmallVectorImpl<Register>::const_iterator>
  650. RegisterBankInfo::OperandsMapper::getVRegs(unsigned OpIdx,
  651. bool ForDebug) const {
  652. (void)ForDebug;
  653. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  654. int StartIdx = OpToNewVRegIdx[OpIdx];
  655. if (StartIdx == OperandsMapper::DontKnowIdx)
  656. return make_range(NewVRegs.end(), NewVRegs.end());
  657. unsigned PartMapSize =
  658. getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns;
  659. SmallVectorImpl<Register>::const_iterator End =
  660. getNewVRegsEnd(StartIdx, PartMapSize);
  661. iterator_range<SmallVectorImpl<Register>::const_iterator> Res =
  662. make_range(&NewVRegs[StartIdx], End);
  663. #ifndef NDEBUG
  664. for (Register VReg : Res)
  665. assert((VReg || ForDebug) && "Some registers are uninitialized");
  666. #endif
  667. return Res;
  668. }
  669. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  670. LLVM_DUMP_METHOD void RegisterBankInfo::OperandsMapper::dump() const {
  671. print(dbgs(), true);
  672. dbgs() << '\n';
  673. }
  674. #endif
  675. void RegisterBankInfo::OperandsMapper::print(raw_ostream &OS,
  676. bool ForDebug) const {
  677. unsigned NumOpds = getInstrMapping().getNumOperands();
  678. if (ForDebug) {
  679. OS << "Mapping for " << getMI() << "\nwith " << getInstrMapping() << '\n';
  680. // Print out the internal state of the index table.
  681. OS << "Populated indices (CellNumber, IndexInNewVRegs): ";
  682. bool IsFirst = true;
  683. for (unsigned Idx = 0; Idx != NumOpds; ++Idx) {
  684. if (OpToNewVRegIdx[Idx] != DontKnowIdx) {
  685. if (!IsFirst)
  686. OS << ", ";
  687. OS << '(' << Idx << ", " << OpToNewVRegIdx[Idx] << ')';
  688. IsFirst = false;
  689. }
  690. }
  691. OS << '\n';
  692. } else
  693. OS << "Mapping ID: " << getInstrMapping().getID() << ' ';
  694. OS << "Operand Mapping: ";
  695. // If we have a function, we can pretty print the name of the registers.
  696. // Otherwise we will print the raw numbers.
  697. const TargetRegisterInfo *TRI =
  698. getMI().getParent() && getMI().getMF()
  699. ? getMI().getMF()->getSubtarget().getRegisterInfo()
  700. : nullptr;
  701. bool IsFirst = true;
  702. for (unsigned Idx = 0; Idx != NumOpds; ++Idx) {
  703. if (OpToNewVRegIdx[Idx] == DontKnowIdx)
  704. continue;
  705. if (!IsFirst)
  706. OS << ", ";
  707. IsFirst = false;
  708. OS << '(' << printReg(getMI().getOperand(Idx).getReg(), TRI) << ", [";
  709. bool IsFirstNewVReg = true;
  710. for (Register VReg : getVRegs(Idx)) {
  711. if (!IsFirstNewVReg)
  712. OS << ", ";
  713. IsFirstNewVReg = false;
  714. OS << printReg(VReg, TRI);
  715. }
  716. OS << "])";
  717. }
  718. }