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