LiveDebugValues.cpp 56 KB

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