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