DebugHandlerBase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Common functionality for different debug information format backends.
  10. // LLVM currently supports DWARF and CodeView.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/DebugHandlerBase.h"
  14. #include "llvm/CodeGen/AsmPrinter.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/MachineInstr.h"
  17. #include "llvm/CodeGen/MachineModuleInfo.h"
  18. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  19. #include "llvm/IR/DebugInfo.h"
  20. #include "llvm/MC/MCStreamer.h"
  21. #include "llvm/Support/CommandLine.h"
  22. using namespace llvm;
  23. #define DEBUG_TYPE "dwarfdebug"
  24. /// If true, we drop variable location ranges which exist entirely outside the
  25. /// variable's lexical scope instruction ranges.
  26. static cl::opt<bool> TrimVarLocs("trim-var-locs", cl::Hidden, cl::init(true));
  27. std::optional<DbgVariableLocation>
  28. DbgVariableLocation::extractFromMachineInstruction(
  29. const MachineInstr &Instruction) {
  30. DbgVariableLocation Location;
  31. // Variables calculated from multiple locations can't be represented here.
  32. if (Instruction.getNumDebugOperands() != 1)
  33. return std::nullopt;
  34. if (!Instruction.getDebugOperand(0).isReg())
  35. return std::nullopt;
  36. Location.Register = Instruction.getDebugOperand(0).getReg();
  37. Location.FragmentInfo.reset();
  38. // We only handle expressions generated by DIExpression::appendOffset,
  39. // which doesn't require a full stack machine.
  40. int64_t Offset = 0;
  41. const DIExpression *DIExpr = Instruction.getDebugExpression();
  42. auto Op = DIExpr->expr_op_begin();
  43. // We can handle a DBG_VALUE_LIST iff it has exactly one location operand that
  44. // appears exactly once at the start of the expression.
  45. if (Instruction.isDebugValueList()) {
  46. if (Instruction.getNumDebugOperands() == 1 &&
  47. Op->getOp() == dwarf::DW_OP_LLVM_arg)
  48. ++Op;
  49. else
  50. return std::nullopt;
  51. }
  52. while (Op != DIExpr->expr_op_end()) {
  53. switch (Op->getOp()) {
  54. case dwarf::DW_OP_constu: {
  55. int Value = Op->getArg(0);
  56. ++Op;
  57. if (Op != DIExpr->expr_op_end()) {
  58. switch (Op->getOp()) {
  59. case dwarf::DW_OP_minus:
  60. Offset -= Value;
  61. break;
  62. case dwarf::DW_OP_plus:
  63. Offset += Value;
  64. break;
  65. default:
  66. continue;
  67. }
  68. }
  69. } break;
  70. case dwarf::DW_OP_plus_uconst:
  71. Offset += Op->getArg(0);
  72. break;
  73. case dwarf::DW_OP_LLVM_fragment:
  74. Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
  75. break;
  76. case dwarf::DW_OP_deref:
  77. Location.LoadChain.push_back(Offset);
  78. Offset = 0;
  79. break;
  80. default:
  81. return std::nullopt;
  82. }
  83. ++Op;
  84. }
  85. // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
  86. // instruction.
  87. // FIXME: Replace these with DIExpression.
  88. if (Instruction.isIndirectDebugValue())
  89. Location.LoadChain.push_back(Offset);
  90. return Location;
  91. }
  92. DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
  93. void DebugHandlerBase::beginModule(Module *M) {
  94. if (M->debug_compile_units().empty())
  95. Asm = nullptr;
  96. }
  97. // Each LexicalScope has first instruction and last instruction to mark
  98. // beginning and end of a scope respectively. Create an inverse map that list
  99. // scopes starts (and ends) with an instruction. One instruction may start (or
  100. // end) multiple scopes. Ignore scopes that are not reachable.
  101. void DebugHandlerBase::identifyScopeMarkers() {
  102. SmallVector<LexicalScope *, 4> WorkList;
  103. WorkList.push_back(LScopes.getCurrentFunctionScope());
  104. while (!WorkList.empty()) {
  105. LexicalScope *S = WorkList.pop_back_val();
  106. const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
  107. if (!Children.empty())
  108. WorkList.append(Children.begin(), Children.end());
  109. if (S->isAbstractScope())
  110. continue;
  111. for (const InsnRange &R : S->getRanges()) {
  112. assert(R.first && "InsnRange does not have first instruction!");
  113. assert(R.second && "InsnRange does not have second instruction!");
  114. requestLabelBeforeInsn(R.first);
  115. requestLabelAfterInsn(R.second);
  116. }
  117. }
  118. }
  119. // Return Label preceding the instruction.
  120. MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
  121. MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
  122. assert(Label && "Didn't insert label before instruction");
  123. return Label;
  124. }
  125. // Return Label immediately following the instruction.
  126. MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
  127. return LabelsAfterInsn.lookup(MI);
  128. }
  129. /// If this type is derived from a base type then return base type size.
  130. uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) {
  131. assert(Ty);
  132. const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
  133. if (!DDTy)
  134. return Ty->getSizeInBits();
  135. unsigned Tag = DDTy->getTag();
  136. if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
  137. Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
  138. Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type &&
  139. Tag != dwarf::DW_TAG_immutable_type)
  140. return DDTy->getSizeInBits();
  141. DIType *BaseType = DDTy->getBaseType();
  142. if (!BaseType)
  143. return 0;
  144. // If this is a derived type, go ahead and get the base type, unless it's a
  145. // reference then it's just the size of the field. Pointer types have no need
  146. // of this since they're a different type of qualification on the type.
  147. if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
  148. BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
  149. return Ty->getSizeInBits();
  150. return getBaseTypeSize(BaseType);
  151. }
  152. bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) {
  153. if (isa<DIStringType>(Ty)) {
  154. // Some transformations (e.g. instcombine) may decide to turn a Fortran
  155. // character object into an integer, and later ones (e.g. SROA) may
  156. // further inject a constant integer in a llvm.dbg.value call to track
  157. // the object's value. Here we trust the transformations are doing the
  158. // right thing, and treat the constant as unsigned to preserve that value
  159. // (i.e. avoid sign extension).
  160. return true;
  161. }
  162. if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
  163. if (CTy->getTag() == dwarf::DW_TAG_enumeration_type) {
  164. if (!(Ty = CTy->getBaseType()))
  165. // FIXME: Enums without a fixed underlying type have unknown signedness
  166. // here, leading to incorrectly emitted constants.
  167. return false;
  168. } else
  169. // (Pieces of) aggregate types that get hacked apart by SROA may be
  170. // represented by a constant. Encode them as unsigned bytes.
  171. return true;
  172. }
  173. if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
  174. dwarf::Tag T = (dwarf::Tag)Ty->getTag();
  175. // Encode pointer constants as unsigned bytes. This is used at least for
  176. // null pointer constant emission.
  177. // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
  178. // here, but accept them for now due to a bug in SROA producing bogus
  179. // dbg.values.
  180. if (T == dwarf::DW_TAG_pointer_type ||
  181. T == dwarf::DW_TAG_ptr_to_member_type ||
  182. T == dwarf::DW_TAG_reference_type ||
  183. T == dwarf::DW_TAG_rvalue_reference_type)
  184. return true;
  185. assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
  186. T == dwarf::DW_TAG_volatile_type ||
  187. T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type ||
  188. T == dwarf::DW_TAG_immutable_type);
  189. assert(DTy->getBaseType() && "Expected valid base type");
  190. return isUnsignedDIType(DTy->getBaseType());
  191. }
  192. auto *BTy = cast<DIBasicType>(Ty);
  193. unsigned Encoding = BTy->getEncoding();
  194. assert((Encoding == dwarf::DW_ATE_unsigned ||
  195. Encoding == dwarf::DW_ATE_unsigned_char ||
  196. Encoding == dwarf::DW_ATE_signed ||
  197. Encoding == dwarf::DW_ATE_signed_char ||
  198. Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
  199. Encoding == dwarf::DW_ATE_boolean ||
  200. (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
  201. Ty->getName() == "decltype(nullptr)")) &&
  202. "Unsupported encoding");
  203. return Encoding == dwarf::DW_ATE_unsigned ||
  204. Encoding == dwarf::DW_ATE_unsigned_char ||
  205. Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
  206. Ty->getTag() == dwarf::DW_TAG_unspecified_type;
  207. }
  208. static bool hasDebugInfo(const MachineModuleInfo *MMI,
  209. const MachineFunction *MF) {
  210. if (!MMI->hasDebugInfo())
  211. return false;
  212. auto *SP = MF->getFunction().getSubprogram();
  213. if (!SP)
  214. return false;
  215. assert(SP->getUnit());
  216. auto EK = SP->getUnit()->getEmissionKind();
  217. if (EK == DICompileUnit::NoDebug)
  218. return false;
  219. return true;
  220. }
  221. void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
  222. PrevInstBB = nullptr;
  223. if (!Asm || !hasDebugInfo(MMI, MF)) {
  224. skippedNonDebugFunction();
  225. return;
  226. }
  227. // Grab the lexical scopes for the function, if we don't have any of those
  228. // then we're not going to be able to do anything.
  229. LScopes.initialize(*MF);
  230. if (LScopes.empty()) {
  231. beginFunctionImpl(MF);
  232. return;
  233. }
  234. // Make sure that each lexical scope will have a begin/end label.
  235. identifyScopeMarkers();
  236. // Calculate history for local variables.
  237. assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
  238. assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
  239. calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
  240. DbgValues, DbgLabels);
  241. InstOrdering.initialize(*MF);
  242. if (TrimVarLocs)
  243. DbgValues.trimLocationRanges(*MF, LScopes, InstOrdering);
  244. LLVM_DEBUG(DbgValues.dump());
  245. // Request labels for the full history.
  246. for (const auto &I : DbgValues) {
  247. const auto &Entries = I.second;
  248. if (Entries.empty())
  249. continue;
  250. auto IsDescribedByReg = [](const MachineInstr *MI) {
  251. return any_of(MI->debug_operands(),
  252. [](auto &MO) { return MO.isReg() && MO.getReg(); });
  253. };
  254. // The first mention of a function argument gets the CurrentFnBegin label,
  255. // so arguments are visible when breaking at function entry.
  256. //
  257. // We do not change the label for values that are described by registers,
  258. // as that could place them above their defining instructions. We should
  259. // ideally not change the labels for constant debug values either, since
  260. // doing that violates the ranges that are calculated in the history map.
  261. // However, we currently do not emit debug values for constant arguments
  262. // directly at the start of the function, so this code is still useful.
  263. const DILocalVariable *DIVar =
  264. Entries.front().getInstr()->getDebugVariable();
  265. if (DIVar->isParameter() &&
  266. getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) {
  267. if (!IsDescribedByReg(Entries.front().getInstr()))
  268. LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
  269. if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
  270. // Mark all non-overlapping initial fragments.
  271. for (const auto *I = Entries.begin(); I != Entries.end(); ++I) {
  272. if (!I->isDbgValue())
  273. continue;
  274. const DIExpression *Fragment = I->getInstr()->getDebugExpression();
  275. if (std::any_of(Entries.begin(), I,
  276. [&](DbgValueHistoryMap::Entry Pred) {
  277. return Pred.isDbgValue() &&
  278. Fragment->fragmentsOverlap(
  279. Pred.getInstr()->getDebugExpression());
  280. }))
  281. break;
  282. // The code that generates location lists for DWARF assumes that the
  283. // entries' start labels are monotonically increasing, and since we
  284. // don't change the label for fragments that are described by
  285. // registers, we must bail out when encountering such a fragment.
  286. if (IsDescribedByReg(I->getInstr()))
  287. break;
  288. LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
  289. }
  290. }
  291. }
  292. for (const auto &Entry : Entries) {
  293. if (Entry.isDbgValue())
  294. requestLabelBeforeInsn(Entry.getInstr());
  295. else
  296. requestLabelAfterInsn(Entry.getInstr());
  297. }
  298. }
  299. // Ensure there is a symbol before DBG_LABEL.
  300. for (const auto &I : DbgLabels) {
  301. const MachineInstr *MI = I.second;
  302. requestLabelBeforeInsn(MI);
  303. }
  304. PrevInstLoc = DebugLoc();
  305. PrevLabel = Asm->getFunctionBegin();
  306. beginFunctionImpl(MF);
  307. }
  308. void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
  309. if (!Asm || !MMI->hasDebugInfo())
  310. return;
  311. assert(CurMI == nullptr);
  312. CurMI = MI;
  313. // Insert labels where requested.
  314. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  315. LabelsBeforeInsn.find(MI);
  316. // No label needed.
  317. if (I == LabelsBeforeInsn.end())
  318. return;
  319. // Label already assigned.
  320. if (I->second)
  321. return;
  322. if (!PrevLabel) {
  323. PrevLabel = MMI->getContext().createTempSymbol();
  324. Asm->OutStreamer->emitLabel(PrevLabel);
  325. }
  326. I->second = PrevLabel;
  327. }
  328. void DebugHandlerBase::endInstruction() {
  329. if (!Asm || !MMI->hasDebugInfo())
  330. return;
  331. assert(CurMI != nullptr);
  332. // Don't create a new label after DBG_VALUE and other instructions that don't
  333. // generate code.
  334. if (!CurMI->isMetaInstruction()) {
  335. PrevLabel = nullptr;
  336. PrevInstBB = CurMI->getParent();
  337. }
  338. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  339. LabelsAfterInsn.find(CurMI);
  340. // No label needed or label already assigned.
  341. if (I == LabelsAfterInsn.end() || I->second) {
  342. CurMI = nullptr;
  343. return;
  344. }
  345. // We need a label after this instruction. With basic block sections, just
  346. // use the end symbol of the section if this is the last instruction of the
  347. // section. This reduces the need for an additional label and also helps
  348. // merging ranges.
  349. if (CurMI->getParent()->isEndSection() && CurMI->getNextNode() == nullptr) {
  350. PrevLabel = CurMI->getParent()->getEndSymbol();
  351. } else if (!PrevLabel) {
  352. PrevLabel = MMI->getContext().createTempSymbol();
  353. Asm->OutStreamer->emitLabel(PrevLabel);
  354. }
  355. I->second = PrevLabel;
  356. CurMI = nullptr;
  357. }
  358. void DebugHandlerBase::endFunction(const MachineFunction *MF) {
  359. if (Asm && hasDebugInfo(MMI, MF))
  360. endFunctionImpl(MF);
  361. DbgValues.clear();
  362. DbgLabels.clear();
  363. LabelsBeforeInsn.clear();
  364. LabelsAfterInsn.clear();
  365. InstOrdering.clear();
  366. }
  367. void DebugHandlerBase::beginBasicBlockSection(const MachineBasicBlock &MBB) {
  368. EpilogBeginBlock = nullptr;
  369. if (!MBB.isEntryBlock())
  370. PrevLabel = MBB.getSymbol();
  371. }
  372. void DebugHandlerBase::endBasicBlockSection(const MachineBasicBlock &MBB) {
  373. PrevLabel = nullptr;
  374. }