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 25 using namespace llvm; 26 27 #define DEBUG_TYPE "dwarfdebug" 28 29 Optional<DbgVariableLocation> 30 DbgVariableLocation::extractFromMachineInstruction( 31 const MachineInstr &Instruction) { 32 DbgVariableLocation Location; 33 if (!Instruction.isDebugValue()) 34 return None; 35 if (!Instruction.getOperand(0).isReg()) 36 return None; 37 Location.Register = Instruction.getOperand(0).getReg(); 38 Location.FragmentInfo.reset(); 39 // We only handle expressions generated by DIExpression::appendOffset, 40 // which doesn't require a full stack machine. 41 int64_t Offset = 0; 42 const DIExpression *DIExpr = Instruction.getDebugExpression(); 43 auto Op = DIExpr->expr_op_begin(); 44 while (Op != DIExpr->expr_op_end()) { 45 switch (Op->getOp()) { 46 case dwarf::DW_OP_constu: { 47 int Value = Op->getArg(0); 48 ++Op; 49 if (Op != DIExpr->expr_op_end()) { 50 switch (Op->getOp()) { 51 case dwarf::DW_OP_minus: 52 Offset -= Value; 53 break; 54 case dwarf::DW_OP_plus: 55 Offset += Value; 56 break; 57 default: 58 continue; 59 } 60 } 61 } break; 62 case dwarf::DW_OP_plus_uconst: 63 Offset += Op->getArg(0); 64 break; 65 case dwarf::DW_OP_LLVM_fragment: 66 Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)}; 67 break; 68 case dwarf::DW_OP_deref: 69 Location.LoadChain.push_back(Offset); 70 Offset = 0; 71 break; 72 default: 73 return None; 74 } 75 ++Op; 76 } 77 78 // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE 79 // instruction. 80 // FIXME: Replace these with DIExpression. 81 if (Instruction.isIndirectDebugValue()) 82 Location.LoadChain.push_back(Offset); 83 84 return Location; 85 } 86 87 DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {} 88 89 // Each LexicalScope has first instruction and last instruction to mark 90 // beginning and end of a scope respectively. Create an inverse map that list 91 // scopes starts (and ends) with an instruction. One instruction may start (or 92 // end) multiple scopes. Ignore scopes that are not reachable. 93 void DebugHandlerBase::identifyScopeMarkers() { 94 SmallVector<LexicalScope *, 4> WorkList; 95 WorkList.push_back(LScopes.getCurrentFunctionScope()); 96 while (!WorkList.empty()) { 97 LexicalScope *S = WorkList.pop_back_val(); 98 99 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren(); 100 if (!Children.empty()) 101 WorkList.append(Children.begin(), Children.end()); 102 103 if (S->isAbstractScope()) 104 continue; 105 106 for (const InsnRange &R : S->getRanges()) { 107 assert(R.first && "InsnRange does not have first instruction!"); 108 assert(R.second && "InsnRange does not have second instruction!"); 109 requestLabelBeforeInsn(R.first); 110 requestLabelAfterInsn(R.second); 111 } 112 } 113 } 114 115 // Return Label preceding the instruction. 116 MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) { 117 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 118 assert(Label && "Didn't insert label before instruction"); 119 return Label; 120 } 121 122 // Return Label immediately following the instruction. 123 MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) { 124 return LabelsAfterInsn.lookup(MI); 125 } 126 127 // Return the function-local offset of an instruction. 128 const MCExpr * 129 DebugHandlerBase::getFunctionLocalOffsetAfterInsn(const MachineInstr *MI) { 130 MCContext &MC = Asm->OutContext; 131 132 MCSymbol *Start = Asm->getFunctionBegin(); 133 const auto *StartRef = MCSymbolRefExpr::create(Start, MC); 134 135 MCSymbol *AfterInsn = getLabelAfterInsn(MI); 136 assert(AfterInsn && "Expected label after instruction"); 137 const auto *AfterRef = MCSymbolRefExpr::create(AfterInsn, MC); 138 139 return MCBinaryExpr::createSub(AfterRef, StartRef, MC); 140 } 141 142 /// If this type is derived from a base type then return base type size. 143 uint64_t DebugHandlerBase::getBaseTypeSize(const DITypeRef TyRef) { 144 DIType *Ty = TyRef.resolve(); 145 assert(Ty); 146 DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty); 147 if (!DDTy) 148 return Ty->getSizeInBits(); 149 150 unsigned Tag = DDTy->getTag(); 151 152 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && 153 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && 154 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type) 155 return DDTy->getSizeInBits(); 156 157 DIType *BaseType = DDTy->getBaseType().resolve(); 158 159 if (!BaseType) 160 return 0; 161 162 // If this is a derived type, go ahead and get the base type, unless it's a 163 // reference then it's just the size of the field. Pointer types have no need 164 // of this since they're a different type of qualification on the type. 165 if (BaseType->getTag() == dwarf::DW_TAG_reference_type || 166 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type) 167 return Ty->getSizeInBits(); 168 169 return getBaseTypeSize(BaseType); 170 } 171 172 static bool hasDebugInfo(const MachineModuleInfo *MMI, 173 const MachineFunction *MF) { 174 if (!MMI->hasDebugInfo()) 175 return false; 176 auto *SP = MF->getFunction().getSubprogram(); 177 if (!SP) 178 return false; 179 assert(SP->getUnit()); 180 auto EK = SP->getUnit()->getEmissionKind(); 181 if (EK == DICompileUnit::NoDebug) 182 return false; 183 return true; 184 } 185 186 void DebugHandlerBase::beginFunction(const MachineFunction *MF) { 187 PrevInstBB = nullptr; 188 189 if (!Asm || !hasDebugInfo(MMI, MF)) { 190 skippedNonDebugFunction(); 191 return; 192 } 193 194 // Grab the lexical scopes for the function, if we don't have any of those 195 // then we're not going to be able to do anything. 196 LScopes.initialize(*MF); 197 if (LScopes.empty()) { 198 beginFunctionImpl(MF); 199 return; 200 } 201 202 // Make sure that each lexical scope will have a begin/end label. 203 identifyScopeMarkers(); 204 205 // Calculate history for local variables. 206 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!"); 207 assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!"); 208 calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(), 209 DbgValues, DbgLabels); 210 LLVM_DEBUG(DbgValues.dump()); 211 212 // Request labels for the full history. 213 for (const auto &I : DbgValues) { 214 const auto &Entries = I.second; 215 if (Entries.empty()) 216 continue; 217 218 auto IsDescribedByReg = [](const MachineInstr *MI) { 219 return MI->getOperand(0).isReg() && MI->getOperand(0).getReg(); 220 }; 221 222 // The first mention of a function argument gets the CurrentFnBegin label, 223 // so arguments are visible when breaking at function entry. 224 // 225 // We do not change the label for values that are described by registers, 226 // as that could place them above their defining instructions. We should 227 // ideally not change the labels for constant debug values either, since 228 // doing that violates the ranges that are calculated in the history map. 229 // However, we currently do not emit debug values for constant arguments 230 // directly at the start of the function, so this code is still useful. 231 const DILocalVariable *DIVar = 232 Entries.front().getInstr()->getDebugVariable(); 233 if (DIVar->isParameter() && 234 getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) { 235 if (!IsDescribedByReg(Entries.front().getInstr())) 236 LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin(); 237 if (Entries.front().getInstr()->getDebugExpression()->isFragment()) { 238 // Mark all non-overlapping initial fragments. 239 for (auto I = Entries.begin(); I != Entries.end(); ++I) { 240 if (!I->isDbgValue()) 241 continue; 242 const DIExpression *Fragment = I->getInstr()->getDebugExpression(); 243 if (std::any_of(Entries.begin(), I, 244 [&](DbgValueHistoryMap::Entry Pred) { 245 return Pred.isDbgValue() && 246 Fragment->fragmentsOverlap( 247 Pred.getInstr()->getDebugExpression()); 248 })) 249 break; 250 if (!IsDescribedByReg(I->getInstr())) 251 LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin(); 252 } 253 } 254 } 255 256 for (const auto &Entry : Entries) { 257 if (Entry.isDbgValue()) 258 requestLabelBeforeInsn(Entry.getInstr()); 259 else 260 requestLabelAfterInsn(Entry.getInstr()); 261 } 262 } 263 264 // Ensure there is a symbol before DBG_LABEL. 265 for (const auto &I : DbgLabels) { 266 const MachineInstr *MI = I.second; 267 requestLabelBeforeInsn(MI); 268 } 269 270 PrevInstLoc = DebugLoc(); 271 PrevLabel = Asm->getFunctionBegin(); 272 beginFunctionImpl(MF); 273 } 274 275 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) { 276 if (!MMI->hasDebugInfo()) 277 return; 278 279 assert(CurMI == nullptr); 280 CurMI = MI; 281 282 // Insert labels where requested. 283 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 284 LabelsBeforeInsn.find(MI); 285 286 // No label needed. 287 if (I == LabelsBeforeInsn.end()) 288 return; 289 290 // Label already assigned. 291 if (I->second) 292 return; 293 294 if (!PrevLabel) { 295 PrevLabel = MMI->getContext().createTempSymbol(); 296 Asm->OutStreamer->EmitLabel(PrevLabel); 297 } 298 I->second = PrevLabel; 299 } 300 301 void DebugHandlerBase::endInstruction() { 302 if (!MMI->hasDebugInfo()) 303 return; 304 305 assert(CurMI != nullptr); 306 // Don't create a new label after DBG_VALUE and other instructions that don't 307 // generate code. 308 if (!CurMI->isMetaInstruction()) { 309 PrevLabel = nullptr; 310 PrevInstBB = CurMI->getParent(); 311 } 312 313 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 314 LabelsAfterInsn.find(CurMI); 315 CurMI = nullptr; 316 317 // No label needed. 318 if (I == LabelsAfterInsn.end()) 319 return; 320 321 // Label already assigned. 322 if (I->second) 323 return; 324 325 // We need a label after this instruction. 326 if (!PrevLabel) { 327 PrevLabel = MMI->getContext().createTempSymbol(); 328 Asm->OutStreamer->EmitLabel(PrevLabel); 329 } 330 I->second = PrevLabel; 331 } 332 333 void DebugHandlerBase::endFunction(const MachineFunction *MF) { 334 if (hasDebugInfo(MMI, MF)) 335 endFunctionImpl(MF); 336 DbgValues.clear(); 337 DbgLabels.clear(); 338 LabelsBeforeInsn.clear(); 339 LabelsAfterInsn.clear(); 340 } 341