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