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