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