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