LiveDebugValues.cpp 54 KB

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