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, ValueTable &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 const ValueTable *MLiveOuts, 1026 const ValueTable *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, const ValueTable *MLiveOuts, 1786 const ValueTable *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 // Pass in an empty unique_ptr for the value tables when accumulating the 1837 // machine transfer function. 1838 process(MI, nullptr, nullptr); 1839 1840 // Also accumulate fragment map. 1841 if (MI.isDebugValue() || MI.isDebugRef()) 1842 accumulateFragmentMap(MI); 1843 1844 // Create a map from the instruction number (if present) to the 1845 // MachineInstr and its position. 1846 if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 1847 auto InstrAndPos = std::make_pair(&MI, CurInst); 1848 auto InsertResult = 1849 DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 1850 1851 // There should never be duplicate instruction numbers. 1852 assert(InsertResult.second); 1853 (void)InsertResult; 1854 } 1855 1856 ++CurInst; 1857 } 1858 1859 // Produce the transfer function, a map of machine location to new value. If 1860 // any machine location has the live-in phi value from the start of the 1861 // block, it's live-through and doesn't need recording in the transfer 1862 // function. 1863 for (auto Location : MTracker->locations()) { 1864 LocIdx Idx = Location.Idx; 1865 ValueIDNum &P = Location.Value; 1866 if (P.isPHI() && P.getLoc() == Idx.asU64()) 1867 continue; 1868 1869 // Insert-or-update. 1870 auto &TransferMap = MLocTransfer[CurBB]; 1871 auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 1872 if (!Result.second) 1873 Result.first->second = P; 1874 } 1875 1876 // Accumulate any bitmask operands into the clobberred reg mask for this 1877 // block. 1878 for (auto &P : MTracker->Masks) { 1879 BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 1880 } 1881 } 1882 1883 // Compute a bitvector of all the registers that are tracked in this block. 1884 BitVector UsedRegs(TRI->getNumRegs()); 1885 for (auto Location : MTracker->locations()) { 1886 unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 1887 // Ignore stack slots, and aliases of the stack pointer. 1888 if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) 1889 continue; 1890 UsedRegs.set(ID); 1891 } 1892 1893 // Check that any regmask-clobber of a register that gets tracked, is not 1894 // live-through in the transfer function. It needs to be clobbered at the 1895 // very least. 1896 for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 1897 BitVector &BV = BlockMasks[I]; 1898 BV.flip(); 1899 BV &= UsedRegs; 1900 // This produces all the bits that we clobber, but also use. Check that 1901 // they're all clobbered or at least set in the designated transfer 1902 // elem. 1903 for (unsigned Bit : BV.set_bits()) { 1904 unsigned ID = MTracker->getLocID(Bit); 1905 LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 1906 auto &TransferMap = MLocTransfer[I]; 1907 1908 // Install a value representing the fact that this location is effectively 1909 // written to in this block. As there's no reserved value, instead use 1910 // a value number that is never generated. Pick the value number for the 1911 // first instruction in the block, def'ing this location, which we know 1912 // this block never used anyway. 1913 ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 1914 auto Result = 1915 TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 1916 if (!Result.second) { 1917 ValueIDNum &ValueID = Result.first->second; 1918 if (ValueID.getBlock() == I && ValueID.isPHI()) 1919 // It was left as live-through. Set it to clobbered. 1920 ValueID = NotGeneratedNum; 1921 } 1922 } 1923 } 1924 } 1925 1926 bool InstrRefBasedLDV::mlocJoin( 1927 MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1928 FuncValueTable &OutLocs, ValueTable &InLocs) { 1929 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1930 bool Changed = false; 1931 1932 // Handle value-propagation when control flow merges on entry to a block. For 1933 // any location without a PHI already placed, the location has the same value 1934 // as its predecessors. If a PHI is placed, test to see whether it's now a 1935 // redundant PHI that we can eliminate. 1936 1937 SmallVector<const MachineBasicBlock *, 8> BlockOrders; 1938 for (auto Pred : MBB.predecessors()) 1939 BlockOrders.push_back(Pred); 1940 1941 // Visit predecessors in RPOT order. 1942 auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1943 return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 1944 }; 1945 llvm::sort(BlockOrders, Cmp); 1946 1947 // Skip entry block. 1948 if (BlockOrders.size() == 0) 1949 return false; 1950 1951 // Step through all machine locations, look at each predecessor and test 1952 // whether we can eliminate redundant PHIs. 1953 for (auto Location : MTracker->locations()) { 1954 LocIdx Idx = Location.Idx; 1955 1956 // Pick out the first predecessors live-out value for this location. It's 1957 // guaranteed to not be a backedge, as we order by RPO. 1958 ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 1959 1960 // If we've already eliminated a PHI here, do no further checking, just 1961 // propagate the first live-in value into this block. 1962 if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { 1963 if (InLocs[Idx.asU64()] != FirstVal) { 1964 InLocs[Idx.asU64()] = FirstVal; 1965 Changed |= true; 1966 } 1967 continue; 1968 } 1969 1970 // We're now examining a PHI to see whether it's un-necessary. Loop around 1971 // the other live-in values and test whether they're all the same. 1972 bool Disagree = false; 1973 for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 1974 const MachineBasicBlock *PredMBB = BlockOrders[I]; 1975 const ValueIDNum &PredLiveOut = 1976 OutLocs[PredMBB->getNumber()][Idx.asU64()]; 1977 1978 // Incoming values agree, continue trying to eliminate this PHI. 1979 if (FirstVal == PredLiveOut) 1980 continue; 1981 1982 // We can also accept a PHI value that feeds back into itself. 1983 if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) 1984 continue; 1985 1986 // Live-out of a predecessor disagrees with the first predecessor. 1987 Disagree = true; 1988 } 1989 1990 // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. 1991 if (!Disagree) { 1992 InLocs[Idx.asU64()] = FirstVal; 1993 Changed |= true; 1994 } 1995 } 1996 1997 // TODO: Reimplement NumInserted and NumRemoved. 1998 return Changed; 1999 } 2000 2001 void InstrRefBasedLDV::findStackIndexInterference( 2002 SmallVectorImpl<unsigned> &Slots) { 2003 // We could spend a bit of time finding the exact, minimal, set of stack 2004 // indexes that interfere with each other, much like reg units. Or, we can 2005 // rely on the fact that: 2006 // * The smallest / lowest index will interfere with everything at zero 2007 // offset, which will be the largest set of registers, 2008 // * Most indexes with non-zero offset will end up being interference units 2009 // anyway. 2010 // So just pick those out and return them. 2011 2012 // We can rely on a single-byte stack index existing already, because we 2013 // initialize them in MLocTracker. 2014 auto It = MTracker->StackSlotIdxes.find({8, 0}); 2015 assert(It != MTracker->StackSlotIdxes.end()); 2016 Slots.push_back(It->second); 2017 2018 // Find anything that has a non-zero offset and add that too. 2019 for (auto &Pair : MTracker->StackSlotIdxes) { 2020 // Is offset zero? If so, ignore. 2021 if (!Pair.first.second) 2022 continue; 2023 Slots.push_back(Pair.second); 2024 } 2025 } 2026 2027 void InstrRefBasedLDV::placeMLocPHIs( 2028 MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2029 FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2030 SmallVector<unsigned, 4> StackUnits; 2031 findStackIndexInterference(StackUnits); 2032 2033 // To avoid repeatedly running the PHI placement algorithm, leverage the 2034 // fact that a def of register MUST also def its register units. Find the 2035 // units for registers, place PHIs for them, and then replicate them for 2036 // aliasing registers. Some inputs that are never def'd (DBG_PHIs of 2037 // arguments) don't lead to register units being tracked, just place PHIs for 2038 // those registers directly. Stack slots have their own form of "unit", 2039 // store them to one side. 2040 SmallSet<Register, 32> RegUnitsToPHIUp; 2041 SmallSet<LocIdx, 32> NormalLocsToPHI; 2042 SmallSet<SpillLocationNo, 32> StackSlots; 2043 for (auto Location : MTracker->locations()) { 2044 LocIdx L = Location.Idx; 2045 if (MTracker->isSpill(L)) { 2046 StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); 2047 continue; 2048 } 2049 2050 Register R = MTracker->LocIdxToLocID[L]; 2051 SmallSet<Register, 8> FoundRegUnits; 2052 bool AnyIllegal = false; 2053 for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { 2054 for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ 2055 if (!MTracker->isRegisterTracked(*URoot)) { 2056 // Not all roots were loaded into the tracking map: this register 2057 // isn't actually def'd anywhere, we only read from it. Generate PHIs 2058 // for this reg, but don't iterate units. 2059 AnyIllegal = true; 2060 } else { 2061 FoundRegUnits.insert(*URoot); 2062 } 2063 } 2064 } 2065 2066 if (AnyIllegal) { 2067 NormalLocsToPHI.insert(L); 2068 continue; 2069 } 2070 2071 RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); 2072 } 2073 2074 // Lambda to fetch PHIs for a given location, and write into the PHIBlocks 2075 // collection. 2076 SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2077 auto CollectPHIsForLoc = [&](LocIdx L) { 2078 // Collect the set of defs. 2079 SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2080 for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 2081 MachineBasicBlock *MBB = OrderToBB[I]; 2082 const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; 2083 if (TransferFunc.find(L) != TransferFunc.end()) 2084 DefBlocks.insert(MBB); 2085 } 2086 2087 // The entry block defs the location too: it's the live-in / argument value. 2088 // Only insert if there are other defs though; everything is trivially live 2089 // through otherwise. 2090 if (!DefBlocks.empty()) 2091 DefBlocks.insert(&*MF.begin()); 2092 2093 // Ask the SSA construction algorithm where we should put PHIs. Clear 2094 // anything that might have been hanging around from earlier. 2095 PHIBlocks.clear(); 2096 BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); 2097 }; 2098 2099 auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { 2100 for (const MachineBasicBlock *MBB : PHIBlocks) 2101 MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); 2102 }; 2103 2104 // For locations with no reg units, just place PHIs. 2105 for (LocIdx L : NormalLocsToPHI) { 2106 CollectPHIsForLoc(L); 2107 // Install those PHI values into the live-in value array. 2108 InstallPHIsAtLoc(L); 2109 } 2110 2111 // For stack slots, calculate PHIs for the equivalent of the units, then 2112 // install for each index. 2113 for (SpillLocationNo Slot : StackSlots) { 2114 for (unsigned Idx : StackUnits) { 2115 unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); 2116 LocIdx L = MTracker->getSpillMLoc(SpillID); 2117 CollectPHIsForLoc(L); 2118 InstallPHIsAtLoc(L); 2119 2120 // Find anything that aliases this stack index, install PHIs for it too. 2121 unsigned Size, Offset; 2122 std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; 2123 for (auto &Pair : MTracker->StackSlotIdxes) { 2124 unsigned ThisSize, ThisOffset; 2125 std::tie(ThisSize, ThisOffset) = Pair.first; 2126 if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) 2127 continue; 2128 2129 unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); 2130 LocIdx ThisL = MTracker->getSpillMLoc(ThisID); 2131 InstallPHIsAtLoc(ThisL); 2132 } 2133 } 2134 } 2135 2136 // For reg units, place PHIs, and then place them for any aliasing registers. 2137 for (Register R : RegUnitsToPHIUp) { 2138 LocIdx L = MTracker->lookupOrTrackRegister(R); 2139 CollectPHIsForLoc(L); 2140 2141 // Install those PHI values into the live-in value array. 2142 InstallPHIsAtLoc(L); 2143 2144 // Now find aliases and install PHIs for those. 2145 for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { 2146 // Super-registers that are "above" the largest register read/written by 2147 // the function will alias, but will not be tracked. 2148 if (!MTracker->isRegisterTracked(*RAI)) 2149 continue; 2150 2151 LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); 2152 InstallPHIsAtLoc(AliasLoc); 2153 } 2154 } 2155 } 2156 2157 void InstrRefBasedLDV::buildMLocValueMap( 2158 MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs, 2159 SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2160 std::priority_queue<unsigned int, std::vector<unsigned int>, 2161 std::greater<unsigned int>> 2162 Worklist, Pending; 2163 2164 // We track what is on the current and pending worklist to avoid inserting 2165 // the same thing twice. We could avoid this with a custom priority queue, 2166 // but this is probably not worth it. 2167 SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2168 2169 // Initialize worklist with every block to be visited. Also produce list of 2170 // all blocks. 2171 SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; 2172 for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2173 Worklist.push(I); 2174 OnWorklist.insert(OrderToBB[I]); 2175 AllBlocks.insert(OrderToBB[I]); 2176 } 2177 2178 // Initialize entry block to PHIs. These represent arguments. 2179 for (auto Location : MTracker->locations()) 2180 MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); 2181 2182 MTracker->reset(); 2183 2184 // Start by placing PHIs, using the usual SSA constructor algorithm. Consider 2185 // any machine-location that isn't live-through a block to be def'd in that 2186 // block. 2187 placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); 2188 2189 // Propagate values to eliminate redundant PHIs. At the same time, this 2190 // produces the table of Block x Location => Value for the entry to each 2191 // block. 2192 // The kind of PHIs we can eliminate are, for example, where one path in a 2193 // conditional spills and restores a register, and the register still has 2194 // the same value once control flow joins, unbeknowns to the PHI placement 2195 // code. Propagating values allows us to identify such un-necessary PHIs and 2196 // remove them. 2197 SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2198 while (!Worklist.empty() || !Pending.empty()) { 2199 // Vector for storing the evaluated block transfer function. 2200 SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2201 2202 while (!Worklist.empty()) { 2203 MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2204 CurBB = MBB->getNumber(); 2205 Worklist.pop(); 2206 2207 // Join the values in all predecessor blocks. 2208 bool InLocsChanged; 2209 InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2210 InLocsChanged |= Visited.insert(MBB).second; 2211 2212 // Don't examine transfer function if we've visited this loc at least 2213 // once, and inlocs haven't changed. 2214 if (!InLocsChanged) 2215 continue; 2216 2217 // Load the current set of live-ins into MLocTracker. 2218 MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2219 2220 // Each element of the transfer function can be a new def, or a read of 2221 // a live-in value. Evaluate each element, and store to "ToRemap". 2222 ToRemap.clear(); 2223 for (auto &P : MLocTransfer[CurBB]) { 2224 if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2225 // This is a movement of whatever was live in. Read it. 2226 ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); 2227 ToRemap.push_back(std::make_pair(P.first, NewID)); 2228 } else { 2229 // It's a def. Just set it. 2230 assert(P.second.getBlock() == CurBB); 2231 ToRemap.push_back(std::make_pair(P.first, P.second)); 2232 } 2233 } 2234 2235 // Commit the transfer function changes into mloc tracker, which 2236 // transforms the contents of the MLocTracker into the live-outs. 2237 for (auto &P : ToRemap) 2238 MTracker->setMLoc(P.first, P.second); 2239 2240 // Now copy out-locs from mloc tracker into out-loc vector, checking 2241 // whether changes have occurred. These changes can have come from both 2242 // the transfer function, and mlocJoin. 2243 bool OLChanged = false; 2244 for (auto Location : MTracker->locations()) { 2245 OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2246 MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2247 } 2248 2249 MTracker->reset(); 2250 2251 // No need to examine successors again if out-locs didn't change. 2252 if (!OLChanged) 2253 continue; 2254 2255 // All successors should be visited: put any back-edges on the pending 2256 // list for the next pass-through, and any other successors to be 2257 // visited this pass, if they're not going to be already. 2258 for (auto s : MBB->successors()) { 2259 // Does branching to this successor represent a back-edge? 2260 if (BBToOrder[s] > BBToOrder[MBB]) { 2261 // No: visit it during this dataflow iteration. 2262 if (OnWorklist.insert(s).second) 2263 Worklist.push(BBToOrder[s]); 2264 } else { 2265 // Yes: visit it on the next iteration. 2266 if (OnPending.insert(s).second) 2267 Pending.push(BBToOrder[s]); 2268 } 2269 } 2270 } 2271 2272 Worklist.swap(Pending); 2273 std::swap(OnPending, OnWorklist); 2274 OnPending.clear(); 2275 // At this point, pending must be empty, since it was just the empty 2276 // worklist 2277 assert(Pending.empty() && "Pending should be empty"); 2278 } 2279 2280 // Once all the live-ins don't change on mlocJoin(), we've eliminated all 2281 // redundant PHIs. 2282 } 2283 2284 void InstrRefBasedLDV::BlockPHIPlacement( 2285 const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2286 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 2287 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { 2288 // Apply IDF calculator to the designated set of location defs, storing 2289 // required PHIs into PHIBlocks. Uses the dominator tree stored in the 2290 // InstrRefBasedLDV object. 2291 IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase()); 2292 2293 IDF.setLiveInBlocks(AllBlocks); 2294 IDF.setDefiningBlocks(DefBlocks); 2295 IDF.calculate(PHIBlocks); 2296 } 2297 2298 Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( 2299 const MachineBasicBlock &MBB, const DebugVariable &Var, 2300 const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs, 2301 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { 2302 // Collect a set of locations from predecessor where its live-out value can 2303 // be found. 2304 SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2305 SmallVector<const DbgValueProperties *, 4> Properties; 2306 unsigned NumLocs = MTracker->getNumLocs(); 2307 2308 // No predecessors means no PHIs. 2309 if (BlockOrders.empty()) 2310 return None; 2311 2312 for (auto p : BlockOrders) { 2313 unsigned ThisBBNum = p->getNumber(); 2314 auto OutValIt = LiveOuts.find(p); 2315 if (OutValIt == LiveOuts.end()) 2316 // If we have a predecessor not in scope, we'll never find a PHI position. 2317 return None; 2318 const DbgValue &OutVal = *OutValIt->second; 2319 2320 if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2321 // Consts and no-values cannot have locations we can join on. 2322 return None; 2323 2324 Properties.push_back(&OutVal.Properties); 2325 2326 // Create new empty vector of locations. 2327 Locs.resize(Locs.size() + 1); 2328 2329 // If the live-in value is a def, find the locations where that value is 2330 // present. Do the same for VPHIs where we know the VPHI value. 2331 if (OutVal.Kind == DbgValue::Def || 2332 (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && 2333 OutVal.ID != ValueIDNum::EmptyValue)) { 2334 ValueIDNum ValToLookFor = OutVal.ID; 2335 // Search the live-outs of the predecessor for the specified value. 2336 for (unsigned int I = 0; I < NumLocs; ++I) { 2337 if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2338 Locs.back().push_back(LocIdx(I)); 2339 } 2340 } else { 2341 assert(OutVal.Kind == DbgValue::VPHI); 2342 // For VPHIs where we don't know the location, we definitely can't find 2343 // a join loc. 2344 if (OutVal.BlockNo != MBB.getNumber()) 2345 return None; 2346 2347 // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. 2348 // a value that's live-through the whole loop. (It has to be a backedge, 2349 // because a block can't dominate itself). We can accept as a PHI location 2350 // any location where the other predecessors agree, _and_ the machine 2351 // locations feed back into themselves. Therefore, add all self-looping 2352 // machine-value PHI locations. 2353 for (unsigned int I = 0; I < NumLocs; ++I) { 2354 ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); 2355 if (MOutLocs[ThisBBNum][I] == MPHI) 2356 Locs.back().push_back(LocIdx(I)); 2357 } 2358 } 2359 } 2360 2361 // We should have found locations for all predecessors, or returned. 2362 assert(Locs.size() == BlockOrders.size()); 2363 2364 // Check that all properties are the same. We can't pick a location if they're 2365 // not. 2366 const DbgValueProperties *Properties0 = Properties[0]; 2367 for (auto *Prop : Properties) 2368 if (*Prop != *Properties0) 2369 return None; 2370 2371 // Starting with the first set of locations, take the intersection with 2372 // subsequent sets. 2373 SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; 2374 for (unsigned int I = 1; I < Locs.size(); ++I) { 2375 auto &LocVec = Locs[I]; 2376 SmallVector<LocIdx, 4> NewCandidates; 2377 std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), 2378 LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); 2379 CandidateLocs = NewCandidates; 2380 } 2381 if (CandidateLocs.empty()) 2382 return None; 2383 2384 // We now have a set of LocIdxes that contain the right output value in 2385 // each of the predecessors. Pick the lowest; if there's a register loc, 2386 // that'll be it. 2387 LocIdx L = *CandidateLocs.begin(); 2388 2389 // Return a PHI-value-number for the found location. 2390 ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2391 return PHIVal; 2392 } 2393 2394 bool InstrRefBasedLDV::vlocJoin( 2395 MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 2396 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2397 DbgValue &LiveIn) { 2398 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2399 bool Changed = false; 2400 2401 // Order predecessors by RPOT order, for exploring them in that order. 2402 SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2403 2404 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2405 return BBToOrder[A] < BBToOrder[B]; 2406 }; 2407 2408 llvm::sort(BlockOrders, Cmp); 2409 2410 unsigned CurBlockRPONum = BBToOrder[&MBB]; 2411 2412 // Collect all the incoming DbgValues for this variable, from predecessor 2413 // live-out values. 2414 SmallVector<InValueT, 8> Values; 2415 bool Bail = false; 2416 int BackEdgesStart = 0; 2417 for (auto p : BlockOrders) { 2418 // If the predecessor isn't in scope / to be explored, we'll never be 2419 // able to join any locations. 2420 if (!BlocksToExplore.contains(p)) { 2421 Bail = true; 2422 break; 2423 } 2424 2425 // All Live-outs will have been initialized. 2426 DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; 2427 2428 // Keep track of where back-edges begin in the Values vector. Relies on 2429 // BlockOrders being sorted by RPO. 2430 unsigned ThisBBRPONum = BBToOrder[p]; 2431 if (ThisBBRPONum < CurBlockRPONum) 2432 ++BackEdgesStart; 2433 2434 Values.push_back(std::make_pair(p, &OutLoc)); 2435 } 2436 2437 // If there were no values, or one of the predecessors couldn't have a 2438 // value, then give up immediately. It's not safe to produce a live-in 2439 // value. Leave as whatever it was before. 2440 if (Bail || Values.size() == 0) 2441 return false; 2442 2443 // All (non-entry) blocks have at least one non-backedge predecessor. 2444 // Pick the variable value from the first of these, to compare against 2445 // all others. 2446 const DbgValue &FirstVal = *Values[0].second; 2447 2448 // If the old live-in value is not a PHI then either a) no PHI is needed 2449 // here, or b) we eliminated the PHI that was here. If so, we can just 2450 // propagate in the first parent's incoming value. 2451 if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { 2452 Changed = LiveIn != FirstVal; 2453 if (Changed) 2454 LiveIn = FirstVal; 2455 return Changed; 2456 } 2457 2458 // Scan for variable values that can never be resolved: if they have 2459 // different DIExpressions, different indirectness, or are mixed constants / 2460 // non-constants. 2461 for (auto &V : Values) { 2462 if (V.second->Properties != FirstVal.Properties) 2463 return false; 2464 if (V.second->Kind == DbgValue::NoVal) 2465 return false; 2466 if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 2467 return false; 2468 } 2469 2470 // Try to eliminate this PHI. Do the incoming values all agree? 2471 bool Disagree = false; 2472 for (auto &V : Values) { 2473 if (*V.second == FirstVal) 2474 continue; // No disagreement. 2475 2476 // Eliminate if a backedge feeds a VPHI back into itself. 2477 if (V.second->Kind == DbgValue::VPHI && 2478 V.second->BlockNo == MBB.getNumber() && 2479 // Is this a backedge? 2480 std::distance(Values.begin(), &V) >= BackEdgesStart) 2481 continue; 2482 2483 Disagree = true; 2484 } 2485 2486 // No disagreement -> live-through value. 2487 if (!Disagree) { 2488 Changed = LiveIn != FirstVal; 2489 if (Changed) 2490 LiveIn = FirstVal; 2491 return Changed; 2492 } else { 2493 // Otherwise use a VPHI. 2494 DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); 2495 Changed = LiveIn != VPHI; 2496 if (Changed) 2497 LiveIn = VPHI; 2498 return Changed; 2499 } 2500 } 2501 2502 void InstrRefBasedLDV::getBlocksForScope( 2503 const DILocation *DILoc, 2504 SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore, 2505 const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) { 2506 // Get the set of "normal" in-lexical-scope blocks. 2507 LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 2508 2509 // VarLoc LiveDebugValues tracks variable locations that are defined in 2510 // blocks not in scope. This is something we could legitimately ignore, but 2511 // lets allow it for now for the sake of coverage. 2512 BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 2513 2514 // Storage for artificial blocks we intend to add to BlocksToExplore. 2515 DenseSet<const MachineBasicBlock *> ToAdd; 2516 2517 // To avoid needlessly dropping large volumes of variable locations, propagate 2518 // variables through aritifical blocks, i.e. those that don't have any 2519 // instructions in scope at all. To accurately replicate VarLoc 2520 // LiveDebugValues, this means exploring all artificial successors too. 2521 // Perform a depth-first-search to enumerate those blocks. 2522 for (auto *MBB : BlocksToExplore) { 2523 // Depth-first-search state: each node is a block and which successor 2524 // we're currently exploring. 2525 SmallVector<std::pair<const MachineBasicBlock *, 2526 MachineBasicBlock::const_succ_iterator>, 2527 8> 2528 DFS; 2529 2530 // Find any artificial successors not already tracked. 2531 for (auto *succ : MBB->successors()) { 2532 if (BlocksToExplore.count(succ)) 2533 continue; 2534 if (!ArtificialBlocks.count(succ)) 2535 continue; 2536 ToAdd.insert(succ); 2537 DFS.push_back({succ, succ->succ_begin()}); 2538 } 2539 2540 // Search all those blocks, depth first. 2541 while (!DFS.empty()) { 2542 const MachineBasicBlock *CurBB = DFS.back().first; 2543 MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 2544 // Walk back if we've explored this blocks successors to the end. 2545 if (CurSucc == CurBB->succ_end()) { 2546 DFS.pop_back(); 2547 continue; 2548 } 2549 2550 // If the current successor is artificial and unexplored, descend into 2551 // it. 2552 if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 2553 ToAdd.insert(*CurSucc); 2554 DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()}); 2555 continue; 2556 } 2557 2558 ++CurSucc; 2559 } 2560 }; 2561 2562 BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 2563 } 2564 2565 void InstrRefBasedLDV::buildVLocValueMap( 2566 const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 2567 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 2568 FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2569 SmallVectorImpl<VLocTracker> &AllTheVLocs) { 2570 // This method is much like buildMLocValueMap: but focuses on a single 2571 // LexicalScope at a time. Pick out a set of blocks and variables that are 2572 // to have their value assignments solved, then run our dataflow algorithm 2573 // until a fixedpoint is reached. 2574 std::priority_queue<unsigned int, std::vector<unsigned int>, 2575 std::greater<unsigned int>> 2576 Worklist, Pending; 2577 SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 2578 2579 // The set of blocks we'll be examining. 2580 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2581 2582 // The order in which to examine them (RPO). 2583 SmallVector<MachineBasicBlock *, 8> BlockOrders; 2584 2585 // RPO ordering function. 2586 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2587 return BBToOrder[A] < BBToOrder[B]; 2588 }; 2589 2590 getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks); 2591 2592 // Single block scope: not interesting! No propagation at all. Note that 2593 // this could probably go above ArtificialBlocks without damage, but 2594 // that then produces output differences from original-live-debug-values, 2595 // which propagates from a single block into many artificial ones. 2596 if (BlocksToExplore.size() == 1) 2597 return; 2598 2599 // Convert a const set to a non-const set. LexicalScopes 2600 // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. 2601 // (Neither of them mutate anything). 2602 SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; 2603 for (const auto *MBB : BlocksToExplore) 2604 MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); 2605 2606 // Picks out relevants blocks RPO order and sort them. 2607 for (auto *MBB : BlocksToExplore) 2608 BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 2609 2610 llvm::sort(BlockOrders, Cmp); 2611 unsigned NumBlocks = BlockOrders.size(); 2612 2613 // Allocate some vectors for storing the live ins and live outs. Large. 2614 SmallVector<DbgValue, 32> LiveIns, LiveOuts; 2615 LiveIns.reserve(NumBlocks); 2616 LiveOuts.reserve(NumBlocks); 2617 2618 // Initialize all values to start as NoVals. This signifies "it's live 2619 // through, but we don't know what it is". 2620 DbgValueProperties EmptyProperties(EmptyExpr, false); 2621 for (unsigned int I = 0; I < NumBlocks; ++I) { 2622 DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2623 LiveIns.push_back(EmptyDbgValue); 2624 LiveOuts.push_back(EmptyDbgValue); 2625 } 2626 2627 // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 2628 // vlocJoin. 2629 LiveIdxT LiveOutIdx, LiveInIdx; 2630 LiveOutIdx.reserve(NumBlocks); 2631 LiveInIdx.reserve(NumBlocks); 2632 for (unsigned I = 0; I < NumBlocks; ++I) { 2633 LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 2634 LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 2635 } 2636 2637 // Loop over each variable and place PHIs for it, then propagate values 2638 // between blocks. This keeps the locality of working on one lexical scope at 2639 // at time, but avoids re-processing variable values because some other 2640 // variable has been assigned. 2641 for (auto &Var : VarsWeCareAbout) { 2642 // Re-initialize live-ins and live-outs, to clear the remains of previous 2643 // variables live-ins / live-outs. 2644 for (unsigned int I = 0; I < NumBlocks; ++I) { 2645 DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2646 LiveIns[I] = EmptyDbgValue; 2647 LiveOuts[I] = EmptyDbgValue; 2648 } 2649 2650 // Place PHIs for variable values, using the LLVM IDF calculator. 2651 // Collect the set of blocks where variables are def'd. 2652 SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2653 for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { 2654 auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; 2655 if (TransferFunc.find(Var) != TransferFunc.end()) 2656 DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); 2657 } 2658 2659 SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2660 2661 // Request the set of PHIs we should insert for this variable. If there's 2662 // only one value definition, things are very simple. 2663 if (DefBlocks.size() == 1) { 2664 placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(), 2665 AllTheVLocs, Var, Output); 2666 continue; 2667 } 2668 2669 // Otherwise: we need to place PHIs through SSA and propagate values. 2670 BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); 2671 2672 // Insert PHIs into the per-block live-in tables for this variable. 2673 for (MachineBasicBlock *PHIMBB : PHIBlocks) { 2674 unsigned BlockNo = PHIMBB->getNumber(); 2675 DbgValue *LiveIn = LiveInIdx[PHIMBB]; 2676 *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); 2677 } 2678 2679 for (auto *MBB : BlockOrders) { 2680 Worklist.push(BBToOrder[MBB]); 2681 OnWorklist.insert(MBB); 2682 } 2683 2684 // Iterate over all the blocks we selected, propagating the variables value. 2685 // This loop does two things: 2686 // * Eliminates un-necessary VPHIs in vlocJoin, 2687 // * Evaluates the blocks transfer function (i.e. variable assignments) and 2688 // stores the result to the blocks live-outs. 2689 // Always evaluate the transfer function on the first iteration, and when 2690 // the live-ins change thereafter. 2691 bool FirstTrip = true; 2692 while (!Worklist.empty() || !Pending.empty()) { 2693 while (!Worklist.empty()) { 2694 auto *MBB = OrderToBB[Worklist.top()]; 2695 CurBB = MBB->getNumber(); 2696 Worklist.pop(); 2697 2698 auto LiveInsIt = LiveInIdx.find(MBB); 2699 assert(LiveInsIt != LiveInIdx.end()); 2700 DbgValue *LiveIn = LiveInsIt->second; 2701 2702 // Join values from predecessors. Updates LiveInIdx, and writes output 2703 // into JoinedInLocs. 2704 bool InLocsChanged = 2705 vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); 2706 2707 SmallVector<const MachineBasicBlock *, 8> Preds; 2708 for (const auto *Pred : MBB->predecessors()) 2709 Preds.push_back(Pred); 2710 2711 // If this block's live-in value is a VPHI, try to pick a machine-value 2712 // for it. This makes the machine-value available and propagated 2713 // through all blocks by the time value propagation finishes. We can't 2714 // do this any earlier as it needs to read the block live-outs. 2715 if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { 2716 // There's a small possibility that on a preceeding path, a VPHI is 2717 // eliminated and transitions from VPHI-with-location to 2718 // live-through-value. As a result, the selected location of any VPHI 2719 // might change, so we need to re-compute it on each iteration. 2720 Optional<ValueIDNum> ValueNum = 2721 pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); 2722 2723 if (ValueNum) { 2724 InLocsChanged |= LiveIn->ID != *ValueNum; 2725 LiveIn->ID = *ValueNum; 2726 } 2727 } 2728 2729 if (!InLocsChanged && !FirstTrip) 2730 continue; 2731 2732 DbgValue *LiveOut = LiveOutIdx[MBB]; 2733 bool OLChanged = false; 2734 2735 // Do transfer function. 2736 auto &VTracker = AllTheVLocs[MBB->getNumber()]; 2737 auto TransferIt = VTracker.Vars.find(Var); 2738 if (TransferIt != VTracker.Vars.end()) { 2739 // Erase on empty transfer (DBG_VALUE $noreg). 2740 if (TransferIt->second.Kind == DbgValue::Undef) { 2741 DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); 2742 if (*LiveOut != NewVal) { 2743 *LiveOut = NewVal; 2744 OLChanged = true; 2745 } 2746 } else { 2747 // Insert new variable value; or overwrite. 2748 if (*LiveOut != TransferIt->second) { 2749 *LiveOut = TransferIt->second; 2750 OLChanged = true; 2751 } 2752 } 2753 } else { 2754 // Just copy live-ins to live-outs, for anything not transferred. 2755 if (*LiveOut != *LiveIn) { 2756 *LiveOut = *LiveIn; 2757 OLChanged = true; 2758 } 2759 } 2760 2761 // If no live-out value changed, there's no need to explore further. 2762 if (!OLChanged) 2763 continue; 2764 2765 // We should visit all successors. Ensure we'll visit any non-backedge 2766 // successors during this dataflow iteration; book backedge successors 2767 // to be visited next time around. 2768 for (auto s : MBB->successors()) { 2769 // Ignore out of scope / not-to-be-explored successors. 2770 if (LiveInIdx.find(s) == LiveInIdx.end()) 2771 continue; 2772 2773 if (BBToOrder[s] > BBToOrder[MBB]) { 2774 if (OnWorklist.insert(s).second) 2775 Worklist.push(BBToOrder[s]); 2776 } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 2777 Pending.push(BBToOrder[s]); 2778 } 2779 } 2780 } 2781 Worklist.swap(Pending); 2782 std::swap(OnWorklist, OnPending); 2783 OnPending.clear(); 2784 assert(Pending.empty()); 2785 FirstTrip = false; 2786 } 2787 2788 // Save live-ins to output vector. Ignore any that are still marked as being 2789 // VPHIs with no location -- those are variables that we know the value of, 2790 // but are not actually available in the register file. 2791 for (auto *MBB : BlockOrders) { 2792 DbgValue *BlockLiveIn = LiveInIdx[MBB]; 2793 if (BlockLiveIn->Kind == DbgValue::NoVal) 2794 continue; 2795 if (BlockLiveIn->Kind == DbgValue::VPHI && 2796 BlockLiveIn->ID == ValueIDNum::EmptyValue) 2797 continue; 2798 if (BlockLiveIn->Kind == DbgValue::VPHI) 2799 BlockLiveIn->Kind = DbgValue::Def; 2800 assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == 2801 Var.getFragment() && "Fragment info missing during value prop"); 2802 Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); 2803 } 2804 } // Per-variable loop. 2805 2806 BlockOrders.clear(); 2807 BlocksToExplore.clear(); 2808 } 2809 2810 void InstrRefBasedLDV::placePHIsForSingleVarDefinition( 2811 const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks, 2812 MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs, 2813 const DebugVariable &Var, LiveInsT &Output) { 2814 // If there is a single definition of the variable, then working out it's 2815 // value everywhere is very simple: it's every block dominated by the 2816 // definition. At the dominance frontier, the usual algorithm would: 2817 // * Place PHIs, 2818 // * Propagate values into them, 2819 // * Find there's no incoming variable value from the other incoming branches 2820 // of the dominance frontier, 2821 // * Specify there's no variable value in blocks past the frontier. 2822 // This is a common case, hence it's worth special-casing it. 2823 2824 // Pick out the variables value from the block transfer function. 2825 VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()]; 2826 auto ValueIt = VLocs.Vars.find(Var); 2827 const DbgValue &Value = ValueIt->second; 2828 2829 // If it's an explicit assignment of "undef", that means there is no location 2830 // anyway, anywhere. 2831 if (Value.Kind == DbgValue::Undef) 2832 return; 2833 2834 // Assign the variable value to entry to each dominated block that's in scope. 2835 // Skip the definition block -- it's assigned the variable value in the middle 2836 // of the block somewhere. 2837 for (auto *ScopeBlock : InScopeBlocks) { 2838 if (!DomTree->properlyDominates(AssignMBB, ScopeBlock)) 2839 continue; 2840 2841 Output[ScopeBlock->getNumber()].push_back({Var, Value}); 2842 } 2843 2844 // All blocks that aren't dominated have no live-in value, thus no variable 2845 // value will be given to them. 2846 } 2847 2848 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2849 void InstrRefBasedLDV::dump_mloc_transfer( 2850 const MLocTransferMap &mloc_transfer) const { 2851 for (auto &P : mloc_transfer) { 2852 std::string foo = MTracker->LocIdxToName(P.first); 2853 std::string bar = MTracker->IDAsString(P.second); 2854 dbgs() << "Loc " << foo << " --> " << bar << "\n"; 2855 } 2856 } 2857 #endif 2858 2859 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 2860 // Build some useful data structures. 2861 2862 LLVMContext &Context = MF.getFunction().getContext(); 2863 EmptyExpr = DIExpression::get(Context, {}); 2864 2865 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 2866 if (const DebugLoc &DL = MI.getDebugLoc()) 2867 return DL.getLine() != 0; 2868 return false; 2869 }; 2870 // Collect a set of all the artificial blocks. 2871 for (auto &MBB : MF) 2872 if (none_of(MBB.instrs(), hasNonArtificialLocation)) 2873 ArtificialBlocks.insert(&MBB); 2874 2875 // Compute mappings of block <=> RPO order. 2876 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 2877 unsigned int RPONumber = 0; 2878 for (MachineBasicBlock *MBB : RPOT) { 2879 OrderToBB[RPONumber] = MBB; 2880 BBToOrder[MBB] = RPONumber; 2881 BBNumToRPO[MBB->getNumber()] = RPONumber; 2882 ++RPONumber; 2883 } 2884 2885 // Order value substitutions by their "source" operand pair, for quick lookup. 2886 llvm::sort(MF.DebugValueSubstitutions); 2887 2888 #ifdef EXPENSIVE_CHECKS 2889 // As an expensive check, test whether there are any duplicate substitution 2890 // sources in the collection. 2891 if (MF.DebugValueSubstitutions.size() > 2) { 2892 for (auto It = MF.DebugValueSubstitutions.begin(); 2893 It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { 2894 assert(It->Src != std::next(It)->Src && "Duplicate variable location " 2895 "substitution seen"); 2896 } 2897 } 2898 #endif 2899 } 2900 2901 // Produce an "ejection map" for blocks, i.e., what's the highest-numbered 2902 // lexical scope it's used in. When exploring in DFS order and we pass that 2903 // scope, the block can be processed and any tracking information freed. 2904 void InstrRefBasedLDV::makeDepthFirstEjectionMap( 2905 SmallVectorImpl<unsigned> &EjectionMap, 2906 const ScopeToDILocT &ScopeToDILocation, 2907 ScopeToAssignBlocksT &ScopeToAssignBlocks) { 2908 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2909 SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2910 auto *TopScope = LS.getCurrentFunctionScope(); 2911 2912 // Unlike lexical scope explorers, we explore in reverse order, to find the 2913 // "last" lexical scope used for each block early. 2914 WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1}); 2915 2916 while (!WorkStack.empty()) { 2917 auto &ScopePosition = WorkStack.back(); 2918 LexicalScope *WS = ScopePosition.first; 2919 ssize_t ChildNum = ScopePosition.second--; 2920 2921 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 2922 if (ChildNum >= 0) { 2923 // If ChildNum is positive, there are remaining children to explore. 2924 // Push the child and its children-count onto the stack. 2925 auto &ChildScope = Children[ChildNum]; 2926 WorkStack.push_back( 2927 std::make_pair(ChildScope, ChildScope->getChildren().size() - 1)); 2928 } else { 2929 WorkStack.pop_back(); 2930 2931 // We've explored all children and any later blocks: examine all blocks 2932 // in our scope. If they haven't yet had an ejection number set, then 2933 // this scope will be the last to use that block. 2934 auto DILocationIt = ScopeToDILocation.find(WS); 2935 if (DILocationIt != ScopeToDILocation.end()) { 2936 getBlocksForScope(DILocationIt->second, BlocksToExplore, 2937 ScopeToAssignBlocks.find(WS)->second); 2938 for (auto *MBB : BlocksToExplore) { 2939 unsigned BBNum = MBB->getNumber(); 2940 if (EjectionMap[BBNum] == 0) 2941 EjectionMap[BBNum] = WS->getDFSOut(); 2942 } 2943 2944 BlocksToExplore.clear(); 2945 } 2946 } 2947 } 2948 } 2949 2950 bool InstrRefBasedLDV::depthFirstVLocAndEmit( 2951 unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation, 2952 const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks, 2953 LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2954 SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF, 2955 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 2956 const TargetPassConfig &TPC) { 2957 TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 2958 unsigned NumLocs = MTracker->getNumLocs(); 2959 VTracker = nullptr; 2960 2961 // No scopes? No variable locations. 2962 if (!LS.getCurrentFunctionScope()) 2963 return false; 2964 2965 // Build map from block number to the last scope that uses the block. 2966 SmallVector<unsigned, 16> EjectionMap; 2967 EjectionMap.resize(MaxNumBlocks, 0); 2968 makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation, 2969 ScopeToAssignBlocks); 2970 2971 // Helper lambda for ejecting a block -- if nothing is going to use the block, 2972 // we can translate the variable location information into DBG_VALUEs and then 2973 // free all of InstrRefBasedLDV's data structures. 2974 auto EjectBlock = [&](MachineBasicBlock &MBB) -> void { 2975 unsigned BBNum = MBB.getNumber(); 2976 AllTheVLocs[BBNum].clear(); 2977 2978 // Prime the transfer-tracker, and then step through all the block 2979 // instructions, installing transfers. 2980 MTracker->reset(); 2981 MTracker->loadFromArray(MInLocs[BBNum], BBNum); 2982 TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs); 2983 2984 CurBB = BBNum; 2985 CurInst = 1; 2986 for (auto &MI : MBB) { 2987 process(MI, MOutLocs.get(), MInLocs.get()); 2988 TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 2989 ++CurInst; 2990 } 2991 2992 // Free machine-location tables for this block. 2993 MInLocs[BBNum].reset(); 2994 MOutLocs[BBNum].reset(); 2995 // We don't need live-in variable values for this block either. 2996 Output[BBNum].clear(); 2997 AllTheVLocs[BBNum].clear(); 2998 }; 2999 3000 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 3001 SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 3002 WorkStack.push_back({LS.getCurrentFunctionScope(), 0}); 3003 unsigned HighestDFSIn = 0; 3004 3005 // Proceed to explore in depth first order. 3006 while (!WorkStack.empty()) { 3007 auto &ScopePosition = WorkStack.back(); 3008 LexicalScope *WS = ScopePosition.first; 3009 ssize_t ChildNum = ScopePosition.second++; 3010 3011 // We obesrve scopes with children twice here, once descending in, once 3012 // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure 3013 // we don't process a scope twice. Additionally, ignore scopes that don't 3014 // have a DILocation -- by proxy, this means we never tracked any variable 3015 // assignments in that scope. 3016 auto DILocIt = ScopeToDILocation.find(WS); 3017 if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) { 3018 const DILocation *DILoc = DILocIt->second; 3019 auto &VarsWeCareAbout = ScopeToVars.find(WS)->second; 3020 auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second; 3021 3022 buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs, 3023 MInLocs, AllTheVLocs); 3024 } 3025 3026 HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn()); 3027 3028 // Descend into any scope nests. 3029 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 3030 if (ChildNum < (ssize_t)Children.size()) { 3031 // There are children to explore -- push onto stack and continue. 3032 auto &ChildScope = Children[ChildNum]; 3033 WorkStack.push_back(std::make_pair(ChildScope, 0)); 3034 } else { 3035 WorkStack.pop_back(); 3036 3037 // We've explored a leaf, or have explored all the children of a scope. 3038 // Try to eject any blocks where this is the last scope it's relevant to. 3039 auto DILocationIt = ScopeToDILocation.find(WS); 3040 if (DILocationIt == ScopeToDILocation.end()) 3041 continue; 3042 3043 getBlocksForScope(DILocationIt->second, BlocksToExplore, 3044 ScopeToAssignBlocks.find(WS)->second); 3045 for (auto *MBB : BlocksToExplore) 3046 if (WS->getDFSOut() == EjectionMap[MBB->getNumber()]) 3047 EjectBlock(const_cast<MachineBasicBlock &>(*MBB)); 3048 3049 BlocksToExplore.clear(); 3050 } 3051 } 3052 3053 // Some artificial blocks may not have been ejected, meaning they're not 3054 // connected to an actual legitimate scope. This can technically happen 3055 // with things like the entry block. In theory, we shouldn't need to do 3056 // anything for such out-of-scope blocks, but for the sake of being similar 3057 // to VarLocBasedLDV, eject these too. 3058 for (auto *MBB : ArtificialBlocks) 3059 if (MOutLocs[MBB->getNumber()]) 3060 EjectBlock(*MBB); 3061 3062 return emitTransfers(AllVarsNumbering); 3063 } 3064 3065 bool InstrRefBasedLDV::emitTransfers( 3066 DenseMap<DebugVariable, unsigned> &AllVarsNumbering) { 3067 // Go through all the transfers recorded in the TransferTracker -- this is 3068 // both the live-ins to a block, and any movements of values that happen 3069 // in the middle. 3070 for (const auto &P : TTracker->Transfers) { 3071 // We have to insert DBG_VALUEs in a consistent order, otherwise they 3072 // appear in DWARF in different orders. Use the order that they appear 3073 // when walking through each block / each instruction, stored in 3074 // AllVarsNumbering. 3075 SmallVector<std::pair<unsigned, MachineInstr *>> Insts; 3076 for (MachineInstr *MI : P.Insts) { 3077 DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(), 3078 MI->getDebugLoc()->getInlinedAt()); 3079 Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI); 3080 } 3081 llvm::sort(Insts, 3082 [](const auto &A, const auto &B) { return A.first < B.first; }); 3083 3084 // Insert either before or after the designated point... 3085 if (P.MBB) { 3086 MachineBasicBlock &MBB = *P.MBB; 3087 for (const auto &Pair : Insts) 3088 MBB.insert(P.Pos, Pair.second); 3089 } else { 3090 // Terminators, like tail calls, can clobber things. Don't try and place 3091 // transfers after them. 3092 if (P.Pos->isTerminator()) 3093 continue; 3094 3095 MachineBasicBlock &MBB = *P.Pos->getParent(); 3096 for (const auto &Pair : Insts) 3097 MBB.insertAfterBundle(P.Pos, Pair.second); 3098 } 3099 } 3100 3101 return TTracker->Transfers.size() != 0; 3102 } 3103 3104 /// Calculate the liveness information for the given machine function and 3105 /// extend ranges across basic blocks. 3106 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 3107 MachineDominatorTree *DomTree, 3108 TargetPassConfig *TPC, 3109 unsigned InputBBLimit, 3110 unsigned InputDbgValLimit) { 3111 // No subprogram means this function contains no debuginfo. 3112 if (!MF.getFunction().getSubprogram()) 3113 return false; 3114 3115 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 3116 this->TPC = TPC; 3117 3118 this->DomTree = DomTree; 3119 TRI = MF.getSubtarget().getRegisterInfo(); 3120 MRI = &MF.getRegInfo(); 3121 TII = MF.getSubtarget().getInstrInfo(); 3122 TFI = MF.getSubtarget().getFrameLowering(); 3123 TFI->getCalleeSaves(MF, CalleeSavedRegs); 3124 MFI = &MF.getFrameInfo(); 3125 LS.initialize(MF); 3126 3127 const auto &STI = MF.getSubtarget(); 3128 AdjustsStackInCalls = MFI->adjustsStack() && 3129 STI.getFrameLowering()->stackProbeFunctionModifiesSP(); 3130 if (AdjustsStackInCalls) 3131 StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); 3132 3133 MTracker = 3134 new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 3135 VTracker = nullptr; 3136 TTracker = nullptr; 3137 3138 SmallVector<MLocTransferMap, 32> MLocTransfer; 3139 SmallVector<VLocTracker, 8> vlocs; 3140 LiveInsT SavedLiveIns; 3141 3142 int MaxNumBlocks = -1; 3143 for (auto &MBB : MF) 3144 MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 3145 assert(MaxNumBlocks >= 0); 3146 ++MaxNumBlocks; 3147 3148 MLocTransfer.resize(MaxNumBlocks); 3149 vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); 3150 SavedLiveIns.resize(MaxNumBlocks); 3151 3152 initialSetup(MF); 3153 3154 produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 3155 3156 // Allocate and initialize two array-of-arrays for the live-in and live-out 3157 // machine values. The outer dimension is the block number; while the inner 3158 // dimension is a LocIdx from MLocTracker. 3159 FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3160 FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3161 unsigned NumLocs = MTracker->getNumLocs(); 3162 for (int i = 0; i < MaxNumBlocks; ++i) { 3163 // These all auto-initialize to ValueIDNum::EmptyValue 3164 MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3165 MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3166 } 3167 3168 // Solve the machine value dataflow problem using the MLocTransfer function, 3169 // storing the computed live-ins / live-outs into the array-of-arrays. We use 3170 // both live-ins and live-outs for decision making in the variable value 3171 // dataflow problem. 3172 buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); 3173 3174 // Patch up debug phi numbers, turning unknown block-live-in values into 3175 // either live-through machine values, or PHIs. 3176 for (auto &DBG_PHI : DebugPHINumToValue) { 3177 // Identify unresolved block-live-ins. 3178 if (!DBG_PHI.ValueRead) 3179 continue; 3180 3181 ValueIDNum &Num = *DBG_PHI.ValueRead; 3182 if (!Num.isPHI()) 3183 continue; 3184 3185 unsigned BlockNo = Num.getBlock(); 3186 LocIdx LocNo = Num.getLoc(); 3187 Num = MInLocs[BlockNo][LocNo.asU64()]; 3188 } 3189 // Later, we'll be looking up ranges of instruction numbers. 3190 llvm::sort(DebugPHINumToValue); 3191 3192 // Walk back through each block / instruction, collecting DBG_VALUE 3193 // instructions and recording what machine value their operands refer to. 3194 for (auto &OrderPair : OrderToBB) { 3195 MachineBasicBlock &MBB = *OrderPair.second; 3196 CurBB = MBB.getNumber(); 3197 VTracker = &vlocs[CurBB]; 3198 VTracker->MBB = &MBB; 3199 MTracker->loadFromArray(MInLocs[CurBB], CurBB); 3200 CurInst = 1; 3201 for (auto &MI : MBB) { 3202 process(MI, MOutLocs.get(), MInLocs.get()); 3203 ++CurInst; 3204 } 3205 MTracker->reset(); 3206 } 3207 3208 // Number all variables in the order that they appear, to be used as a stable 3209 // insertion order later. 3210 DenseMap<DebugVariable, unsigned> AllVarsNumbering; 3211 3212 // Map from one LexicalScope to all the variables in that scope. 3213 ScopeToVarsT ScopeToVars; 3214 3215 // Map from One lexical scope to all blocks where assignments happen for 3216 // that scope. 3217 ScopeToAssignBlocksT ScopeToAssignBlocks; 3218 3219 // Store map of DILocations that describes scopes. 3220 ScopeToDILocT ScopeToDILocation; 3221 3222 // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3223 // the order is unimportant, it just has to be stable. 3224 unsigned VarAssignCount = 0; 3225 for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3226 auto *MBB = OrderToBB[I]; 3227 auto *VTracker = &vlocs[MBB->getNumber()]; 3228 // Collect each variable with a DBG_VALUE in this block. 3229 for (auto &idx : VTracker->Vars) { 3230 const auto &Var = idx.first; 3231 const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3232 assert(ScopeLoc != nullptr); 3233 auto *Scope = LS.findLexicalScope(ScopeLoc); 3234 3235 // No insts in scope -> shouldn't have been recorded. 3236 assert(Scope != nullptr); 3237 3238 AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3239 ScopeToVars[Scope].insert(Var); 3240 ScopeToAssignBlocks[Scope].insert(VTracker->MBB); 3241 ScopeToDILocation[Scope] = ScopeLoc; 3242 ++VarAssignCount; 3243 } 3244 } 3245 3246 bool Changed = false; 3247 3248 // If we have an extremely large number of variable assignments and blocks, 3249 // bail out at this point. We've burnt some time doing analysis already, 3250 // however we should cut our losses. 3251 if ((unsigned)MaxNumBlocks > InputBBLimit && 3252 VarAssignCount > InputDbgValLimit) { 3253 LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() 3254 << " has " << MaxNumBlocks << " basic blocks and " 3255 << VarAssignCount 3256 << " variable assignments, exceeding limits.\n"); 3257 } else { 3258 // Optionally, solve the variable value problem and emit to blocks by using 3259 // a lexical-scope-depth search. It should be functionally identical to 3260 // the "else" block of this condition. 3261 Changed = depthFirstVLocAndEmit( 3262 MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks, 3263 SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC); 3264 } 3265 3266 delete MTracker; 3267 delete TTracker; 3268 MTracker = nullptr; 3269 VTracker = nullptr; 3270 TTracker = nullptr; 3271 3272 ArtificialBlocks.clear(); 3273 OrderToBB.clear(); 3274 BBToOrder.clear(); 3275 BBNumToRPO.clear(); 3276 DebugInstrNumToInstr.clear(); 3277 DebugPHINumToValue.clear(); 3278 OverlapFragments.clear(); 3279 SeenFragments.clear(); 3280 SeenDbgPHIs.clear(); 3281 3282 return Changed; 3283 } 3284 3285 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3286 return new InstrRefBasedLDV(); 3287 } 3288 3289 namespace { 3290 class LDVSSABlock; 3291 class LDVSSAUpdater; 3292 3293 // Pick a type to identify incoming block values as we construct SSA. We 3294 // can't use anything more robust than an integer unfortunately, as SSAUpdater 3295 // expects to zero-initialize the type. 3296 typedef uint64_t BlockValueNum; 3297 3298 /// Represents an SSA PHI node for the SSA updater class. Contains the block 3299 /// this PHI is in, the value number it would have, and the expected incoming 3300 /// values from parent blocks. 3301 class LDVSSAPhi { 3302 public: 3303 SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3304 LDVSSABlock *ParentBlock; 3305 BlockValueNum PHIValNum; 3306 LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3307 : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3308 3309 LDVSSABlock *getParent() { return ParentBlock; } 3310 }; 3311 3312 /// Thin wrapper around a block predecessor iterator. Only difference from a 3313 /// normal block iterator is that it dereferences to an LDVSSABlock. 3314 class LDVSSABlockIterator { 3315 public: 3316 MachineBasicBlock::pred_iterator PredIt; 3317 LDVSSAUpdater &Updater; 3318 3319 LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3320 LDVSSAUpdater &Updater) 3321 : PredIt(PredIt), Updater(Updater) {} 3322 3323 bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3324 return OtherIt.PredIt != PredIt; 3325 } 3326 3327 LDVSSABlockIterator &operator++() { 3328 ++PredIt; 3329 return *this; 3330 } 3331 3332 LDVSSABlock *operator*(); 3333 }; 3334 3335 /// Thin wrapper around a block for SSA Updater interface. Necessary because 3336 /// we need to track the PHI value(s) that we may have observed as necessary 3337 /// in this block. 3338 class LDVSSABlock { 3339 public: 3340 MachineBasicBlock &BB; 3341 LDVSSAUpdater &Updater; 3342 using PHIListT = SmallVector<LDVSSAPhi, 1>; 3343 /// List of PHIs in this block. There should only ever be one. 3344 PHIListT PHIList; 3345 3346 LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3347 : BB(BB), Updater(Updater) {} 3348 3349 LDVSSABlockIterator succ_begin() { 3350 return LDVSSABlockIterator(BB.succ_begin(), Updater); 3351 } 3352 3353 LDVSSABlockIterator succ_end() { 3354 return LDVSSABlockIterator(BB.succ_end(), Updater); 3355 } 3356 3357 /// SSAUpdater has requested a PHI: create that within this block record. 3358 LDVSSAPhi *newPHI(BlockValueNum Value) { 3359 PHIList.emplace_back(Value, this); 3360 return &PHIList.back(); 3361 } 3362 3363 /// SSAUpdater wishes to know what PHIs already exist in this block. 3364 PHIListT &phis() { return PHIList; } 3365 }; 3366 3367 /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3368 /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3369 // SSAUpdaterTraits<LDVSSAUpdater>. 3370 class LDVSSAUpdater { 3371 public: 3372 /// Map of value numbers to PHI records. 3373 DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3374 /// Map of which blocks generate Undef values -- blocks that are not 3375 /// dominated by any Def. 3376 DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3377 /// Map of machine blocks to our own records of them. 3378 DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3379 /// Machine location where any PHI must occur. 3380 LocIdx Loc; 3381 /// Table of live-in machine value numbers for blocks / locations. 3382 const ValueTable *MLiveIns; 3383 3384 LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns) 3385 : Loc(L), MLiveIns(MLiveIns) {} 3386 3387 void reset() { 3388 for (auto &Block : BlockMap) 3389 delete Block.second; 3390 3391 PHIs.clear(); 3392 UndefMap.clear(); 3393 BlockMap.clear(); 3394 } 3395 3396 ~LDVSSAUpdater() { reset(); } 3397 3398 /// For a given MBB, create a wrapper block for it. Stores it in the 3399 /// LDVSSAUpdater block map. 3400 LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3401 auto it = BlockMap.find(BB); 3402 if (it == BlockMap.end()) { 3403 BlockMap[BB] = new LDVSSABlock(*BB, *this); 3404 it = BlockMap.find(BB); 3405 } 3406 return it->second; 3407 } 3408 3409 /// Find the live-in value number for the given block. Looks up the value at 3410 /// the PHI location on entry. 3411 BlockValueNum getValue(LDVSSABlock *LDVBB) { 3412 return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3413 } 3414 }; 3415 3416 LDVSSABlock *LDVSSABlockIterator::operator*() { 3417 return Updater.getSSALDVBlock(*PredIt); 3418 } 3419 3420 #ifndef NDEBUG 3421 3422 raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3423 out << "SSALDVPHI " << PHI.PHIValNum; 3424 return out; 3425 } 3426 3427 #endif 3428 3429 } // namespace 3430 3431 namespace llvm { 3432 3433 /// Template specialization to give SSAUpdater access to CFG and value 3434 /// information. SSAUpdater calls methods in these traits, passing in the 3435 /// LDVSSAUpdater object, to learn about blocks and the values they define. 3436 /// It also provides methods to create PHI nodes and track them. 3437 template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3438 public: 3439 using BlkT = LDVSSABlock; 3440 using ValT = BlockValueNum; 3441 using PhiT = LDVSSAPhi; 3442 using BlkSucc_iterator = LDVSSABlockIterator; 3443 3444 // Methods to access block successors -- dereferencing to our wrapper class. 3445 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3446 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3447 3448 /// Iterator for PHI operands. 3449 class PHI_iterator { 3450 private: 3451 LDVSSAPhi *PHI; 3452 unsigned Idx; 3453 3454 public: 3455 explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3456 : PHI(P), Idx(0) {} 3457 PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3458 : PHI(P), Idx(PHI->IncomingValues.size()) {} 3459 3460 PHI_iterator &operator++() { 3461 Idx++; 3462 return *this; 3463 } 3464 bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3465 bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3466 3467 BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3468 3469 LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3470 }; 3471 3472 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3473 3474 static inline PHI_iterator PHI_end(PhiT *PHI) { 3475 return PHI_iterator(PHI, true); 3476 } 3477 3478 /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3479 /// vector. 3480 static void FindPredecessorBlocks(LDVSSABlock *BB, 3481 SmallVectorImpl<LDVSSABlock *> *Preds) { 3482 for (MachineBasicBlock *Pred : BB->BB.predecessors()) 3483 Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); 3484 } 3485 3486 /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3487 /// register. For LiveDebugValues, represents a block identified as not having 3488 /// any DBG_PHI predecessors. 3489 static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3490 // Create a value number for this block -- it needs to be unique and in the 3491 // "undef" collection, so that we know it's not real. Use a number 3492 // representing a PHI into this block. 3493 BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3494 Updater->UndefMap[&BB->BB] = Num; 3495 return Num; 3496 } 3497 3498 /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3499 /// SSAUpdater will populate it with information about incoming values. The 3500 /// value number of this PHI is whatever the machine value number problem 3501 /// solution determined it to be. This includes non-phi values if SSAUpdater 3502 /// tries to create a PHI where the incoming values are identical. 3503 static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3504 LDVSSAUpdater *Updater) { 3505 BlockValueNum PHIValNum = Updater->getValue(BB); 3506 LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3507 Updater->PHIs[PHIValNum] = PHI; 3508 return PHIValNum; 3509 } 3510 3511 /// AddPHIOperand - Add the specified value as an operand of the PHI for 3512 /// the specified predecessor block. 3513 static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3514 PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3515 } 3516 3517 /// ValueIsPHI - Check if the instruction that defines the specified value 3518 /// is a PHI instruction. 3519 static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3520 auto PHIIt = Updater->PHIs.find(Val); 3521 if (PHIIt == Updater->PHIs.end()) 3522 return nullptr; 3523 return PHIIt->second; 3524 } 3525 3526 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3527 /// operands, i.e., it was just added. 3528 static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3529 LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3530 if (PHI && PHI->IncomingValues.size() == 0) 3531 return PHI; 3532 return nullptr; 3533 } 3534 3535 /// GetPHIValue - For the specified PHI instruction, return the value 3536 /// that it defines. 3537 static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3538 }; 3539 3540 } // end namespace llvm 3541 3542 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs( 3543 MachineFunction &MF, const ValueTable *MLiveOuts, 3544 const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3545 assert(MLiveOuts && MLiveIns && 3546 "Tried to resolve DBG_PHI before location " 3547 "tables allocated?"); 3548 3549 // This function will be called twice per DBG_INSTR_REF, and might end up 3550 // computing lots of SSA information: memoize it. 3551 auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here); 3552 if (SeenDbgPHIIt != SeenDbgPHIs.end()) 3553 return SeenDbgPHIIt->second; 3554 3555 Optional<ValueIDNum> Result = 3556 resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum); 3557 SeenDbgPHIs.insert({&Here, Result}); 3558 return Result; 3559 } 3560 3561 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl( 3562 MachineFunction &MF, const ValueTable *MLiveOuts, 3563 const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3564 // Pick out records of DBG_PHI instructions that have been observed. If there 3565 // are none, then we cannot compute a value number. 3566 auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3567 DebugPHINumToValue.end(), InstrNum); 3568 auto LowerIt = RangePair.first; 3569 auto UpperIt = RangePair.second; 3570 3571 // No DBG_PHI means there can be no location. 3572 if (LowerIt == UpperIt) 3573 return None; 3574 3575 // If any DBG_PHIs referred to a location we didn't understand, don't try to 3576 // compute a value. There might be scenarios where we could recover a value 3577 // for some range of DBG_INSTR_REFs, but at this point we can have high 3578 // confidence that we've seen a bug. 3579 auto DBGPHIRange = make_range(LowerIt, UpperIt); 3580 for (const DebugPHIRecord &DBG_PHI : DBGPHIRange) 3581 if (!DBG_PHI.ValueRead) 3582 return None; 3583 3584 // If there's only one DBG_PHI, then that is our value number. 3585 if (std::distance(LowerIt, UpperIt) == 1) 3586 return *LowerIt->ValueRead; 3587 3588 // Pick out the location (physreg, slot) where any PHIs must occur. It's 3589 // technically possible for us to merge values in different registers in each 3590 // block, but highly unlikely that LLVM will generate such code after register 3591 // allocation. 3592 LocIdx Loc = *LowerIt->ReadLoc; 3593 3594 // We have several DBG_PHIs, and a use position (the Here inst). All each 3595 // DBG_PHI does is identify a value at a program position. We can treat each 3596 // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3597 // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3598 // determine which Def is used at the Use, and any PHIs that happen along 3599 // the way. 3600 // Adapted LLVM SSA Updater: 3601 LDVSSAUpdater Updater(Loc, MLiveIns); 3602 // Map of which Def or PHI is the current value in each block. 3603 DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3604 // Set of PHIs that we have created along the way. 3605 SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3606 3607 // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3608 // for the SSAUpdater. 3609 for (const auto &DBG_PHI : DBGPHIRange) { 3610 LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3611 const ValueIDNum &Num = *DBG_PHI.ValueRead; 3612 AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3613 } 3614 3615 LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3616 const auto &AvailIt = AvailableValues.find(HereBlock); 3617 if (AvailIt != AvailableValues.end()) { 3618 // Actually, we already know what the value is -- the Use is in the same 3619 // block as the Def. 3620 return ValueIDNum::fromU64(AvailIt->second); 3621 } 3622 3623 // Otherwise, we must use the SSA Updater. It will identify the value number 3624 // that we are to use, and the PHIs that must happen along the way. 3625 SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3626 BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3627 ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3628 3629 // We have the number for a PHI, or possibly live-through value, to be used 3630 // at this Use. There are a number of things we have to check about it though: 3631 // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3632 // Use was not completely dominated by DBG_PHIs and we should abort. 3633 // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3634 // we've left SSA form. Validate that the inputs to each PHI are the 3635 // expected values. 3636 // * Is a PHI we've created actually a merging of values, or are all the 3637 // predecessor values the same, leading to a non-PHI machine value number? 3638 // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3639 // the ValidatedValues collection below to sort this out. 3640 DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3641 3642 // Define all the input DBG_PHI values in ValidatedValues. 3643 for (const auto &DBG_PHI : DBGPHIRange) { 3644 LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3645 const ValueIDNum &Num = *DBG_PHI.ValueRead; 3646 ValidatedValues.insert(std::make_pair(Block, Num)); 3647 } 3648 3649 // Sort PHIs to validate into RPO-order. 3650 SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3651 for (auto &PHI : CreatedPHIs) 3652 SortedPHIs.push_back(PHI); 3653 3654 std::sort( 3655 SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3656 return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3657 }); 3658 3659 for (auto &PHI : SortedPHIs) { 3660 ValueIDNum ThisBlockValueNum = 3661 MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3662 3663 // Are all these things actually defined? 3664 for (auto &PHIIt : PHI->IncomingValues) { 3665 // Any undef input means DBG_PHIs didn't dominate the use point. 3666 if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3667 return None; 3668 3669 ValueIDNum ValueToCheck; 3670 const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 3671 3672 auto VVal = ValidatedValues.find(PHIIt.first); 3673 if (VVal == ValidatedValues.end()) { 3674 // We cross a loop, and this is a backedge. LLVMs tail duplication 3675 // happens so late that DBG_PHI instructions should not be able to 3676 // migrate into loops -- meaning we can only be live-through this 3677 // loop. 3678 ValueToCheck = ThisBlockValueNum; 3679 } else { 3680 // Does the block have as a live-out, in the location we're examining, 3681 // the value that we expect? If not, it's been moved or clobbered. 3682 ValueToCheck = VVal->second; 3683 } 3684 3685 if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 3686 return None; 3687 } 3688 3689 // Record this value as validated. 3690 ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 3691 } 3692 3693 // All the PHIs are valid: we can return what the SSAUpdater said our value 3694 // number was. 3695 return Result; 3696 } 3697