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