1 //===- InstrRefBasedImpl.h - 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 #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H 10 #define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H 11 12 #include "llvm/ADT/DenseMap.h" 13 #include "llvm/ADT/SmallPtrSet.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/ADT/UniqueVector.h" 16 #include "llvm/CodeGen/LexicalScopes.h" 17 #include "llvm/CodeGen/MachineBasicBlock.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineInstr.h" 21 #include "llvm/CodeGen/TargetFrameLowering.h" 22 #include "llvm/CodeGen/TargetInstrInfo.h" 23 #include "llvm/CodeGen/TargetPassConfig.h" 24 #include "llvm/IR/DebugInfoMetadata.h" 25 26 #include "LiveDebugValues.h" 27 28 class TransferTracker; 29 30 // Forward dec of unit test class, so that we can peer into the LDV object. 31 class InstrRefLDVTest; 32 33 namespace LiveDebugValues { 34 35 class MLocTracker; 36 37 using namespace llvm; 38 39 /// Handle-class for a particular "location". This value-type uniquely 40 /// symbolises a register or stack location, allowing manipulation of locations 41 /// without concern for where that location is. Practically, this allows us to 42 /// treat the state of the machine at a particular point as an array of values, 43 /// rather than a map of values. 44 class LocIdx { 45 unsigned Location; 46 47 // Default constructor is private, initializing to an illegal location number. 48 // Use only for "not an entry" elements in IndexedMaps. 49 LocIdx() : Location(UINT_MAX) {} 50 51 public: 52 #define NUM_LOC_BITS 24 53 LocIdx(unsigned L) : Location(L) { 54 assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits"); 55 } 56 57 static LocIdx MakeIllegalLoc() { return LocIdx(); } 58 static LocIdx MakeTombstoneLoc() { 59 LocIdx L = LocIdx(); 60 --L.Location; 61 return L; 62 } 63 64 bool isIllegal() const { return Location == UINT_MAX; } 65 66 uint64_t asU64() const { return Location; } 67 68 bool operator==(unsigned L) const { return Location == L; } 69 70 bool operator==(const LocIdx &L) const { return Location == L.Location; } 71 72 bool operator!=(unsigned L) const { return !(*this == L); } 73 74 bool operator!=(const LocIdx &L) const { return !(*this == L); } 75 76 bool operator<(const LocIdx &Other) const { 77 return Location < Other.Location; 78 } 79 }; 80 81 // The location at which a spilled value resides. It consists of a register and 82 // an offset. 83 struct SpillLoc { 84 unsigned SpillBase; 85 StackOffset SpillOffset; 86 bool operator==(const SpillLoc &Other) const { 87 return std::make_pair(SpillBase, SpillOffset) == 88 std::make_pair(Other.SpillBase, Other.SpillOffset); 89 } 90 bool operator<(const SpillLoc &Other) const { 91 return std::make_tuple(SpillBase, SpillOffset.getFixed(), 92 SpillOffset.getScalable()) < 93 std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(), 94 Other.SpillOffset.getScalable()); 95 } 96 }; 97 98 /// Unique identifier for a value defined by an instruction, as a value type. 99 /// Casts back and forth to a uint64_t. Probably replacable with something less 100 /// bit-constrained. Each value identifies the instruction and machine location 101 /// where the value is defined, although there may be no corresponding machine 102 /// operand for it (ex: regmasks clobbering values). The instructions are 103 /// one-based, and definitions that are PHIs have instruction number zero. 104 /// 105 /// The obvious limits of a 1M block function or 1M instruction blocks are 106 /// problematic; but by that point we should probably have bailed out of 107 /// trying to analyse the function. 108 class ValueIDNum { 109 union { 110 struct { 111 uint64_t BlockNo : 20; /// The block where the def happens. 112 uint64_t InstNo : 20; /// The Instruction where the def happens. 113 /// One based, is distance from start of block. 114 uint64_t LocNo 115 : NUM_LOC_BITS; /// The machine location where the def happens. 116 } s; 117 uint64_t Value; 118 } u; 119 120 static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?"); 121 122 public: 123 // Default-initialize to EmptyValue. This is necessary to make IndexedMaps 124 // of values to work. 125 ValueIDNum() { u.Value = EmptyValue.asU64(); } 126 127 ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) { 128 u.s = {Block, Inst, Loc}; 129 } 130 131 ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) { 132 u.s = {Block, Inst, Loc.asU64()}; 133 } 134 135 uint64_t getBlock() const { return u.s.BlockNo; } 136 uint64_t getInst() const { return u.s.InstNo; } 137 uint64_t getLoc() const { return u.s.LocNo; } 138 bool isPHI() const { return u.s.InstNo == 0; } 139 140 uint64_t asU64() const { return u.Value; } 141 142 static ValueIDNum fromU64(uint64_t v) { 143 ValueIDNum Val; 144 Val.u.Value = v; 145 return Val; 146 } 147 148 bool operator<(const ValueIDNum &Other) const { 149 return asU64() < Other.asU64(); 150 } 151 152 bool operator==(const ValueIDNum &Other) const { 153 return u.Value == Other.u.Value; 154 } 155 156 bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); } 157 158 std::string asString(const std::string &mlocname) const { 159 return Twine("Value{bb: ") 160 .concat(Twine(u.s.BlockNo) 161 .concat(Twine(", inst: ") 162 .concat((u.s.InstNo ? Twine(u.s.InstNo) 163 : Twine("live-in")) 164 .concat(Twine(", loc: ").concat( 165 Twine(mlocname))) 166 .concat(Twine("}"))))) 167 .str(); 168 } 169 170 static ValueIDNum EmptyValue; 171 static ValueIDNum TombstoneValue; 172 }; 173 174 /// Thin wrapper around an integer -- designed to give more type safety to 175 /// spill location numbers. 176 class SpillLocationNo { 177 public: 178 explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {} 179 unsigned SpillNo; 180 unsigned id() const { return SpillNo; } 181 182 bool operator<(const SpillLocationNo &Other) const { 183 return SpillNo < Other.SpillNo; 184 } 185 186 bool operator==(const SpillLocationNo &Other) const { 187 return SpillNo == Other.SpillNo; 188 } 189 bool operator!=(const SpillLocationNo &Other) const { 190 return !(*this == Other); 191 } 192 }; 193 194 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify 195 /// the the value, and Boolean of whether or not it's indirect. 196 class DbgValueProperties { 197 public: 198 DbgValueProperties(const DIExpression *DIExpr, bool Indirect) 199 : DIExpr(DIExpr), Indirect(Indirect) {} 200 201 /// Extract properties from an existing DBG_VALUE instruction. 202 DbgValueProperties(const MachineInstr &MI) { 203 assert(MI.isDebugValue()); 204 DIExpr = MI.getDebugExpression(); 205 Indirect = MI.getOperand(1).isImm(); 206 } 207 208 bool operator==(const DbgValueProperties &Other) const { 209 return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect); 210 } 211 212 bool operator!=(const DbgValueProperties &Other) const { 213 return !(*this == Other); 214 } 215 216 const DIExpression *DIExpr; 217 bool Indirect; 218 }; 219 220 /// Class recording the (high level) _value_ of a variable. Identifies either 221 /// the value of the variable as a ValueIDNum, or a constant MachineOperand. 222 /// This class also stores meta-information about how the value is qualified. 223 /// Used to reason about variable values when performing the second 224 /// (DebugVariable specific) dataflow analysis. 225 class DbgValue { 226 public: 227 /// If Kind is Def, the value number that this value is based on. VPHIs set 228 /// this field to EmptyValue if there is no machine-value for this VPHI, or 229 /// the corresponding machine-value if there is one. 230 ValueIDNum ID; 231 /// If Kind is Const, the MachineOperand defining this value. 232 Optional<MachineOperand> MO; 233 /// For a NoVal or VPHI DbgValue, which block it was generated in. 234 int BlockNo; 235 236 /// Qualifiers for the ValueIDNum above. 237 DbgValueProperties Properties; 238 239 typedef enum { 240 Undef, // Represents a DBG_VALUE $noreg in the transfer function only. 241 Def, // This value is defined by an inst, or is a PHI value. 242 Const, // A constant value contained in the MachineOperand field. 243 VPHI, // Incoming values to BlockNo differ, those values must be joined by 244 // a PHI in this block. 245 NoVal, // Empty DbgValue indicating an unknown value. Used as initializer, 246 // before dominating blocks values are propagated in. 247 } KindT; 248 /// Discriminator for whether this is a constant or an in-program value. 249 KindT Kind; 250 251 DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind) 252 : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) { 253 assert(Kind == Def); 254 } 255 256 DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind) 257 : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo), 258 Properties(Prop), Kind(Kind) { 259 assert(Kind == NoVal || Kind == VPHI); 260 } 261 262 DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind) 263 : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop), 264 Kind(Kind) { 265 assert(Kind == Const); 266 } 267 268 DbgValue(const DbgValueProperties &Prop, KindT Kind) 269 : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop), 270 Kind(Kind) { 271 assert(Kind == Undef && 272 "Empty DbgValue constructor must pass in Undef kind"); 273 } 274 275 #ifndef NDEBUG 276 void dump(const MLocTracker *MTrack) const; 277 #endif 278 279 bool operator==(const DbgValue &Other) const { 280 if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties)) 281 return false; 282 else if (Kind == Def && ID != Other.ID) 283 return false; 284 else if (Kind == NoVal && BlockNo != Other.BlockNo) 285 return false; 286 else if (Kind == Const) 287 return MO->isIdenticalTo(*Other.MO); 288 else if (Kind == VPHI && BlockNo != Other.BlockNo) 289 return false; 290 else if (Kind == VPHI && ID != Other.ID) 291 return false; 292 293 return true; 294 } 295 296 bool operator!=(const DbgValue &Other) const { return !(*this == Other); } 297 }; 298 299 class LocIdxToIndexFunctor { 300 public: 301 using argument_type = LocIdx; 302 unsigned operator()(const LocIdx &L) const { return L.asU64(); } 303 }; 304 305 /// Tracker for what values are in machine locations. Listens to the Things 306 /// being Done by various instructions, and maintains a table of what machine 307 /// locations have what values (as defined by a ValueIDNum). 308 /// 309 /// There are potentially a much larger number of machine locations on the 310 /// target machine than the actual working-set size of the function. On x86 for 311 /// example, we're extremely unlikely to want to track values through control 312 /// or debug registers. To avoid doing so, MLocTracker has several layers of 313 /// indirection going on, described below, to avoid unnecessarily tracking 314 /// any location. 315 /// 316 /// Here's a sort of diagram of the indexes, read from the bottom up: 317 /// 318 /// Size on stack Offset on stack 319 /// \ / 320 /// Stack Idx (Where in slot is this?) 321 /// / 322 /// / 323 /// Slot Num (%stack.0) / 324 /// FrameIdx => SpillNum / 325 /// \ / 326 /// SpillID (int) Register number (int) 327 /// \ / 328 /// LocationID => LocIdx 329 /// | 330 /// LocIdx => ValueIDNum 331 /// 332 /// The aim here is that the LocIdx => ValueIDNum vector is just an array of 333 /// values in numbered locations, so that later analyses can ignore whether the 334 /// location is a register or otherwise. To map a register / spill location to 335 /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to 336 /// build a LocationID for a stack slot, you need to combine identifiers for 337 /// which stack slot it is and where within that slot is being described. 338 /// 339 /// Register mask operands cause trouble by technically defining every register; 340 /// various hacks are used to avoid tracking registers that are never read and 341 /// only written by regmasks. 342 class MLocTracker { 343 public: 344 MachineFunction &MF; 345 const TargetInstrInfo &TII; 346 const TargetRegisterInfo &TRI; 347 const TargetLowering &TLI; 348 349 /// IndexedMap type, mapping from LocIdx to ValueIDNum. 350 using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>; 351 352 /// Map of LocIdxes to the ValueIDNums that they store. This is tightly 353 /// packed, entries only exist for locations that are being tracked. 354 LocToValueType LocIdxToIDNum; 355 356 /// "Map" of machine location IDs (i.e., raw register or spill number) to the 357 /// LocIdx key / number for that location. There are always at least as many 358 /// as the number of registers on the target -- if the value in the register 359 /// is not being tracked, then the LocIdx value will be zero. New entries are 360 /// appended if a new spill slot begins being tracked. 361 /// This, and the corresponding reverse map persist for the analysis of the 362 /// whole function, and is necessarying for decoding various vectors of 363 /// values. 364 std::vector<LocIdx> LocIDToLocIdx; 365 366 /// Inverse map of LocIDToLocIdx. 367 IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID; 368 369 /// When clobbering register masks, we chose to not believe the machine model 370 /// and don't clobber SP. Do the same for SP aliases, and for efficiency, 371 /// keep a set of them here. 372 SmallSet<Register, 8> SPAliases; 373 374 /// Unique-ification of spill. Used to number them -- their LocID number is 375 /// the index in SpillLocs minus one plus NumRegs. 376 UniqueVector<SpillLoc> SpillLocs; 377 378 // If we discover a new machine location, assign it an mphi with this 379 // block number. 380 unsigned CurBB; 381 382 /// Cached local copy of the number of registers the target has. 383 unsigned NumRegs; 384 385 /// Number of slot indexes the target has -- distinct segments of a stack 386 /// slot that can take on the value of a subregister, when a super-register 387 /// is written to the stack. 388 unsigned NumSlotIdxes; 389 390 /// Collection of register mask operands that have been observed. Second part 391 /// of pair indicates the instruction that they happened in. Used to 392 /// reconstruct where defs happened if we start tracking a location later 393 /// on. 394 SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks; 395 396 /// Pair for describing a position within a stack slot -- first the size in 397 /// bits, then the offset. 398 typedef std::pair<unsigned short, unsigned short> StackSlotPos; 399 400 /// Map from a size/offset pair describing a position in a stack slot, to a 401 /// numeric identifier for that position. Allows easier identification of 402 /// individual positions. 403 DenseMap<StackSlotPos, unsigned> StackSlotIdxes; 404 405 /// Inverse of StackSlotIdxes. 406 DenseMap<unsigned, StackSlotPos> StackIdxesToPos; 407 408 /// Iterator for locations and the values they contain. Dereferencing 409 /// produces a struct/pair containing the LocIdx key for this location, 410 /// and a reference to the value currently stored. Simplifies the process 411 /// of seeking a particular location. 412 class MLocIterator { 413 LocToValueType &ValueMap; 414 LocIdx Idx; 415 416 public: 417 class value_type { 418 public: 419 value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {} 420 const LocIdx Idx; /// Read-only index of this location. 421 ValueIDNum &Value; /// Reference to the stored value at this location. 422 }; 423 424 MLocIterator(LocToValueType &ValueMap, LocIdx Idx) 425 : ValueMap(ValueMap), Idx(Idx) {} 426 427 bool operator==(const MLocIterator &Other) const { 428 assert(&ValueMap == &Other.ValueMap); 429 return Idx == Other.Idx; 430 } 431 432 bool operator!=(const MLocIterator &Other) const { 433 return !(*this == Other); 434 } 435 436 void operator++() { Idx = LocIdx(Idx.asU64() + 1); } 437 438 value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); } 439 }; 440 441 MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 442 const TargetRegisterInfo &TRI, const TargetLowering &TLI); 443 444 /// Produce location ID number for a Register. Provides some small amount of 445 /// type safety. 446 /// \param Reg The register we're looking up. 447 unsigned getLocID(Register Reg) { return Reg.id(); } 448 449 /// Produce location ID number for a spill position. 450 /// \param Spill The number of the spill we're fetching the location for. 451 /// \param SpillSubReg Subregister within the spill we're addressing. 452 unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) { 453 unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg); 454 unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg); 455 return getLocID(Spill, {Size, Offs}); 456 } 457 458 /// Produce location ID number for a spill position. 459 /// \param Spill The number of the spill we're fetching the location for. 460 /// \apram SpillIdx size/offset within the spill slot to be addressed. 461 unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) { 462 unsigned SlotNo = Spill.id() - 1; 463 SlotNo *= NumSlotIdxes; 464 assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end()); 465 SlotNo += StackSlotIdxes[Idx]; 466 SlotNo += NumRegs; 467 return SlotNo; 468 } 469 470 /// Given a spill number, and a slot within the spill, calculate the ID number 471 /// for that location. 472 unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) { 473 unsigned SlotNo = Spill.id() - 1; 474 SlotNo *= NumSlotIdxes; 475 SlotNo += Idx; 476 SlotNo += NumRegs; 477 return SlotNo; 478 } 479 480 /// Return the spill number that a location ID corresponds to. 481 SpillLocationNo locIDToSpill(unsigned ID) const { 482 assert(ID >= NumRegs); 483 ID -= NumRegs; 484 // Truncate away the index part, leaving only the spill number. 485 ID /= NumSlotIdxes; 486 return SpillLocationNo(ID + 1); // The UniqueVector is one-based. 487 } 488 489 /// Returns the spill-slot size/offs that a location ID corresponds to. 490 StackSlotPos locIDToSpillIdx(unsigned ID) const { 491 assert(ID >= NumRegs); 492 ID -= NumRegs; 493 unsigned Idx = ID % NumSlotIdxes; 494 return StackIdxesToPos.find(Idx)->second; 495 } 496 497 unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); } 498 499 /// Reset all locations to contain a PHI value at the designated block. Used 500 /// sometimes for actual PHI values, othertimes to indicate the block entry 501 /// value (before any more information is known). 502 void setMPhis(unsigned NewCurBB) { 503 CurBB = NewCurBB; 504 for (auto Location : locations()) 505 Location.Value = {CurBB, 0, Location.Idx}; 506 } 507 508 /// Load values for each location from array of ValueIDNums. Take current 509 /// bbnum just in case we read a value from a hitherto untouched register. 510 void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) { 511 CurBB = NewCurBB; 512 // Iterate over all tracked locations, and load each locations live-in 513 // value into our local index. 514 for (auto Location : locations()) 515 Location.Value = Locs[Location.Idx.asU64()]; 516 } 517 518 /// Wipe any un-necessary location records after traversing a block. 519 void reset(void) { 520 // We could reset all the location values too; however either loadFromArray 521 // or setMPhis should be called before this object is re-used. Just 522 // clear Masks, they're definitely not needed. 523 Masks.clear(); 524 } 525 526 /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of 527 /// the information in this pass uninterpretable. 528 void clear(void) { 529 reset(); 530 LocIDToLocIdx.clear(); 531 LocIdxToLocID.clear(); 532 LocIdxToIDNum.clear(); 533 // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 534 // 0 535 SpillLocs = decltype(SpillLocs)(); 536 StackSlotIdxes.clear(); 537 StackIdxesToPos.clear(); 538 539 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 540 } 541 542 /// Set a locaiton to a certain value. 543 void setMLoc(LocIdx L, ValueIDNum Num) { 544 assert(L.asU64() < LocIdxToIDNum.size()); 545 LocIdxToIDNum[L] = Num; 546 } 547 548 /// Read the value of a particular location 549 ValueIDNum readMLoc(LocIdx L) { 550 assert(L.asU64() < LocIdxToIDNum.size()); 551 return LocIdxToIDNum[L]; 552 } 553 554 /// Create a LocIdx for an untracked register ID. Initialize it to either an 555 /// mphi value representing a live-in, or a recent register mask clobber. 556 LocIdx trackRegister(unsigned ID); 557 558 LocIdx lookupOrTrackRegister(unsigned ID) { 559 LocIdx &Index = LocIDToLocIdx[ID]; 560 if (Index.isIllegal()) 561 Index = trackRegister(ID); 562 return Index; 563 } 564 565 /// Is register R currently tracked by MLocTracker? 566 bool isRegisterTracked(Register R) { 567 LocIdx &Index = LocIDToLocIdx[R]; 568 return !Index.isIllegal(); 569 } 570 571 /// Record a definition of the specified register at the given block / inst. 572 /// This doesn't take a ValueIDNum, because the definition and its location 573 /// are synonymous. 574 void defReg(Register R, unsigned BB, unsigned Inst) { 575 unsigned ID = getLocID(R); 576 LocIdx Idx = lookupOrTrackRegister(ID); 577 ValueIDNum ValueID = {BB, Inst, Idx}; 578 LocIdxToIDNum[Idx] = ValueID; 579 } 580 581 /// Set a register to a value number. To be used if the value number is 582 /// known in advance. 583 void setReg(Register R, ValueIDNum ValueID) { 584 unsigned ID = getLocID(R); 585 LocIdx Idx = lookupOrTrackRegister(ID); 586 LocIdxToIDNum[Idx] = ValueID; 587 } 588 589 ValueIDNum readReg(Register R) { 590 unsigned ID = getLocID(R); 591 LocIdx Idx = lookupOrTrackRegister(ID); 592 return LocIdxToIDNum[Idx]; 593 } 594 595 /// Reset a register value to zero / empty. Needed to replicate the 596 /// VarLoc implementation where a copy to/from a register effectively 597 /// clears the contents of the source register. (Values can only have one 598 /// machine location in VarLocBasedImpl). 599 void wipeRegister(Register R) { 600 unsigned ID = getLocID(R); 601 LocIdx Idx = LocIDToLocIdx[ID]; 602 LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue; 603 } 604 605 /// Determine the LocIdx of an existing register. 606 LocIdx getRegMLoc(Register R) { 607 unsigned ID = getLocID(R); 608 assert(ID < LocIDToLocIdx.size()); 609 assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap. 610 return LocIDToLocIdx[ID]; 611 } 612 613 /// Record a RegMask operand being executed. Defs any register we currently 614 /// track, stores a pointer to the mask in case we have to account for it 615 /// later. 616 void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID); 617 618 /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked. 619 SpillLocationNo getOrTrackSpillLoc(SpillLoc L); 620 621 // Get LocIdx of a spill ID. 622 LocIdx getSpillMLoc(unsigned SpillID) { 623 assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap. 624 return LocIDToLocIdx[SpillID]; 625 } 626 627 /// Return true if Idx is a spill machine location. 628 bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; } 629 630 MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); } 631 632 MLocIterator end() { 633 return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size()); 634 } 635 636 /// Return a range over all locations currently tracked. 637 iterator_range<MLocIterator> locations() { 638 return llvm::make_range(begin(), end()); 639 } 640 641 std::string LocIdxToName(LocIdx Idx) const; 642 643 std::string IDAsString(const ValueIDNum &Num) const; 644 645 #ifndef NDEBUG 646 LLVM_DUMP_METHOD void dump(); 647 648 LLVM_DUMP_METHOD void dump_mloc_map(); 649 #endif 650 651 /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the 652 /// information in \pProperties, for variable Var. Don't insert it anywhere, 653 /// just return the builder for it. 654 MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var, 655 const DbgValueProperties &Properties); 656 }; 657 658 /// Collection of DBG_VALUEs observed when traversing a block. Records each 659 /// variable and the value the DBG_VALUE refers to. Requires the machine value 660 /// location dataflow algorithm to have run already, so that values can be 661 /// identified. 662 class VLocTracker { 663 public: 664 /// Map DebugVariable to the latest Value it's defined to have. 665 /// Needs to be a MapVector because we determine order-in-the-input-MIR from 666 /// the order in this container. 667 /// We only retain the last DbgValue in each block for each variable, to 668 /// determine the blocks live-out variable value. The Vars container forms the 669 /// transfer function for this block, as part of the dataflow analysis. The 670 /// movement of values between locations inside of a block is handled at a 671 /// much later stage, in the TransferTracker class. 672 MapVector<DebugVariable, DbgValue> Vars; 673 DenseMap<DebugVariable, const DILocation *> Scopes; 674 MachineBasicBlock *MBB = nullptr; 675 676 public: 677 VLocTracker() {} 678 679 void defVar(const MachineInstr &MI, const DbgValueProperties &Properties, 680 Optional<ValueIDNum> ID) { 681 assert(MI.isDebugValue() || MI.isDebugRef()); 682 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 683 MI.getDebugLoc()->getInlinedAt()); 684 DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def) 685 : DbgValue(Properties, DbgValue::Undef); 686 687 // Attempt insertion; overwrite if it's already mapped. 688 auto Result = Vars.insert(std::make_pair(Var, Rec)); 689 if (!Result.second) 690 Result.first->second = Rec; 691 Scopes[Var] = MI.getDebugLoc().get(); 692 } 693 694 void defVar(const MachineInstr &MI, const MachineOperand &MO) { 695 // Only DBG_VALUEs can define constant-valued variables. 696 assert(MI.isDebugValue()); 697 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 698 MI.getDebugLoc()->getInlinedAt()); 699 DbgValueProperties Properties(MI); 700 DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const); 701 702 // Attempt insertion; overwrite if it's already mapped. 703 auto Result = Vars.insert(std::make_pair(Var, Rec)); 704 if (!Result.second) 705 Result.first->second = Rec; 706 Scopes[Var] = MI.getDebugLoc().get(); 707 } 708 }; 709 710 /// Types for recording sets of variable fragments that overlap. For a given 711 /// local variable, we record all other fragments of that variable that could 712 /// overlap it, to reduce search time. 713 using FragmentOfVar = 714 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>; 715 using OverlapMap = 716 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>; 717 718 // XXX XXX docs 719 class InstrRefBasedLDV : public LDVImpl { 720 public: 721 friend class ::InstrRefLDVTest; 722 723 using FragmentInfo = DIExpression::FragmentInfo; 724 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>; 725 726 // Helper while building OverlapMap, a map of all fragments seen for a given 727 // DILocalVariable. 728 using VarToFragments = 729 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>; 730 731 /// Machine location/value transfer function, a mapping of which locations 732 /// are assigned which new values. 733 using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>; 734 735 /// Live in/out structure for the variable values: a per-block map of 736 /// variables to their values. 737 using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>; 738 739 using VarAndLoc = std::pair<DebugVariable, DbgValue>; 740 741 /// Type for a live-in value: the predecessor block, and its value. 742 using InValueT = std::pair<MachineBasicBlock *, DbgValue *>; 743 744 /// Vector (per block) of a collection (inner smallvector) of live-ins. 745 /// Used as the result type for the variable value dataflow problem. 746 using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>; 747 748 private: 749 MachineDominatorTree *DomTree; 750 const TargetRegisterInfo *TRI; 751 const MachineRegisterInfo *MRI; 752 const TargetInstrInfo *TII; 753 const TargetFrameLowering *TFI; 754 const MachineFrameInfo *MFI; 755 BitVector CalleeSavedRegs; 756 LexicalScopes LS; 757 TargetPassConfig *TPC; 758 759 // An empty DIExpression. Used default / placeholder DbgValueProperties 760 // objects, as we can't have null expressions. 761 const DIExpression *EmptyExpr; 762 763 /// Object to track machine locations as we step through a block. Could 764 /// probably be a field rather than a pointer, as it's always used. 765 MLocTracker *MTracker = nullptr; 766 767 /// Number of the current block LiveDebugValues is stepping through. 768 unsigned CurBB; 769 770 /// Number of the current instruction LiveDebugValues is evaluating. 771 unsigned CurInst; 772 773 /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl 774 /// steps through a block. Reads the values at each location from the 775 /// MLocTracker object. 776 VLocTracker *VTracker = nullptr; 777 778 /// Tracker for transfers, listens to DBG_VALUEs and transfers of values 779 /// between locations during stepping, creates new DBG_VALUEs when values move 780 /// location. 781 TransferTracker *TTracker = nullptr; 782 783 /// Blocks which are artificial, i.e. blocks which exclusively contain 784 /// instructions without DebugLocs, or with line 0 locations. 785 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks; 786 787 // Mapping of blocks to and from their RPOT order. 788 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 789 DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder; 790 DenseMap<unsigned, unsigned> BBNumToRPO; 791 792 /// Pair of MachineInstr, and its 1-based offset into the containing block. 793 using InstAndNum = std::pair<const MachineInstr *, unsigned>; 794 /// Map from debug instruction number to the MachineInstr labelled with that 795 /// number, and its location within the function. Used to transform 796 /// instruction numbers in DBG_INSTR_REFs into machine value numbers. 797 std::map<uint64_t, InstAndNum> DebugInstrNumToInstr; 798 799 /// Record of where we observed a DBG_PHI instruction. 800 class DebugPHIRecord { 801 public: 802 uint64_t InstrNum; ///< Instruction number of this DBG_PHI. 803 MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred. 804 ValueIDNum ValueRead; ///< The value number read by the DBG_PHI. 805 LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads. 806 807 operator unsigned() const { return InstrNum; } 808 }; 809 810 /// Map from instruction numbers defined by DBG_PHIs to a record of what that 811 /// DBG_PHI read and where. Populated and edited during the machine value 812 /// location problem -- we use LLVMs SSA Updater to fix changes by 813 /// optimizations that destroy PHI instructions. 814 SmallVector<DebugPHIRecord, 32> DebugPHINumToValue; 815 816 // Map of overlapping variable fragments. 817 OverlapMap OverlapFragments; 818 VarToFragments SeenFragments; 819 820 /// Tests whether this instruction is a spill to a stack slot. 821 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF); 822 823 /// Decide if @MI is a spill instruction and return true if it is. We use 2 824 /// criteria to make this decision: 825 /// - Is this instruction a store to a spill slot? 826 /// - Is there a register operand that is both used and killed? 827 /// TODO: Store optimization can fold spills into other stores (including 828 /// other spills). We do not handle this yet (more than one memory operand). 829 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF, 830 unsigned &Reg); 831 832 /// If a given instruction is identified as a spill, return the spill slot 833 /// and set \p Reg to the spilled register. 834 Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI, 835 MachineFunction *MF, unsigned &Reg); 836 837 /// Given a spill instruction, extract the spill slot information, ensure it's 838 /// tracked, and return the spill number. 839 SpillLocationNo extractSpillBaseRegAndOffset(const MachineInstr &MI); 840 841 /// Observe a single instruction while stepping through a block. 842 void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr, 843 ValueIDNum **MLiveIns = nullptr); 844 845 /// Examines whether \p MI is a DBG_VALUE and notifies trackers. 846 /// \returns true if MI was recognized and processed. 847 bool transferDebugValue(const MachineInstr &MI); 848 849 /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers. 850 /// \returns true if MI was recognized and processed. 851 bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts, 852 ValueIDNum **MLiveIns); 853 854 /// Stores value-information about where this PHI occurred, and what 855 /// instruction number is associated with it. 856 /// \returns true if MI was recognized and processed. 857 bool transferDebugPHI(MachineInstr &MI); 858 859 /// Examines whether \p MI is copy instruction, and notifies trackers. 860 /// \returns true if MI was recognized and processed. 861 bool transferRegisterCopy(MachineInstr &MI); 862 863 /// Examines whether \p MI is stack spill or restore instruction, and 864 /// notifies trackers. \returns true if MI was recognized and processed. 865 bool transferSpillOrRestoreInst(MachineInstr &MI); 866 867 /// Examines \p MI for any registers that it defines, and notifies trackers. 868 void transferRegisterDef(MachineInstr &MI); 869 870 /// Copy one location to the other, accounting for movement of subregisters 871 /// too. 872 void performCopy(Register Src, Register Dst); 873 874 void accumulateFragmentMap(MachineInstr &MI); 875 876 /// Determine the machine value number referred to by (potentially several) 877 /// DBG_PHI instructions. Block duplication and tail folding can duplicate 878 /// DBG_PHIs, shifting the position where values in registers merge, and 879 /// forming another mini-ssa problem to solve. 880 /// \p Here the position of a DBG_INSTR_REF seeking a machine value number 881 /// \p InstrNum Debug instruction number defined by DBG_PHI instructions. 882 /// \returns The machine value number at position Here, or None. 883 Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF, 884 ValueIDNum **MLiveOuts, 885 ValueIDNum **MLiveIns, MachineInstr &Here, 886 uint64_t InstrNum); 887 888 /// Step through the function, recording register definitions and movements 889 /// in an MLocTracker. Convert the observations into a per-block transfer 890 /// function in \p MLocTransfer, suitable for using with the machine value 891 /// location dataflow problem. 892 void 893 produceMLocTransferFunction(MachineFunction &MF, 894 SmallVectorImpl<MLocTransferMap> &MLocTransfer, 895 unsigned MaxNumBlocks); 896 897 /// Solve the machine value location dataflow problem. Takes as input the 898 /// transfer functions in \p MLocTransfer. Writes the output live-in and 899 /// live-out arrays to the (initialized to zero) multidimensional arrays in 900 /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block 901 /// number, the inner by LocIdx. 902 void buildMLocValueMap(MachineFunction &MF, ValueIDNum **MInLocs, 903 ValueIDNum **MOutLocs, 904 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 905 906 /// Examine the stack indexes (i.e. offsets within the stack) to find the 907 /// basic units of interference -- like reg units, but for the stack. 908 void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots); 909 910 /// Install PHI values into the live-in array for each block, according to 911 /// the IDF of each register. 912 void placeMLocPHIs(MachineFunction &MF, 913 SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 914 ValueIDNum **MInLocs, 915 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 916 917 /// Calculate the iterated-dominance-frontier for a set of defs, using the 918 /// existing LLVM facilities for this. Works for a single "value" or 919 /// machine/variable location. 920 /// \p AllBlocks Set of blocks where we might consume the value. 921 /// \p DefBlocks Set of blocks where the value/location is defined. 922 /// \p PHIBlocks Output set of blocks where PHIs must be placed. 923 void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 924 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 925 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks); 926 927 /// Perform a control flow join (lattice value meet) of the values in machine 928 /// locations at \p MBB. Follows the algorithm described in the file-comment, 929 /// reading live-outs of predecessors from \p OutLocs, the current live ins 930 /// from \p InLocs, and assigning the newly computed live ins back into 931 /// \p InLocs. \returns two bools -- the first indicates whether a change 932 /// was made, the second whether a lattice downgrade occurred. If the latter 933 /// is true, revisiting this block is necessary. 934 bool mlocJoin(MachineBasicBlock &MBB, 935 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 936 ValueIDNum **OutLocs, ValueIDNum *InLocs); 937 938 /// Solve the variable value dataflow problem, for a single lexical scope. 939 /// Uses the algorithm from the file comment to resolve control flow joins 940 /// using PHI placement and value propagation. Reads the locations of machine 941 /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap) 942 /// and reads the variable values transfer function from \p AllTheVlocs. 943 /// Live-in and Live-out variable values are stored locally, with the live-ins 944 /// permanently stored to \p Output once a fixedpoint is reached. 945 /// \p VarsWeCareAbout contains a collection of the variables in \p Scope 946 /// that we should be tracking. 947 /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's 948 /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks 949 /// locations through. 950 void buildVLocValueMap(const DILocation *DILoc, 951 const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 952 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, 953 LiveInsT &Output, ValueIDNum **MOutLocs, 954 ValueIDNum **MInLocs, 955 SmallVectorImpl<VLocTracker> &AllTheVLocs); 956 957 /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the 958 /// live-in values coming from predecessors live-outs, and replaces any PHIs 959 /// already present in this blocks live-ins with a live-through value if the 960 /// PHI isn't needed. 961 /// \p LiveIn Old live-in value, overwritten with new one if live-in changes. 962 /// \returns true if any live-ins change value, either from value propagation 963 /// or PHI elimination. 964 bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 965 SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks, 966 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 967 DbgValue &LiveIn); 968 969 /// For the given block and live-outs feeding into it, try to find a 970 /// machine location where all the variable values join together. 971 /// \returns Value ID of a machine PHI if an appropriate one is available. 972 Optional<ValueIDNum> 973 pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var, 974 const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 975 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders); 976 977 /// Given the solutions to the two dataflow problems, machine value locations 978 /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the 979 /// TransferTracker class over the function to produce live-in and transfer 980 /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the 981 /// order given by AllVarsNumbering -- this could be any stable order, but 982 /// right now "order of appearence in function, when explored in RPO", so 983 /// that we can compare explictly against VarLocBasedImpl. 984 void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns, 985 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 986 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 987 const TargetPassConfig &TPC); 988 989 /// Boilerplate computation of some initial sets, artifical blocks and 990 /// RPOT block ordering. 991 void initialSetup(MachineFunction &MF); 992 993 bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree, 994 TargetPassConfig *TPC, unsigned InputBBLimit, 995 unsigned InputDbgValLimit) override; 996 997 public: 998 /// Default construct and initialize the pass. 999 InstrRefBasedLDV(); 1000 1001 LLVM_DUMP_METHOD 1002 void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const; 1003 1004 bool isCalleeSaved(LocIdx L) const; 1005 1006 bool hasFoldedStackStore(const MachineInstr &MI) { 1007 // Instruction must have a memory operand that's a stack slot, and isn't 1008 // aliased, meaning it's a spill from regalloc instead of a variable. 1009 // If it's aliased, we can't guarantee its value. 1010 if (!MI.hasOneMemOperand()) 1011 return false; 1012 auto *MemOperand = *MI.memoperands_begin(); 1013 return MemOperand->isStore() && 1014 MemOperand->getPseudoValue() && 1015 MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack 1016 && !MemOperand->getPseudoValue()->isAliased(MFI); 1017 } 1018 1019 Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI); 1020 }; 1021 1022 } // namespace LiveDebugValues 1023 1024 namespace llvm { 1025 using namespace LiveDebugValues; 1026 1027 template <> struct DenseMapInfo<LocIdx> { 1028 static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); } 1029 static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); } 1030 1031 static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); } 1032 1033 static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; } 1034 }; 1035 1036 template <> struct DenseMapInfo<ValueIDNum> { 1037 static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; } 1038 static inline ValueIDNum getTombstoneKey() { 1039 return ValueIDNum::TombstoneValue; 1040 } 1041 1042 static unsigned getHashValue(const ValueIDNum &Val) { return Val.asU64(); } 1043 1044 static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) { 1045 return A == B; 1046 } 1047 }; 1048 1049 } // end namespace llvm 1050 1051 #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */ 1052