1 //===- InstrRefBasedImpl.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 /// \file InstrRefBasedImpl.cpp 9 /// 10 /// This is a separate implementation of LiveDebugValues, see 11 /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information. 12 /// 13 /// This pass propagates variable locations between basic blocks, resolving 14 /// control flow conflicts between them. The problem is SSA construction, where 15 /// each debug instruction assigns the *value* that a variable has, and every 16 /// instruction where the variable is in scope uses that variable. The resulting 17 /// map of instruction-to-value is then translated into a register (or spill) 18 /// location for each variable over each instruction. 19 /// 20 /// The primary difference from normal SSA construction is that we cannot 21 /// _create_ PHI values that contain variable values. CodeGen has already 22 /// completed, and we can't alter it just to make debug-info complete. Thus: 23 /// we can identify function positions where we would like a PHI value for a 24 /// variable, but must search the MachineFunction to see whether such a PHI is 25 /// available. If no such PHI exists, the variable location must be dropped. 26 /// 27 /// To achieve this, we perform two kinds of analysis. First, we identify 28 /// every value defined by every instruction (ignoring those that only move 29 /// another value), then re-compute an SSA-form representation of the 30 /// MachineFunction, using value propagation to eliminate any un-necessary 31 /// PHI values. This gives us a map of every value computed in the function, 32 /// and its location within the register file / stack. 33 /// 34 /// Secondly, for each variable we perform the same analysis, where each debug 35 /// instruction is considered a def, and every instruction where the variable 36 /// is in lexical scope as a use. Value propagation is used again to eliminate 37 /// any un-necessary PHIs. This gives us a map of each variable to the value 38 /// it should have in a block. 39 /// 40 /// Once both are complete, we have two maps for each block: 41 /// * Variables to the values they should have, 42 /// * Values to the register / spill slot they are located in. 43 /// After which we can marry-up variable values with a location, and emit 44 /// DBG_VALUE instructions specifying those locations. Variable locations may 45 /// be dropped in this process due to the desired variable value not being 46 /// resident in any machine location, or because there is no PHI value in any 47 /// location that accurately represents the desired value. The building of 48 /// location lists for each block is left to DbgEntityHistoryCalculator. 49 /// 50 /// This pass is kept efficient because the size of the first SSA problem 51 /// is proportional to the working-set size of the function, which the compiler 52 /// tries to keep small. (It's also proportional to the number of blocks). 53 /// Additionally, we repeatedly perform the second SSA problem analysis with 54 /// only the variables and blocks in a single lexical scope, exploiting their 55 /// locality. 56 /// 57 /// ### Terminology 58 /// 59 /// A machine location is a register or spill slot, a value is something that's 60 /// defined by an instruction or PHI node, while a variable value is the value 61 /// assigned to a variable. A variable location is a machine location, that must 62 /// contain the appropriate variable value. A value that is a PHI node is 63 /// occasionally called an mphi. 64 /// 65 /// The first SSA problem is the "machine value location" problem, 66 /// because we're determining which machine locations contain which values. 67 /// The "locations" are constant: what's unknown is what value they contain. 68 /// 69 /// The second SSA problem (the one for variables) is the "variable value 70 /// problem", because it's determining what values a variable has, rather than 71 /// what location those values are placed in. 72 /// 73 /// TODO: 74 /// Overlapping fragments 75 /// Entry values 76 /// Add back DEBUG statements for debugging this 77 /// Collect statistics 78 /// 79 //===----------------------------------------------------------------------===// 80 81 #include "llvm/ADT/DenseMap.h" 82 #include "llvm/ADT/PostOrderIterator.h" 83 #include "llvm/ADT/STLExtras.h" 84 #include "llvm/ADT/SmallPtrSet.h" 85 #include "llvm/ADT/SmallSet.h" 86 #include "llvm/ADT/SmallVector.h" 87 #include "llvm/BinaryFormat/Dwarf.h" 88 #include "llvm/CodeGen/LexicalScopes.h" 89 #include "llvm/CodeGen/MachineBasicBlock.h" 90 #include "llvm/CodeGen/MachineDominators.h" 91 #include "llvm/CodeGen/MachineFrameInfo.h" 92 #include "llvm/CodeGen/MachineFunction.h" 93 #include "llvm/CodeGen/MachineInstr.h" 94 #include "llvm/CodeGen/MachineInstrBuilder.h" 95 #include "llvm/CodeGen/MachineInstrBundle.h" 96 #include "llvm/CodeGen/MachineMemOperand.h" 97 #include "llvm/CodeGen/MachineOperand.h" 98 #include "llvm/CodeGen/PseudoSourceValue.h" 99 #include "llvm/CodeGen/TargetFrameLowering.h" 100 #include "llvm/CodeGen/TargetInstrInfo.h" 101 #include "llvm/CodeGen/TargetLowering.h" 102 #include "llvm/CodeGen/TargetPassConfig.h" 103 #include "llvm/CodeGen/TargetRegisterInfo.h" 104 #include "llvm/CodeGen/TargetSubtargetInfo.h" 105 #include "llvm/Config/llvm-config.h" 106 #include "llvm/IR/DebugInfoMetadata.h" 107 #include "llvm/IR/DebugLoc.h" 108 #include "llvm/IR/Function.h" 109 #include "llvm/MC/MCRegisterInfo.h" 110 #include "llvm/Support/Casting.h" 111 #include "llvm/Support/Compiler.h" 112 #include "llvm/Support/Debug.h" 113 #include "llvm/Support/GenericIteratedDominanceFrontier.h" 114 #include "llvm/Support/TypeSize.h" 115 #include "llvm/Support/raw_ostream.h" 116 #include "llvm/Target/TargetMachine.h" 117 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 118 #include <algorithm> 119 #include <cassert> 120 #include <climits> 121 #include <cstdint> 122 #include <functional> 123 #include <queue> 124 #include <tuple> 125 #include <utility> 126 #include <vector> 127 128 #include "InstrRefBasedImpl.h" 129 #include "LiveDebugValues.h" 130 131 using namespace llvm; 132 using namespace LiveDebugValues; 133 134 // SSAUpdaterImple sets DEBUG_TYPE, change it. 135 #undef DEBUG_TYPE 136 #define DEBUG_TYPE "livedebugvalues" 137 138 // Act more like the VarLoc implementation, by propagating some locations too 139 // far and ignoring some transfers. 140 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, 141 cl::desc("Act like old LiveDebugValues did"), 142 cl::init(false)); 143 144 // Limit for the maximum number of stack slots we should track, past which we 145 // will ignore any spills. InstrRefBasedLDV gathers detailed information on all 146 // stack slots which leads to high memory consumption, and in some scenarios 147 // (such as asan with very many locals) the working set of the function can be 148 // very large, causing many spills. In these scenarios, it is very unlikely that 149 // the developer has hundreds of variables live at the same time that they're 150 // carefully thinking about -- instead, they probably autogenerated the code. 151 // When this happens, gracefully stop tracking excess spill slots, rather than 152 // consuming all the developer's memory. 153 static cl::opt<unsigned> 154 StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden, 155 cl::desc("livedebugvalues-stack-ws-limit"), 156 cl::init(250)); 157 158 /// Tracker for converting machine value locations and variable values into 159 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs 160 /// specifying block live-in locations and transfers within blocks. 161 /// 162 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker 163 /// and must be initialized with the set of variable values that are live-in to 164 /// the block. The caller then repeatedly calls process(). TransferTracker picks 165 /// out variable locations for the live-in variable values (if there _is_ a 166 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is 167 /// stepped through, transfers of values between machine locations are 168 /// identified and if profitable, a DBG_VALUE created. 169 /// 170 /// This is where debug use-before-defs would be resolved: a variable with an 171 /// unavailable value could materialize in the middle of a block, when the 172 /// value becomes available. Or, we could detect clobbers and re-specify the 173 /// variable in a backup location. (XXX these are unimplemented). 174 class TransferTracker { 175 public: 176 const TargetInstrInfo *TII; 177 const TargetLowering *TLI; 178 /// This machine location tracker is assumed to always contain the up-to-date 179 /// value mapping for all machine locations. TransferTracker only reads 180 /// information from it. (XXX make it const?) 181 MLocTracker *MTracker; 182 MachineFunction &MF; 183 bool ShouldEmitDebugEntryValues; 184 185 /// Record of all changes in variable locations at a block position. Awkwardly 186 /// we allow inserting either before or after the point: MBB != nullptr 187 /// indicates it's before, otherwise after. 188 struct Transfer { 189 MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes 190 MachineBasicBlock *MBB; /// non-null if we should insert after. 191 SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. 192 }; 193 194 struct LocAndProperties { 195 LocIdx Loc; 196 DbgValueProperties Properties; 197 }; 198 199 /// Collection of transfers (DBG_VALUEs) to be inserted. 200 SmallVector<Transfer, 32> Transfers; 201 202 /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences 203 /// between TransferTrackers view of variable locations and MLocTrackers. For 204 /// example, MLocTracker observes all clobbers, but TransferTracker lazily 205 /// does not. 206 SmallVector<ValueIDNum, 32> VarLocs; 207 208 /// Map from LocIdxes to which DebugVariables are based that location. 209 /// Mantained while stepping through the block. Not accurate if 210 /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. 211 DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; 212 213 /// Map from DebugVariable to it's current location and qualifying meta 214 /// information. To be used in conjunction with ActiveMLocs to construct 215 /// enough information for the DBG_VALUEs for a particular LocIdx. 216 DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; 217 218 /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. 219 SmallVector<MachineInstr *, 4> PendingDbgValues; 220 221 /// Record of a use-before-def: created when a value that's live-in to the 222 /// current block isn't available in any machine location, but it will be 223 /// defined in this block. 224 struct UseBeforeDef { 225 /// Value of this variable, def'd in block. 226 ValueIDNum ID; 227 /// Identity of this variable. 228 DebugVariable Var; 229 /// Additional variable properties. 230 DbgValueProperties Properties; 231 }; 232 233 /// Map from instruction index (within the block) to the set of UseBeforeDefs 234 /// that become defined at that instruction. 235 DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; 236 237 /// The set of variables that are in UseBeforeDefs and can become a location 238 /// once the relevant value is defined. An element being erased from this 239 /// collection prevents the use-before-def materializing. 240 DenseSet<DebugVariable> UseBeforeDefVariables; 241 242 const TargetRegisterInfo &TRI; 243 const BitVector &CalleeSavedRegs; 244 245 TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, 246 MachineFunction &MF, const TargetRegisterInfo &TRI, 247 const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) 248 : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), 249 CalleeSavedRegs(CalleeSavedRegs) { 250 TLI = MF.getSubtarget().getTargetLowering(); 251 auto &TM = TPC.getTM<TargetMachine>(); 252 ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); 253 } 254 255 /// Load object with live-in variable values. \p mlocs contains the live-in 256 /// values in each machine location, while \p vlocs the live-in variable 257 /// values. This method picks variable locations for the live-in variables, 258 /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other 259 /// object fields to track variable locations as we step through the block. 260 /// FIXME: could just examine mloctracker instead of passing in \p mlocs? 261 void 262 loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, 263 const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, 264 unsigned NumLocs) { 265 ActiveMLocs.clear(); 266 ActiveVLocs.clear(); 267 VarLocs.clear(); 268 VarLocs.reserve(NumLocs); 269 UseBeforeDefs.clear(); 270 UseBeforeDefVariables.clear(); 271 272 auto isCalleeSaved = [&](LocIdx L) { 273 unsigned Reg = MTracker->LocIdxToLocID[L]; 274 if (Reg >= MTracker->NumRegs) 275 return false; 276 for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) 277 if (CalleeSavedRegs.test(*RAI)) 278 return true; 279 return false; 280 }; 281 282 // Map of the preferred location for each value. 283 DenseMap<ValueIDNum, LocIdx> ValueToLoc; 284 285 // Initialized the preferred-location map with illegal locations, to be 286 // filled in later. 287 for (auto &VLoc : VLocs) 288 if (VLoc.second.Kind == DbgValue::Def) 289 ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()}); 290 291 ActiveMLocs.reserve(VLocs.size()); 292 ActiveVLocs.reserve(VLocs.size()); 293 294 // Produce a map of value numbers to the current machine locs they live 295 // in. When emulating VarLocBasedImpl, there should only be one 296 // location; when not, we get to pick. 297 for (auto Location : MTracker->locations()) { 298 LocIdx Idx = Location.Idx; 299 ValueIDNum &VNum = MLocs[Idx.asU64()]; 300 VarLocs.push_back(VNum); 301 302 // Is there a variable that wants a location for this value? If not, skip. 303 auto VIt = ValueToLoc.find(VNum); 304 if (VIt == ValueToLoc.end()) 305 continue; 306 307 LocIdx CurLoc = VIt->second; 308 // In order of preference, pick: 309 // * Callee saved registers, 310 // * Other registers, 311 // * Spill slots. 312 if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) || 313 (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) { 314 // Insert, or overwrite if insertion failed. 315 VIt->second = Idx; 316 } 317 } 318 319 // Now map variables to their picked LocIdxes. 320 for (const auto &Var : VLocs) { 321 if (Var.second.Kind == DbgValue::Const) { 322 PendingDbgValues.push_back( 323 emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties)); 324 continue; 325 } 326 327 // If the value has no location, we can't make a variable location. 328 const ValueIDNum &Num = Var.second.ID; 329 auto ValuesPreferredLoc = ValueToLoc.find(Num); 330 if (ValuesPreferredLoc->second.isIllegal()) { 331 // If it's a def that occurs in this block, register it as a 332 // use-before-def to be resolved as we step through the block. 333 if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) 334 addUseBeforeDef(Var.first, Var.second.Properties, Num); 335 else 336 recoverAsEntryValue(Var.first, Var.second.Properties, Num); 337 continue; 338 } 339 340 LocIdx M = ValuesPreferredLoc->second; 341 auto NewValue = LocAndProperties{M, Var.second.Properties}; 342 auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); 343 if (!Result.second) 344 Result.first->second = NewValue; 345 ActiveMLocs[M].insert(Var.first); 346 PendingDbgValues.push_back( 347 MTracker->emitLoc(M, Var.first, Var.second.Properties)); 348 } 349 flushDbgValues(MBB.begin(), &MBB); 350 } 351 352 /// Record that \p Var has value \p ID, a value that becomes available 353 /// later in the function. 354 void addUseBeforeDef(const DebugVariable &Var, 355 const DbgValueProperties &Properties, ValueIDNum ID) { 356 UseBeforeDef UBD = {ID, Var, Properties}; 357 UseBeforeDefs[ID.getInst()].push_back(UBD); 358 UseBeforeDefVariables.insert(Var); 359 } 360 361 /// After the instruction at index \p Inst and position \p pos has been 362 /// processed, check whether it defines a variable value in a use-before-def. 363 /// If so, and the variable value hasn't changed since the start of the 364 /// block, create a DBG_VALUE. 365 void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { 366 auto MIt = UseBeforeDefs.find(Inst); 367 if (MIt == UseBeforeDefs.end()) 368 return; 369 370 for (auto &Use : MIt->second) { 371 LocIdx L = Use.ID.getLoc(); 372 373 // If something goes very wrong, we might end up labelling a COPY 374 // instruction or similar with an instruction number, where it doesn't 375 // actually define a new value, instead it moves a value. In case this 376 // happens, discard. 377 if (MTracker->readMLoc(L) != Use.ID) 378 continue; 379 380 // If a different debug instruction defined the variable value / location 381 // since the start of the block, don't materialize this use-before-def. 382 if (!UseBeforeDefVariables.count(Use.Var)) 383 continue; 384 385 PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); 386 } 387 flushDbgValues(pos, nullptr); 388 } 389 390 /// Helper to move created DBG_VALUEs into Transfers collection. 391 void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { 392 if (PendingDbgValues.size() == 0) 393 return; 394 395 // Pick out the instruction start position. 396 MachineBasicBlock::instr_iterator BundleStart; 397 if (MBB && Pos == MBB->begin()) 398 BundleStart = MBB->instr_begin(); 399 else 400 BundleStart = getBundleStart(Pos->getIterator()); 401 402 Transfers.push_back({BundleStart, MBB, PendingDbgValues}); 403 PendingDbgValues.clear(); 404 } 405 406 bool isEntryValueVariable(const DebugVariable &Var, 407 const DIExpression *Expr) const { 408 if (!Var.getVariable()->isParameter()) 409 return false; 410 411 if (Var.getInlinedAt()) 412 return false; 413 414 if (Expr->getNumElements() > 0) 415 return false; 416 417 return true; 418 } 419 420 bool isEntryValueValue(const ValueIDNum &Val) const { 421 // Must be in entry block (block number zero), and be a PHI / live-in value. 422 if (Val.getBlock() || !Val.isPHI()) 423 return false; 424 425 // Entry values must enter in a register. 426 if (MTracker->isSpill(Val.getLoc())) 427 return false; 428 429 Register SP = TLI->getStackPointerRegisterToSaveRestore(); 430 Register FP = TRI.getFrameRegister(MF); 431 Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; 432 return Reg != SP && Reg != FP; 433 } 434 435 bool recoverAsEntryValue(const DebugVariable &Var, 436 const DbgValueProperties &Prop, 437 const ValueIDNum &Num) { 438 // Is this variable location a candidate to be an entry value. First, 439 // should we be trying this at all? 440 if (!ShouldEmitDebugEntryValues) 441 return false; 442 443 // Is the variable appropriate for entry values (i.e., is a parameter). 444 if (!isEntryValueVariable(Var, Prop.DIExpr)) 445 return false; 446 447 // Is the value assigned to this variable still the entry value? 448 if (!isEntryValueValue(Num)) 449 return false; 450 451 // Emit a variable location using an entry value expression. 452 DIExpression *NewExpr = 453 DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); 454 Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; 455 MachineOperand MO = MachineOperand::CreateReg(Reg, false); 456 457 PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); 458 return true; 459 } 460 461 /// Change a variable value after encountering a DBG_VALUE inside a block. 462 void redefVar(const MachineInstr &MI) { 463 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 464 MI.getDebugLoc()->getInlinedAt()); 465 DbgValueProperties Properties(MI); 466 467 const MachineOperand &MO = MI.getOperand(0); 468 469 // Ignore non-register locations, we don't transfer those. 470 if (!MO.isReg() || MO.getReg() == 0) { 471 auto It = ActiveVLocs.find(Var); 472 if (It != ActiveVLocs.end()) { 473 ActiveMLocs[It->second.Loc].erase(Var); 474 ActiveVLocs.erase(It); 475 } 476 // Any use-before-defs no longer apply. 477 UseBeforeDefVariables.erase(Var); 478 return; 479 } 480 481 Register Reg = MO.getReg(); 482 LocIdx NewLoc = MTracker->getRegMLoc(Reg); 483 redefVar(MI, Properties, NewLoc); 484 } 485 486 /// Handle a change in variable location within a block. Terminate the 487 /// variables current location, and record the value it now refers to, so 488 /// that we can detect location transfers later on. 489 void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, 490 Optional<LocIdx> OptNewLoc) { 491 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 492 MI.getDebugLoc()->getInlinedAt()); 493 // Any use-before-defs no longer apply. 494 UseBeforeDefVariables.erase(Var); 495 496 // Erase any previous location, 497 auto It = ActiveVLocs.find(Var); 498 if (It != ActiveVLocs.end()) 499 ActiveMLocs[It->second.Loc].erase(Var); 500 501 // If there _is_ no new location, all we had to do was erase. 502 if (!OptNewLoc) 503 return; 504 LocIdx NewLoc = *OptNewLoc; 505 506 // Check whether our local copy of values-by-location in #VarLocs is out of 507 // date. Wipe old tracking data for the location if it's been clobbered in 508 // the meantime. 509 if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) { 510 for (auto &P : ActiveMLocs[NewLoc]) { 511 ActiveVLocs.erase(P); 512 } 513 ActiveMLocs[NewLoc.asU64()].clear(); 514 VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc); 515 } 516 517 ActiveMLocs[NewLoc].insert(Var); 518 if (It == ActiveVLocs.end()) { 519 ActiveVLocs.insert( 520 std::make_pair(Var, LocAndProperties{NewLoc, Properties})); 521 } else { 522 It->second.Loc = NewLoc; 523 It->second.Properties = Properties; 524 } 525 } 526 527 /// Account for a location \p mloc being clobbered. Examine the variable 528 /// locations that will be terminated: and try to recover them by using 529 /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to 530 /// explicitly terminate a location if it can't be recovered. 531 void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, 532 bool MakeUndef = true) { 533 auto ActiveMLocIt = ActiveMLocs.find(MLoc); 534 if (ActiveMLocIt == ActiveMLocs.end()) 535 return; 536 537 // What was the old variable value? 538 ValueIDNum OldValue = VarLocs[MLoc.asU64()]; 539 VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; 540 541 // Examine the remaining variable locations: if we can find the same value 542 // again, we can recover the location. 543 Optional<LocIdx> NewLoc = None; 544 for (auto Loc : MTracker->locations()) 545 if (Loc.Value == OldValue) 546 NewLoc = Loc.Idx; 547 548 // If there is no location, and we weren't asked to make the variable 549 // explicitly undef, then stop here. 550 if (!NewLoc && !MakeUndef) { 551 // Try and recover a few more locations with entry values. 552 for (auto &Var : ActiveMLocIt->second) { 553 auto &Prop = ActiveVLocs.find(Var)->second.Properties; 554 recoverAsEntryValue(Var, Prop, OldValue); 555 } 556 flushDbgValues(Pos, nullptr); 557 return; 558 } 559 560 // Examine all the variables based on this location. 561 DenseSet<DebugVariable> NewMLocs; 562 for (auto &Var : ActiveMLocIt->second) { 563 auto ActiveVLocIt = ActiveVLocs.find(Var); 564 // Re-state the variable location: if there's no replacement then NewLoc 565 // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE 566 // identifying the alternative location will be emitted. 567 const DbgValueProperties &Properties = ActiveVLocIt->second.Properties; 568 PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); 569 570 // Update machine locations <=> variable locations maps. Defer updating 571 // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. 572 if (!NewLoc) { 573 ActiveVLocs.erase(ActiveVLocIt); 574 } else { 575 ActiveVLocIt->second.Loc = *NewLoc; 576 NewMLocs.insert(Var); 577 } 578 } 579 580 // Commit any deferred ActiveMLoc changes. 581 if (!NewMLocs.empty()) 582 for (auto &Var : NewMLocs) 583 ActiveMLocs[*NewLoc].insert(Var); 584 585 // We lazily track what locations have which values; if we've found a new 586 // location for the clobbered value, remember it. 587 if (NewLoc) 588 VarLocs[NewLoc->asU64()] = OldValue; 589 590 flushDbgValues(Pos, nullptr); 591 592 // Re-find ActiveMLocIt, iterator could have been invalidated. 593 ActiveMLocIt = ActiveMLocs.find(MLoc); 594 ActiveMLocIt->second.clear(); 595 } 596 597 /// Transfer variables based on \p Src to be based on \p Dst. This handles 598 /// both register copies as well as spills and restores. Creates DBG_VALUEs 599 /// describing the movement. 600 void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { 601 // Does Src still contain the value num we expect? If not, it's been 602 // clobbered in the meantime, and our variable locations are stale. 603 if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src)) 604 return; 605 606 // assert(ActiveMLocs[Dst].size() == 0); 607 //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? 608 609 // Move set of active variables from one location to another. 610 auto MovingVars = ActiveMLocs[Src]; 611 ActiveMLocs[Dst] = MovingVars; 612 VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; 613 614 // For each variable based on Src; create a location at Dst. 615 for (auto &Var : MovingVars) { 616 auto ActiveVLocIt = ActiveVLocs.find(Var); 617 assert(ActiveVLocIt != ActiveVLocs.end()); 618 ActiveVLocIt->second.Loc = Dst; 619 620 MachineInstr *MI = 621 MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); 622 PendingDbgValues.push_back(MI); 623 } 624 ActiveMLocs[Src].clear(); 625 flushDbgValues(Pos, nullptr); 626 627 // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data 628 // about the old location. 629 if (EmulateOldLDV) 630 VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; 631 } 632 633 MachineInstrBuilder emitMOLoc(const MachineOperand &MO, 634 const DebugVariable &Var, 635 const DbgValueProperties &Properties) { 636 DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 637 Var.getVariable()->getScope(), 638 const_cast<DILocation *>(Var.getInlinedAt())); 639 auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 640 MIB.add(MO); 641 if (Properties.Indirect) 642 MIB.addImm(0); 643 else 644 MIB.addReg(0); 645 MIB.addMetadata(Var.getVariable()); 646 MIB.addMetadata(Properties.DIExpr); 647 return MIB; 648 } 649 }; 650 651 //===----------------------------------------------------------------------===// 652 // Implementation 653 //===----------------------------------------------------------------------===// 654 655 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; 656 ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1}; 657 658 #ifndef NDEBUG 659 void DbgValue::dump(const MLocTracker *MTrack) const { 660 if (Kind == Const) { 661 MO->dump(); 662 } else if (Kind == NoVal) { 663 dbgs() << "NoVal(" << BlockNo << ")"; 664 } else if (Kind == VPHI) { 665 dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")"; 666 } else { 667 assert(Kind == Def); 668 dbgs() << MTrack->IDAsString(ID); 669 } 670 if (Properties.Indirect) 671 dbgs() << " indir"; 672 if (Properties.DIExpr) 673 dbgs() << " " << *Properties.DIExpr; 674 } 675 #endif 676 677 MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 678 const TargetRegisterInfo &TRI, 679 const TargetLowering &TLI) 680 : MF(MF), TII(TII), TRI(TRI), TLI(TLI), 681 LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) { 682 NumRegs = TRI.getNumRegs(); 683 reset(); 684 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 685 assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure 686 687 // Always track SP. This avoids the implicit clobbering caused by regmasks 688 // from affectings its values. (LiveDebugValues disbelieves calls and 689 // regmasks that claim to clobber SP). 690 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 691 if (SP) { 692 unsigned ID = getLocID(SP); 693 (void)lookupOrTrackRegister(ID); 694 695 for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI) 696 SPAliases.insert(*RAI); 697 } 698 699 // Build some common stack positions -- full registers being spilt to the 700 // stack. 701 StackSlotIdxes.insert({{8, 0}, 0}); 702 StackSlotIdxes.insert({{16, 0}, 1}); 703 StackSlotIdxes.insert({{32, 0}, 2}); 704 StackSlotIdxes.insert({{64, 0}, 3}); 705 StackSlotIdxes.insert({{128, 0}, 4}); 706 StackSlotIdxes.insert({{256, 0}, 5}); 707 StackSlotIdxes.insert({{512, 0}, 6}); 708 709 // Traverse all the subregister idxes, and ensure there's an index for them. 710 // Duplicates are no problem: we're interested in their position in the 711 // stack slot, we don't want to type the slot. 712 for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) { 713 unsigned Size = TRI.getSubRegIdxSize(I); 714 unsigned Offs = TRI.getSubRegIdxOffset(I); 715 unsigned Idx = StackSlotIdxes.size(); 716 717 // Some subregs have -1, -2 and so forth fed into their fields, to mean 718 // special backend things. Ignore those. 719 if (Size > 60000 || Offs > 60000) 720 continue; 721 722 StackSlotIdxes.insert({{Size, Offs}, Idx}); 723 } 724 725 // There may also be strange register class sizes (think x86 fp80s). 726 for (const TargetRegisterClass *RC : TRI.regclasses()) { 727 unsigned Size = TRI.getRegSizeInBits(*RC); 728 729 // We might see special reserved values as sizes, and classes for other 730 // stuff the machine tries to model. If it's more than 512 bits, then it 731 // is very unlikely to be a register than can be spilt. 732 if (Size > 512) 733 continue; 734 735 unsigned Idx = StackSlotIdxes.size(); 736 StackSlotIdxes.insert({{Size, 0}, Idx}); 737 } 738 739 for (auto &Idx : StackSlotIdxes) 740 StackIdxesToPos[Idx.second] = Idx.first; 741 742 NumSlotIdxes = StackSlotIdxes.size(); 743 } 744 745 LocIdx MLocTracker::trackRegister(unsigned ID) { 746 assert(ID != 0); 747 LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); 748 LocIdxToIDNum.grow(NewIdx); 749 LocIdxToLocID.grow(NewIdx); 750 751 // Default: it's an mphi. 752 ValueIDNum ValNum = {CurBB, 0, NewIdx}; 753 // Was this reg ever touched by a regmask? 754 for (const auto &MaskPair : reverse(Masks)) { 755 if (MaskPair.first->clobbersPhysReg(ID)) { 756 // There was an earlier def we skipped. 757 ValNum = {CurBB, MaskPair.second, NewIdx}; 758 break; 759 } 760 } 761 762 LocIdxToIDNum[NewIdx] = ValNum; 763 LocIdxToLocID[NewIdx] = ID; 764 return NewIdx; 765 } 766 767 void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB, 768 unsigned InstID) { 769 // Def any register we track have that isn't preserved. The regmask 770 // terminates the liveness of a register, meaning its value can't be 771 // relied upon -- we represent this by giving it a new value. 772 for (auto Location : locations()) { 773 unsigned ID = LocIdxToLocID[Location.Idx]; 774 // Don't clobber SP, even if the mask says it's clobbered. 775 if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID)) 776 defReg(ID, CurBB, InstID); 777 } 778 Masks.push_back(std::make_pair(MO, InstID)); 779 } 780 781 Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) { 782 SpillLocationNo SpillID(SpillLocs.idFor(L)); 783 784 if (SpillID.id() == 0) { 785 // If there is no location, and we have reached the limit of how many stack 786 // slots to track, then don't track this one. 787 if (SpillLocs.size() >= StackWorkingSetLimit) 788 return None; 789 790 // Spill location is untracked: create record for this one, and all 791 // subregister slots too. 792 SpillID = SpillLocationNo(SpillLocs.insert(L)); 793 for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) { 794 unsigned L = getSpillIDWithIdx(SpillID, StackIdx); 795 LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx 796 LocIdxToIDNum.grow(Idx); 797 LocIdxToLocID.grow(Idx); 798 LocIDToLocIdx.push_back(Idx); 799 LocIdxToLocID[Idx] = L; 800 // Initialize to PHI value; corresponds to the location's live-in value 801 // during transfer function construction. 802 LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx); 803 } 804 } 805 return SpillID; 806 } 807 808 std::string MLocTracker::LocIdxToName(LocIdx Idx) const { 809 unsigned ID = LocIdxToLocID[Idx]; 810 if (ID >= NumRegs) { 811 StackSlotPos Pos = locIDToSpillIdx(ID); 812 ID -= NumRegs; 813 unsigned Slot = ID / NumSlotIdxes; 814 return Twine("slot ") 815 .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first) 816 .concat(Twine(" offs ").concat(Twine(Pos.second)))))) 817 .str(); 818 } else { 819 return TRI.getRegAsmName(ID).str(); 820 } 821 } 822 823 std::string MLocTracker::IDAsString(const ValueIDNum &Num) const { 824 std::string DefName = LocIdxToName(Num.getLoc()); 825 return Num.asString(DefName); 826 } 827 828 #ifndef NDEBUG 829 LLVM_DUMP_METHOD void MLocTracker::dump() { 830 for (auto Location : locations()) { 831 std::string MLocName = LocIdxToName(Location.Value.getLoc()); 832 std::string DefName = Location.Value.asString(MLocName); 833 dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; 834 } 835 } 836 837 LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() { 838 for (auto Location : locations()) { 839 std::string foo = LocIdxToName(Location.Idx); 840 dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; 841 } 842 } 843 #endif 844 845 MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc, 846 const DebugVariable &Var, 847 const DbgValueProperties &Properties) { 848 DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 849 Var.getVariable()->getScope(), 850 const_cast<DILocation *>(Var.getInlinedAt())); 851 auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); 852 853 const DIExpression *Expr = Properties.DIExpr; 854 if (!MLoc) { 855 // No location -> DBG_VALUE $noreg 856 MIB.addReg(0); 857 MIB.addReg(0); 858 } else if (LocIdxToLocID[*MLoc] >= NumRegs) { 859 unsigned LocID = LocIdxToLocID[*MLoc]; 860 SpillLocationNo SpillID = locIDToSpill(LocID); 861 StackSlotPos StackIdx = locIDToSpillIdx(LocID); 862 unsigned short Offset = StackIdx.second; 863 864 // TODO: support variables that are located in spill slots, with non-zero 865 // offsets from the start of the spill slot. It would require some more 866 // complex DIExpression calculations. This doesn't seem to be produced by 867 // LLVM right now, so don't try and support it. 868 // Accept no-subregister slots and subregisters where the offset is zero. 869 // The consumer should already have type information to work out how large 870 // the variable is. 871 if (Offset == 0) { 872 const SpillLoc &Spill = SpillLocs[SpillID.id()]; 873 Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset, 874 Spill.SpillOffset); 875 unsigned Base = Spill.SpillBase; 876 MIB.addReg(Base); 877 MIB.addImm(0); 878 879 // Being on the stack makes this location indirect; if it was _already_ 880 // indirect though, we need to add extra indirection. See this test for 881 // a scenario where this happens: 882 // llvm/test/DebugInfo/X86/spill-nontrivial-param.ll 883 if (Properties.Indirect) { 884 std::vector<uint64_t> Elts = {dwarf::DW_OP_deref}; 885 Expr = DIExpression::append(Expr, Elts); 886 } 887 } else { 888 // This is a stack location with a weird subregister offset: emit an undef 889 // DBG_VALUE instead. 890 MIB.addReg(0); 891 MIB.addReg(0); 892 } 893 } else { 894 // Non-empty, non-stack slot, must be a plain register. 895 unsigned LocID = LocIdxToLocID[*MLoc]; 896 MIB.addReg(LocID); 897 if (Properties.Indirect) 898 MIB.addImm(0); 899 else 900 MIB.addReg(0); 901 } 902 903 MIB.addMetadata(Var.getVariable()); 904 MIB.addMetadata(Expr); 905 return MIB; 906 } 907 908 /// Default construct and initialize the pass. 909 InstrRefBasedLDV::InstrRefBasedLDV() = default; 910 911 bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const { 912 unsigned Reg = MTracker->LocIdxToLocID[L]; 913 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 914 if (CalleeSavedRegs.test(*RAI)) 915 return true; 916 return false; 917 } 918 919 //===----------------------------------------------------------------------===// 920 // Debug Range Extension Implementation 921 //===----------------------------------------------------------------------===// 922 923 #ifndef NDEBUG 924 // Something to restore in the future. 925 // void InstrRefBasedLDV::printVarLocInMBB(..) 926 #endif 927 928 Optional<SpillLocationNo> 929 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 930 assert(MI.hasOneMemOperand() && 931 "Spill instruction does not have exactly one memory operand?"); 932 auto MMOI = MI.memoperands_begin(); 933 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 934 assert(PVal->kind() == PseudoSourceValue::FixedStack && 935 "Inconsistent memory operand in spill instruction"); 936 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 937 const MachineBasicBlock *MBB = MI.getParent(); 938 Register Reg; 939 StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 940 return MTracker->getOrTrackSpillLoc({Reg, Offset}); 941 } 942 943 Optional<LocIdx> 944 InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) { 945 Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI); 946 if (!SpillLoc) 947 return None; 948 949 // Where in the stack slot is this value defined -- i.e., what size of value 950 // is this? An important question, because it could be loaded into a register 951 // from the stack at some point. Happily the memory operand will tell us 952 // the size written to the stack. 953 auto *MemOperand = *MI.memoperands_begin(); 954 unsigned SizeInBits = MemOperand->getSizeInBits(); 955 956 // Find that position in the stack indexes we're tracking. 957 auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0}); 958 if (IdxIt == MTracker->StackSlotIdxes.end()) 959 // That index is not tracked. This is suprising, and unlikely to ever 960 // occur, but the safe action is to indicate the variable is optimised out. 961 return None; 962 963 unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second); 964 return MTracker->getSpillMLoc(SpillID); 965 } 966 967 /// End all previous ranges related to @MI and start a new range from @MI 968 /// if it is a DBG_VALUE instr. 969 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { 970 if (!MI.isDebugValue()) 971 return false; 972 973 const DILocalVariable *Var = MI.getDebugVariable(); 974 const DIExpression *Expr = MI.getDebugExpression(); 975 const DILocation *DebugLoc = MI.getDebugLoc(); 976 const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 977 assert(Var->isValidLocationForIntrinsic(DebugLoc) && 978 "Expected inlined-at fields to agree"); 979 980 DebugVariable V(Var, Expr, InlinedAt); 981 DbgValueProperties Properties(MI); 982 983 // If there are no instructions in this lexical scope, do no location tracking 984 // at all, this variable shouldn't get a legitimate location range. 985 auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 986 if (Scope == nullptr) 987 return true; // handled it; by doing nothing 988 989 // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to 990 // contribute to locations in this block, but don't propagate further. 991 // Interpret it like a DBG_VALUE $noreg. 992 if (MI.isDebugValueList()) { 993 if (VTracker) 994 VTracker->defVar(MI, Properties, None); 995 if (TTracker) 996 TTracker->redefVar(MI, Properties, None); 997 return true; 998 } 999 1000 const MachineOperand &MO = MI.getOperand(0); 1001 1002 // MLocTracker needs to know that this register is read, even if it's only 1003 // read by a debug inst. 1004 if (MO.isReg() && MO.getReg() != 0) 1005 (void)MTracker->readReg(MO.getReg()); 1006 1007 // If we're preparing for the second analysis (variables), the machine value 1008 // locations are already solved, and we report this DBG_VALUE and the value 1009 // it refers to to VLocTracker. 1010 if (VTracker) { 1011 if (MO.isReg()) { 1012 // Feed defVar the new variable location, or if this is a 1013 // DBG_VALUE $noreg, feed defVar None. 1014 if (MO.getReg()) 1015 VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); 1016 else 1017 VTracker->defVar(MI, Properties, None); 1018 } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || 1019 MI.getOperand(0).isCImm()) { 1020 VTracker->defVar(MI, MI.getOperand(0)); 1021 } 1022 } 1023 1024 // If performing final tracking of transfers, report this variable definition 1025 // to the TransferTracker too. 1026 if (TTracker) 1027 TTracker->redefVar(MI); 1028 return true; 1029 } 1030 1031 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, 1032 const ValueTable *MLiveOuts, 1033 const ValueTable *MLiveIns) { 1034 if (!MI.isDebugRef()) 1035 return false; 1036 1037 // Only handle this instruction when we are building the variable value 1038 // transfer function. 1039 if (!VTracker && !TTracker) 1040 return false; 1041 1042 unsigned InstNo = MI.getOperand(0).getImm(); 1043 unsigned OpNo = MI.getOperand(1).getImm(); 1044 1045 const DILocalVariable *Var = MI.getDebugVariable(); 1046 const DIExpression *Expr = MI.getDebugExpression(); 1047 const DILocation *DebugLoc = MI.getDebugLoc(); 1048 const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1049 assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1050 "Expected inlined-at fields to agree"); 1051 1052 DebugVariable V(Var, Expr, InlinedAt); 1053 1054 auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1055 if (Scope == nullptr) 1056 return true; // Handled by doing nothing. This variable is never in scope. 1057 1058 const MachineFunction &MF = *MI.getParent()->getParent(); 1059 1060 // Various optimizations may have happened to the value during codegen, 1061 // recorded in the value substitution table. Apply any substitutions to 1062 // the instruction / operand number in this DBG_INSTR_REF, and collect 1063 // any subregister extractions performed during optimization. 1064 1065 // Create dummy substitution with Src set, for lookup. 1066 auto SoughtSub = 1067 MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0); 1068 1069 SmallVector<unsigned, 4> SeenSubregs; 1070 auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1071 while (LowerBoundIt != MF.DebugValueSubstitutions.end() && 1072 LowerBoundIt->Src == SoughtSub.Src) { 1073 std::tie(InstNo, OpNo) = LowerBoundIt->Dest; 1074 SoughtSub.Src = LowerBoundIt->Dest; 1075 if (unsigned Subreg = LowerBoundIt->Subreg) 1076 SeenSubregs.push_back(Subreg); 1077 LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1078 } 1079 1080 // Default machine value number is <None> -- if no instruction defines 1081 // the corresponding value, it must have been optimized out. 1082 Optional<ValueIDNum> NewID = None; 1083 1084 // Try to lookup the instruction number, and find the machine value number 1085 // that it defines. It could be an instruction, or a PHI. 1086 auto InstrIt = DebugInstrNumToInstr.find(InstNo); 1087 auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), 1088 DebugPHINumToValue.end(), InstNo); 1089 if (InstrIt != DebugInstrNumToInstr.end()) { 1090 const MachineInstr &TargetInstr = *InstrIt->second.first; 1091 uint64_t BlockNo = TargetInstr.getParent()->getNumber(); 1092 1093 // Pick out the designated operand. It might be a memory reference, if 1094 // a register def was folded into a stack store. 1095 if (OpNo == MachineFunction::DebugOperandMemNumber && 1096 TargetInstr.hasOneMemOperand()) { 1097 Optional<LocIdx> L = findLocationForMemOperand(TargetInstr); 1098 if (L) 1099 NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L); 1100 } else if (OpNo != MachineFunction::DebugOperandMemNumber) { 1101 // Permit the debug-info to be completely wrong: identifying a nonexistant 1102 // operand, or one that is not a register definition, means something 1103 // unexpected happened during optimisation. Broken debug-info, however, 1104 // shouldn't crash the compiler -- instead leave the variable value as 1105 // None, which will make it appear "optimised out". 1106 if (OpNo < TargetInstr.getNumOperands()) { 1107 const MachineOperand &MO = TargetInstr.getOperand(OpNo); 1108 1109 if (MO.isReg() && MO.isDef() && MO.getReg()) { 1110 unsigned LocID = MTracker->getLocID(MO.getReg()); 1111 LocIdx L = MTracker->LocIDToLocIdx[LocID]; 1112 NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); 1113 } 1114 } 1115 1116 if (!NewID) { 1117 LLVM_DEBUG( 1118 { dbgs() << "Seen instruction reference to illegal operand\n"; }); 1119 } 1120 } 1121 // else: NewID is left as None. 1122 } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { 1123 // It's actually a PHI value. Which value it is might not be obvious, use 1124 // the resolver helper to find out. 1125 NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, 1126 MI, InstNo); 1127 } 1128 1129 // Apply any subregister extractions, in reverse. We might have seen code 1130 // like this: 1131 // CALL64 @foo, implicit-def $rax 1132 // %0:gr64 = COPY $rax 1133 // %1:gr32 = COPY %0.sub_32bit 1134 // %2:gr16 = COPY %1.sub_16bit 1135 // %3:gr8 = COPY %2.sub_8bit 1136 // In which case each copy would have been recorded as a substitution with 1137 // a subregister qualifier. Apply those qualifiers now. 1138 if (NewID && !SeenSubregs.empty()) { 1139 unsigned Offset = 0; 1140 unsigned Size = 0; 1141 1142 // Look at each subregister that we passed through, and progressively 1143 // narrow in, accumulating any offsets that occur. Substitutions should 1144 // only ever be the same or narrower width than what they read from; 1145 // iterate in reverse order so that we go from wide to small. 1146 for (unsigned Subreg : reverse(SeenSubregs)) { 1147 unsigned ThisSize = TRI->getSubRegIdxSize(Subreg); 1148 unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg); 1149 Offset += ThisOffset; 1150 Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize); 1151 } 1152 1153 // If that worked, look for an appropriate subregister with the register 1154 // where the define happens. Don't look at values that were defined during 1155 // a stack write: we can't currently express register locations within 1156 // spills. 1157 LocIdx L = NewID->getLoc(); 1158 if (NewID && !MTracker->isSpill(L)) { 1159 // Find the register class for the register where this def happened. 1160 // FIXME: no index for this? 1161 Register Reg = MTracker->LocIdxToLocID[L]; 1162 const TargetRegisterClass *TRC = nullptr; 1163 for (auto *TRCI : TRI->regclasses()) 1164 if (TRCI->contains(Reg)) 1165 TRC = TRCI; 1166 assert(TRC && "Couldn't find target register class?"); 1167 1168 // If the register we have isn't the right size or in the right place, 1169 // Try to find a subregister inside it. 1170 unsigned MainRegSize = TRI->getRegSizeInBits(*TRC); 1171 if (Size != MainRegSize || Offset) { 1172 // Enumerate all subregisters, searching. 1173 Register NewReg = 0; 1174 for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1175 unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1176 unsigned SubregSize = TRI->getSubRegIdxSize(Subreg); 1177 unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg); 1178 if (SubregSize == Size && SubregOffset == Offset) { 1179 NewReg = *SRI; 1180 break; 1181 } 1182 } 1183 1184 // If we didn't find anything: there's no way to express our value. 1185 if (!NewReg) { 1186 NewID = None; 1187 } else { 1188 // Re-state the value as being defined within the subregister 1189 // that we found. 1190 LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg); 1191 NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc); 1192 } 1193 } 1194 } else { 1195 // If we can't handle subregisters, unset the new value. 1196 NewID = None; 1197 } 1198 } 1199 1200 // We, we have a value number or None. Tell the variable value tracker about 1201 // it. The rest of this LiveDebugValues implementation acts exactly the same 1202 // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that 1203 // aren't immediately available). 1204 DbgValueProperties Properties(Expr, false); 1205 if (VTracker) 1206 VTracker->defVar(MI, Properties, NewID); 1207 1208 // If we're on the final pass through the function, decompose this INSTR_REF 1209 // into a plain DBG_VALUE. 1210 if (!TTracker) 1211 return true; 1212 1213 // Pick a location for the machine value number, if such a location exists. 1214 // (This information could be stored in TransferTracker to make it faster). 1215 Optional<LocIdx> FoundLoc = None; 1216 for (auto Location : MTracker->locations()) { 1217 LocIdx CurL = Location.Idx; 1218 ValueIDNum ID = MTracker->readMLoc(CurL); 1219 if (NewID && ID == NewID) { 1220 // If this is the first location with that value, pick it. Otherwise, 1221 // consider whether it's a "longer term" location. 1222 if (!FoundLoc) { 1223 FoundLoc = CurL; 1224 continue; 1225 } 1226 1227 if (MTracker->isSpill(CurL)) 1228 FoundLoc = CurL; // Spills are a longer term location. 1229 else if (!MTracker->isSpill(*FoundLoc) && 1230 !MTracker->isSpill(CurL) && 1231 !isCalleeSaved(*FoundLoc) && 1232 isCalleeSaved(CurL)) 1233 FoundLoc = CurL; // Callee saved regs are longer term than normal. 1234 } 1235 } 1236 1237 // Tell transfer tracker that the variable value has changed. 1238 TTracker->redefVar(MI, Properties, FoundLoc); 1239 1240 // If there was a value with no location; but the value is defined in a 1241 // later instruction in this block, this is a block-local use-before-def. 1242 if (!FoundLoc && NewID && NewID->getBlock() == CurBB && 1243 NewID->getInst() > CurInst) 1244 TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); 1245 1246 // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. 1247 // This DBG_VALUE is potentially a $noreg / undefined location, if 1248 // FoundLoc is None. 1249 // (XXX -- could morph the DBG_INSTR_REF in the future). 1250 MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); 1251 TTracker->PendingDbgValues.push_back(DbgMI); 1252 TTracker->flushDbgValues(MI.getIterator(), nullptr); 1253 return true; 1254 } 1255 1256 bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { 1257 if (!MI.isDebugPHI()) 1258 return false; 1259 1260 // Analyse these only when solving the machine value location problem. 1261 if (VTracker || TTracker) 1262 return true; 1263 1264 // First operand is the value location, either a stack slot or register. 1265 // Second is the debug instruction number of the original PHI. 1266 const MachineOperand &MO = MI.getOperand(0); 1267 unsigned InstrNum = MI.getOperand(1).getImm(); 1268 1269 auto EmitBadPHI = [this, &MI, InstrNum](void) -> bool { 1270 // Helper lambda to do any accounting when we fail to find a location for 1271 // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a 1272 // dead stack slot, for example. 1273 // Record a DebugPHIRecord with an empty value + location. 1274 DebugPHINumToValue.push_back({InstrNum, MI.getParent(), None, None}); 1275 return true; 1276 }; 1277 1278 if (MO.isReg() && MO.getReg()) { 1279 // The value is whatever's currently in the register. Read and record it, 1280 // to be analysed later. 1281 Register Reg = MO.getReg(); 1282 ValueIDNum Num = MTracker->readReg(Reg); 1283 auto PHIRec = DebugPHIRecord( 1284 {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); 1285 DebugPHINumToValue.push_back(PHIRec); 1286 1287 // Ensure this register is tracked. 1288 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1289 MTracker->lookupOrTrackRegister(*RAI); 1290 } else if (MO.isFI()) { 1291 // The value is whatever's in this stack slot. 1292 unsigned FI = MO.getIndex(); 1293 1294 // If the stack slot is dead, then this was optimized away. 1295 // FIXME: stack slot colouring should account for slots that get merged. 1296 if (MFI->isDeadObjectIndex(FI)) 1297 return EmitBadPHI(); 1298 1299 // Identify this spill slot, ensure it's tracked. 1300 Register Base; 1301 StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); 1302 SpillLoc SL = {Base, Offs}; 1303 Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL); 1304 1305 // We might be able to find a value, but have chosen not to, to avoid 1306 // tracking too much stack information. 1307 if (!SpillNo) 1308 return EmitBadPHI(); 1309 1310 // Any stack location DBG_PHI should have an associate bit-size. 1311 assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?"); 1312 unsigned slotBitSize = MI.getOperand(2).getImm(); 1313 1314 unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0}); 1315 LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID); 1316 ValueIDNum Result = MTracker->readMLoc(SpillLoc); 1317 1318 // Record this DBG_PHI for later analysis. 1319 auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc}); 1320 DebugPHINumToValue.push_back(DbgPHI); 1321 } else { 1322 // Else: if the operand is neither a legal register or a stack slot, then 1323 // we're being fed illegal debug-info. Record an empty PHI, so that any 1324 // debug users trying to read this number will be put off trying to 1325 // interpret the value. 1326 LLVM_DEBUG( 1327 { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; }); 1328 return EmitBadPHI(); 1329 } 1330 1331 return true; 1332 } 1333 1334 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { 1335 // Meta Instructions do not affect the debug liveness of any register they 1336 // define. 1337 if (MI.isImplicitDef()) { 1338 // Except when there's an implicit def, and the location it's defining has 1339 // no value number. The whole point of an implicit def is to announce that 1340 // the register is live, without be specific about it's value. So define 1341 // a value if there isn't one already. 1342 ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); 1343 // Has a legitimate value -> ignore the implicit def. 1344 if (Num.getLoc() != 0) 1345 return; 1346 // Otherwise, def it here. 1347 } else if (MI.isMetaInstruction()) 1348 return; 1349 1350 // We always ignore SP defines on call instructions, they don't actually 1351 // change the value of the stack pointer... except for win32's _chkstk. This 1352 // is rare: filter quickly for the common case (no stack adjustments, not a 1353 // call, etc). If it is a call that modifies SP, recognise the SP register 1354 // defs. 1355 bool CallChangesSP = false; 1356 if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() && 1357 !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data())) 1358 CallChangesSP = true; 1359 1360 // Test whether we should ignore a def of this register due to it being part 1361 // of the stack pointer. 1362 auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool { 1363 if (CallChangesSP) 1364 return false; 1365 return MI.isCall() && MTracker->SPAliases.count(R); 1366 }; 1367 1368 // Find the regs killed by MI, and find regmasks of preserved regs. 1369 // Max out the number of statically allocated elements in `DeadRegs`, as this 1370 // prevents fallback to std::set::count() operations. 1371 SmallSet<uint32_t, 32> DeadRegs; 1372 SmallVector<const uint32_t *, 4> RegMasks; 1373 SmallVector<const MachineOperand *, 4> RegMaskPtrs; 1374 for (const MachineOperand &MO : MI.operands()) { 1375 // Determine whether the operand is a register def. 1376 if (MO.isReg() && MO.isDef() && MO.getReg() && 1377 Register::isPhysicalRegister(MO.getReg()) && 1378 !IgnoreSPAlias(MO.getReg())) { 1379 // Remove ranges of all aliased registers. 1380 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1381 // FIXME: Can we break out of this loop early if no insertion occurs? 1382 DeadRegs.insert(*RAI); 1383 } else if (MO.isRegMask()) { 1384 RegMasks.push_back(MO.getRegMask()); 1385 RegMaskPtrs.push_back(&MO); 1386 } 1387 } 1388 1389 // Tell MLocTracker about all definitions, of regmasks and otherwise. 1390 for (uint32_t DeadReg : DeadRegs) 1391 MTracker->defReg(DeadReg, CurBB, CurInst); 1392 1393 for (auto *MO : RegMaskPtrs) 1394 MTracker->writeRegMask(MO, CurBB, CurInst); 1395 1396 // If this instruction writes to a spill slot, def that slot. 1397 if (hasFoldedStackStore(MI)) { 1398 if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1399 for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1400 unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1401 LocIdx L = MTracker->getSpillMLoc(SpillID); 1402 MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L)); 1403 } 1404 } 1405 } 1406 1407 if (!TTracker) 1408 return; 1409 1410 // When committing variable values to locations: tell transfer tracker that 1411 // we've clobbered things. It may be able to recover the variable from a 1412 // different location. 1413 1414 // Inform TTracker about any direct clobbers. 1415 for (uint32_t DeadReg : DeadRegs) { 1416 LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); 1417 TTracker->clobberMloc(Loc, MI.getIterator(), false); 1418 } 1419 1420 // Look for any clobbers performed by a register mask. Only test locations 1421 // that are actually being tracked. 1422 if (!RegMaskPtrs.empty()) { 1423 for (auto L : MTracker->locations()) { 1424 // Stack locations can't be clobbered by regmasks. 1425 if (MTracker->isSpill(L.Idx)) 1426 continue; 1427 1428 Register Reg = MTracker->LocIdxToLocID[L.Idx]; 1429 if (IgnoreSPAlias(Reg)) 1430 continue; 1431 1432 for (auto *MO : RegMaskPtrs) 1433 if (MO->clobbersPhysReg(Reg)) 1434 TTracker->clobberMloc(L.Idx, MI.getIterator(), false); 1435 } 1436 } 1437 1438 // Tell TTracker about any folded stack store. 1439 if (hasFoldedStackStore(MI)) { 1440 if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1441 for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1442 unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1443 LocIdx L = MTracker->getSpillMLoc(SpillID); 1444 TTracker->clobberMloc(L, MI.getIterator(), true); 1445 } 1446 } 1447 } 1448 } 1449 1450 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { 1451 // In all circumstances, re-def all aliases. It's definitely a new value now. 1452 for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI) 1453 MTracker->defReg(*RAI, CurBB, CurInst); 1454 1455 ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); 1456 MTracker->setReg(DstRegNum, SrcValue); 1457 1458 // Copy subregisters from one location to another. 1459 for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { 1460 unsigned SrcSubReg = SRI.getSubReg(); 1461 unsigned SubRegIdx = SRI.getSubRegIndex(); 1462 unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); 1463 if (!DstSubReg) 1464 continue; 1465 1466 // Do copy. There are two matching subregisters, the source value should 1467 // have been def'd when the super-reg was, the latter might not be tracked 1468 // yet. 1469 // This will force SrcSubReg to be tracked, if it isn't yet. Will read 1470 // mphi values if it wasn't tracked. 1471 LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg); 1472 LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg); 1473 (void)SrcL; 1474 (void)DstL; 1475 ValueIDNum CpyValue = MTracker->readReg(SrcSubReg); 1476 1477 MTracker->setReg(DstSubReg, CpyValue); 1478 } 1479 } 1480 1481 Optional<SpillLocationNo> 1482 InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, 1483 MachineFunction *MF) { 1484 // TODO: Handle multiple stores folded into one. 1485 if (!MI.hasOneMemOperand()) 1486 return None; 1487 1488 // Reject any memory operand that's aliased -- we can't guarantee its value. 1489 auto MMOI = MI.memoperands_begin(); 1490 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 1491 if (PVal->isAliased(MFI)) 1492 return None; 1493 1494 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 1495 return None; // This is not a spill instruction, since no valid size was 1496 // returned from either function. 1497 1498 return extractSpillBaseRegAndOffset(MI); 1499 } 1500 1501 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, 1502 MachineFunction *MF, unsigned &Reg) { 1503 if (!isSpillInstruction(MI, MF)) 1504 return false; 1505 1506 int FI; 1507 Reg = TII->isStoreToStackSlotPostFE(MI, FI); 1508 return Reg != 0; 1509 } 1510 1511 Optional<SpillLocationNo> 1512 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, 1513 MachineFunction *MF, unsigned &Reg) { 1514 if (!MI.hasOneMemOperand()) 1515 return None; 1516 1517 // FIXME: Handle folded restore instructions with more than one memory 1518 // operand. 1519 if (MI.getRestoreSize(TII)) { 1520 Reg = MI.getOperand(0).getReg(); 1521 return extractSpillBaseRegAndOffset(MI); 1522 } 1523 return None; 1524 } 1525 1526 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { 1527 // XXX -- it's too difficult to implement VarLocBasedImpl's stack location 1528 // limitations under the new model. Therefore, when comparing them, compare 1529 // versions that don't attempt spills or restores at all. 1530 if (EmulateOldLDV) 1531 return false; 1532 1533 // Strictly limit ourselves to plain loads and stores, not all instructions 1534 // that can access the stack. 1535 int DummyFI = -1; 1536 if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) && 1537 !TII->isLoadFromStackSlotPostFE(MI, DummyFI)) 1538 return false; 1539 1540 MachineFunction *MF = MI.getMF(); 1541 unsigned Reg; 1542 1543 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 1544 1545 // Strictly limit ourselves to plain loads and stores, not all instructions 1546 // that can access the stack. 1547 int FIDummy; 1548 if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) && 1549 !TII->isLoadFromStackSlotPostFE(MI, FIDummy)) 1550 return false; 1551 1552 // First, if there are any DBG_VALUEs pointing at a spill slot that is 1553 // written to, terminate that variable location. The value in memory 1554 // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. 1555 if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) { 1556 // Un-set this location and clobber, so that earlier locations don't 1557 // continue past this store. 1558 for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) { 1559 unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx); 1560 Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID); 1561 if (!MLoc) 1562 continue; 1563 1564 // We need to over-write the stack slot with something (here, a def at 1565 // this instruction) to ensure no values are preserved in this stack slot 1566 // after the spill. It also prevents TTracker from trying to recover the 1567 // location and re-installing it in the same place. 1568 ValueIDNum Def(CurBB, CurInst, *MLoc); 1569 MTracker->setMLoc(*MLoc, Def); 1570 if (TTracker) 1571 TTracker->clobberMloc(*MLoc, MI.getIterator()); 1572 } 1573 } 1574 1575 // Try to recognise spill and restore instructions that may transfer a value. 1576 if (isLocationSpill(MI, MF, Reg)) { 1577 // isLocationSpill returning true should guarantee we can extract a 1578 // location. 1579 SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI); 1580 1581 auto DoTransfer = [&](Register SrcReg, unsigned SpillID) { 1582 auto ReadValue = MTracker->readReg(SrcReg); 1583 LocIdx DstLoc = MTracker->getSpillMLoc(SpillID); 1584 MTracker->setMLoc(DstLoc, ReadValue); 1585 1586 if (TTracker) { 1587 LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg); 1588 TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator()); 1589 } 1590 }; 1591 1592 // Then, transfer subreg bits. 1593 for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1594 // Ensure this reg is tracked, 1595 (void)MTracker->lookupOrTrackRegister(*SRI); 1596 unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI); 1597 unsigned SpillID = MTracker->getLocID(Loc, SubregIdx); 1598 DoTransfer(*SRI, SpillID); 1599 } 1600 1601 // Directly lookup size of main source reg, and transfer. 1602 unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1603 unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); 1604 DoTransfer(Reg, SpillID); 1605 } else { 1606 Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg); 1607 if (!Loc) 1608 return false; 1609 1610 // Assumption: we're reading from the base of the stack slot, not some 1611 // offset into it. It seems very unlikely LLVM would ever generate 1612 // restores where this wasn't true. This then becomes a question of what 1613 // subregisters in the destination register line up with positions in the 1614 // stack slot. 1615 1616 // Def all registers that alias the destination. 1617 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1618 MTracker->defReg(*RAI, CurBB, CurInst); 1619 1620 // Now find subregisters within the destination register, and load values 1621 // from stack slot positions. 1622 auto DoTransfer = [&](Register DestReg, unsigned SpillID) { 1623 LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID); 1624 auto ReadValue = MTracker->readMLoc(SrcIdx); 1625 MTracker->setReg(DestReg, ReadValue); 1626 }; 1627 1628 for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1629 unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1630 unsigned SpillID = MTracker->getLocID(*Loc, Subreg); 1631 DoTransfer(*SRI, SpillID); 1632 } 1633 1634 // Directly look up this registers slot idx by size, and transfer. 1635 unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1636 unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0}); 1637 DoTransfer(Reg, SpillID); 1638 } 1639 return true; 1640 } 1641 1642 bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { 1643 auto DestSrc = TII->isCopyInstr(MI); 1644 if (!DestSrc) 1645 return false; 1646 1647 const MachineOperand *DestRegOp = DestSrc->Destination; 1648 const MachineOperand *SrcRegOp = DestSrc->Source; 1649 1650 auto isCalleeSavedReg = [&](unsigned Reg) { 1651 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1652 if (CalleeSavedRegs.test(*RAI)) 1653 return true; 1654 return false; 1655 }; 1656 1657 Register SrcReg = SrcRegOp->getReg(); 1658 Register DestReg = DestRegOp->getReg(); 1659 1660 // Ignore identity copies. Yep, these make it as far as LiveDebugValues. 1661 if (SrcReg == DestReg) 1662 return true; 1663 1664 // For emulating VarLocBasedImpl: 1665 // We want to recognize instructions where destination register is callee 1666 // saved register. If register that could be clobbered by the call is 1667 // included, there would be a great chance that it is going to be clobbered 1668 // soon. It is more likely that previous register, which is callee saved, is 1669 // going to stay unclobbered longer, even if it is killed. 1670 // 1671 // For InstrRefBasedImpl, we can track multiple locations per value, so 1672 // ignore this condition. 1673 if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) 1674 return false; 1675 1676 // InstrRefBasedImpl only followed killing copies. 1677 if (EmulateOldLDV && !SrcRegOp->isKill()) 1678 return false; 1679 1680 // Copy MTracker info, including subregs if available. 1681 InstrRefBasedLDV::performCopy(SrcReg, DestReg); 1682 1683 // Only produce a transfer of DBG_VALUE within a block where old LDV 1684 // would have. We might make use of the additional value tracking in some 1685 // other way, later. 1686 if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) 1687 TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), 1688 MTracker->getRegMLoc(DestReg), MI.getIterator()); 1689 1690 // VarLocBasedImpl would quit tracking the old location after copying. 1691 if (EmulateOldLDV && SrcReg != DestReg) 1692 MTracker->defReg(SrcReg, CurBB, CurInst); 1693 1694 // Finally, the copy might have clobbered variables based on the destination 1695 // register. Tell TTracker about it, in case a backup location exists. 1696 if (TTracker) { 1697 for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { 1698 LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); 1699 TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false); 1700 } 1701 } 1702 1703 return true; 1704 } 1705 1706 /// Accumulate a mapping between each DILocalVariable fragment and other 1707 /// fragments of that DILocalVariable which overlap. This reduces work during 1708 /// the data-flow stage from "Find any overlapping fragments" to "Check if the 1709 /// known-to-overlap fragments are present". 1710 /// \param MI A previously unprocessed debug instruction to analyze for 1711 /// fragment usage. 1712 void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { 1713 assert(MI.isDebugValue() || MI.isDebugRef()); 1714 DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 1715 MI.getDebugLoc()->getInlinedAt()); 1716 FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 1717 1718 // If this is the first sighting of this variable, then we are guaranteed 1719 // there are currently no overlapping fragments either. Initialize the set 1720 // of seen fragments, record no overlaps for the current one, and return. 1721 auto SeenIt = SeenFragments.find(MIVar.getVariable()); 1722 if (SeenIt == SeenFragments.end()) { 1723 SmallSet<FragmentInfo, 4> OneFragment; 1724 OneFragment.insert(ThisFragment); 1725 SeenFragments.insert({MIVar.getVariable(), OneFragment}); 1726 1727 OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1728 return; 1729 } 1730 1731 // If this particular Variable/Fragment pair already exists in the overlap 1732 // map, it has already been accounted for. 1733 auto IsInOLapMap = 1734 OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1735 if (!IsInOLapMap.second) 1736 return; 1737 1738 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 1739 auto &AllSeenFragments = SeenIt->second; 1740 1741 // Otherwise, examine all other seen fragments for this variable, with "this" 1742 // fragment being a previously unseen fragment. Record any pair of 1743 // overlapping fragments. 1744 for (auto &ASeenFragment : AllSeenFragments) { 1745 // Does this previously seen fragment overlap? 1746 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 1747 // Yes: Mark the current fragment as being overlapped. 1748 ThisFragmentsOverlaps.push_back(ASeenFragment); 1749 // Mark the previously seen fragment as being overlapped by the current 1750 // one. 1751 auto ASeenFragmentsOverlaps = 1752 OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); 1753 assert(ASeenFragmentsOverlaps != OverlapFragments.end() && 1754 "Previously seen var fragment has no vector of overlaps"); 1755 ASeenFragmentsOverlaps->second.push_back(ThisFragment); 1756 } 1757 } 1758 1759 AllSeenFragments.insert(ThisFragment); 1760 } 1761 1762 void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts, 1763 const ValueTable *MLiveIns) { 1764 // Try to interpret an MI as a debug or transfer instruction. Only if it's 1765 // none of these should we interpret it's register defs as new value 1766 // definitions. 1767 if (transferDebugValue(MI)) 1768 return; 1769 if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) 1770 return; 1771 if (transferDebugPHI(MI)) 1772 return; 1773 if (transferRegisterCopy(MI)) 1774 return; 1775 if (transferSpillOrRestoreInst(MI)) 1776 return; 1777 transferRegisterDef(MI); 1778 } 1779 1780 void InstrRefBasedLDV::produceMLocTransferFunction( 1781 MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, 1782 unsigned MaxNumBlocks) { 1783 // Because we try to optimize around register mask operands by ignoring regs 1784 // that aren't currently tracked, we set up something ugly for later: RegMask 1785 // operands that are seen earlier than the first use of a register, still need 1786 // to clobber that register in the transfer function. But this information 1787 // isn't actively recorded. Instead, we track each RegMask used in each block, 1788 // and accumulated the clobbered but untracked registers in each block into 1789 // the following bitvector. Later, if new values are tracked, we can add 1790 // appropriate clobbers. 1791 SmallVector<BitVector, 32> BlockMasks; 1792 BlockMasks.resize(MaxNumBlocks); 1793 1794 // Reserve one bit per register for the masks described above. 1795 unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); 1796 for (auto &BV : BlockMasks) 1797 BV.resize(TRI->getNumRegs(), true); 1798 1799 // Step through all instructions and inhale the transfer function. 1800 for (auto &MBB : MF) { 1801 // Object fields that are read by trackers to know where we are in the 1802 // function. 1803 CurBB = MBB.getNumber(); 1804 CurInst = 1; 1805 1806 // Set all machine locations to a PHI value. For transfer function 1807 // production only, this signifies the live-in value to the block. 1808 MTracker->reset(); 1809 MTracker->setMPhis(CurBB); 1810 1811 // Step through each instruction in this block. 1812 for (auto &MI : MBB) { 1813 // Pass in an empty unique_ptr for the value tables when accumulating the 1814 // machine transfer function. 1815 process(MI, nullptr, nullptr); 1816 1817 // Also accumulate fragment map. 1818 if (MI.isDebugValue() || MI.isDebugRef()) 1819 accumulateFragmentMap(MI); 1820 1821 // Create a map from the instruction number (if present) to the 1822 // MachineInstr and its position. 1823 if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 1824 auto InstrAndPos = std::make_pair(&MI, CurInst); 1825 auto InsertResult = 1826 DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 1827 1828 // There should never be duplicate instruction numbers. 1829 assert(InsertResult.second); 1830 (void)InsertResult; 1831 } 1832 1833 ++CurInst; 1834 } 1835 1836 // Produce the transfer function, a map of machine location to new value. If 1837 // any machine location has the live-in phi value from the start of the 1838 // block, it's live-through and doesn't need recording in the transfer 1839 // function. 1840 for (auto Location : MTracker->locations()) { 1841 LocIdx Idx = Location.Idx; 1842 ValueIDNum &P = Location.Value; 1843 if (P.isPHI() && P.getLoc() == Idx.asU64()) 1844 continue; 1845 1846 // Insert-or-update. 1847 auto &TransferMap = MLocTransfer[CurBB]; 1848 auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 1849 if (!Result.second) 1850 Result.first->second = P; 1851 } 1852 1853 // Accumulate any bitmask operands into the clobberred reg mask for this 1854 // block. 1855 for (auto &P : MTracker->Masks) { 1856 BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 1857 } 1858 } 1859 1860 // Compute a bitvector of all the registers that are tracked in this block. 1861 BitVector UsedRegs(TRI->getNumRegs()); 1862 for (auto Location : MTracker->locations()) { 1863 unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 1864 // Ignore stack slots, and aliases of the stack pointer. 1865 if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) 1866 continue; 1867 UsedRegs.set(ID); 1868 } 1869 1870 // Check that any regmask-clobber of a register that gets tracked, is not 1871 // live-through in the transfer function. It needs to be clobbered at the 1872 // very least. 1873 for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 1874 BitVector &BV = BlockMasks[I]; 1875 BV.flip(); 1876 BV &= UsedRegs; 1877 // This produces all the bits that we clobber, but also use. Check that 1878 // they're all clobbered or at least set in the designated transfer 1879 // elem. 1880 for (unsigned Bit : BV.set_bits()) { 1881 unsigned ID = MTracker->getLocID(Bit); 1882 LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 1883 auto &TransferMap = MLocTransfer[I]; 1884 1885 // Install a value representing the fact that this location is effectively 1886 // written to in this block. As there's no reserved value, instead use 1887 // a value number that is never generated. Pick the value number for the 1888 // first instruction in the block, def'ing this location, which we know 1889 // this block never used anyway. 1890 ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 1891 auto Result = 1892 TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 1893 if (!Result.second) { 1894 ValueIDNum &ValueID = Result.first->second; 1895 if (ValueID.getBlock() == I && ValueID.isPHI()) 1896 // It was left as live-through. Set it to clobbered. 1897 ValueID = NotGeneratedNum; 1898 } 1899 } 1900 } 1901 } 1902 1903 bool InstrRefBasedLDV::mlocJoin( 1904 MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1905 FuncValueTable &OutLocs, ValueTable &InLocs) { 1906 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1907 bool Changed = false; 1908 1909 // Handle value-propagation when control flow merges on entry to a block. For 1910 // any location without a PHI already placed, the location has the same value 1911 // as its predecessors. If a PHI is placed, test to see whether it's now a 1912 // redundant PHI that we can eliminate. 1913 1914 SmallVector<const MachineBasicBlock *, 8> BlockOrders; 1915 for (auto Pred : MBB.predecessors()) 1916 BlockOrders.push_back(Pred); 1917 1918 // Visit predecessors in RPOT order. 1919 auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1920 return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 1921 }; 1922 llvm::sort(BlockOrders, Cmp); 1923 1924 // Skip entry block. 1925 if (BlockOrders.size() == 0) 1926 return false; 1927 1928 // Step through all machine locations, look at each predecessor and test 1929 // whether we can eliminate redundant PHIs. 1930 for (auto Location : MTracker->locations()) { 1931 LocIdx Idx = Location.Idx; 1932 1933 // Pick out the first predecessors live-out value for this location. It's 1934 // guaranteed to not be a backedge, as we order by RPO. 1935 ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 1936 1937 // If we've already eliminated a PHI here, do no further checking, just 1938 // propagate the first live-in value into this block. 1939 if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { 1940 if (InLocs[Idx.asU64()] != FirstVal) { 1941 InLocs[Idx.asU64()] = FirstVal; 1942 Changed |= true; 1943 } 1944 continue; 1945 } 1946 1947 // We're now examining a PHI to see whether it's un-necessary. Loop around 1948 // the other live-in values and test whether they're all the same. 1949 bool Disagree = false; 1950 for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 1951 const MachineBasicBlock *PredMBB = BlockOrders[I]; 1952 const ValueIDNum &PredLiveOut = 1953 OutLocs[PredMBB->getNumber()][Idx.asU64()]; 1954 1955 // Incoming values agree, continue trying to eliminate this PHI. 1956 if (FirstVal == PredLiveOut) 1957 continue; 1958 1959 // We can also accept a PHI value that feeds back into itself. 1960 if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) 1961 continue; 1962 1963 // Live-out of a predecessor disagrees with the first predecessor. 1964 Disagree = true; 1965 } 1966 1967 // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. 1968 if (!Disagree) { 1969 InLocs[Idx.asU64()] = FirstVal; 1970 Changed |= true; 1971 } 1972 } 1973 1974 // TODO: Reimplement NumInserted and NumRemoved. 1975 return Changed; 1976 } 1977 1978 void InstrRefBasedLDV::findStackIndexInterference( 1979 SmallVectorImpl<unsigned> &Slots) { 1980 // We could spend a bit of time finding the exact, minimal, set of stack 1981 // indexes that interfere with each other, much like reg units. Or, we can 1982 // rely on the fact that: 1983 // * The smallest / lowest index will interfere with everything at zero 1984 // offset, which will be the largest set of registers, 1985 // * Most indexes with non-zero offset will end up being interference units 1986 // anyway. 1987 // So just pick those out and return them. 1988 1989 // We can rely on a single-byte stack index existing already, because we 1990 // initialize them in MLocTracker. 1991 auto It = MTracker->StackSlotIdxes.find({8, 0}); 1992 assert(It != MTracker->StackSlotIdxes.end()); 1993 Slots.push_back(It->second); 1994 1995 // Find anything that has a non-zero offset and add that too. 1996 for (auto &Pair : MTracker->StackSlotIdxes) { 1997 // Is offset zero? If so, ignore. 1998 if (!Pair.first.second) 1999 continue; 2000 Slots.push_back(Pair.second); 2001 } 2002 } 2003 2004 void InstrRefBasedLDV::placeMLocPHIs( 2005 MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2006 FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2007 SmallVector<unsigned, 4> StackUnits; 2008 findStackIndexInterference(StackUnits); 2009 2010 // To avoid repeatedly running the PHI placement algorithm, leverage the 2011 // fact that a def of register MUST also def its register units. Find the 2012 // units for registers, place PHIs for them, and then replicate them for 2013 // aliasing registers. Some inputs that are never def'd (DBG_PHIs of 2014 // arguments) don't lead to register units being tracked, just place PHIs for 2015 // those registers directly. Stack slots have their own form of "unit", 2016 // store them to one side. 2017 SmallSet<Register, 32> RegUnitsToPHIUp; 2018 SmallSet<LocIdx, 32> NormalLocsToPHI; 2019 SmallSet<SpillLocationNo, 32> StackSlots; 2020 for (auto Location : MTracker->locations()) { 2021 LocIdx L = Location.Idx; 2022 if (MTracker->isSpill(L)) { 2023 StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); 2024 continue; 2025 } 2026 2027 Register R = MTracker->LocIdxToLocID[L]; 2028 SmallSet<Register, 8> FoundRegUnits; 2029 bool AnyIllegal = false; 2030 for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { 2031 for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ 2032 if (!MTracker->isRegisterTracked(*URoot)) { 2033 // Not all roots were loaded into the tracking map: this register 2034 // isn't actually def'd anywhere, we only read from it. Generate PHIs 2035 // for this reg, but don't iterate units. 2036 AnyIllegal = true; 2037 } else { 2038 FoundRegUnits.insert(*URoot); 2039 } 2040 } 2041 } 2042 2043 if (AnyIllegal) { 2044 NormalLocsToPHI.insert(L); 2045 continue; 2046 } 2047 2048 RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); 2049 } 2050 2051 // Lambda to fetch PHIs for a given location, and write into the PHIBlocks 2052 // collection. 2053 SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2054 auto CollectPHIsForLoc = [&](LocIdx L) { 2055 // Collect the set of defs. 2056 SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2057 for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 2058 MachineBasicBlock *MBB = OrderToBB[I]; 2059 const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; 2060 if (TransferFunc.find(L) != TransferFunc.end()) 2061 DefBlocks.insert(MBB); 2062 } 2063 2064 // The entry block defs the location too: it's the live-in / argument value. 2065 // Only insert if there are other defs though; everything is trivially live 2066 // through otherwise. 2067 if (!DefBlocks.empty()) 2068 DefBlocks.insert(&*MF.begin()); 2069 2070 // Ask the SSA construction algorithm where we should put PHIs. Clear 2071 // anything that might have been hanging around from earlier. 2072 PHIBlocks.clear(); 2073 BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); 2074 }; 2075 2076 auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { 2077 for (const MachineBasicBlock *MBB : PHIBlocks) 2078 MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); 2079 }; 2080 2081 // For locations with no reg units, just place PHIs. 2082 for (LocIdx L : NormalLocsToPHI) { 2083 CollectPHIsForLoc(L); 2084 // Install those PHI values into the live-in value array. 2085 InstallPHIsAtLoc(L); 2086 } 2087 2088 // For stack slots, calculate PHIs for the equivalent of the units, then 2089 // install for each index. 2090 for (SpillLocationNo Slot : StackSlots) { 2091 for (unsigned Idx : StackUnits) { 2092 unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); 2093 LocIdx L = MTracker->getSpillMLoc(SpillID); 2094 CollectPHIsForLoc(L); 2095 InstallPHIsAtLoc(L); 2096 2097 // Find anything that aliases this stack index, install PHIs for it too. 2098 unsigned Size, Offset; 2099 std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; 2100 for (auto &Pair : MTracker->StackSlotIdxes) { 2101 unsigned ThisSize, ThisOffset; 2102 std::tie(ThisSize, ThisOffset) = Pair.first; 2103 if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) 2104 continue; 2105 2106 unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); 2107 LocIdx ThisL = MTracker->getSpillMLoc(ThisID); 2108 InstallPHIsAtLoc(ThisL); 2109 } 2110 } 2111 } 2112 2113 // For reg units, place PHIs, and then place them for any aliasing registers. 2114 for (Register R : RegUnitsToPHIUp) { 2115 LocIdx L = MTracker->lookupOrTrackRegister(R); 2116 CollectPHIsForLoc(L); 2117 2118 // Install those PHI values into the live-in value array. 2119 InstallPHIsAtLoc(L); 2120 2121 // Now find aliases and install PHIs for those. 2122 for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { 2123 // Super-registers that are "above" the largest register read/written by 2124 // the function will alias, but will not be tracked. 2125 if (!MTracker->isRegisterTracked(*RAI)) 2126 continue; 2127 2128 LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); 2129 InstallPHIsAtLoc(AliasLoc); 2130 } 2131 } 2132 } 2133 2134 void InstrRefBasedLDV::buildMLocValueMap( 2135 MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs, 2136 SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2137 std::priority_queue<unsigned int, std::vector<unsigned int>, 2138 std::greater<unsigned int>> 2139 Worklist, Pending; 2140 2141 // We track what is on the current and pending worklist to avoid inserting 2142 // the same thing twice. We could avoid this with a custom priority queue, 2143 // but this is probably not worth it. 2144 SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2145 2146 // Initialize worklist with every block to be visited. Also produce list of 2147 // all blocks. 2148 SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; 2149 for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2150 Worklist.push(I); 2151 OnWorklist.insert(OrderToBB[I]); 2152 AllBlocks.insert(OrderToBB[I]); 2153 } 2154 2155 // Initialize entry block to PHIs. These represent arguments. 2156 for (auto Location : MTracker->locations()) 2157 MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); 2158 2159 MTracker->reset(); 2160 2161 // Start by placing PHIs, using the usual SSA constructor algorithm. Consider 2162 // any machine-location that isn't live-through a block to be def'd in that 2163 // block. 2164 placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); 2165 2166 // Propagate values to eliminate redundant PHIs. At the same time, this 2167 // produces the table of Block x Location => Value for the entry to each 2168 // block. 2169 // The kind of PHIs we can eliminate are, for example, where one path in a 2170 // conditional spills and restores a register, and the register still has 2171 // the same value once control flow joins, unbeknowns to the PHI placement 2172 // code. Propagating values allows us to identify such un-necessary PHIs and 2173 // remove them. 2174 SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2175 while (!Worklist.empty() || !Pending.empty()) { 2176 // Vector for storing the evaluated block transfer function. 2177 SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2178 2179 while (!Worklist.empty()) { 2180 MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2181 CurBB = MBB->getNumber(); 2182 Worklist.pop(); 2183 2184 // Join the values in all predecessor blocks. 2185 bool InLocsChanged; 2186 InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2187 InLocsChanged |= Visited.insert(MBB).second; 2188 2189 // Don't examine transfer function if we've visited this loc at least 2190 // once, and inlocs haven't changed. 2191 if (!InLocsChanged) 2192 continue; 2193 2194 // Load the current set of live-ins into MLocTracker. 2195 MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2196 2197 // Each element of the transfer function can be a new def, or a read of 2198 // a live-in value. Evaluate each element, and store to "ToRemap". 2199 ToRemap.clear(); 2200 for (auto &P : MLocTransfer[CurBB]) { 2201 if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2202 // This is a movement of whatever was live in. Read it. 2203 ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); 2204 ToRemap.push_back(std::make_pair(P.first, NewID)); 2205 } else { 2206 // It's a def. Just set it. 2207 assert(P.second.getBlock() == CurBB); 2208 ToRemap.push_back(std::make_pair(P.first, P.second)); 2209 } 2210 } 2211 2212 // Commit the transfer function changes into mloc tracker, which 2213 // transforms the contents of the MLocTracker into the live-outs. 2214 for (auto &P : ToRemap) 2215 MTracker->setMLoc(P.first, P.second); 2216 2217 // Now copy out-locs from mloc tracker into out-loc vector, checking 2218 // whether changes have occurred. These changes can have come from both 2219 // the transfer function, and mlocJoin. 2220 bool OLChanged = false; 2221 for (auto Location : MTracker->locations()) { 2222 OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2223 MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2224 } 2225 2226 MTracker->reset(); 2227 2228 // No need to examine successors again if out-locs didn't change. 2229 if (!OLChanged) 2230 continue; 2231 2232 // All successors should be visited: put any back-edges on the pending 2233 // list for the next pass-through, and any other successors to be 2234 // visited this pass, if they're not going to be already. 2235 for (auto s : MBB->successors()) { 2236 // Does branching to this successor represent a back-edge? 2237 if (BBToOrder[s] > BBToOrder[MBB]) { 2238 // No: visit it during this dataflow iteration. 2239 if (OnWorklist.insert(s).second) 2240 Worklist.push(BBToOrder[s]); 2241 } else { 2242 // Yes: visit it on the next iteration. 2243 if (OnPending.insert(s).second) 2244 Pending.push(BBToOrder[s]); 2245 } 2246 } 2247 } 2248 2249 Worklist.swap(Pending); 2250 std::swap(OnPending, OnWorklist); 2251 OnPending.clear(); 2252 // At this point, pending must be empty, since it was just the empty 2253 // worklist 2254 assert(Pending.empty() && "Pending should be empty"); 2255 } 2256 2257 // Once all the live-ins don't change on mlocJoin(), we've eliminated all 2258 // redundant PHIs. 2259 } 2260 2261 void InstrRefBasedLDV::BlockPHIPlacement( 2262 const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2263 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 2264 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { 2265 // Apply IDF calculator to the designated set of location defs, storing 2266 // required PHIs into PHIBlocks. Uses the dominator tree stored in the 2267 // InstrRefBasedLDV object. 2268 IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase()); 2269 2270 IDF.setLiveInBlocks(AllBlocks); 2271 IDF.setDefiningBlocks(DefBlocks); 2272 IDF.calculate(PHIBlocks); 2273 } 2274 2275 Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( 2276 const MachineBasicBlock &MBB, const DebugVariable &Var, 2277 const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs, 2278 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { 2279 // Collect a set of locations from predecessor where its live-out value can 2280 // be found. 2281 SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2282 SmallVector<const DbgValueProperties *, 4> Properties; 2283 unsigned NumLocs = MTracker->getNumLocs(); 2284 2285 // No predecessors means no PHIs. 2286 if (BlockOrders.empty()) 2287 return None; 2288 2289 for (auto p : BlockOrders) { 2290 unsigned ThisBBNum = p->getNumber(); 2291 auto OutValIt = LiveOuts.find(p); 2292 if (OutValIt == LiveOuts.end()) 2293 // If we have a predecessor not in scope, we'll never find a PHI position. 2294 return None; 2295 const DbgValue &OutVal = *OutValIt->second; 2296 2297 if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2298 // Consts and no-values cannot have locations we can join on. 2299 return None; 2300 2301 Properties.push_back(&OutVal.Properties); 2302 2303 // Create new empty vector of locations. 2304 Locs.resize(Locs.size() + 1); 2305 2306 // If the live-in value is a def, find the locations where that value is 2307 // present. Do the same for VPHIs where we know the VPHI value. 2308 if (OutVal.Kind == DbgValue::Def || 2309 (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && 2310 OutVal.ID != ValueIDNum::EmptyValue)) { 2311 ValueIDNum ValToLookFor = OutVal.ID; 2312 // Search the live-outs of the predecessor for the specified value. 2313 for (unsigned int I = 0; I < NumLocs; ++I) { 2314 if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2315 Locs.back().push_back(LocIdx(I)); 2316 } 2317 } else { 2318 assert(OutVal.Kind == DbgValue::VPHI); 2319 // For VPHIs where we don't know the location, we definitely can't find 2320 // a join loc. 2321 if (OutVal.BlockNo != MBB.getNumber()) 2322 return None; 2323 2324 // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. 2325 // a value that's live-through the whole loop. (It has to be a backedge, 2326 // because a block can't dominate itself). We can accept as a PHI location 2327 // any location where the other predecessors agree, _and_ the machine 2328 // locations feed back into themselves. Therefore, add all self-looping 2329 // machine-value PHI locations. 2330 for (unsigned int I = 0; I < NumLocs; ++I) { 2331 ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); 2332 if (MOutLocs[ThisBBNum][I] == MPHI) 2333 Locs.back().push_back(LocIdx(I)); 2334 } 2335 } 2336 } 2337 2338 // We should have found locations for all predecessors, or returned. 2339 assert(Locs.size() == BlockOrders.size()); 2340 2341 // Check that all properties are the same. We can't pick a location if they're 2342 // not. 2343 const DbgValueProperties *Properties0 = Properties[0]; 2344 for (auto *Prop : Properties) 2345 if (*Prop != *Properties0) 2346 return None; 2347 2348 // Starting with the first set of locations, take the intersection with 2349 // subsequent sets. 2350 SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; 2351 for (unsigned int I = 1; I < Locs.size(); ++I) { 2352 auto &LocVec = Locs[I]; 2353 SmallVector<LocIdx, 4> NewCandidates; 2354 std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), 2355 LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); 2356 CandidateLocs = NewCandidates; 2357 } 2358 if (CandidateLocs.empty()) 2359 return None; 2360 2361 // We now have a set of LocIdxes that contain the right output value in 2362 // each of the predecessors. Pick the lowest; if there's a register loc, 2363 // that'll be it. 2364 LocIdx L = *CandidateLocs.begin(); 2365 2366 // Return a PHI-value-number for the found location. 2367 ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2368 return PHIVal; 2369 } 2370 2371 bool InstrRefBasedLDV::vlocJoin( 2372 MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 2373 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2374 DbgValue &LiveIn) { 2375 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2376 bool Changed = false; 2377 2378 // Order predecessors by RPOT order, for exploring them in that order. 2379 SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2380 2381 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2382 return BBToOrder[A] < BBToOrder[B]; 2383 }; 2384 2385 llvm::sort(BlockOrders, Cmp); 2386 2387 unsigned CurBlockRPONum = BBToOrder[&MBB]; 2388 2389 // Collect all the incoming DbgValues for this variable, from predecessor 2390 // live-out values. 2391 SmallVector<InValueT, 8> Values; 2392 bool Bail = false; 2393 int BackEdgesStart = 0; 2394 for (auto p : BlockOrders) { 2395 // If the predecessor isn't in scope / to be explored, we'll never be 2396 // able to join any locations. 2397 if (!BlocksToExplore.contains(p)) { 2398 Bail = true; 2399 break; 2400 } 2401 2402 // All Live-outs will have been initialized. 2403 DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; 2404 2405 // Keep track of where back-edges begin in the Values vector. Relies on 2406 // BlockOrders being sorted by RPO. 2407 unsigned ThisBBRPONum = BBToOrder[p]; 2408 if (ThisBBRPONum < CurBlockRPONum) 2409 ++BackEdgesStart; 2410 2411 Values.push_back(std::make_pair(p, &OutLoc)); 2412 } 2413 2414 // If there were no values, or one of the predecessors couldn't have a 2415 // value, then give up immediately. It's not safe to produce a live-in 2416 // value. Leave as whatever it was before. 2417 if (Bail || Values.size() == 0) 2418 return false; 2419 2420 // All (non-entry) blocks have at least one non-backedge predecessor. 2421 // Pick the variable value from the first of these, to compare against 2422 // all others. 2423 const DbgValue &FirstVal = *Values[0].second; 2424 2425 // If the old live-in value is not a PHI then either a) no PHI is needed 2426 // here, or b) we eliminated the PHI that was here. If so, we can just 2427 // propagate in the first parent's incoming value. 2428 if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { 2429 Changed = LiveIn != FirstVal; 2430 if (Changed) 2431 LiveIn = FirstVal; 2432 return Changed; 2433 } 2434 2435 // Scan for variable values that can never be resolved: if they have 2436 // different DIExpressions, different indirectness, or are mixed constants / 2437 // non-constants. 2438 for (auto &V : Values) { 2439 if (V.second->Properties != FirstVal.Properties) 2440 return false; 2441 if (V.second->Kind == DbgValue::NoVal) 2442 return false; 2443 if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 2444 return false; 2445 } 2446 2447 // Try to eliminate this PHI. Do the incoming values all agree? 2448 bool Disagree = false; 2449 for (auto &V : Values) { 2450 if (*V.second == FirstVal) 2451 continue; // No disagreement. 2452 2453 // Eliminate if a backedge feeds a VPHI back into itself. 2454 if (V.second->Kind == DbgValue::VPHI && 2455 V.second->BlockNo == MBB.getNumber() && 2456 // Is this a backedge? 2457 std::distance(Values.begin(), &V) >= BackEdgesStart) 2458 continue; 2459 2460 Disagree = true; 2461 } 2462 2463 // No disagreement -> live-through value. 2464 if (!Disagree) { 2465 Changed = LiveIn != FirstVal; 2466 if (Changed) 2467 LiveIn = FirstVal; 2468 return Changed; 2469 } else { 2470 // Otherwise use a VPHI. 2471 DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); 2472 Changed = LiveIn != VPHI; 2473 if (Changed) 2474 LiveIn = VPHI; 2475 return Changed; 2476 } 2477 } 2478 2479 void InstrRefBasedLDV::getBlocksForScope( 2480 const DILocation *DILoc, 2481 SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore, 2482 const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) { 2483 // Get the set of "normal" in-lexical-scope blocks. 2484 LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 2485 2486 // VarLoc LiveDebugValues tracks variable locations that are defined in 2487 // blocks not in scope. This is something we could legitimately ignore, but 2488 // lets allow it for now for the sake of coverage. 2489 BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 2490 2491 // Storage for artificial blocks we intend to add to BlocksToExplore. 2492 DenseSet<const MachineBasicBlock *> ToAdd; 2493 2494 // To avoid needlessly dropping large volumes of variable locations, propagate 2495 // variables through aritifical blocks, i.e. those that don't have any 2496 // instructions in scope at all. To accurately replicate VarLoc 2497 // LiveDebugValues, this means exploring all artificial successors too. 2498 // Perform a depth-first-search to enumerate those blocks. 2499 for (auto *MBB : BlocksToExplore) { 2500 // Depth-first-search state: each node is a block and which successor 2501 // we're currently exploring. 2502 SmallVector<std::pair<const MachineBasicBlock *, 2503 MachineBasicBlock::const_succ_iterator>, 2504 8> 2505 DFS; 2506 2507 // Find any artificial successors not already tracked. 2508 for (auto *succ : MBB->successors()) { 2509 if (BlocksToExplore.count(succ)) 2510 continue; 2511 if (!ArtificialBlocks.count(succ)) 2512 continue; 2513 ToAdd.insert(succ); 2514 DFS.push_back({succ, succ->succ_begin()}); 2515 } 2516 2517 // Search all those blocks, depth first. 2518 while (!DFS.empty()) { 2519 const MachineBasicBlock *CurBB = DFS.back().first; 2520 MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 2521 // Walk back if we've explored this blocks successors to the end. 2522 if (CurSucc == CurBB->succ_end()) { 2523 DFS.pop_back(); 2524 continue; 2525 } 2526 2527 // If the current successor is artificial and unexplored, descend into 2528 // it. 2529 if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 2530 ToAdd.insert(*CurSucc); 2531 DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()}); 2532 continue; 2533 } 2534 2535 ++CurSucc; 2536 } 2537 }; 2538 2539 BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 2540 } 2541 2542 void InstrRefBasedLDV::buildVLocValueMap( 2543 const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 2544 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 2545 FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2546 SmallVectorImpl<VLocTracker> &AllTheVLocs) { 2547 // This method is much like buildMLocValueMap: but focuses on a single 2548 // LexicalScope at a time. Pick out a set of blocks and variables that are 2549 // to have their value assignments solved, then run our dataflow algorithm 2550 // until a fixedpoint is reached. 2551 std::priority_queue<unsigned int, std::vector<unsigned int>, 2552 std::greater<unsigned int>> 2553 Worklist, Pending; 2554 SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 2555 2556 // The set of blocks we'll be examining. 2557 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2558 2559 // The order in which to examine them (RPO). 2560 SmallVector<MachineBasicBlock *, 8> BlockOrders; 2561 2562 // RPO ordering function. 2563 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2564 return BBToOrder[A] < BBToOrder[B]; 2565 }; 2566 2567 getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks); 2568 2569 // Single block scope: not interesting! No propagation at all. Note that 2570 // this could probably go above ArtificialBlocks without damage, but 2571 // that then produces output differences from original-live-debug-values, 2572 // which propagates from a single block into many artificial ones. 2573 if (BlocksToExplore.size() == 1) 2574 return; 2575 2576 // Convert a const set to a non-const set. LexicalScopes 2577 // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. 2578 // (Neither of them mutate anything). 2579 SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; 2580 for (const auto *MBB : BlocksToExplore) 2581 MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); 2582 2583 // Picks out relevants blocks RPO order and sort them. 2584 for (auto *MBB : BlocksToExplore) 2585 BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 2586 2587 llvm::sort(BlockOrders, Cmp); 2588 unsigned NumBlocks = BlockOrders.size(); 2589 2590 // Allocate some vectors for storing the live ins and live outs. Large. 2591 SmallVector<DbgValue, 32> LiveIns, LiveOuts; 2592 LiveIns.reserve(NumBlocks); 2593 LiveOuts.reserve(NumBlocks); 2594 2595 // Initialize all values to start as NoVals. This signifies "it's live 2596 // through, but we don't know what it is". 2597 DbgValueProperties EmptyProperties(EmptyExpr, false); 2598 for (unsigned int I = 0; I < NumBlocks; ++I) { 2599 DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2600 LiveIns.push_back(EmptyDbgValue); 2601 LiveOuts.push_back(EmptyDbgValue); 2602 } 2603 2604 // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 2605 // vlocJoin. 2606 LiveIdxT LiveOutIdx, LiveInIdx; 2607 LiveOutIdx.reserve(NumBlocks); 2608 LiveInIdx.reserve(NumBlocks); 2609 for (unsigned I = 0; I < NumBlocks; ++I) { 2610 LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 2611 LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 2612 } 2613 2614 // Loop over each variable and place PHIs for it, then propagate values 2615 // between blocks. This keeps the locality of working on one lexical scope at 2616 // at time, but avoids re-processing variable values because some other 2617 // variable has been assigned. 2618 for (auto &Var : VarsWeCareAbout) { 2619 // Re-initialize live-ins and live-outs, to clear the remains of previous 2620 // variables live-ins / live-outs. 2621 for (unsigned int I = 0; I < NumBlocks; ++I) { 2622 DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2623 LiveIns[I] = EmptyDbgValue; 2624 LiveOuts[I] = EmptyDbgValue; 2625 } 2626 2627 // Place PHIs for variable values, using the LLVM IDF calculator. 2628 // Collect the set of blocks where variables are def'd. 2629 SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2630 for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { 2631 auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; 2632 if (TransferFunc.find(Var) != TransferFunc.end()) 2633 DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); 2634 } 2635 2636 SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2637 2638 // Request the set of PHIs we should insert for this variable. If there's 2639 // only one value definition, things are very simple. 2640 if (DefBlocks.size() == 1) { 2641 placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(), 2642 AllTheVLocs, Var, Output); 2643 continue; 2644 } 2645 2646 // Otherwise: we need to place PHIs through SSA and propagate values. 2647 BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); 2648 2649 // Insert PHIs into the per-block live-in tables for this variable. 2650 for (MachineBasicBlock *PHIMBB : PHIBlocks) { 2651 unsigned BlockNo = PHIMBB->getNumber(); 2652 DbgValue *LiveIn = LiveInIdx[PHIMBB]; 2653 *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); 2654 } 2655 2656 for (auto *MBB : BlockOrders) { 2657 Worklist.push(BBToOrder[MBB]); 2658 OnWorklist.insert(MBB); 2659 } 2660 2661 // Iterate over all the blocks we selected, propagating the variables value. 2662 // This loop does two things: 2663 // * Eliminates un-necessary VPHIs in vlocJoin, 2664 // * Evaluates the blocks transfer function (i.e. variable assignments) and 2665 // stores the result to the blocks live-outs. 2666 // Always evaluate the transfer function on the first iteration, and when 2667 // the live-ins change thereafter. 2668 bool FirstTrip = true; 2669 while (!Worklist.empty() || !Pending.empty()) { 2670 while (!Worklist.empty()) { 2671 auto *MBB = OrderToBB[Worklist.top()]; 2672 CurBB = MBB->getNumber(); 2673 Worklist.pop(); 2674 2675 auto LiveInsIt = LiveInIdx.find(MBB); 2676 assert(LiveInsIt != LiveInIdx.end()); 2677 DbgValue *LiveIn = LiveInsIt->second; 2678 2679 // Join values from predecessors. Updates LiveInIdx, and writes output 2680 // into JoinedInLocs. 2681 bool InLocsChanged = 2682 vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); 2683 2684 SmallVector<const MachineBasicBlock *, 8> Preds; 2685 for (const auto *Pred : MBB->predecessors()) 2686 Preds.push_back(Pred); 2687 2688 // If this block's live-in value is a VPHI, try to pick a machine-value 2689 // for it. This makes the machine-value available and propagated 2690 // through all blocks by the time value propagation finishes. We can't 2691 // do this any earlier as it needs to read the block live-outs. 2692 if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { 2693 // There's a small possibility that on a preceeding path, a VPHI is 2694 // eliminated and transitions from VPHI-with-location to 2695 // live-through-value. As a result, the selected location of any VPHI 2696 // might change, so we need to re-compute it on each iteration. 2697 Optional<ValueIDNum> ValueNum = 2698 pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); 2699 2700 if (ValueNum) { 2701 InLocsChanged |= LiveIn->ID != *ValueNum; 2702 LiveIn->ID = *ValueNum; 2703 } 2704 } 2705 2706 if (!InLocsChanged && !FirstTrip) 2707 continue; 2708 2709 DbgValue *LiveOut = LiveOutIdx[MBB]; 2710 bool OLChanged = false; 2711 2712 // Do transfer function. 2713 auto &VTracker = AllTheVLocs[MBB->getNumber()]; 2714 auto TransferIt = VTracker.Vars.find(Var); 2715 if (TransferIt != VTracker.Vars.end()) { 2716 // Erase on empty transfer (DBG_VALUE $noreg). 2717 if (TransferIt->second.Kind == DbgValue::Undef) { 2718 DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); 2719 if (*LiveOut != NewVal) { 2720 *LiveOut = NewVal; 2721 OLChanged = true; 2722 } 2723 } else { 2724 // Insert new variable value; or overwrite. 2725 if (*LiveOut != TransferIt->second) { 2726 *LiveOut = TransferIt->second; 2727 OLChanged = true; 2728 } 2729 } 2730 } else { 2731 // Just copy live-ins to live-outs, for anything not transferred. 2732 if (*LiveOut != *LiveIn) { 2733 *LiveOut = *LiveIn; 2734 OLChanged = true; 2735 } 2736 } 2737 2738 // If no live-out value changed, there's no need to explore further. 2739 if (!OLChanged) 2740 continue; 2741 2742 // We should visit all successors. Ensure we'll visit any non-backedge 2743 // successors during this dataflow iteration; book backedge successors 2744 // to be visited next time around. 2745 for (auto s : MBB->successors()) { 2746 // Ignore out of scope / not-to-be-explored successors. 2747 if (LiveInIdx.find(s) == LiveInIdx.end()) 2748 continue; 2749 2750 if (BBToOrder[s] > BBToOrder[MBB]) { 2751 if (OnWorklist.insert(s).second) 2752 Worklist.push(BBToOrder[s]); 2753 } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 2754 Pending.push(BBToOrder[s]); 2755 } 2756 } 2757 } 2758 Worklist.swap(Pending); 2759 std::swap(OnWorklist, OnPending); 2760 OnPending.clear(); 2761 assert(Pending.empty()); 2762 FirstTrip = false; 2763 } 2764 2765 // Save live-ins to output vector. Ignore any that are still marked as being 2766 // VPHIs with no location -- those are variables that we know the value of, 2767 // but are not actually available in the register file. 2768 for (auto *MBB : BlockOrders) { 2769 DbgValue *BlockLiveIn = LiveInIdx[MBB]; 2770 if (BlockLiveIn->Kind == DbgValue::NoVal) 2771 continue; 2772 if (BlockLiveIn->Kind == DbgValue::VPHI && 2773 BlockLiveIn->ID == ValueIDNum::EmptyValue) 2774 continue; 2775 if (BlockLiveIn->Kind == DbgValue::VPHI) 2776 BlockLiveIn->Kind = DbgValue::Def; 2777 assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == 2778 Var.getFragment() && "Fragment info missing during value prop"); 2779 Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); 2780 } 2781 } // Per-variable loop. 2782 2783 BlockOrders.clear(); 2784 BlocksToExplore.clear(); 2785 } 2786 2787 void InstrRefBasedLDV::placePHIsForSingleVarDefinition( 2788 const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks, 2789 MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs, 2790 const DebugVariable &Var, LiveInsT &Output) { 2791 // If there is a single definition of the variable, then working out it's 2792 // value everywhere is very simple: it's every block dominated by the 2793 // definition. At the dominance frontier, the usual algorithm would: 2794 // * Place PHIs, 2795 // * Propagate values into them, 2796 // * Find there's no incoming variable value from the other incoming branches 2797 // of the dominance frontier, 2798 // * Specify there's no variable value in blocks past the frontier. 2799 // This is a common case, hence it's worth special-casing it. 2800 2801 // Pick out the variables value from the block transfer function. 2802 VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()]; 2803 auto ValueIt = VLocs.Vars.find(Var); 2804 const DbgValue &Value = ValueIt->second; 2805 2806 // If it's an explicit assignment of "undef", that means there is no location 2807 // anyway, anywhere. 2808 if (Value.Kind == DbgValue::Undef) 2809 return; 2810 2811 // Assign the variable value to entry to each dominated block that's in scope. 2812 // Skip the definition block -- it's assigned the variable value in the middle 2813 // of the block somewhere. 2814 for (auto *ScopeBlock : InScopeBlocks) { 2815 if (!DomTree->properlyDominates(AssignMBB, ScopeBlock)) 2816 continue; 2817 2818 Output[ScopeBlock->getNumber()].push_back({Var, Value}); 2819 } 2820 2821 // All blocks that aren't dominated have no live-in value, thus no variable 2822 // value will be given to them. 2823 } 2824 2825 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2826 void InstrRefBasedLDV::dump_mloc_transfer( 2827 const MLocTransferMap &mloc_transfer) const { 2828 for (auto &P : mloc_transfer) { 2829 std::string foo = MTracker->LocIdxToName(P.first); 2830 std::string bar = MTracker->IDAsString(P.second); 2831 dbgs() << "Loc " << foo << " --> " << bar << "\n"; 2832 } 2833 } 2834 #endif 2835 2836 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 2837 // Build some useful data structures. 2838 2839 LLVMContext &Context = MF.getFunction().getContext(); 2840 EmptyExpr = DIExpression::get(Context, {}); 2841 2842 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 2843 if (const DebugLoc &DL = MI.getDebugLoc()) 2844 return DL.getLine() != 0; 2845 return false; 2846 }; 2847 // Collect a set of all the artificial blocks. 2848 for (auto &MBB : MF) 2849 if (none_of(MBB.instrs(), hasNonArtificialLocation)) 2850 ArtificialBlocks.insert(&MBB); 2851 2852 // Compute mappings of block <=> RPO order. 2853 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 2854 unsigned int RPONumber = 0; 2855 for (MachineBasicBlock *MBB : RPOT) { 2856 OrderToBB[RPONumber] = MBB; 2857 BBToOrder[MBB] = RPONumber; 2858 BBNumToRPO[MBB->getNumber()] = RPONumber; 2859 ++RPONumber; 2860 } 2861 2862 // Order value substitutions by their "source" operand pair, for quick lookup. 2863 llvm::sort(MF.DebugValueSubstitutions); 2864 2865 #ifdef EXPENSIVE_CHECKS 2866 // As an expensive check, test whether there are any duplicate substitution 2867 // sources in the collection. 2868 if (MF.DebugValueSubstitutions.size() > 2) { 2869 for (auto It = MF.DebugValueSubstitutions.begin(); 2870 It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { 2871 assert(It->Src != std::next(It)->Src && "Duplicate variable location " 2872 "substitution seen"); 2873 } 2874 } 2875 #endif 2876 } 2877 2878 // Produce an "ejection map" for blocks, i.e., what's the highest-numbered 2879 // lexical scope it's used in. When exploring in DFS order and we pass that 2880 // scope, the block can be processed and any tracking information freed. 2881 void InstrRefBasedLDV::makeDepthFirstEjectionMap( 2882 SmallVectorImpl<unsigned> &EjectionMap, 2883 const ScopeToDILocT &ScopeToDILocation, 2884 ScopeToAssignBlocksT &ScopeToAssignBlocks) { 2885 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2886 SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2887 auto *TopScope = LS.getCurrentFunctionScope(); 2888 2889 // Unlike lexical scope explorers, we explore in reverse order, to find the 2890 // "last" lexical scope used for each block early. 2891 WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1}); 2892 2893 while (!WorkStack.empty()) { 2894 auto &ScopePosition = WorkStack.back(); 2895 LexicalScope *WS = ScopePosition.first; 2896 ssize_t ChildNum = ScopePosition.second--; 2897 2898 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 2899 if (ChildNum >= 0) { 2900 // If ChildNum is positive, there are remaining children to explore. 2901 // Push the child and its children-count onto the stack. 2902 auto &ChildScope = Children[ChildNum]; 2903 WorkStack.push_back( 2904 std::make_pair(ChildScope, ChildScope->getChildren().size() - 1)); 2905 } else { 2906 WorkStack.pop_back(); 2907 2908 // We've explored all children and any later blocks: examine all blocks 2909 // in our scope. If they haven't yet had an ejection number set, then 2910 // this scope will be the last to use that block. 2911 auto DILocationIt = ScopeToDILocation.find(WS); 2912 if (DILocationIt != ScopeToDILocation.end()) { 2913 getBlocksForScope(DILocationIt->second, BlocksToExplore, 2914 ScopeToAssignBlocks.find(WS)->second); 2915 for (auto *MBB : BlocksToExplore) { 2916 unsigned BBNum = MBB->getNumber(); 2917 if (EjectionMap[BBNum] == 0) 2918 EjectionMap[BBNum] = WS->getDFSOut(); 2919 } 2920 2921 BlocksToExplore.clear(); 2922 } 2923 } 2924 } 2925 } 2926 2927 bool InstrRefBasedLDV::depthFirstVLocAndEmit( 2928 unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation, 2929 const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks, 2930 LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2931 SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF, 2932 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 2933 const TargetPassConfig &TPC) { 2934 TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 2935 unsigned NumLocs = MTracker->getNumLocs(); 2936 VTracker = nullptr; 2937 2938 // No scopes? No variable locations. 2939 if (!LS.getCurrentFunctionScope()) 2940 return false; 2941 2942 // Build map from block number to the last scope that uses the block. 2943 SmallVector<unsigned, 16> EjectionMap; 2944 EjectionMap.resize(MaxNumBlocks, 0); 2945 makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation, 2946 ScopeToAssignBlocks); 2947 2948 // Helper lambda for ejecting a block -- if nothing is going to use the block, 2949 // we can translate the variable location information into DBG_VALUEs and then 2950 // free all of InstrRefBasedLDV's data structures. 2951 auto EjectBlock = [&](MachineBasicBlock &MBB) -> void { 2952 unsigned BBNum = MBB.getNumber(); 2953 AllTheVLocs[BBNum].clear(); 2954 2955 // Prime the transfer-tracker, and then step through all the block 2956 // instructions, installing transfers. 2957 MTracker->reset(); 2958 MTracker->loadFromArray(MInLocs[BBNum], BBNum); 2959 TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs); 2960 2961 CurBB = BBNum; 2962 CurInst = 1; 2963 for (auto &MI : MBB) { 2964 process(MI, MOutLocs.get(), MInLocs.get()); 2965 TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 2966 ++CurInst; 2967 } 2968 2969 // Free machine-location tables for this block. 2970 MInLocs[BBNum].reset(); 2971 MOutLocs[BBNum].reset(); 2972 // We don't need live-in variable values for this block either. 2973 Output[BBNum].clear(); 2974 AllTheVLocs[BBNum].clear(); 2975 }; 2976 2977 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2978 SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2979 WorkStack.push_back({LS.getCurrentFunctionScope(), 0}); 2980 unsigned HighestDFSIn = 0; 2981 2982 // Proceed to explore in depth first order. 2983 while (!WorkStack.empty()) { 2984 auto &ScopePosition = WorkStack.back(); 2985 LexicalScope *WS = ScopePosition.first; 2986 ssize_t ChildNum = ScopePosition.second++; 2987 2988 // We obesrve scopes with children twice here, once descending in, once 2989 // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure 2990 // we don't process a scope twice. Additionally, ignore scopes that don't 2991 // have a DILocation -- by proxy, this means we never tracked any variable 2992 // assignments in that scope. 2993 auto DILocIt = ScopeToDILocation.find(WS); 2994 if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) { 2995 const DILocation *DILoc = DILocIt->second; 2996 auto &VarsWeCareAbout = ScopeToVars.find(WS)->second; 2997 auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second; 2998 2999 buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs, 3000 MInLocs, AllTheVLocs); 3001 } 3002 3003 HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn()); 3004 3005 // Descend into any scope nests. 3006 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 3007 if (ChildNum < (ssize_t)Children.size()) { 3008 // There are children to explore -- push onto stack and continue. 3009 auto &ChildScope = Children[ChildNum]; 3010 WorkStack.push_back(std::make_pair(ChildScope, 0)); 3011 } else { 3012 WorkStack.pop_back(); 3013 3014 // We've explored a leaf, or have explored all the children of a scope. 3015 // Try to eject any blocks where this is the last scope it's relevant to. 3016 auto DILocationIt = ScopeToDILocation.find(WS); 3017 if (DILocationIt == ScopeToDILocation.end()) 3018 continue; 3019 3020 getBlocksForScope(DILocationIt->second, BlocksToExplore, 3021 ScopeToAssignBlocks.find(WS)->second); 3022 for (auto *MBB : BlocksToExplore) 3023 if (WS->getDFSOut() == EjectionMap[MBB->getNumber()]) 3024 EjectBlock(const_cast<MachineBasicBlock &>(*MBB)); 3025 3026 BlocksToExplore.clear(); 3027 } 3028 } 3029 3030 // Some artificial blocks may not have been ejected, meaning they're not 3031 // connected to an actual legitimate scope. This can technically happen 3032 // with things like the entry block. In theory, we shouldn't need to do 3033 // anything for such out-of-scope blocks, but for the sake of being similar 3034 // to VarLocBasedLDV, eject these too. 3035 for (auto *MBB : ArtificialBlocks) 3036 if (MOutLocs[MBB->getNumber()]) 3037 EjectBlock(*MBB); 3038 3039 return emitTransfers(AllVarsNumbering); 3040 } 3041 3042 bool InstrRefBasedLDV::emitTransfers( 3043 DenseMap<DebugVariable, unsigned> &AllVarsNumbering) { 3044 // Go through all the transfers recorded in the TransferTracker -- this is 3045 // both the live-ins to a block, and any movements of values that happen 3046 // in the middle. 3047 for (const auto &P : TTracker->Transfers) { 3048 // We have to insert DBG_VALUEs in a consistent order, otherwise they 3049 // appear in DWARF in different orders. Use the order that they appear 3050 // when walking through each block / each instruction, stored in 3051 // AllVarsNumbering. 3052 SmallVector<std::pair<unsigned, MachineInstr *>> Insts; 3053 for (MachineInstr *MI : P.Insts) { 3054 DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(), 3055 MI->getDebugLoc()->getInlinedAt()); 3056 Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI); 3057 } 3058 llvm::sort(Insts, 3059 [](const auto &A, const auto &B) { return A.first < B.first; }); 3060 3061 // Insert either before or after the designated point... 3062 if (P.MBB) { 3063 MachineBasicBlock &MBB = *P.MBB; 3064 for (const auto &Pair : Insts) 3065 MBB.insert(P.Pos, Pair.second); 3066 } else { 3067 // Terminators, like tail calls, can clobber things. Don't try and place 3068 // transfers after them. 3069 if (P.Pos->isTerminator()) 3070 continue; 3071 3072 MachineBasicBlock &MBB = *P.Pos->getParent(); 3073 for (const auto &Pair : Insts) 3074 MBB.insertAfterBundle(P.Pos, Pair.second); 3075 } 3076 } 3077 3078 return TTracker->Transfers.size() != 0; 3079 } 3080 3081 /// Calculate the liveness information for the given machine function and 3082 /// extend ranges across basic blocks. 3083 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 3084 MachineDominatorTree *DomTree, 3085 TargetPassConfig *TPC, 3086 unsigned InputBBLimit, 3087 unsigned InputDbgValLimit) { 3088 // No subprogram means this function contains no debuginfo. 3089 if (!MF.getFunction().getSubprogram()) 3090 return false; 3091 3092 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 3093 this->TPC = TPC; 3094 3095 this->DomTree = DomTree; 3096 TRI = MF.getSubtarget().getRegisterInfo(); 3097 MRI = &MF.getRegInfo(); 3098 TII = MF.getSubtarget().getInstrInfo(); 3099 TFI = MF.getSubtarget().getFrameLowering(); 3100 TFI->getCalleeSaves(MF, CalleeSavedRegs); 3101 MFI = &MF.getFrameInfo(); 3102 LS.initialize(MF); 3103 3104 const auto &STI = MF.getSubtarget(); 3105 AdjustsStackInCalls = MFI->adjustsStack() && 3106 STI.getFrameLowering()->stackProbeFunctionModifiesSP(); 3107 if (AdjustsStackInCalls) 3108 StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); 3109 3110 MTracker = 3111 new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 3112 VTracker = nullptr; 3113 TTracker = nullptr; 3114 3115 SmallVector<MLocTransferMap, 32> MLocTransfer; 3116 SmallVector<VLocTracker, 8> vlocs; 3117 LiveInsT SavedLiveIns; 3118 3119 int MaxNumBlocks = -1; 3120 for (auto &MBB : MF) 3121 MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 3122 assert(MaxNumBlocks >= 0); 3123 ++MaxNumBlocks; 3124 3125 MLocTransfer.resize(MaxNumBlocks); 3126 vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); 3127 SavedLiveIns.resize(MaxNumBlocks); 3128 3129 initialSetup(MF); 3130 3131 produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 3132 3133 // Allocate and initialize two array-of-arrays for the live-in and live-out 3134 // machine values. The outer dimension is the block number; while the inner 3135 // dimension is a LocIdx from MLocTracker. 3136 FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3137 FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3138 unsigned NumLocs = MTracker->getNumLocs(); 3139 for (int i = 0; i < MaxNumBlocks; ++i) { 3140 // These all auto-initialize to ValueIDNum::EmptyValue 3141 MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3142 MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3143 } 3144 3145 // Solve the machine value dataflow problem using the MLocTransfer function, 3146 // storing the computed live-ins / live-outs into the array-of-arrays. We use 3147 // both live-ins and live-outs for decision making in the variable value 3148 // dataflow problem. 3149 buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); 3150 3151 // Patch up debug phi numbers, turning unknown block-live-in values into 3152 // either live-through machine values, or PHIs. 3153 for (auto &DBG_PHI : DebugPHINumToValue) { 3154 // Identify unresolved block-live-ins. 3155 if (!DBG_PHI.ValueRead) 3156 continue; 3157 3158 ValueIDNum &Num = *DBG_PHI.ValueRead; 3159 if (!Num.isPHI()) 3160 continue; 3161 3162 unsigned BlockNo = Num.getBlock(); 3163 LocIdx LocNo = Num.getLoc(); 3164 Num = MInLocs[BlockNo][LocNo.asU64()]; 3165 } 3166 // Later, we'll be looking up ranges of instruction numbers. 3167 llvm::sort(DebugPHINumToValue); 3168 3169 // Walk back through each block / instruction, collecting DBG_VALUE 3170 // instructions and recording what machine value their operands refer to. 3171 for (auto &OrderPair : OrderToBB) { 3172 MachineBasicBlock &MBB = *OrderPair.second; 3173 CurBB = MBB.getNumber(); 3174 VTracker = &vlocs[CurBB]; 3175 VTracker->MBB = &MBB; 3176 MTracker->loadFromArray(MInLocs[CurBB], CurBB); 3177 CurInst = 1; 3178 for (auto &MI : MBB) { 3179 process(MI, MOutLocs.get(), MInLocs.get()); 3180 ++CurInst; 3181 } 3182 MTracker->reset(); 3183 } 3184 3185 // Number all variables in the order that they appear, to be used as a stable 3186 // insertion order later. 3187 DenseMap<DebugVariable, unsigned> AllVarsNumbering; 3188 3189 // Map from one LexicalScope to all the variables in that scope. 3190 ScopeToVarsT ScopeToVars; 3191 3192 // Map from One lexical scope to all blocks where assignments happen for 3193 // that scope. 3194 ScopeToAssignBlocksT ScopeToAssignBlocks; 3195 3196 // Store map of DILocations that describes scopes. 3197 ScopeToDILocT ScopeToDILocation; 3198 3199 // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3200 // the order is unimportant, it just has to be stable. 3201 unsigned VarAssignCount = 0; 3202 for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3203 auto *MBB = OrderToBB[I]; 3204 auto *VTracker = &vlocs[MBB->getNumber()]; 3205 // Collect each variable with a DBG_VALUE in this block. 3206 for (auto &idx : VTracker->Vars) { 3207 const auto &Var = idx.first; 3208 const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3209 assert(ScopeLoc != nullptr); 3210 auto *Scope = LS.findLexicalScope(ScopeLoc); 3211 3212 // No insts in scope -> shouldn't have been recorded. 3213 assert(Scope != nullptr); 3214 3215 AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3216 ScopeToVars[Scope].insert(Var); 3217 ScopeToAssignBlocks[Scope].insert(VTracker->MBB); 3218 ScopeToDILocation[Scope] = ScopeLoc; 3219 ++VarAssignCount; 3220 } 3221 } 3222 3223 bool Changed = false; 3224 3225 // If we have an extremely large number of variable assignments and blocks, 3226 // bail out at this point. We've burnt some time doing analysis already, 3227 // however we should cut our losses. 3228 if ((unsigned)MaxNumBlocks > InputBBLimit && 3229 VarAssignCount > InputDbgValLimit) { 3230 LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() 3231 << " has " << MaxNumBlocks << " basic blocks and " 3232 << VarAssignCount 3233 << " variable assignments, exceeding limits.\n"); 3234 } else { 3235 // Optionally, solve the variable value problem and emit to blocks by using 3236 // a lexical-scope-depth search. It should be functionally identical to 3237 // the "else" block of this condition. 3238 Changed = depthFirstVLocAndEmit( 3239 MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks, 3240 SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC); 3241 } 3242 3243 delete MTracker; 3244 delete TTracker; 3245 MTracker = nullptr; 3246 VTracker = nullptr; 3247 TTracker = nullptr; 3248 3249 ArtificialBlocks.clear(); 3250 OrderToBB.clear(); 3251 BBToOrder.clear(); 3252 BBNumToRPO.clear(); 3253 DebugInstrNumToInstr.clear(); 3254 DebugPHINumToValue.clear(); 3255 OverlapFragments.clear(); 3256 SeenFragments.clear(); 3257 SeenDbgPHIs.clear(); 3258 3259 return Changed; 3260 } 3261 3262 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3263 return new InstrRefBasedLDV(); 3264 } 3265 3266 namespace { 3267 class LDVSSABlock; 3268 class LDVSSAUpdater; 3269 3270 // Pick a type to identify incoming block values as we construct SSA. We 3271 // can't use anything more robust than an integer unfortunately, as SSAUpdater 3272 // expects to zero-initialize the type. 3273 typedef uint64_t BlockValueNum; 3274 3275 /// Represents an SSA PHI node for the SSA updater class. Contains the block 3276 /// this PHI is in, the value number it would have, and the expected incoming 3277 /// values from parent blocks. 3278 class LDVSSAPhi { 3279 public: 3280 SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3281 LDVSSABlock *ParentBlock; 3282 BlockValueNum PHIValNum; 3283 LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3284 : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3285 3286 LDVSSABlock *getParent() { return ParentBlock; } 3287 }; 3288 3289 /// Thin wrapper around a block predecessor iterator. Only difference from a 3290 /// normal block iterator is that it dereferences to an LDVSSABlock. 3291 class LDVSSABlockIterator { 3292 public: 3293 MachineBasicBlock::pred_iterator PredIt; 3294 LDVSSAUpdater &Updater; 3295 3296 LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3297 LDVSSAUpdater &Updater) 3298 : PredIt(PredIt), Updater(Updater) {} 3299 3300 bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3301 return OtherIt.PredIt != PredIt; 3302 } 3303 3304 LDVSSABlockIterator &operator++() { 3305 ++PredIt; 3306 return *this; 3307 } 3308 3309 LDVSSABlock *operator*(); 3310 }; 3311 3312 /// Thin wrapper around a block for SSA Updater interface. Necessary because 3313 /// we need to track the PHI value(s) that we may have observed as necessary 3314 /// in this block. 3315 class LDVSSABlock { 3316 public: 3317 MachineBasicBlock &BB; 3318 LDVSSAUpdater &Updater; 3319 using PHIListT = SmallVector<LDVSSAPhi, 1>; 3320 /// List of PHIs in this block. There should only ever be one. 3321 PHIListT PHIList; 3322 3323 LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3324 : BB(BB), Updater(Updater) {} 3325 3326 LDVSSABlockIterator succ_begin() { 3327 return LDVSSABlockIterator(BB.succ_begin(), Updater); 3328 } 3329 3330 LDVSSABlockIterator succ_end() { 3331 return LDVSSABlockIterator(BB.succ_end(), Updater); 3332 } 3333 3334 /// SSAUpdater has requested a PHI: create that within this block record. 3335 LDVSSAPhi *newPHI(BlockValueNum Value) { 3336 PHIList.emplace_back(Value, this); 3337 return &PHIList.back(); 3338 } 3339 3340 /// SSAUpdater wishes to know what PHIs already exist in this block. 3341 PHIListT &phis() { return PHIList; } 3342 }; 3343 3344 /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3345 /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3346 // SSAUpdaterTraits<LDVSSAUpdater>. 3347 class LDVSSAUpdater { 3348 public: 3349 /// Map of value numbers to PHI records. 3350 DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3351 /// Map of which blocks generate Undef values -- blocks that are not 3352 /// dominated by any Def. 3353 DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3354 /// Map of machine blocks to our own records of them. 3355 DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3356 /// Machine location where any PHI must occur. 3357 LocIdx Loc; 3358 /// Table of live-in machine value numbers for blocks / locations. 3359 const ValueTable *MLiveIns; 3360 3361 LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns) 3362 : Loc(L), MLiveIns(MLiveIns) {} 3363 3364 void reset() { 3365 for (auto &Block : BlockMap) 3366 delete Block.second; 3367 3368 PHIs.clear(); 3369 UndefMap.clear(); 3370 BlockMap.clear(); 3371 } 3372 3373 ~LDVSSAUpdater() { reset(); } 3374 3375 /// For a given MBB, create a wrapper block for it. Stores it in the 3376 /// LDVSSAUpdater block map. 3377 LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3378 auto it = BlockMap.find(BB); 3379 if (it == BlockMap.end()) { 3380 BlockMap[BB] = new LDVSSABlock(*BB, *this); 3381 it = BlockMap.find(BB); 3382 } 3383 return it->second; 3384 } 3385 3386 /// Find the live-in value number for the given block. Looks up the value at 3387 /// the PHI location on entry. 3388 BlockValueNum getValue(LDVSSABlock *LDVBB) { 3389 return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3390 } 3391 }; 3392 3393 LDVSSABlock *LDVSSABlockIterator::operator*() { 3394 return Updater.getSSALDVBlock(*PredIt); 3395 } 3396 3397 #ifndef NDEBUG 3398 3399 raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3400 out << "SSALDVPHI " << PHI.PHIValNum; 3401 return out; 3402 } 3403 3404 #endif 3405 3406 } // namespace 3407 3408 namespace llvm { 3409 3410 /// Template specialization to give SSAUpdater access to CFG and value 3411 /// information. SSAUpdater calls methods in these traits, passing in the 3412 /// LDVSSAUpdater object, to learn about blocks and the values they define. 3413 /// It also provides methods to create PHI nodes and track them. 3414 template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3415 public: 3416 using BlkT = LDVSSABlock; 3417 using ValT = BlockValueNum; 3418 using PhiT = LDVSSAPhi; 3419 using BlkSucc_iterator = LDVSSABlockIterator; 3420 3421 // Methods to access block successors -- dereferencing to our wrapper class. 3422 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3423 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3424 3425 /// Iterator for PHI operands. 3426 class PHI_iterator { 3427 private: 3428 LDVSSAPhi *PHI; 3429 unsigned Idx; 3430 3431 public: 3432 explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3433 : PHI(P), Idx(0) {} 3434 PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3435 : PHI(P), Idx(PHI->IncomingValues.size()) {} 3436 3437 PHI_iterator &operator++() { 3438 Idx++; 3439 return *this; 3440 } 3441 bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3442 bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3443 3444 BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3445 3446 LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3447 }; 3448 3449 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3450 3451 static inline PHI_iterator PHI_end(PhiT *PHI) { 3452 return PHI_iterator(PHI, true); 3453 } 3454 3455 /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3456 /// vector. 3457 static void FindPredecessorBlocks(LDVSSABlock *BB, 3458 SmallVectorImpl<LDVSSABlock *> *Preds) { 3459 for (MachineBasicBlock *Pred : BB->BB.predecessors()) 3460 Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); 3461 } 3462 3463 /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3464 /// register. For LiveDebugValues, represents a block identified as not having 3465 /// any DBG_PHI predecessors. 3466 static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3467 // Create a value number for this block -- it needs to be unique and in the 3468 // "undef" collection, so that we know it's not real. Use a number 3469 // representing a PHI into this block. 3470 BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3471 Updater->UndefMap[&BB->BB] = Num; 3472 return Num; 3473 } 3474 3475 /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3476 /// SSAUpdater will populate it with information about incoming values. The 3477 /// value number of this PHI is whatever the machine value number problem 3478 /// solution determined it to be. This includes non-phi values if SSAUpdater 3479 /// tries to create a PHI where the incoming values are identical. 3480 static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3481 LDVSSAUpdater *Updater) { 3482 BlockValueNum PHIValNum = Updater->getValue(BB); 3483 LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3484 Updater->PHIs[PHIValNum] = PHI; 3485 return PHIValNum; 3486 } 3487 3488 /// AddPHIOperand - Add the specified value as an operand of the PHI for 3489 /// the specified predecessor block. 3490 static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3491 PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3492 } 3493 3494 /// ValueIsPHI - Check if the instruction that defines the specified value 3495 /// is a PHI instruction. 3496 static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3497 auto PHIIt = Updater->PHIs.find(Val); 3498 if (PHIIt == Updater->PHIs.end()) 3499 return nullptr; 3500 return PHIIt->second; 3501 } 3502 3503 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3504 /// operands, i.e., it was just added. 3505 static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3506 LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3507 if (PHI && PHI->IncomingValues.size() == 0) 3508 return PHI; 3509 return nullptr; 3510 } 3511 3512 /// GetPHIValue - For the specified PHI instruction, return the value 3513 /// that it defines. 3514 static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3515 }; 3516 3517 } // end namespace llvm 3518 3519 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs( 3520 MachineFunction &MF, const ValueTable *MLiveOuts, 3521 const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3522 assert(MLiveOuts && MLiveIns && 3523 "Tried to resolve DBG_PHI before location " 3524 "tables allocated?"); 3525 3526 // This function will be called twice per DBG_INSTR_REF, and might end up 3527 // computing lots of SSA information: memoize it. 3528 auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here); 3529 if (SeenDbgPHIIt != SeenDbgPHIs.end()) 3530 return SeenDbgPHIIt->second; 3531 3532 Optional<ValueIDNum> Result = 3533 resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum); 3534 SeenDbgPHIs.insert({&Here, Result}); 3535 return Result; 3536 } 3537 3538 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl( 3539 MachineFunction &MF, const ValueTable *MLiveOuts, 3540 const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3541 // Pick out records of DBG_PHI instructions that have been observed. If there 3542 // are none, then we cannot compute a value number. 3543 auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3544 DebugPHINumToValue.end(), InstrNum); 3545 auto LowerIt = RangePair.first; 3546 auto UpperIt = RangePair.second; 3547 3548 // No DBG_PHI means there can be no location. 3549 if (LowerIt == UpperIt) 3550 return None; 3551 3552 // If any DBG_PHIs referred to a location we didn't understand, don't try to 3553 // compute a value. There might be scenarios where we could recover a value 3554 // for some range of DBG_INSTR_REFs, but at this point we can have high 3555 // confidence that we've seen a bug. 3556 auto DBGPHIRange = make_range(LowerIt, UpperIt); 3557 for (const DebugPHIRecord &DBG_PHI : DBGPHIRange) 3558 if (!DBG_PHI.ValueRead) 3559 return None; 3560 3561 // If there's only one DBG_PHI, then that is our value number. 3562 if (std::distance(LowerIt, UpperIt) == 1) 3563 return *LowerIt->ValueRead; 3564 3565 // Pick out the location (physreg, slot) where any PHIs must occur. It's 3566 // technically possible for us to merge values in different registers in each 3567 // block, but highly unlikely that LLVM will generate such code after register 3568 // allocation. 3569 LocIdx Loc = *LowerIt->ReadLoc; 3570 3571 // We have several DBG_PHIs, and a use position (the Here inst). All each 3572 // DBG_PHI does is identify a value at a program position. We can treat each 3573 // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3574 // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3575 // determine which Def is used at the Use, and any PHIs that happen along 3576 // the way. 3577 // Adapted LLVM SSA Updater: 3578 LDVSSAUpdater Updater(Loc, MLiveIns); 3579 // Map of which Def or PHI is the current value in each block. 3580 DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3581 // Set of PHIs that we have created along the way. 3582 SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3583 3584 // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3585 // for the SSAUpdater. 3586 for (const auto &DBG_PHI : DBGPHIRange) { 3587 LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3588 const ValueIDNum &Num = *DBG_PHI.ValueRead; 3589 AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3590 } 3591 3592 LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3593 const auto &AvailIt = AvailableValues.find(HereBlock); 3594 if (AvailIt != AvailableValues.end()) { 3595 // Actually, we already know what the value is -- the Use is in the same 3596 // block as the Def. 3597 return ValueIDNum::fromU64(AvailIt->second); 3598 } 3599 3600 // Otherwise, we must use the SSA Updater. It will identify the value number 3601 // that we are to use, and the PHIs that must happen along the way. 3602 SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3603 BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3604 ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3605 3606 // We have the number for a PHI, or possibly live-through value, to be used 3607 // at this Use. There are a number of things we have to check about it though: 3608 // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3609 // Use was not completely dominated by DBG_PHIs and we should abort. 3610 // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3611 // we've left SSA form. Validate that the inputs to each PHI are the 3612 // expected values. 3613 // * Is a PHI we've created actually a merging of values, or are all the 3614 // predecessor values the same, leading to a non-PHI machine value number? 3615 // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3616 // the ValidatedValues collection below to sort this out. 3617 DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3618 3619 // Define all the input DBG_PHI values in ValidatedValues. 3620 for (const auto &DBG_PHI : DBGPHIRange) { 3621 LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3622 const ValueIDNum &Num = *DBG_PHI.ValueRead; 3623 ValidatedValues.insert(std::make_pair(Block, Num)); 3624 } 3625 3626 // Sort PHIs to validate into RPO-order. 3627 SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3628 for (auto &PHI : CreatedPHIs) 3629 SortedPHIs.push_back(PHI); 3630 3631 std::sort( 3632 SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3633 return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3634 }); 3635 3636 for (auto &PHI : SortedPHIs) { 3637 ValueIDNum ThisBlockValueNum = 3638 MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3639 3640 // Are all these things actually defined? 3641 for (auto &PHIIt : PHI->IncomingValues) { 3642 // Any undef input means DBG_PHIs didn't dominate the use point. 3643 if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3644 return None; 3645 3646 ValueIDNum ValueToCheck; 3647 const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 3648 3649 auto VVal = ValidatedValues.find(PHIIt.first); 3650 if (VVal == ValidatedValues.end()) { 3651 // We cross a loop, and this is a backedge. LLVMs tail duplication 3652 // happens so late that DBG_PHI instructions should not be able to 3653 // migrate into loops -- meaning we can only be live-through this 3654 // loop. 3655 ValueToCheck = ThisBlockValueNum; 3656 } else { 3657 // Does the block have as a live-out, in the location we're examining, 3658 // the value that we expect? If not, it's been moved or clobbered. 3659 ValueToCheck = VVal->second; 3660 } 3661 3662 if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 3663 return None; 3664 } 3665 3666 // Record this value as validated. 3667 ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 3668 } 3669 3670 // All the PHIs are valid: we can return what the SSAUpdater said our value 3671 // number was. 3672 return Result; 3673 } 3674