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