LiveDebugValues.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. //===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// This pass implements a data flow analysis that propagates debug location
  10. /// information by inserting additional DBG_VALUE instructions into the machine
  11. /// instruction stream. The pass internally builds debug location liveness
  12. /// ranges to determine the points where additional DBG_VALUEs need to be
  13. /// inserted.
  14. ///
  15. /// This is a separate pass from DbgValueHistoryCalculator to facilitate
  16. /// testing and improve modularity.
  17. ///
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/SparseBitVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/ADT/UniqueVector.h"
  27. #include "llvm/CodeGen/LexicalScopes.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineFrameInfo.h"
  30. #include "llvm/CodeGen/MachineFunction.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineMemOperand.h"
  35. #include "llvm/CodeGen/MachineOperand.h"
  36. #include "llvm/CodeGen/PseudoSourceValue.h"
  37. #include "llvm/CodeGen/RegisterScavenging.h"
  38. #include "llvm/CodeGen/TargetFrameLowering.h"
  39. #include "llvm/CodeGen/TargetInstrInfo.h"
  40. #include "llvm/CodeGen/TargetLowering.h"
  41. #include "llvm/CodeGen/TargetRegisterInfo.h"
  42. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  43. #include "llvm/Config/llvm-config.h"
  44. #include "llvm/IR/DIBuilder.h"
  45. #include "llvm/IR/DebugInfoMetadata.h"
  46. #include "llvm/IR/DebugLoc.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/MC/MCRegisterInfo.h"
  50. #include "llvm/Pass.h"
  51. #include "llvm/Support/Casting.h"
  52. #include "llvm/Support/Compiler.h"
  53. #include "llvm/Support/Debug.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include <algorithm>
  56. #include <cassert>
  57. #include <cstdint>
  58. #include <functional>
  59. #include <queue>
  60. #include <tuple>
  61. #include <utility>
  62. #include <vector>
  63. using namespace llvm;
  64. #define DEBUG_TYPE "livedebugvalues"
  65. STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
  66. // If @MI is a DBG_VALUE with debug value described by a defined
  67. // register, returns the number of this register. In the other case, returns 0.
  68. static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
  69. assert(MI.isDebugValue() && "expected a DBG_VALUE");
  70. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  71. // If location of variable is described using a register (directly
  72. // or indirectly), this register is always a first operand.
  73. return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : Register();
  74. }
  75. namespace {
  76. class LiveDebugValues : public MachineFunctionPass {
  77. private:
  78. const TargetRegisterInfo *TRI;
  79. const TargetInstrInfo *TII;
  80. const TargetFrameLowering *TFI;
  81. BitVector CalleeSavedRegs;
  82. LexicalScopes LS;
  83. enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
  84. /// Keeps track of lexical scopes associated with a user value's source
  85. /// location.
  86. class UserValueScopes {
  87. DebugLoc DL;
  88. LexicalScopes &LS;
  89. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  90. public:
  91. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
  92. /// Return true if current scope dominates at least one machine
  93. /// instruction in a given machine basic block.
  94. bool dominates(MachineBasicBlock *MBB) {
  95. if (LBlocks.empty())
  96. LS.getMachineBasicBlocks(DL, LBlocks);
  97. return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
  98. }
  99. };
  100. using FragmentInfo = DIExpression::FragmentInfo;
  101. using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
  102. /// Storage for identifying a potentially inlined instance of a variable,
  103. /// or a fragment thereof.
  104. class DebugVariable {
  105. const DILocalVariable *Variable;
  106. OptFragmentInfo Fragment;
  107. const DILocation *InlinedAt;
  108. /// Fragment that will overlap all other fragments. Used as default when
  109. /// caller demands a fragment.
  110. static const FragmentInfo DefaultFragment;
  111. public:
  112. DebugVariable(const DILocalVariable *Var, OptFragmentInfo &&FragmentInfo,
  113. const DILocation *InlinedAt)
  114. : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
  115. DebugVariable(const DILocalVariable *Var, OptFragmentInfo &FragmentInfo,
  116. const DILocation *InlinedAt)
  117. : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
  118. DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
  119. const DILocation *InlinedAt)
  120. : DebugVariable(Var, DIExpr->getFragmentInfo(), InlinedAt) {}
  121. DebugVariable(const MachineInstr &MI)
  122. : DebugVariable(MI.getDebugVariable(),
  123. MI.getDebugExpression()->getFragmentInfo(),
  124. MI.getDebugLoc()->getInlinedAt()) {}
  125. const DILocalVariable *getVar() const { return Variable; }
  126. const OptFragmentInfo &getFragment() const { return Fragment; }
  127. const DILocation *getInlinedAt() const { return InlinedAt; }
  128. const FragmentInfo getFragmentDefault() const {
  129. return Fragment.getValueOr(DefaultFragment);
  130. }
  131. static bool isFragmentDefault(FragmentInfo &F) {
  132. return F == DefaultFragment;
  133. }
  134. bool operator==(const DebugVariable &Other) const {
  135. return std::tie(Variable, Fragment, InlinedAt) ==
  136. std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
  137. }
  138. bool operator<(const DebugVariable &Other) const {
  139. return std::tie(Variable, Fragment, InlinedAt) <
  140. std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
  141. }
  142. };
  143. friend struct llvm::DenseMapInfo<DebugVariable>;
  144. /// A pair of debug variable and value location.
  145. struct VarLoc {
  146. // The location at which a spilled variable resides. It consists of a
  147. // register and an offset.
  148. struct SpillLoc {
  149. unsigned SpillBase;
  150. int SpillOffset;
  151. bool operator==(const SpillLoc &Other) const {
  152. return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
  153. }
  154. };
  155. const DebugVariable Var;
  156. const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
  157. mutable UserValueScopes UVS;
  158. enum VarLocKind {
  159. InvalidKind = 0,
  160. RegisterKind,
  161. SpillLocKind,
  162. ImmediateKind
  163. } Kind = InvalidKind;
  164. /// The value location. Stored separately to avoid repeatedly
  165. /// extracting it from MI.
  166. union {
  167. uint64_t RegNo;
  168. SpillLoc SpillLocation;
  169. uint64_t Hash;
  170. int64_t Immediate;
  171. const ConstantFP *FPImm;
  172. const ConstantInt *CImm;
  173. } Loc;
  174. VarLoc(const MachineInstr &MI, LexicalScopes &LS)
  175. : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS) {
  176. static_assert((sizeof(Loc) == sizeof(uint64_t)),
  177. "hash does not cover all members of Loc");
  178. assert(MI.isDebugValue() && "not a DBG_VALUE");
  179. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  180. if (int RegNo = isDbgValueDescribedByReg(MI)) {
  181. Kind = RegisterKind;
  182. Loc.RegNo = RegNo;
  183. } else if (MI.getOperand(0).isImm()) {
  184. Kind = ImmediateKind;
  185. Loc.Immediate = MI.getOperand(0).getImm();
  186. } else if (MI.getOperand(0).isFPImm()) {
  187. Kind = ImmediateKind;
  188. Loc.FPImm = MI.getOperand(0).getFPImm();
  189. } else if (MI.getOperand(0).isCImm()) {
  190. Kind = ImmediateKind;
  191. Loc.CImm = MI.getOperand(0).getCImm();
  192. }
  193. }
  194. /// The constructor for spill locations.
  195. VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
  196. LexicalScopes &LS)
  197. : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS) {
  198. assert(MI.isDebugValue() && "not a DBG_VALUE");
  199. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  200. Kind = SpillLocKind;
  201. Loc.SpillLocation = {SpillBase, SpillOffset};
  202. }
  203. // Is the Loc field a constant or constant object?
  204. bool isConstant() const { return Kind == ImmediateKind; }
  205. /// If this variable is described by a register, return it,
  206. /// otherwise return 0.
  207. unsigned isDescribedByReg() const {
  208. if (Kind == RegisterKind)
  209. return Loc.RegNo;
  210. return 0;
  211. }
  212. /// Determine whether the lexical scope of this value's debug location
  213. /// dominates MBB.
  214. bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
  215. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  216. LLVM_DUMP_METHOD void dump() const { MI.dump(); }
  217. #endif
  218. bool operator==(const VarLoc &Other) const {
  219. return Kind == Other.Kind && Var == Other.Var &&
  220. Loc.Hash == Other.Loc.Hash;
  221. }
  222. /// This operator guarantees that VarLocs are sorted by Variable first.
  223. bool operator<(const VarLoc &Other) const {
  224. if (Var == Other.Var)
  225. return Loc.Hash < Other.Loc.Hash;
  226. return Var < Other.Var;
  227. }
  228. };
  229. using VarLocMap = UniqueVector<VarLoc>;
  230. using VarLocSet = SparseBitVector<>;
  231. using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
  232. struct TransferDebugPair {
  233. MachineInstr *TransferInst;
  234. MachineInstr *DebugInst;
  235. };
  236. using TransferMap = SmallVector<TransferDebugPair, 4>;
  237. // Types for recording sets of variable fragments that overlap. For a given
  238. // local variable, we record all other fragments of that variable that could
  239. // overlap it, to reduce search time.
  240. using FragmentOfVar =
  241. std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
  242. using OverlapMap =
  243. DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
  244. // Helper while building OverlapMap, a map of all fragments seen for a given
  245. // DILocalVariable.
  246. using VarToFragments =
  247. DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
  248. /// This holds the working set of currently open ranges. For fast
  249. /// access, this is done both as a set of VarLocIDs, and a map of
  250. /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
  251. /// previous open ranges for the same variable.
  252. class OpenRangesSet {
  253. VarLocSet VarLocs;
  254. SmallDenseMap<DebugVariable, unsigned, 8> Vars;
  255. OverlapMap &OverlappingFragments;
  256. public:
  257. OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
  258. const VarLocSet &getVarLocs() const { return VarLocs; }
  259. /// Terminate all open ranges for Var by removing it from the set.
  260. void erase(DebugVariable Var);
  261. /// Terminate all open ranges listed in \c KillSet by removing
  262. /// them from the set.
  263. void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
  264. VarLocs.intersectWithComplement(KillSet);
  265. for (unsigned ID : KillSet)
  266. Vars.erase(VarLocIDs[ID].Var);
  267. }
  268. /// Insert a new range into the set.
  269. void insert(unsigned VarLocID, DebugVariable Var) {
  270. VarLocs.set(VarLocID);
  271. Vars.insert({Var, VarLocID});
  272. }
  273. /// Empty the set.
  274. void clear() {
  275. VarLocs.clear();
  276. Vars.clear();
  277. }
  278. /// Return whether the set is empty or not.
  279. bool empty() const {
  280. assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
  281. return VarLocs.empty();
  282. }
  283. };
  284. bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
  285. unsigned &Reg);
  286. /// If a given instruction is identified as a spill, return the spill location
  287. /// and set \p Reg to the spilled register.
  288. Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
  289. MachineFunction *MF,
  290. unsigned &Reg);
  291. /// Given a spill instruction, extract the register and offset used to
  292. /// address the spill location in a target independent way.
  293. VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
  294. void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
  295. TransferMap &Transfers, VarLocMap &VarLocIDs,
  296. unsigned OldVarID, TransferKind Kind,
  297. unsigned NewReg = 0);
  298. void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
  299. VarLocMap &VarLocIDs);
  300. void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  301. VarLocMap &VarLocIDs, TransferMap &Transfers);
  302. void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
  303. VarLocMap &VarLocIDs, TransferMap &Transfers);
  304. void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
  305. const VarLocMap &VarLocIDs);
  306. bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  307. VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
  308. bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  309. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  310. TransferMap &Transfers, bool transferChanges,
  311. OverlapMap &OverlapFragments, VarToFragments &SeenFragments);
  312. void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
  313. OverlapMap &OLapMap);
  314. bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  315. const VarLocMap &VarLocIDs,
  316. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  317. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
  318. bool ExtendRanges(MachineFunction &MF);
  319. public:
  320. static char ID;
  321. /// Default construct and initialize the pass.
  322. LiveDebugValues();
  323. /// Tell the pass manager which passes we depend on and what
  324. /// information we preserve.
  325. void getAnalysisUsage(AnalysisUsage &AU) const override;
  326. MachineFunctionProperties getRequiredProperties() const override {
  327. return MachineFunctionProperties().set(
  328. MachineFunctionProperties::Property::NoVRegs);
  329. }
  330. /// Print to ostream with a message.
  331. void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
  332. const VarLocMap &VarLocIDs, const char *msg,
  333. raw_ostream &Out) const;
  334. /// Calculate the liveness information for the given machine function.
  335. bool runOnMachineFunction(MachineFunction &MF) override;
  336. };
  337. } // end anonymous namespace
  338. namespace llvm {
  339. template <> struct DenseMapInfo<LiveDebugValues::DebugVariable> {
  340. using DV = LiveDebugValues::DebugVariable;
  341. using OptFragmentInfo = LiveDebugValues::OptFragmentInfo;
  342. using FragmentInfo = LiveDebugValues::FragmentInfo;
  343. // Empty key: no key should be generated that has no DILocalVariable.
  344. static inline DV getEmptyKey() {
  345. return DV(nullptr, OptFragmentInfo(), nullptr);
  346. }
  347. // Difference in tombstone is that the Optional is meaningful
  348. static inline DV getTombstoneKey() {
  349. return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
  350. }
  351. static unsigned getHashValue(const DV &D) {
  352. unsigned HV = 0;
  353. const OptFragmentInfo &Fragment = D.getFragment();
  354. if (Fragment)
  355. HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
  356. return hash_combine(D.getVar(), HV, D.getInlinedAt());
  357. }
  358. static bool isEqual(const DV &A, const DV &B) { return A == B; }
  359. };
  360. } // namespace llvm
  361. //===----------------------------------------------------------------------===//
  362. // Implementation
  363. //===----------------------------------------------------------------------===//
  364. const DIExpression::FragmentInfo
  365. LiveDebugValues::DebugVariable::DefaultFragment = {
  366. std::numeric_limits<uint64_t>::max(),
  367. std::numeric_limits<uint64_t>::min()};
  368. char LiveDebugValues::ID = 0;
  369. char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
  370. INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
  371. false, false)
  372. /// Default construct and initialize the pass.
  373. LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
  374. initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
  375. }
  376. /// Tell the pass manager which passes we depend on and what information we
  377. /// preserve.
  378. void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
  379. AU.setPreservesCFG();
  380. MachineFunctionPass::getAnalysisUsage(AU);
  381. }
  382. /// Erase a variable from the set of open ranges, and additionally erase any
  383. /// fragments that may overlap it.
  384. void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var) {
  385. // Erasure helper.
  386. auto DoErase = [this](DebugVariable VarToErase) {
  387. auto It = Vars.find(VarToErase);
  388. if (It != Vars.end()) {
  389. unsigned ID = It->second;
  390. VarLocs.reset(ID);
  391. Vars.erase(It);
  392. }
  393. };
  394. // Erase the variable/fragment that ends here.
  395. DoErase(Var);
  396. // Extract the fragment. Interpret an empty fragment as one that covers all
  397. // possible bits.
  398. FragmentInfo ThisFragment = Var.getFragmentDefault();
  399. // There may be fragments that overlap the designated fragment. Look them up
  400. // in the pre-computed overlap map, and erase them too.
  401. auto MapIt = OverlappingFragments.find({Var.getVar(), ThisFragment});
  402. if (MapIt != OverlappingFragments.end()) {
  403. for (auto Fragment : MapIt->second) {
  404. LiveDebugValues::OptFragmentInfo FragmentHolder;
  405. if (!DebugVariable::isFragmentDefault(Fragment))
  406. FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
  407. DoErase({Var.getVar(), FragmentHolder, Var.getInlinedAt()});
  408. }
  409. }
  410. }
  411. //===----------------------------------------------------------------------===//
  412. // Debug Range Extension Implementation
  413. //===----------------------------------------------------------------------===//
  414. #ifndef NDEBUG
  415. void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
  416. const VarLocInMBB &V,
  417. const VarLocMap &VarLocIDs,
  418. const char *msg,
  419. raw_ostream &Out) const {
  420. Out << '\n' << msg << '\n';
  421. for (const MachineBasicBlock &BB : MF) {
  422. const VarLocSet &L = V.lookup(&BB);
  423. if (L.empty())
  424. continue;
  425. Out << "MBB: " << BB.getNumber() << ":\n";
  426. for (unsigned VLL : L) {
  427. const VarLoc &VL = VarLocIDs[VLL];
  428. Out << " Var: " << VL.Var.getVar()->getName();
  429. Out << " MI: ";
  430. VL.dump();
  431. }
  432. }
  433. Out << "\n";
  434. }
  435. #endif
  436. LiveDebugValues::VarLoc::SpillLoc
  437. LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
  438. assert(MI.hasOneMemOperand() &&
  439. "Spill instruction does not have exactly one memory operand?");
  440. auto MMOI = MI.memoperands_begin();
  441. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  442. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  443. "Inconsistent memory operand in spill instruction");
  444. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  445. const MachineBasicBlock *MBB = MI.getParent();
  446. unsigned Reg;
  447. int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  448. return {Reg, Offset};
  449. }
  450. /// End all previous ranges related to @MI and start a new range from @MI
  451. /// if it is a DBG_VALUE instr.
  452. void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
  453. OpenRangesSet &OpenRanges,
  454. VarLocMap &VarLocIDs) {
  455. if (!MI.isDebugValue())
  456. return;
  457. const DILocalVariable *Var = MI.getDebugVariable();
  458. const DIExpression *Expr = MI.getDebugExpression();
  459. const DILocation *DebugLoc = MI.getDebugLoc();
  460. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  461. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  462. "Expected inlined-at fields to agree");
  463. // End all previous ranges of Var.
  464. DebugVariable V(Var, Expr, InlinedAt);
  465. OpenRanges.erase(V);
  466. // Add the VarLoc to OpenRanges from this DBG_VALUE.
  467. unsigned ID;
  468. if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
  469. MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
  470. // Use normal VarLoc constructor for registers and immediates.
  471. VarLoc VL(MI, LS);
  472. ID = VarLocIDs.insert(VL);
  473. OpenRanges.insert(ID, VL.Var);
  474. } else if (MI.hasOneMemOperand()) {
  475. // It's a stack spill -- fetch spill base and offset.
  476. VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
  477. VarLoc VL(MI, SpillLocation.SpillBase, SpillLocation.SpillOffset, LS);
  478. ID = VarLocIDs.insert(VL);
  479. OpenRanges.insert(ID, VL.Var);
  480. } else {
  481. // This must be an undefined location. We should leave OpenRanges closed.
  482. assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
  483. "Unexpected non-undef DBG_VALUE encountered");
  484. }
  485. }
  486. /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
  487. /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
  488. /// new VarLoc. If \p NewReg is different than default zero value then the
  489. /// new location will be register location created by the copy like instruction,
  490. /// otherwise it is variable's location on the stack.
  491. void LiveDebugValues::insertTransferDebugPair(
  492. MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
  493. VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
  494. unsigned NewReg) {
  495. const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
  496. MachineFunction *MF = MI.getParent()->getParent();
  497. MachineInstr *NewDebugInstr;
  498. auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &DebugInstr,
  499. &VarLocIDs](VarLoc &VL, MachineInstr *NewDebugInstr) {
  500. unsigned LocId = VarLocIDs.insert(VL);
  501. // Close this variable's previous location range.
  502. DebugVariable V(*DebugInstr);
  503. OpenRanges.erase(V);
  504. OpenRanges.insert(LocId, VL.Var);
  505. // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
  506. // after MI. Keep track of the pairing.
  507. TransferDebugPair MIP = {&MI, NewDebugInstr};
  508. Transfers.push_back(MIP);
  509. };
  510. // End all previous ranges of Var.
  511. OpenRanges.erase(VarLocIDs[OldVarID].Var);
  512. switch (Kind) {
  513. case TransferKind::TransferCopy: {
  514. assert(NewReg &&
  515. "No register supplied when handling a copy of a debug value");
  516. // Create a DBG_VALUE instruction to describe the Var in its new
  517. // register location.
  518. NewDebugInstr = BuildMI(
  519. *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(),
  520. DebugInstr->isIndirectDebugValue(), NewReg,
  521. DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
  522. if (DebugInstr->isIndirectDebugValue())
  523. NewDebugInstr->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
  524. VarLoc VL(*NewDebugInstr, LS);
  525. ProcessVarLoc(VL, NewDebugInstr);
  526. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
  527. NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
  528. /*SkipOpers*/false, /*SkipDebugLoc*/false,
  529. /*AddNewLine*/true, TII));
  530. return;
  531. }
  532. case TransferKind::TransferSpill: {
  533. // Create a DBG_VALUE instruction to describe the Var in its spilled
  534. // location.
  535. VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
  536. auto *SpillExpr = DIExpression::prepend(DebugInstr->getDebugExpression(),
  537. DIExpression::ApplyOffset,
  538. SpillLocation.SpillOffset);
  539. NewDebugInstr = BuildMI(
  540. *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), true,
  541. SpillLocation.SpillBase, DebugInstr->getDebugVariable(), SpillExpr);
  542. VarLoc VL(*NewDebugInstr, SpillLocation.SpillBase,
  543. SpillLocation.SpillOffset, LS);
  544. ProcessVarLoc(VL, NewDebugInstr);
  545. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
  546. NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
  547. /*SkipOpers*/false, /*SkipDebugLoc*/false,
  548. /*AddNewLine*/true, TII));
  549. return;
  550. }
  551. case TransferKind::TransferRestore: {
  552. assert(NewReg &&
  553. "No register supplied when handling a restore of a debug value");
  554. MachineFunction *MF = MI.getMF();
  555. DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
  556. NewDebugInstr =
  557. BuildMI(*MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), false,
  558. NewReg, DebugInstr->getDebugVariable(), DIB.createExpression());
  559. VarLoc VL(*NewDebugInstr, LS);
  560. ProcessVarLoc(VL, NewDebugInstr);
  561. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
  562. NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
  563. /*SkipOpers*/false, /*SkipDebugLoc*/false,
  564. /*AddNewLine*/true, TII));
  565. return;
  566. }
  567. }
  568. llvm_unreachable("Invalid transfer kind");
  569. }
  570. /// A definition of a register may mark the end of a range.
  571. void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
  572. OpenRangesSet &OpenRanges,
  573. const VarLocMap &VarLocIDs) {
  574. MachineFunction *MF = MI.getMF();
  575. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  576. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  577. SparseBitVector<> KillSet;
  578. for (const MachineOperand &MO : MI.operands()) {
  579. // Determine whether the operand is a register def. Assume that call
  580. // instructions never clobber SP, because some backends (e.g., AArch64)
  581. // never list SP in the regmask.
  582. if (MO.isReg() && MO.isDef() && MO.getReg() &&
  583. TRI->isPhysicalRegister(MO.getReg()) &&
  584. !(MI.isCall() && MO.getReg() == SP)) {
  585. // Remove ranges of all aliased registers.
  586. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  587. for (unsigned ID : OpenRanges.getVarLocs())
  588. if (VarLocIDs[ID].isDescribedByReg() == *RAI)
  589. KillSet.set(ID);
  590. } else if (MO.isRegMask()) {
  591. // Remove ranges of all clobbered registers. Register masks don't usually
  592. // list SP as preserved. While the debug info may be off for an
  593. // instruction or two around callee-cleanup calls, transferring the
  594. // DEBUG_VALUE across the call is still a better user experience.
  595. for (unsigned ID : OpenRanges.getVarLocs()) {
  596. unsigned Reg = VarLocIDs[ID].isDescribedByReg();
  597. if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
  598. KillSet.set(ID);
  599. }
  600. }
  601. }
  602. OpenRanges.erase(KillSet, VarLocIDs);
  603. }
  604. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  605. /// criteria to make this decision:
  606. /// - Is this instruction a store to a spill slot?
  607. /// - Is there a register operand that is both used and killed?
  608. /// TODO: Store optimization can fold spills into other stores (including
  609. /// other spills). We do not handle this yet (more than one memory operand).
  610. bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
  611. MachineFunction *MF, unsigned &Reg) {
  612. SmallVector<const MachineMemOperand*, 1> Accesses;
  613. // TODO: Handle multiple stores folded into one.
  614. if (!MI.hasOneMemOperand())
  615. return false;
  616. if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
  617. return false; // This is not a spill instruction, since no valid size was
  618. // returned from either function.
  619. auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
  620. if (!MO.isReg() || !MO.isUse()) {
  621. Reg = 0;
  622. return false;
  623. }
  624. Reg = MO.getReg();
  625. return MO.isKill();
  626. };
  627. for (const MachineOperand &MO : MI.operands()) {
  628. // In a spill instruction generated by the InlineSpiller the spilled
  629. // register has its kill flag set.
  630. if (isKilledReg(MO, Reg))
  631. return true;
  632. if (Reg != 0) {
  633. // Check whether next instruction kills the spilled register.
  634. // FIXME: Current solution does not cover search for killed register in
  635. // bundles and instructions further down the chain.
  636. auto NextI = std::next(MI.getIterator());
  637. // Skip next instruction that points to basic block end iterator.
  638. if (MI.getParent()->end() == NextI)
  639. continue;
  640. unsigned RegNext;
  641. for (const MachineOperand &MONext : NextI->operands()) {
  642. // Return true if we came across the register from the
  643. // previous spill instruction that is killed in NextI.
  644. if (isKilledReg(MONext, RegNext) && RegNext == Reg)
  645. return true;
  646. }
  647. }
  648. }
  649. // Return false if we didn't find spilled register.
  650. return false;
  651. }
  652. Optional<LiveDebugValues::VarLoc::SpillLoc>
  653. LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
  654. MachineFunction *MF, unsigned &Reg) {
  655. if (!MI.hasOneMemOperand())
  656. return None;
  657. // FIXME: Handle folded restore instructions with more than one memory
  658. // operand.
  659. if (MI.getRestoreSize(TII)) {
  660. Reg = MI.getOperand(0).getReg();
  661. return extractSpillBaseRegAndOffset(MI);
  662. }
  663. return None;
  664. }
  665. /// A spilled register may indicate that we have to end the current range of
  666. /// a variable and create a new one for the spill location.
  667. /// A restored register may indicate the reverse situation.
  668. /// We don't want to insert any instructions in process(), so we just create
  669. /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
  670. /// It will be inserted into the BB when we're done iterating over the
  671. /// instructions.
  672. void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
  673. OpenRangesSet &OpenRanges,
  674. VarLocMap &VarLocIDs,
  675. TransferMap &Transfers) {
  676. MachineFunction *MF = MI.getMF();
  677. TransferKind TKind;
  678. unsigned Reg;
  679. Optional<VarLoc::SpillLoc> Loc;
  680. LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
  681. if (isSpillInstruction(MI, MF, Reg)) {
  682. TKind = TransferKind::TransferSpill;
  683. LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
  684. LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
  685. << "\n");
  686. } else {
  687. if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
  688. return;
  689. TKind = TransferKind::TransferRestore;
  690. LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
  691. LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
  692. << "\n");
  693. }
  694. // Check if the register or spill location is the location of a debug value.
  695. for (unsigned ID : OpenRanges.getVarLocs()) {
  696. if (TKind == TransferKind::TransferSpill &&
  697. VarLocIDs[ID].isDescribedByReg() == Reg) {
  698. LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
  699. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  700. } else if (TKind == TransferKind::TransferRestore &&
  701. VarLocIDs[ID].Loc.SpillLocation == *Loc) {
  702. LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
  703. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  704. } else
  705. continue;
  706. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
  707. Reg);
  708. return;
  709. }
  710. }
  711. /// If \p MI is a register copy instruction, that copies a previously tracked
  712. /// value from one register to another register that is callee saved, we
  713. /// create new DBG_VALUE instruction described with copy destination register.
  714. void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
  715. OpenRangesSet &OpenRanges,
  716. VarLocMap &VarLocIDs,
  717. TransferMap &Transfers) {
  718. const MachineOperand *SrcRegOp, *DestRegOp;
  719. if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
  720. !DestRegOp->isDef())
  721. return;
  722. auto isCalleSavedReg = [&](unsigned Reg) {
  723. for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
  724. if (CalleeSavedRegs.test(*RAI))
  725. return true;
  726. return false;
  727. };
  728. unsigned SrcReg = SrcRegOp->getReg();
  729. unsigned DestReg = DestRegOp->getReg();
  730. // We want to recognize instructions where destination register is callee
  731. // saved register. If register that could be clobbered by the call is
  732. // included, there would be a great chance that it is going to be clobbered
  733. // soon. It is more likely that previous register location, which is callee
  734. // saved, is going to stay unclobbered longer, even if it is killed.
  735. if (!isCalleSavedReg(DestReg))
  736. return;
  737. for (unsigned ID : OpenRanges.getVarLocs()) {
  738. if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
  739. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
  740. TransferKind::TransferCopy, DestReg);
  741. return;
  742. }
  743. }
  744. }
  745. /// Terminate all open ranges at the end of the current basic block.
  746. bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
  747. OpenRangesSet &OpenRanges,
  748. VarLocInMBB &OutLocs,
  749. const VarLocMap &VarLocIDs) {
  750. bool Changed = false;
  751. const MachineBasicBlock *CurMBB = MI.getParent();
  752. if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
  753. return false;
  754. if (OpenRanges.empty())
  755. return false;
  756. LLVM_DEBUG(for (unsigned ID
  757. : OpenRanges.getVarLocs()) {
  758. // Copy OpenRanges to OutLocs, if not already present.
  759. dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
  760. VarLocIDs[ID].dump();
  761. });
  762. VarLocSet &VLS = OutLocs[CurMBB];
  763. Changed = VLS |= OpenRanges.getVarLocs();
  764. // New OutLocs set may be different due to spill, restore or register
  765. // copy instruction processing.
  766. if (Changed)
  767. VLS = OpenRanges.getVarLocs();
  768. OpenRanges.clear();
  769. return Changed;
  770. }
  771. /// Accumulate a mapping between each DILocalVariable fragment and other
  772. /// fragments of that DILocalVariable which overlap. This reduces work during
  773. /// the data-flow stage from "Find any overlapping fragments" to "Check if the
  774. /// known-to-overlap fragments are present".
  775. /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
  776. /// fragment usage.
  777. /// \param SeenFragments Map from DILocalVariable to all fragments of that
  778. /// Variable which are known to exist.
  779. /// \param OverlappingFragments The overlap map being constructed, from one
  780. /// Var/Fragment pair to a vector of fragments known to overlap.
  781. void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
  782. VarToFragments &SeenFragments,
  783. OverlapMap &OverlappingFragments) {
  784. DebugVariable MIVar(MI);
  785. FragmentInfo ThisFragment = MIVar.getFragmentDefault();
  786. // If this is the first sighting of this variable, then we are guaranteed
  787. // there are currently no overlapping fragments either. Initialize the set
  788. // of seen fragments, record no overlaps for the current one, and return.
  789. auto SeenIt = SeenFragments.find(MIVar.getVar());
  790. if (SeenIt == SeenFragments.end()) {
  791. SmallSet<FragmentInfo, 4> OneFragment;
  792. OneFragment.insert(ThisFragment);
  793. SeenFragments.insert({MIVar.getVar(), OneFragment});
  794. OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
  795. return;
  796. }
  797. // If this particular Variable/Fragment pair already exists in the overlap
  798. // map, it has already been accounted for.
  799. auto IsInOLapMap =
  800. OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
  801. if (!IsInOLapMap.second)
  802. return;
  803. auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
  804. auto &AllSeenFragments = SeenIt->second;
  805. // Otherwise, examine all other seen fragments for this variable, with "this"
  806. // fragment being a previously unseen fragment. Record any pair of
  807. // overlapping fragments.
  808. for (auto &ASeenFragment : AllSeenFragments) {
  809. // Does this previously seen fragment overlap?
  810. if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
  811. // Yes: Mark the current fragment as being overlapped.
  812. ThisFragmentsOverlaps.push_back(ASeenFragment);
  813. // Mark the previously seen fragment as being overlapped by the current
  814. // one.
  815. auto ASeenFragmentsOverlaps =
  816. OverlappingFragments.find({MIVar.getVar(), ASeenFragment});
  817. assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
  818. "Previously seen var fragment has no vector of overlaps");
  819. ASeenFragmentsOverlaps->second.push_back(ThisFragment);
  820. }
  821. }
  822. AllSeenFragments.insert(ThisFragment);
  823. }
  824. /// This routine creates OpenRanges and OutLocs.
  825. bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  826. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  827. TransferMap &Transfers, bool transferChanges,
  828. OverlapMap &OverlapFragments,
  829. VarToFragments &SeenFragments) {
  830. bool Changed = false;
  831. transferDebugValue(MI, OpenRanges, VarLocIDs);
  832. transferRegisterDef(MI, OpenRanges, VarLocIDs);
  833. if (transferChanges) {
  834. transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
  835. transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
  836. } else {
  837. // Build up a map of overlapping fragments on the first run through.
  838. if (MI.isDebugValue())
  839. accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
  840. }
  841. Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
  842. return Changed;
  843. }
  844. /// This routine joins the analysis results of all incoming edges in @MBB by
  845. /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
  846. /// source variable in all the predecessors of @MBB reside in the same location.
  847. bool LiveDebugValues::join(
  848. MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  849. const VarLocMap &VarLocIDs,
  850. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  851. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
  852. LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
  853. bool Changed = false;
  854. VarLocSet InLocsT; // Temporary incoming locations.
  855. // For all predecessors of this MBB, find the set of VarLocs that
  856. // can be joined.
  857. int NumVisited = 0;
  858. for (auto p : MBB.predecessors()) {
  859. // Ignore unvisited predecessor blocks. As we are processing
  860. // the blocks in reverse post-order any unvisited block can
  861. // be considered to not remove any incoming values.
  862. if (!Visited.count(p)) {
  863. LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
  864. << "\n");
  865. continue;
  866. }
  867. auto OL = OutLocs.find(p);
  868. // Join is null in case of empty OutLocs from any of the pred.
  869. if (OL == OutLocs.end())
  870. return false;
  871. // Just copy over the Out locs to incoming locs for the first visited
  872. // predecessor, and for all other predecessors join the Out locs.
  873. if (!NumVisited)
  874. InLocsT = OL->second;
  875. else
  876. InLocsT &= OL->second;
  877. LLVM_DEBUG({
  878. if (!InLocsT.empty()) {
  879. for (auto ID : InLocsT)
  880. dbgs() << " gathered candidate incoming var: "
  881. << VarLocIDs[ID].Var.getVar()->getName() << "\n";
  882. }
  883. });
  884. NumVisited++;
  885. }
  886. // Filter out DBG_VALUES that are out of scope.
  887. VarLocSet KillSet;
  888. bool IsArtificial = ArtificialBlocks.count(&MBB);
  889. if (!IsArtificial) {
  890. for (auto ID : InLocsT) {
  891. if (!VarLocIDs[ID].dominates(MBB)) {
  892. KillSet.set(ID);
  893. LLVM_DEBUG({
  894. auto Name = VarLocIDs[ID].Var.getVar()->getName();
  895. dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
  896. });
  897. }
  898. }
  899. }
  900. InLocsT.intersectWithComplement(KillSet);
  901. // As we are processing blocks in reverse post-order we
  902. // should have processed at least one predecessor, unless it
  903. // is the entry block which has no predecessor.
  904. assert((NumVisited || MBB.pred_empty()) &&
  905. "Should have processed at least one predecessor");
  906. if (InLocsT.empty())
  907. return false;
  908. VarLocSet &ILS = InLocs[&MBB];
  909. // Insert DBG_VALUE instructions, if not already inserted.
  910. VarLocSet Diff = InLocsT;
  911. Diff.intersectWithComplement(ILS);
  912. for (auto ID : Diff) {
  913. // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
  914. // new range is started for the var from the mbb's beginning by inserting
  915. // a new DBG_VALUE. process() will end this range however appropriate.
  916. const VarLoc &DiffIt = VarLocIDs[ID];
  917. const MachineInstr *DebugInstr = &DiffIt.MI;
  918. MachineInstr *MI = nullptr;
  919. if (DiffIt.isConstant()) {
  920. MachineOperand MO(DebugInstr->getOperand(0));
  921. MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
  922. DebugInstr->getDesc(), false, MO,
  923. DebugInstr->getDebugVariable(),
  924. DebugInstr->getDebugExpression());
  925. } else {
  926. MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
  927. DebugInstr->getDesc(), DebugInstr->isIndirectDebugValue(),
  928. DebugInstr->getOperand(0).getReg(),
  929. DebugInstr->getDebugVariable(),
  930. DebugInstr->getDebugExpression());
  931. if (DebugInstr->isIndirectDebugValue())
  932. MI->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
  933. }
  934. LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
  935. ILS.set(ID);
  936. ++NumInserted;
  937. Changed = true;
  938. }
  939. return Changed;
  940. }
  941. /// Calculate the liveness information for the given machine function and
  942. /// extend ranges across basic blocks.
  943. bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
  944. LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
  945. bool Changed = false;
  946. bool OLChanged = false;
  947. bool MBBJoined = false;
  948. VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
  949. OverlapMap OverlapFragments; // Map of overlapping variable fragments
  950. OpenRangesSet OpenRanges(OverlapFragments);
  951. // Ranges that are open until end of bb.
  952. VarLocInMBB OutLocs; // Ranges that exist beyond bb.
  953. VarLocInMBB InLocs; // Ranges that are incoming after joining.
  954. TransferMap Transfers; // DBG_VALUEs associated with spills.
  955. VarToFragments SeenFragments;
  956. // Blocks which are artificial, i.e. blocks which exclusively contain
  957. // instructions without locations, or with line 0 locations.
  958. SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
  959. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  960. DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
  961. std::priority_queue<unsigned int, std::vector<unsigned int>,
  962. std::greater<unsigned int>>
  963. Worklist;
  964. std::priority_queue<unsigned int, std::vector<unsigned int>,
  965. std::greater<unsigned int>>
  966. Pending;
  967. enum : bool { dontTransferChanges = false, transferChanges = true };
  968. // Initialize every mbb with OutLocs.
  969. // We are not looking at any spill instructions during the initial pass
  970. // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
  971. // instructions for spills of registers that are known to be user variables
  972. // within the BB in which the spill occurs.
  973. for (auto &MBB : MF) {
  974. for (auto &MI : MBB) {
  975. process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  976. dontTransferChanges, OverlapFragments, SeenFragments);
  977. }
  978. }
  979. auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
  980. if (const DebugLoc &DL = MI.getDebugLoc())
  981. return DL.getLine() != 0;
  982. return false;
  983. };
  984. for (auto &MBB : MF)
  985. if (none_of(MBB.instrs(), hasNonArtificialLocation))
  986. ArtificialBlocks.insert(&MBB);
  987. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  988. "OutLocs after initialization", dbgs()));
  989. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  990. unsigned int RPONumber = 0;
  991. for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
  992. OrderToBB[RPONumber] = *RI;
  993. BBToOrder[*RI] = RPONumber;
  994. Worklist.push(RPONumber);
  995. ++RPONumber;
  996. }
  997. // This is a standard "union of predecessor outs" dataflow problem.
  998. // To solve it, we perform join() and process() using the two worklist method
  999. // until the ranges converge.
  1000. // Ranges have converged when both worklists are empty.
  1001. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  1002. while (!Worklist.empty() || !Pending.empty()) {
  1003. // We track what is on the pending worklist to avoid inserting the same
  1004. // thing twice. We could avoid this with a custom priority queue, but this
  1005. // is probably not worth it.
  1006. SmallPtrSet<MachineBasicBlock *, 16> OnPending;
  1007. LLVM_DEBUG(dbgs() << "Processing Worklist\n");
  1008. while (!Worklist.empty()) {
  1009. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  1010. Worklist.pop();
  1011. MBBJoined =
  1012. join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
  1013. Visited.insert(MBB);
  1014. if (MBBJoined) {
  1015. MBBJoined = false;
  1016. Changed = true;
  1017. // Now that we have started to extend ranges across BBs we need to
  1018. // examine spill instructions to see whether they spill registers that
  1019. // correspond to user variables.
  1020. for (auto &MI : *MBB)
  1021. OLChanged |=
  1022. process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  1023. transferChanges, OverlapFragments, SeenFragments);
  1024. // Add any DBG_VALUE instructions necessitated by spills.
  1025. for (auto &TR : Transfers)
  1026. MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
  1027. TR.DebugInst);
  1028. Transfers.clear();
  1029. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  1030. "OutLocs after propagating", dbgs()));
  1031. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
  1032. "InLocs after propagating", dbgs()));
  1033. if (OLChanged) {
  1034. OLChanged = false;
  1035. for (auto s : MBB->successors())
  1036. if (OnPending.insert(s).second) {
  1037. Pending.push(BBToOrder[s]);
  1038. }
  1039. }
  1040. }
  1041. }
  1042. Worklist.swap(Pending);
  1043. // At this point, pending must be empty, since it was just the empty
  1044. // worklist
  1045. assert(Pending.empty() && "Pending should be empty");
  1046. }
  1047. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
  1048. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
  1049. return Changed;
  1050. }
  1051. bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
  1052. if (!MF.getFunction().getSubprogram())
  1053. // LiveDebugValues will already have removed all DBG_VALUEs.
  1054. return false;
  1055. // Skip functions from NoDebug compilation units.
  1056. if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  1057. DICompileUnit::NoDebug)
  1058. return false;
  1059. TRI = MF.getSubtarget().getRegisterInfo();
  1060. TII = MF.getSubtarget().getInstrInfo();
  1061. TFI = MF.getSubtarget().getFrameLowering();
  1062. TFI->determineCalleeSaves(MF, CalleeSavedRegs,
  1063. make_unique<RegScavenger>().get());
  1064. LS.initialize(MF);
  1065. bool Changed = ExtendRanges(MF);
  1066. return Changed;
  1067. }