1e8d8bef9SDimitry Andric //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric /// \file InstrRefBasedImpl.cpp 9e8d8bef9SDimitry Andric /// 10e8d8bef9SDimitry Andric /// This is a separate implementation of LiveDebugValues, see 11e8d8bef9SDimitry Andric /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information. 12e8d8bef9SDimitry Andric /// 13e8d8bef9SDimitry Andric /// This pass propagates variable locations between basic blocks, resolving 14349cc55cSDimitry Andric /// control flow conflicts between them. The problem is SSA construction, where 15349cc55cSDimitry Andric /// each debug instruction assigns the *value* that a variable has, and every 16349cc55cSDimitry Andric /// instruction where the variable is in scope uses that variable. The resulting 17349cc55cSDimitry Andric /// map of instruction-to-value is then translated into a register (or spill) 18349cc55cSDimitry Andric /// location for each variable over each instruction. 19e8d8bef9SDimitry Andric /// 20349cc55cSDimitry Andric /// The primary difference from normal SSA construction is that we cannot 21349cc55cSDimitry Andric /// _create_ PHI values that contain variable values. CodeGen has already 22349cc55cSDimitry Andric /// completed, and we can't alter it just to make debug-info complete. Thus: 23349cc55cSDimitry Andric /// we can identify function positions where we would like a PHI value for a 24349cc55cSDimitry Andric /// variable, but must search the MachineFunction to see whether such a PHI is 25349cc55cSDimitry Andric /// available. If no such PHI exists, the variable location must be dropped. 26e8d8bef9SDimitry Andric /// 27349cc55cSDimitry Andric /// To achieve this, we perform two kinds of analysis. First, we identify 28e8d8bef9SDimitry Andric /// every value defined by every instruction (ignoring those that only move 29349cc55cSDimitry Andric /// another value), then re-compute an SSA-form representation of the 30349cc55cSDimitry Andric /// MachineFunction, using value propagation to eliminate any un-necessary 31349cc55cSDimitry Andric /// PHI values. This gives us a map of every value computed in the function, 32349cc55cSDimitry Andric /// and its location within the register file / stack. 33e8d8bef9SDimitry Andric /// 34349cc55cSDimitry Andric /// Secondly, for each variable we perform the same analysis, where each debug 35349cc55cSDimitry Andric /// instruction is considered a def, and every instruction where the variable 36349cc55cSDimitry Andric /// is in lexical scope as a use. Value propagation is used again to eliminate 37349cc55cSDimitry Andric /// any un-necessary PHIs. This gives us a map of each variable to the value 38349cc55cSDimitry Andric /// it should have in a block. 39e8d8bef9SDimitry Andric /// 40349cc55cSDimitry Andric /// Once both are complete, we have two maps for each block: 41349cc55cSDimitry Andric /// * Variables to the values they should have, 42349cc55cSDimitry Andric /// * Values to the register / spill slot they are located in. 43349cc55cSDimitry Andric /// After which we can marry-up variable values with a location, and emit 44349cc55cSDimitry Andric /// DBG_VALUE instructions specifying those locations. Variable locations may 45349cc55cSDimitry Andric /// be dropped in this process due to the desired variable value not being 46349cc55cSDimitry Andric /// resident in any machine location, or because there is no PHI value in any 47349cc55cSDimitry Andric /// location that accurately represents the desired value. The building of 48349cc55cSDimitry Andric /// location lists for each block is left to DbgEntityHistoryCalculator. 49e8d8bef9SDimitry Andric /// 50349cc55cSDimitry Andric /// This pass is kept efficient because the size of the first SSA problem 51349cc55cSDimitry Andric /// is proportional to the working-set size of the function, which the compiler 52349cc55cSDimitry Andric /// tries to keep small. (It's also proportional to the number of blocks). 53349cc55cSDimitry Andric /// Additionally, we repeatedly perform the second SSA problem analysis with 54349cc55cSDimitry Andric /// only the variables and blocks in a single lexical scope, exploiting their 55349cc55cSDimitry Andric /// locality. 56e8d8bef9SDimitry Andric /// 57e8d8bef9SDimitry Andric /// ### Terminology 58e8d8bef9SDimitry Andric /// 59e8d8bef9SDimitry Andric /// A machine location is a register or spill slot, a value is something that's 60e8d8bef9SDimitry Andric /// defined by an instruction or PHI node, while a variable value is the value 61e8d8bef9SDimitry Andric /// assigned to a variable. A variable location is a machine location, that must 62e8d8bef9SDimitry Andric /// contain the appropriate variable value. A value that is a PHI node is 63e8d8bef9SDimitry Andric /// occasionally called an mphi. 64e8d8bef9SDimitry Andric /// 65349cc55cSDimitry Andric /// The first SSA problem is the "machine value location" problem, 66e8d8bef9SDimitry Andric /// because we're determining which machine locations contain which values. 67e8d8bef9SDimitry Andric /// The "locations" are constant: what's unknown is what value they contain. 68e8d8bef9SDimitry Andric /// 69349cc55cSDimitry Andric /// The second SSA problem (the one for variables) is the "variable value 70e8d8bef9SDimitry Andric /// problem", because it's determining what values a variable has, rather than 71349cc55cSDimitry Andric /// what location those values are placed in. 72e8d8bef9SDimitry Andric /// 73e8d8bef9SDimitry Andric /// TODO: 74e8d8bef9SDimitry Andric /// Overlapping fragments 75e8d8bef9SDimitry Andric /// Entry values 76e8d8bef9SDimitry Andric /// Add back DEBUG statements for debugging this 77e8d8bef9SDimitry Andric /// Collect statistics 78e8d8bef9SDimitry Andric /// 79e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 80e8d8bef9SDimitry Andric 81e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h" 82e8d8bef9SDimitry Andric #include "llvm/ADT/PostOrderIterator.h" 83fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h" 84e8d8bef9SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 85e8d8bef9SDimitry Andric #include "llvm/ADT/SmallSet.h" 86e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 87e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h" 88349cc55cSDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h" 89e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h" 90e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 91349cc55cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 92e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h" 93e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 94e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 95e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 96e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 97fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h" 98e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h" 99e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 100e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h" 101e8d8bef9SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h" 102e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h" 103e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 104e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h" 105e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 106e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 107e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 108e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 109e8d8bef9SDimitry Andric #include "llvm/IR/DIBuilder.h" 110e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 111e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h" 112e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 113e8d8bef9SDimitry Andric #include "llvm/IR/Module.h" 114e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h" 115e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h" 116e8d8bef9SDimitry Andric #include "llvm/Pass.h" 117e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 118e8d8bef9SDimitry Andric #include "llvm/Support/Compiler.h" 119e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 120e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h" 121e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 122fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h" 123fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 124e8d8bef9SDimitry Andric #include <algorithm> 125e8d8bef9SDimitry Andric #include <cassert> 126e8d8bef9SDimitry Andric #include <cstdint> 127e8d8bef9SDimitry Andric #include <functional> 128349cc55cSDimitry Andric #include <limits.h> 129349cc55cSDimitry Andric #include <limits> 130e8d8bef9SDimitry Andric #include <queue> 131e8d8bef9SDimitry Andric #include <tuple> 132e8d8bef9SDimitry Andric #include <utility> 133e8d8bef9SDimitry Andric #include <vector> 134e8d8bef9SDimitry Andric 135349cc55cSDimitry Andric #include "InstrRefBasedImpl.h" 136e8d8bef9SDimitry Andric #include "LiveDebugValues.h" 137e8d8bef9SDimitry Andric 138e8d8bef9SDimitry Andric using namespace llvm; 139349cc55cSDimitry Andric using namespace LiveDebugValues; 140e8d8bef9SDimitry Andric 141fe6060f1SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it. 142fe6060f1SDimitry Andric #undef DEBUG_TYPE 143e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues" 144e8d8bef9SDimitry Andric 145e8d8bef9SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too 146e8d8bef9SDimitry Andric // far and ignoring some transfers. 147e8d8bef9SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, 148e8d8bef9SDimitry Andric cl::desc("Act like old LiveDebugValues did"), 149e8d8bef9SDimitry Andric cl::init(false)); 150e8d8bef9SDimitry Andric 151e8d8bef9SDimitry Andric /// Tracker for converting machine value locations and variable values into 152e8d8bef9SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs 153e8d8bef9SDimitry Andric /// specifying block live-in locations and transfers within blocks. 154e8d8bef9SDimitry Andric /// 155e8d8bef9SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker 156e8d8bef9SDimitry Andric /// and must be initialized with the set of variable values that are live-in to 157e8d8bef9SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks 158e8d8bef9SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a 159e8d8bef9SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is 160e8d8bef9SDimitry Andric /// stepped through, transfers of values between machine locations are 161e8d8bef9SDimitry Andric /// identified and if profitable, a DBG_VALUE created. 162e8d8bef9SDimitry Andric /// 163e8d8bef9SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an 164e8d8bef9SDimitry Andric /// unavailable value could materialize in the middle of a block, when the 165e8d8bef9SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the 166e8d8bef9SDimitry Andric /// variable in a backup location. (XXX these are unimplemented). 167e8d8bef9SDimitry Andric class TransferTracker { 168e8d8bef9SDimitry Andric public: 169e8d8bef9SDimitry Andric const TargetInstrInfo *TII; 170fe6060f1SDimitry Andric const TargetLowering *TLI; 171e8d8bef9SDimitry Andric /// This machine location tracker is assumed to always contain the up-to-date 172e8d8bef9SDimitry Andric /// value mapping for all machine locations. TransferTracker only reads 173e8d8bef9SDimitry Andric /// information from it. (XXX make it const?) 174e8d8bef9SDimitry Andric MLocTracker *MTracker; 175e8d8bef9SDimitry Andric MachineFunction &MF; 176fe6060f1SDimitry Andric bool ShouldEmitDebugEntryValues; 177e8d8bef9SDimitry Andric 178e8d8bef9SDimitry Andric /// Record of all changes in variable locations at a block position. Awkwardly 179e8d8bef9SDimitry Andric /// we allow inserting either before or after the point: MBB != nullptr 180e8d8bef9SDimitry Andric /// indicates it's before, otherwise after. 181e8d8bef9SDimitry Andric struct Transfer { 182fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes 183e8d8bef9SDimitry Andric MachineBasicBlock *MBB; /// non-null if we should insert after. 184e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. 185e8d8bef9SDimitry Andric }; 186e8d8bef9SDimitry Andric 187fe6060f1SDimitry Andric struct LocAndProperties { 188e8d8bef9SDimitry Andric LocIdx Loc; 189e8d8bef9SDimitry Andric DbgValueProperties Properties; 190fe6060f1SDimitry Andric }; 191e8d8bef9SDimitry Andric 192e8d8bef9SDimitry Andric /// Collection of transfers (DBG_VALUEs) to be inserted. 193e8d8bef9SDimitry Andric SmallVector<Transfer, 32> Transfers; 194e8d8bef9SDimitry Andric 195e8d8bef9SDimitry Andric /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences 196e8d8bef9SDimitry Andric /// between TransferTrackers view of variable locations and MLocTrackers. For 197e8d8bef9SDimitry Andric /// example, MLocTracker observes all clobbers, but TransferTracker lazily 198e8d8bef9SDimitry Andric /// does not. 199349cc55cSDimitry Andric SmallVector<ValueIDNum, 32> VarLocs; 200e8d8bef9SDimitry Andric 201e8d8bef9SDimitry Andric /// Map from LocIdxes to which DebugVariables are based that location. 202e8d8bef9SDimitry Andric /// Mantained while stepping through the block. Not accurate if 203e8d8bef9SDimitry Andric /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. 204349cc55cSDimitry Andric DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; 205e8d8bef9SDimitry Andric 206e8d8bef9SDimitry Andric /// Map from DebugVariable to it's current location and qualifying meta 207e8d8bef9SDimitry Andric /// information. To be used in conjunction with ActiveMLocs to construct 208e8d8bef9SDimitry Andric /// enough information for the DBG_VALUEs for a particular LocIdx. 209e8d8bef9SDimitry Andric DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; 210e8d8bef9SDimitry Andric 211e8d8bef9SDimitry Andric /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. 212e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> PendingDbgValues; 213e8d8bef9SDimitry Andric 214e8d8bef9SDimitry Andric /// Record of a use-before-def: created when a value that's live-in to the 215e8d8bef9SDimitry Andric /// current block isn't available in any machine location, but it will be 216e8d8bef9SDimitry Andric /// defined in this block. 217e8d8bef9SDimitry Andric struct UseBeforeDef { 218e8d8bef9SDimitry Andric /// Value of this variable, def'd in block. 219e8d8bef9SDimitry Andric ValueIDNum ID; 220e8d8bef9SDimitry Andric /// Identity of this variable. 221e8d8bef9SDimitry Andric DebugVariable Var; 222e8d8bef9SDimitry Andric /// Additional variable properties. 223e8d8bef9SDimitry Andric DbgValueProperties Properties; 224e8d8bef9SDimitry Andric }; 225e8d8bef9SDimitry Andric 226e8d8bef9SDimitry Andric /// Map from instruction index (within the block) to the set of UseBeforeDefs 227e8d8bef9SDimitry Andric /// that become defined at that instruction. 228e8d8bef9SDimitry Andric DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; 229e8d8bef9SDimitry Andric 230e8d8bef9SDimitry Andric /// The set of variables that are in UseBeforeDefs and can become a location 231e8d8bef9SDimitry Andric /// once the relevant value is defined. An element being erased from this 232e8d8bef9SDimitry Andric /// collection prevents the use-before-def materializing. 233e8d8bef9SDimitry Andric DenseSet<DebugVariable> UseBeforeDefVariables; 234e8d8bef9SDimitry Andric 235e8d8bef9SDimitry Andric const TargetRegisterInfo &TRI; 236e8d8bef9SDimitry Andric const BitVector &CalleeSavedRegs; 237e8d8bef9SDimitry Andric 238e8d8bef9SDimitry Andric TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, 239e8d8bef9SDimitry Andric MachineFunction &MF, const TargetRegisterInfo &TRI, 240fe6060f1SDimitry Andric const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) 241e8d8bef9SDimitry Andric : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), 242fe6060f1SDimitry Andric CalleeSavedRegs(CalleeSavedRegs) { 243fe6060f1SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 244fe6060f1SDimitry Andric auto &TM = TPC.getTM<TargetMachine>(); 245fe6060f1SDimitry Andric ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); 246fe6060f1SDimitry Andric } 247e8d8bef9SDimitry Andric 248e8d8bef9SDimitry Andric /// Load object with live-in variable values. \p mlocs contains the live-in 249e8d8bef9SDimitry Andric /// values in each machine location, while \p vlocs the live-in variable 250e8d8bef9SDimitry Andric /// values. This method picks variable locations for the live-in variables, 251e8d8bef9SDimitry Andric /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other 252e8d8bef9SDimitry Andric /// object fields to track variable locations as we step through the block. 253e8d8bef9SDimitry Andric /// FIXME: could just examine mloctracker instead of passing in \p mlocs? 254*04eeddc0SDimitry Andric void 255*04eeddc0SDimitry Andric loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs, 256*04eeddc0SDimitry Andric const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, 257e8d8bef9SDimitry Andric unsigned NumLocs) { 258e8d8bef9SDimitry Andric ActiveMLocs.clear(); 259e8d8bef9SDimitry Andric ActiveVLocs.clear(); 260e8d8bef9SDimitry Andric VarLocs.clear(); 261e8d8bef9SDimitry Andric VarLocs.reserve(NumLocs); 262e8d8bef9SDimitry Andric UseBeforeDefs.clear(); 263e8d8bef9SDimitry Andric UseBeforeDefVariables.clear(); 264e8d8bef9SDimitry Andric 265e8d8bef9SDimitry Andric auto isCalleeSaved = [&](LocIdx L) { 266e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 267e8d8bef9SDimitry Andric if (Reg >= MTracker->NumRegs) 268e8d8bef9SDimitry Andric return false; 269e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) 270e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 271e8d8bef9SDimitry Andric return true; 272e8d8bef9SDimitry Andric return false; 273e8d8bef9SDimitry Andric }; 274e8d8bef9SDimitry Andric 275e8d8bef9SDimitry Andric // Map of the preferred location for each value. 276*04eeddc0SDimitry Andric DenseMap<ValueIDNum, LocIdx> ValueToLoc; 277349cc55cSDimitry Andric ActiveMLocs.reserve(VLocs.size()); 278349cc55cSDimitry Andric ActiveVLocs.reserve(VLocs.size()); 279e8d8bef9SDimitry Andric 280e8d8bef9SDimitry Andric // Produce a map of value numbers to the current machine locs they live 281e8d8bef9SDimitry Andric // in. When emulating VarLocBasedImpl, there should only be one 282e8d8bef9SDimitry Andric // location; when not, we get to pick. 283e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 284e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 285e8d8bef9SDimitry Andric ValueIDNum &VNum = MLocs[Idx.asU64()]; 286e8d8bef9SDimitry Andric VarLocs.push_back(VNum); 287*04eeddc0SDimitry Andric 288*04eeddc0SDimitry Andric // Short-circuit unnecessary preferred location update. 289*04eeddc0SDimitry Andric if (VLocs.empty()) 290*04eeddc0SDimitry Andric continue; 291*04eeddc0SDimitry Andric 292e8d8bef9SDimitry Andric auto it = ValueToLoc.find(VNum); 293e8d8bef9SDimitry Andric // In order of preference, pick: 294e8d8bef9SDimitry Andric // * Callee saved registers, 295e8d8bef9SDimitry Andric // * Other registers, 296e8d8bef9SDimitry Andric // * Spill slots. 297e8d8bef9SDimitry Andric if (it == ValueToLoc.end() || MTracker->isSpill(it->second) || 298e8d8bef9SDimitry Andric (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) { 299e8d8bef9SDimitry Andric // Insert, or overwrite if insertion failed. 300e8d8bef9SDimitry Andric auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx)); 301e8d8bef9SDimitry Andric if (!PrefLocRes.second) 302e8d8bef9SDimitry Andric PrefLocRes.first->second = Idx; 303e8d8bef9SDimitry Andric } 304e8d8bef9SDimitry Andric } 305e8d8bef9SDimitry Andric 306e8d8bef9SDimitry Andric // Now map variables to their picked LocIdxes. 307*04eeddc0SDimitry Andric for (const auto &Var : VLocs) { 308e8d8bef9SDimitry Andric if (Var.second.Kind == DbgValue::Const) { 309e8d8bef9SDimitry Andric PendingDbgValues.push_back( 310349cc55cSDimitry Andric emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties)); 311e8d8bef9SDimitry Andric continue; 312e8d8bef9SDimitry Andric } 313e8d8bef9SDimitry Andric 314e8d8bef9SDimitry Andric // If the value has no location, we can't make a variable location. 315e8d8bef9SDimitry Andric const ValueIDNum &Num = Var.second.ID; 316e8d8bef9SDimitry Andric auto ValuesPreferredLoc = ValueToLoc.find(Num); 317e8d8bef9SDimitry Andric if (ValuesPreferredLoc == ValueToLoc.end()) { 318e8d8bef9SDimitry Andric // If it's a def that occurs in this block, register it as a 319e8d8bef9SDimitry Andric // use-before-def to be resolved as we step through the block. 320e8d8bef9SDimitry Andric if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) 321e8d8bef9SDimitry Andric addUseBeforeDef(Var.first, Var.second.Properties, Num); 322fe6060f1SDimitry Andric else 323fe6060f1SDimitry Andric recoverAsEntryValue(Var.first, Var.second.Properties, Num); 324e8d8bef9SDimitry Andric continue; 325e8d8bef9SDimitry Andric } 326e8d8bef9SDimitry Andric 327e8d8bef9SDimitry Andric LocIdx M = ValuesPreferredLoc->second; 328e8d8bef9SDimitry Andric auto NewValue = LocAndProperties{M, Var.second.Properties}; 329e8d8bef9SDimitry Andric auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); 330e8d8bef9SDimitry Andric if (!Result.second) 331e8d8bef9SDimitry Andric Result.first->second = NewValue; 332e8d8bef9SDimitry Andric ActiveMLocs[M].insert(Var.first); 333e8d8bef9SDimitry Andric PendingDbgValues.push_back( 334e8d8bef9SDimitry Andric MTracker->emitLoc(M, Var.first, Var.second.Properties)); 335e8d8bef9SDimitry Andric } 336e8d8bef9SDimitry Andric flushDbgValues(MBB.begin(), &MBB); 337e8d8bef9SDimitry Andric } 338e8d8bef9SDimitry Andric 339e8d8bef9SDimitry Andric /// Record that \p Var has value \p ID, a value that becomes available 340e8d8bef9SDimitry Andric /// later in the function. 341e8d8bef9SDimitry Andric void addUseBeforeDef(const DebugVariable &Var, 342e8d8bef9SDimitry Andric const DbgValueProperties &Properties, ValueIDNum ID) { 343e8d8bef9SDimitry Andric UseBeforeDef UBD = {ID, Var, Properties}; 344e8d8bef9SDimitry Andric UseBeforeDefs[ID.getInst()].push_back(UBD); 345e8d8bef9SDimitry Andric UseBeforeDefVariables.insert(Var); 346e8d8bef9SDimitry Andric } 347e8d8bef9SDimitry Andric 348e8d8bef9SDimitry Andric /// After the instruction at index \p Inst and position \p pos has been 349e8d8bef9SDimitry Andric /// processed, check whether it defines a variable value in a use-before-def. 350e8d8bef9SDimitry Andric /// If so, and the variable value hasn't changed since the start of the 351e8d8bef9SDimitry Andric /// block, create a DBG_VALUE. 352e8d8bef9SDimitry Andric void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { 353e8d8bef9SDimitry Andric auto MIt = UseBeforeDefs.find(Inst); 354e8d8bef9SDimitry Andric if (MIt == UseBeforeDefs.end()) 355e8d8bef9SDimitry Andric return; 356e8d8bef9SDimitry Andric 357e8d8bef9SDimitry Andric for (auto &Use : MIt->second) { 358e8d8bef9SDimitry Andric LocIdx L = Use.ID.getLoc(); 359e8d8bef9SDimitry Andric 360e8d8bef9SDimitry Andric // If something goes very wrong, we might end up labelling a COPY 361e8d8bef9SDimitry Andric // instruction or similar with an instruction number, where it doesn't 362e8d8bef9SDimitry Andric // actually define a new value, instead it moves a value. In case this 363e8d8bef9SDimitry Andric // happens, discard. 364349cc55cSDimitry Andric if (MTracker->readMLoc(L) != Use.ID) 365e8d8bef9SDimitry Andric continue; 366e8d8bef9SDimitry Andric 367e8d8bef9SDimitry Andric // If a different debug instruction defined the variable value / location 368e8d8bef9SDimitry Andric // since the start of the block, don't materialize this use-before-def. 369e8d8bef9SDimitry Andric if (!UseBeforeDefVariables.count(Use.Var)) 370e8d8bef9SDimitry Andric continue; 371e8d8bef9SDimitry Andric 372e8d8bef9SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); 373e8d8bef9SDimitry Andric } 374e8d8bef9SDimitry Andric flushDbgValues(pos, nullptr); 375e8d8bef9SDimitry Andric } 376e8d8bef9SDimitry Andric 377e8d8bef9SDimitry Andric /// Helper to move created DBG_VALUEs into Transfers collection. 378e8d8bef9SDimitry Andric void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { 379fe6060f1SDimitry Andric if (PendingDbgValues.size() == 0) 380fe6060f1SDimitry Andric return; 381fe6060f1SDimitry Andric 382fe6060f1SDimitry Andric // Pick out the instruction start position. 383fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator BundleStart; 384fe6060f1SDimitry Andric if (MBB && Pos == MBB->begin()) 385fe6060f1SDimitry Andric BundleStart = MBB->instr_begin(); 386fe6060f1SDimitry Andric else 387fe6060f1SDimitry Andric BundleStart = getBundleStart(Pos->getIterator()); 388fe6060f1SDimitry Andric 389fe6060f1SDimitry Andric Transfers.push_back({BundleStart, MBB, PendingDbgValues}); 390e8d8bef9SDimitry Andric PendingDbgValues.clear(); 391e8d8bef9SDimitry Andric } 392fe6060f1SDimitry Andric 393fe6060f1SDimitry Andric bool isEntryValueVariable(const DebugVariable &Var, 394fe6060f1SDimitry Andric const DIExpression *Expr) const { 395fe6060f1SDimitry Andric if (!Var.getVariable()->isParameter()) 396fe6060f1SDimitry Andric return false; 397fe6060f1SDimitry Andric 398fe6060f1SDimitry Andric if (Var.getInlinedAt()) 399fe6060f1SDimitry Andric return false; 400fe6060f1SDimitry Andric 401fe6060f1SDimitry Andric if (Expr->getNumElements() > 0) 402fe6060f1SDimitry Andric return false; 403fe6060f1SDimitry Andric 404fe6060f1SDimitry Andric return true; 405fe6060f1SDimitry Andric } 406fe6060f1SDimitry Andric 407fe6060f1SDimitry Andric bool isEntryValueValue(const ValueIDNum &Val) const { 408fe6060f1SDimitry Andric // Must be in entry block (block number zero), and be a PHI / live-in value. 409fe6060f1SDimitry Andric if (Val.getBlock() || !Val.isPHI()) 410fe6060f1SDimitry Andric return false; 411fe6060f1SDimitry Andric 412fe6060f1SDimitry Andric // Entry values must enter in a register. 413fe6060f1SDimitry Andric if (MTracker->isSpill(Val.getLoc())) 414fe6060f1SDimitry Andric return false; 415fe6060f1SDimitry Andric 416fe6060f1SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore(); 417fe6060f1SDimitry Andric Register FP = TRI.getFrameRegister(MF); 418fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; 419fe6060f1SDimitry Andric return Reg != SP && Reg != FP; 420fe6060f1SDimitry Andric } 421fe6060f1SDimitry Andric 422*04eeddc0SDimitry Andric bool recoverAsEntryValue(const DebugVariable &Var, 423*04eeddc0SDimitry Andric const DbgValueProperties &Prop, 424fe6060f1SDimitry Andric const ValueIDNum &Num) { 425fe6060f1SDimitry Andric // Is this variable location a candidate to be an entry value. First, 426fe6060f1SDimitry Andric // should we be trying this at all? 427fe6060f1SDimitry Andric if (!ShouldEmitDebugEntryValues) 428fe6060f1SDimitry Andric return false; 429fe6060f1SDimitry Andric 430fe6060f1SDimitry Andric // Is the variable appropriate for entry values (i.e., is a parameter). 431fe6060f1SDimitry Andric if (!isEntryValueVariable(Var, Prop.DIExpr)) 432fe6060f1SDimitry Andric return false; 433fe6060f1SDimitry Andric 434fe6060f1SDimitry Andric // Is the value assigned to this variable still the entry value? 435fe6060f1SDimitry Andric if (!isEntryValueValue(Num)) 436fe6060f1SDimitry Andric return false; 437fe6060f1SDimitry Andric 438fe6060f1SDimitry Andric // Emit a variable location using an entry value expression. 439fe6060f1SDimitry Andric DIExpression *NewExpr = 440fe6060f1SDimitry Andric DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); 441fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; 442fe6060f1SDimitry Andric MachineOperand MO = MachineOperand::CreateReg(Reg, false); 443fe6060f1SDimitry Andric 444fe6060f1SDimitry Andric PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); 445fe6060f1SDimitry Andric return true; 446e8d8bef9SDimitry Andric } 447e8d8bef9SDimitry Andric 448e8d8bef9SDimitry Andric /// Change a variable value after encountering a DBG_VALUE inside a block. 449e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI) { 450e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 451e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 452e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 453e8d8bef9SDimitry Andric 454e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 455e8d8bef9SDimitry Andric 456e8d8bef9SDimitry Andric // Ignore non-register locations, we don't transfer those. 457e8d8bef9SDimitry Andric if (!MO.isReg() || MO.getReg() == 0) { 458e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 459e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) { 460e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 461e8d8bef9SDimitry Andric ActiveVLocs.erase(It); 462e8d8bef9SDimitry Andric } 463e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 464e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 465e8d8bef9SDimitry Andric return; 466e8d8bef9SDimitry Andric } 467e8d8bef9SDimitry Andric 468e8d8bef9SDimitry Andric Register Reg = MO.getReg(); 469e8d8bef9SDimitry Andric LocIdx NewLoc = MTracker->getRegMLoc(Reg); 470e8d8bef9SDimitry Andric redefVar(MI, Properties, NewLoc); 471e8d8bef9SDimitry Andric } 472e8d8bef9SDimitry Andric 473e8d8bef9SDimitry Andric /// Handle a change in variable location within a block. Terminate the 474e8d8bef9SDimitry Andric /// variables current location, and record the value it now refers to, so 475e8d8bef9SDimitry Andric /// that we can detect location transfers later on. 476e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, 477e8d8bef9SDimitry Andric Optional<LocIdx> OptNewLoc) { 478e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 479e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 480e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 481e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 482e8d8bef9SDimitry Andric 483e8d8bef9SDimitry Andric // Erase any previous location, 484e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 485e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) 486e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 487e8d8bef9SDimitry Andric 488e8d8bef9SDimitry Andric // If there _is_ no new location, all we had to do was erase. 489e8d8bef9SDimitry Andric if (!OptNewLoc) 490e8d8bef9SDimitry Andric return; 491e8d8bef9SDimitry Andric LocIdx NewLoc = *OptNewLoc; 492e8d8bef9SDimitry Andric 493e8d8bef9SDimitry Andric // Check whether our local copy of values-by-location in #VarLocs is out of 494e8d8bef9SDimitry Andric // date. Wipe old tracking data for the location if it's been clobbered in 495e8d8bef9SDimitry Andric // the meantime. 496349cc55cSDimitry Andric if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) { 497e8d8bef9SDimitry Andric for (auto &P : ActiveMLocs[NewLoc]) { 498e8d8bef9SDimitry Andric ActiveVLocs.erase(P); 499e8d8bef9SDimitry Andric } 500e8d8bef9SDimitry Andric ActiveMLocs[NewLoc.asU64()].clear(); 501349cc55cSDimitry Andric VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc); 502e8d8bef9SDimitry Andric } 503e8d8bef9SDimitry Andric 504e8d8bef9SDimitry Andric ActiveMLocs[NewLoc].insert(Var); 505e8d8bef9SDimitry Andric if (It == ActiveVLocs.end()) { 506e8d8bef9SDimitry Andric ActiveVLocs.insert( 507e8d8bef9SDimitry Andric std::make_pair(Var, LocAndProperties{NewLoc, Properties})); 508e8d8bef9SDimitry Andric } else { 509e8d8bef9SDimitry Andric It->second.Loc = NewLoc; 510e8d8bef9SDimitry Andric It->second.Properties = Properties; 511e8d8bef9SDimitry Andric } 512e8d8bef9SDimitry Andric } 513e8d8bef9SDimitry Andric 514fe6060f1SDimitry Andric /// Account for a location \p mloc being clobbered. Examine the variable 515fe6060f1SDimitry Andric /// locations that will be terminated: and try to recover them by using 516fe6060f1SDimitry Andric /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to 517fe6060f1SDimitry Andric /// explicitly terminate a location if it can't be recovered. 518fe6060f1SDimitry Andric void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, 519fe6060f1SDimitry Andric bool MakeUndef = true) { 520e8d8bef9SDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc); 521e8d8bef9SDimitry Andric if (ActiveMLocIt == ActiveMLocs.end()) 522e8d8bef9SDimitry Andric return; 523e8d8bef9SDimitry Andric 524fe6060f1SDimitry Andric // What was the old variable value? 525fe6060f1SDimitry Andric ValueIDNum OldValue = VarLocs[MLoc.asU64()]; 526e8d8bef9SDimitry Andric VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; 527e8d8bef9SDimitry Andric 528fe6060f1SDimitry Andric // Examine the remaining variable locations: if we can find the same value 529fe6060f1SDimitry Andric // again, we can recover the location. 530fe6060f1SDimitry Andric Optional<LocIdx> NewLoc = None; 531fe6060f1SDimitry Andric for (auto Loc : MTracker->locations()) 532fe6060f1SDimitry Andric if (Loc.Value == OldValue) 533fe6060f1SDimitry Andric NewLoc = Loc.Idx; 534fe6060f1SDimitry Andric 535fe6060f1SDimitry Andric // If there is no location, and we weren't asked to make the variable 536fe6060f1SDimitry Andric // explicitly undef, then stop here. 537fe6060f1SDimitry Andric if (!NewLoc && !MakeUndef) { 538fe6060f1SDimitry Andric // Try and recover a few more locations with entry values. 539fe6060f1SDimitry Andric for (auto &Var : ActiveMLocIt->second) { 540fe6060f1SDimitry Andric auto &Prop = ActiveVLocs.find(Var)->second.Properties; 541fe6060f1SDimitry Andric recoverAsEntryValue(Var, Prop, OldValue); 542fe6060f1SDimitry Andric } 543fe6060f1SDimitry Andric flushDbgValues(Pos, nullptr); 544fe6060f1SDimitry Andric return; 545fe6060f1SDimitry Andric } 546fe6060f1SDimitry Andric 547fe6060f1SDimitry Andric // Examine all the variables based on this location. 548fe6060f1SDimitry Andric DenseSet<DebugVariable> NewMLocs; 549e8d8bef9SDimitry Andric for (auto &Var : ActiveMLocIt->second) { 550e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 551fe6060f1SDimitry Andric // Re-state the variable location: if there's no replacement then NewLoc 552fe6060f1SDimitry Andric // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE 553fe6060f1SDimitry Andric // identifying the alternative location will be emitted. 5544824e7fdSDimitry Andric const DbgValueProperties &Properties = ActiveVLocIt->second.Properties; 555fe6060f1SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); 556fe6060f1SDimitry Andric 557fe6060f1SDimitry Andric // Update machine locations <=> variable locations maps. Defer updating 558fe6060f1SDimitry Andric // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. 559fe6060f1SDimitry Andric if (!NewLoc) { 560e8d8bef9SDimitry Andric ActiveVLocs.erase(ActiveVLocIt); 561fe6060f1SDimitry Andric } else { 562fe6060f1SDimitry Andric ActiveVLocIt->second.Loc = *NewLoc; 563fe6060f1SDimitry Andric NewMLocs.insert(Var); 564e8d8bef9SDimitry Andric } 565fe6060f1SDimitry Andric } 566fe6060f1SDimitry Andric 567fe6060f1SDimitry Andric // Commit any deferred ActiveMLoc changes. 568fe6060f1SDimitry Andric if (!NewMLocs.empty()) 569fe6060f1SDimitry Andric for (auto &Var : NewMLocs) 570fe6060f1SDimitry Andric ActiveMLocs[*NewLoc].insert(Var); 571fe6060f1SDimitry Andric 572fe6060f1SDimitry Andric // We lazily track what locations have which values; if we've found a new 573fe6060f1SDimitry Andric // location for the clobbered value, remember it. 574fe6060f1SDimitry Andric if (NewLoc) 575fe6060f1SDimitry Andric VarLocs[NewLoc->asU64()] = OldValue; 576fe6060f1SDimitry Andric 577e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 578e8d8bef9SDimitry Andric 579349cc55cSDimitry Andric // Re-find ActiveMLocIt, iterator could have been invalidated. 580349cc55cSDimitry Andric ActiveMLocIt = ActiveMLocs.find(MLoc); 581e8d8bef9SDimitry Andric ActiveMLocIt->second.clear(); 582e8d8bef9SDimitry Andric } 583e8d8bef9SDimitry Andric 584e8d8bef9SDimitry Andric /// Transfer variables based on \p Src to be based on \p Dst. This handles 585e8d8bef9SDimitry Andric /// both register copies as well as spills and restores. Creates DBG_VALUEs 586e8d8bef9SDimitry Andric /// describing the movement. 587e8d8bef9SDimitry Andric void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { 588e8d8bef9SDimitry Andric // Does Src still contain the value num we expect? If not, it's been 589e8d8bef9SDimitry Andric // clobbered in the meantime, and our variable locations are stale. 590349cc55cSDimitry Andric if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src)) 591e8d8bef9SDimitry Andric return; 592e8d8bef9SDimitry Andric 593e8d8bef9SDimitry Andric // assert(ActiveMLocs[Dst].size() == 0); 594e8d8bef9SDimitry Andric //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? 595349cc55cSDimitry Andric 596349cc55cSDimitry Andric // Move set of active variables from one location to another. 597349cc55cSDimitry Andric auto MovingVars = ActiveMLocs[Src]; 598349cc55cSDimitry Andric ActiveMLocs[Dst] = MovingVars; 599e8d8bef9SDimitry Andric VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; 600e8d8bef9SDimitry Andric 601e8d8bef9SDimitry Andric // For each variable based on Src; create a location at Dst. 602349cc55cSDimitry Andric for (auto &Var : MovingVars) { 603e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 604e8d8bef9SDimitry Andric assert(ActiveVLocIt != ActiveVLocs.end()); 605e8d8bef9SDimitry Andric ActiveVLocIt->second.Loc = Dst; 606e8d8bef9SDimitry Andric 607e8d8bef9SDimitry Andric MachineInstr *MI = 608e8d8bef9SDimitry Andric MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); 609e8d8bef9SDimitry Andric PendingDbgValues.push_back(MI); 610e8d8bef9SDimitry Andric } 611e8d8bef9SDimitry Andric ActiveMLocs[Src].clear(); 612e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 613e8d8bef9SDimitry Andric 614e8d8bef9SDimitry Andric // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data 615e8d8bef9SDimitry Andric // about the old location. 616e8d8bef9SDimitry Andric if (EmulateOldLDV) 617e8d8bef9SDimitry Andric VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; 618e8d8bef9SDimitry Andric } 619e8d8bef9SDimitry Andric 620e8d8bef9SDimitry Andric MachineInstrBuilder emitMOLoc(const MachineOperand &MO, 621e8d8bef9SDimitry Andric const DebugVariable &Var, 622e8d8bef9SDimitry Andric const DbgValueProperties &Properties) { 623e8d8bef9SDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 624e8d8bef9SDimitry Andric Var.getVariable()->getScope(), 625e8d8bef9SDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 626e8d8bef9SDimitry Andric auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 627e8d8bef9SDimitry Andric MIB.add(MO); 628e8d8bef9SDimitry Andric if (Properties.Indirect) 629e8d8bef9SDimitry Andric MIB.addImm(0); 630e8d8bef9SDimitry Andric else 631e8d8bef9SDimitry Andric MIB.addReg(0); 632e8d8bef9SDimitry Andric MIB.addMetadata(Var.getVariable()); 633e8d8bef9SDimitry Andric MIB.addMetadata(Properties.DIExpr); 634e8d8bef9SDimitry Andric return MIB; 635e8d8bef9SDimitry Andric } 636e8d8bef9SDimitry Andric }; 637e8d8bef9SDimitry Andric 638349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 639349cc55cSDimitry Andric // Implementation 640349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 641e8d8bef9SDimitry Andric 642349cc55cSDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; 643349cc55cSDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1}; 644e8d8bef9SDimitry Andric 645349cc55cSDimitry Andric #ifndef NDEBUG 646349cc55cSDimitry Andric void DbgValue::dump(const MLocTracker *MTrack) const { 647349cc55cSDimitry Andric if (Kind == Const) { 648349cc55cSDimitry Andric MO->dump(); 649349cc55cSDimitry Andric } else if (Kind == NoVal) { 650349cc55cSDimitry Andric dbgs() << "NoVal(" << BlockNo << ")"; 651349cc55cSDimitry Andric } else if (Kind == VPHI) { 652349cc55cSDimitry Andric dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")"; 653349cc55cSDimitry Andric } else { 654349cc55cSDimitry Andric assert(Kind == Def); 655349cc55cSDimitry Andric dbgs() << MTrack->IDAsString(ID); 656349cc55cSDimitry Andric } 657349cc55cSDimitry Andric if (Properties.Indirect) 658349cc55cSDimitry Andric dbgs() << " indir"; 659349cc55cSDimitry Andric if (Properties.DIExpr) 660349cc55cSDimitry Andric dbgs() << " " << *Properties.DIExpr; 661349cc55cSDimitry Andric } 662349cc55cSDimitry Andric #endif 663e8d8bef9SDimitry Andric 664349cc55cSDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 665349cc55cSDimitry Andric const TargetRegisterInfo &TRI, 666349cc55cSDimitry Andric const TargetLowering &TLI) 667349cc55cSDimitry Andric : MF(MF), TII(TII), TRI(TRI), TLI(TLI), 668349cc55cSDimitry Andric LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) { 669349cc55cSDimitry Andric NumRegs = TRI.getNumRegs(); 670349cc55cSDimitry Andric reset(); 671349cc55cSDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 672349cc55cSDimitry Andric assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure 673e8d8bef9SDimitry Andric 674349cc55cSDimitry Andric // Always track SP. This avoids the implicit clobbering caused by regmasks 675349cc55cSDimitry Andric // from affectings its values. (LiveDebugValues disbelieves calls and 676349cc55cSDimitry Andric // regmasks that claim to clobber SP). 677349cc55cSDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore(); 678349cc55cSDimitry Andric if (SP) { 679349cc55cSDimitry Andric unsigned ID = getLocID(SP); 680349cc55cSDimitry Andric (void)lookupOrTrackRegister(ID); 681e8d8bef9SDimitry Andric 682349cc55cSDimitry Andric for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI) 683349cc55cSDimitry Andric SPAliases.insert(*RAI); 684349cc55cSDimitry Andric } 685e8d8bef9SDimitry Andric 686349cc55cSDimitry Andric // Build some common stack positions -- full registers being spilt to the 687349cc55cSDimitry Andric // stack. 688349cc55cSDimitry Andric StackSlotIdxes.insert({{8, 0}, 0}); 689349cc55cSDimitry Andric StackSlotIdxes.insert({{16, 0}, 1}); 690349cc55cSDimitry Andric StackSlotIdxes.insert({{32, 0}, 2}); 691349cc55cSDimitry Andric StackSlotIdxes.insert({{64, 0}, 3}); 692349cc55cSDimitry Andric StackSlotIdxes.insert({{128, 0}, 4}); 693349cc55cSDimitry Andric StackSlotIdxes.insert({{256, 0}, 5}); 694349cc55cSDimitry Andric StackSlotIdxes.insert({{512, 0}, 6}); 695e8d8bef9SDimitry Andric 696349cc55cSDimitry Andric // Traverse all the subregister idxes, and ensure there's an index for them. 697349cc55cSDimitry Andric // Duplicates are no problem: we're interested in their position in the 698349cc55cSDimitry Andric // stack slot, we don't want to type the slot. 699349cc55cSDimitry Andric for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) { 700349cc55cSDimitry Andric unsigned Size = TRI.getSubRegIdxSize(I); 701349cc55cSDimitry Andric unsigned Offs = TRI.getSubRegIdxOffset(I); 702349cc55cSDimitry Andric unsigned Idx = StackSlotIdxes.size(); 703e8d8bef9SDimitry Andric 704349cc55cSDimitry Andric // Some subregs have -1, -2 and so forth fed into their fields, to mean 705349cc55cSDimitry Andric // special backend things. Ignore those. 706349cc55cSDimitry Andric if (Size > 60000 || Offs > 60000) 707349cc55cSDimitry Andric continue; 708e8d8bef9SDimitry Andric 709349cc55cSDimitry Andric StackSlotIdxes.insert({{Size, Offs}, Idx}); 710349cc55cSDimitry Andric } 711e8d8bef9SDimitry Andric 712349cc55cSDimitry Andric for (auto &Idx : StackSlotIdxes) 713349cc55cSDimitry Andric StackIdxesToPos[Idx.second] = Idx.first; 714e8d8bef9SDimitry Andric 715349cc55cSDimitry Andric NumSlotIdxes = StackSlotIdxes.size(); 716349cc55cSDimitry Andric } 717e8d8bef9SDimitry Andric 718349cc55cSDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) { 719349cc55cSDimitry Andric assert(ID != 0); 720349cc55cSDimitry Andric LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); 721349cc55cSDimitry Andric LocIdxToIDNum.grow(NewIdx); 722349cc55cSDimitry Andric LocIdxToLocID.grow(NewIdx); 723e8d8bef9SDimitry Andric 724349cc55cSDimitry Andric // Default: it's an mphi. 725349cc55cSDimitry Andric ValueIDNum ValNum = {CurBB, 0, NewIdx}; 726349cc55cSDimitry Andric // Was this reg ever touched by a regmask? 727349cc55cSDimitry Andric for (const auto &MaskPair : reverse(Masks)) { 728349cc55cSDimitry Andric if (MaskPair.first->clobbersPhysReg(ID)) { 729349cc55cSDimitry Andric // There was an earlier def we skipped. 730349cc55cSDimitry Andric ValNum = {CurBB, MaskPair.second, NewIdx}; 731349cc55cSDimitry Andric break; 732349cc55cSDimitry Andric } 733349cc55cSDimitry Andric } 734e8d8bef9SDimitry Andric 735349cc55cSDimitry Andric LocIdxToIDNum[NewIdx] = ValNum; 736349cc55cSDimitry Andric LocIdxToLocID[NewIdx] = ID; 737349cc55cSDimitry Andric return NewIdx; 738349cc55cSDimitry Andric } 739e8d8bef9SDimitry Andric 740349cc55cSDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB, 741349cc55cSDimitry Andric unsigned InstID) { 742349cc55cSDimitry Andric // Def any register we track have that isn't preserved. The regmask 743349cc55cSDimitry Andric // terminates the liveness of a register, meaning its value can't be 744349cc55cSDimitry Andric // relied upon -- we represent this by giving it a new value. 745349cc55cSDimitry Andric for (auto Location : locations()) { 746349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Location.Idx]; 747349cc55cSDimitry Andric // Don't clobber SP, even if the mask says it's clobbered. 748349cc55cSDimitry Andric if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID)) 749349cc55cSDimitry Andric defReg(ID, CurBB, InstID); 750349cc55cSDimitry Andric } 751349cc55cSDimitry Andric Masks.push_back(std::make_pair(MO, InstID)); 752349cc55cSDimitry Andric } 753e8d8bef9SDimitry Andric 754349cc55cSDimitry Andric SpillLocationNo MLocTracker::getOrTrackSpillLoc(SpillLoc L) { 755349cc55cSDimitry Andric SpillLocationNo SpillID(SpillLocs.idFor(L)); 756349cc55cSDimitry Andric if (SpillID.id() == 0) { 757349cc55cSDimitry Andric // Spill location is untracked: create record for this one, and all 758349cc55cSDimitry Andric // subregister slots too. 759349cc55cSDimitry Andric SpillID = SpillLocationNo(SpillLocs.insert(L)); 760349cc55cSDimitry Andric for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) { 761349cc55cSDimitry Andric unsigned L = getSpillIDWithIdx(SpillID, StackIdx); 762349cc55cSDimitry Andric LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx 763349cc55cSDimitry Andric LocIdxToIDNum.grow(Idx); 764349cc55cSDimitry Andric LocIdxToLocID.grow(Idx); 765349cc55cSDimitry Andric LocIDToLocIdx.push_back(Idx); 766349cc55cSDimitry Andric LocIdxToLocID[Idx] = L; 767349cc55cSDimitry Andric // Initialize to PHI value; corresponds to the location's live-in value 768349cc55cSDimitry Andric // during transfer function construction. 769349cc55cSDimitry Andric LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx); 770349cc55cSDimitry Andric } 771349cc55cSDimitry Andric } 772349cc55cSDimitry Andric return SpillID; 773349cc55cSDimitry Andric } 774fe6060f1SDimitry Andric 775349cc55cSDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const { 776349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Idx]; 777349cc55cSDimitry Andric if (ID >= NumRegs) { 778349cc55cSDimitry Andric StackSlotPos Pos = locIDToSpillIdx(ID); 779349cc55cSDimitry Andric ID -= NumRegs; 780349cc55cSDimitry Andric unsigned Slot = ID / NumSlotIdxes; 781349cc55cSDimitry Andric return Twine("slot ") 782349cc55cSDimitry Andric .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first) 783349cc55cSDimitry Andric .concat(Twine(" offs ").concat(Twine(Pos.second)))))) 784349cc55cSDimitry Andric .str(); 785349cc55cSDimitry Andric } else { 786349cc55cSDimitry Andric return TRI.getRegAsmName(ID).str(); 787349cc55cSDimitry Andric } 788349cc55cSDimitry Andric } 789fe6060f1SDimitry Andric 790349cc55cSDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const { 791349cc55cSDimitry Andric std::string DefName = LocIdxToName(Num.getLoc()); 792349cc55cSDimitry Andric return Num.asString(DefName); 793349cc55cSDimitry Andric } 794fe6060f1SDimitry Andric 795349cc55cSDimitry Andric #ifndef NDEBUG 796349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() { 797349cc55cSDimitry Andric for (auto Location : locations()) { 798349cc55cSDimitry Andric std::string MLocName = LocIdxToName(Location.Value.getLoc()); 799349cc55cSDimitry Andric std::string DefName = Location.Value.asString(MLocName); 800349cc55cSDimitry Andric dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; 801349cc55cSDimitry Andric } 802349cc55cSDimitry Andric } 803e8d8bef9SDimitry Andric 804349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() { 805349cc55cSDimitry Andric for (auto Location : locations()) { 806349cc55cSDimitry Andric std::string foo = LocIdxToName(Location.Idx); 807349cc55cSDimitry Andric dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; 808349cc55cSDimitry Andric } 809349cc55cSDimitry Andric } 810349cc55cSDimitry Andric #endif 811e8d8bef9SDimitry Andric 812349cc55cSDimitry Andric MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc, 813349cc55cSDimitry Andric const DebugVariable &Var, 814349cc55cSDimitry Andric const DbgValueProperties &Properties) { 815349cc55cSDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 816349cc55cSDimitry Andric Var.getVariable()->getScope(), 817349cc55cSDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 818349cc55cSDimitry Andric auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); 819e8d8bef9SDimitry Andric 820349cc55cSDimitry Andric const DIExpression *Expr = Properties.DIExpr; 821349cc55cSDimitry Andric if (!MLoc) { 822349cc55cSDimitry Andric // No location -> DBG_VALUE $noreg 823349cc55cSDimitry Andric MIB.addReg(0); 824349cc55cSDimitry Andric MIB.addReg(0); 825349cc55cSDimitry Andric } else if (LocIdxToLocID[*MLoc] >= NumRegs) { 826349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 827349cc55cSDimitry Andric SpillLocationNo SpillID = locIDToSpill(LocID); 828349cc55cSDimitry Andric StackSlotPos StackIdx = locIDToSpillIdx(LocID); 829349cc55cSDimitry Andric unsigned short Offset = StackIdx.second; 830e8d8bef9SDimitry Andric 831349cc55cSDimitry Andric // TODO: support variables that are located in spill slots, with non-zero 832349cc55cSDimitry Andric // offsets from the start of the spill slot. It would require some more 833349cc55cSDimitry Andric // complex DIExpression calculations. This doesn't seem to be produced by 834349cc55cSDimitry Andric // LLVM right now, so don't try and support it. 835349cc55cSDimitry Andric // Accept no-subregister slots and subregisters where the offset is zero. 836349cc55cSDimitry Andric // The consumer should already have type information to work out how large 837349cc55cSDimitry Andric // the variable is. 838349cc55cSDimitry Andric if (Offset == 0) { 839349cc55cSDimitry Andric const SpillLoc &Spill = SpillLocs[SpillID.id()]; 840349cc55cSDimitry Andric Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset, 841349cc55cSDimitry Andric Spill.SpillOffset); 842349cc55cSDimitry Andric unsigned Base = Spill.SpillBase; 843349cc55cSDimitry Andric MIB.addReg(Base); 844349cc55cSDimitry Andric MIB.addImm(0); 8454824e7fdSDimitry Andric 8464824e7fdSDimitry Andric // Being on the stack makes this location indirect; if it was _already_ 8474824e7fdSDimitry Andric // indirect though, we need to add extra indirection. See this test for 8484824e7fdSDimitry Andric // a scenario where this happens: 8494824e7fdSDimitry Andric // llvm/test/DebugInfo/X86/spill-nontrivial-param.ll 8504824e7fdSDimitry Andric if (Properties.Indirect) { 8514824e7fdSDimitry Andric std::vector<uint64_t> Elts = {dwarf::DW_OP_deref}; 8524824e7fdSDimitry Andric Expr = DIExpression::append(Expr, Elts); 8534824e7fdSDimitry Andric } 854349cc55cSDimitry Andric } else { 855349cc55cSDimitry Andric // This is a stack location with a weird subregister offset: emit an undef 856349cc55cSDimitry Andric // DBG_VALUE instead. 857349cc55cSDimitry Andric MIB.addReg(0); 858349cc55cSDimitry Andric MIB.addReg(0); 859349cc55cSDimitry Andric } 860349cc55cSDimitry Andric } else { 861349cc55cSDimitry Andric // Non-empty, non-stack slot, must be a plain register. 862349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 863349cc55cSDimitry Andric MIB.addReg(LocID); 864349cc55cSDimitry Andric if (Properties.Indirect) 865349cc55cSDimitry Andric MIB.addImm(0); 866349cc55cSDimitry Andric else 867349cc55cSDimitry Andric MIB.addReg(0); 868349cc55cSDimitry Andric } 869e8d8bef9SDimitry Andric 870349cc55cSDimitry Andric MIB.addMetadata(Var.getVariable()); 871349cc55cSDimitry Andric MIB.addMetadata(Expr); 872349cc55cSDimitry Andric return MIB; 873349cc55cSDimitry Andric } 874e8d8bef9SDimitry Andric 875e8d8bef9SDimitry Andric /// Default construct and initialize the pass. 876349cc55cSDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() {} 877e8d8bef9SDimitry Andric 878349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const { 879e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 880e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 881e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 882e8d8bef9SDimitry Andric return true; 883e8d8bef9SDimitry Andric return false; 884e8d8bef9SDimitry Andric } 885e8d8bef9SDimitry Andric 886e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 887e8d8bef9SDimitry Andric // Debug Range Extension Implementation 888e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 889e8d8bef9SDimitry Andric 890e8d8bef9SDimitry Andric #ifndef NDEBUG 891e8d8bef9SDimitry Andric // Something to restore in the future. 892e8d8bef9SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..) 893e8d8bef9SDimitry Andric #endif 894e8d8bef9SDimitry Andric 895349cc55cSDimitry Andric SpillLocationNo 896e8d8bef9SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 897e8d8bef9SDimitry Andric assert(MI.hasOneMemOperand() && 898e8d8bef9SDimitry Andric "Spill instruction does not have exactly one memory operand?"); 899e8d8bef9SDimitry Andric auto MMOI = MI.memoperands_begin(); 900e8d8bef9SDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 901e8d8bef9SDimitry Andric assert(PVal->kind() == PseudoSourceValue::FixedStack && 902e8d8bef9SDimitry Andric "Inconsistent memory operand in spill instruction"); 903e8d8bef9SDimitry Andric int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 904e8d8bef9SDimitry Andric const MachineBasicBlock *MBB = MI.getParent(); 905e8d8bef9SDimitry Andric Register Reg; 906e8d8bef9SDimitry Andric StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 907349cc55cSDimitry Andric return MTracker->getOrTrackSpillLoc({Reg, Offset}); 908349cc55cSDimitry Andric } 909349cc55cSDimitry Andric 910349cc55cSDimitry Andric Optional<LocIdx> InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) { 911349cc55cSDimitry Andric SpillLocationNo SpillLoc = extractSpillBaseRegAndOffset(MI); 912349cc55cSDimitry Andric 913349cc55cSDimitry Andric // Where in the stack slot is this value defined -- i.e., what size of value 914349cc55cSDimitry Andric // is this? An important question, because it could be loaded into a register 915349cc55cSDimitry Andric // from the stack at some point. Happily the memory operand will tell us 916349cc55cSDimitry Andric // the size written to the stack. 917349cc55cSDimitry Andric auto *MemOperand = *MI.memoperands_begin(); 918349cc55cSDimitry Andric unsigned SizeInBits = MemOperand->getSizeInBits(); 919349cc55cSDimitry Andric 920349cc55cSDimitry Andric // Find that position in the stack indexes we're tracking. 921349cc55cSDimitry Andric auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0}); 922349cc55cSDimitry Andric if (IdxIt == MTracker->StackSlotIdxes.end()) 923349cc55cSDimitry Andric // That index is not tracked. This is suprising, and unlikely to ever 924349cc55cSDimitry Andric // occur, but the safe action is to indicate the variable is optimised out. 925349cc55cSDimitry Andric return None; 926349cc55cSDimitry Andric 927349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(SpillLoc, IdxIt->second); 928349cc55cSDimitry Andric return MTracker->getSpillMLoc(SpillID); 929e8d8bef9SDimitry Andric } 930e8d8bef9SDimitry Andric 931e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI 932e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr. 933e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { 934e8d8bef9SDimitry Andric if (!MI.isDebugValue()) 935e8d8bef9SDimitry Andric return false; 936e8d8bef9SDimitry Andric 937e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 938e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 939e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 940e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 941e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 942e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 943e8d8bef9SDimitry Andric 944e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 945e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 946e8d8bef9SDimitry Andric 947e8d8bef9SDimitry Andric // If there are no instructions in this lexical scope, do no location tracking 948e8d8bef9SDimitry Andric // at all, this variable shouldn't get a legitimate location range. 949e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 950e8d8bef9SDimitry Andric if (Scope == nullptr) 951e8d8bef9SDimitry Andric return true; // handled it; by doing nothing 952e8d8bef9SDimitry Andric 953349cc55cSDimitry Andric // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to 954349cc55cSDimitry Andric // contribute to locations in this block, but don't propagate further. 955349cc55cSDimitry Andric // Interpret it like a DBG_VALUE $noreg. 956349cc55cSDimitry Andric if (MI.isDebugValueList()) { 957349cc55cSDimitry Andric if (VTracker) 958349cc55cSDimitry Andric VTracker->defVar(MI, Properties, None); 959349cc55cSDimitry Andric if (TTracker) 960349cc55cSDimitry Andric TTracker->redefVar(MI, Properties, None); 961349cc55cSDimitry Andric return true; 962349cc55cSDimitry Andric } 963349cc55cSDimitry Andric 964e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 965e8d8bef9SDimitry Andric 966e8d8bef9SDimitry Andric // MLocTracker needs to know that this register is read, even if it's only 967e8d8bef9SDimitry Andric // read by a debug inst. 968e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg() != 0) 969e8d8bef9SDimitry Andric (void)MTracker->readReg(MO.getReg()); 970e8d8bef9SDimitry Andric 971e8d8bef9SDimitry Andric // If we're preparing for the second analysis (variables), the machine value 972e8d8bef9SDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value 973e8d8bef9SDimitry Andric // it refers to to VLocTracker. 974e8d8bef9SDimitry Andric if (VTracker) { 975e8d8bef9SDimitry Andric if (MO.isReg()) { 976e8d8bef9SDimitry Andric // Feed defVar the new variable location, or if this is a 977e8d8bef9SDimitry Andric // DBG_VALUE $noreg, feed defVar None. 978e8d8bef9SDimitry Andric if (MO.getReg()) 979e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); 980e8d8bef9SDimitry Andric else 981e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, None); 982e8d8bef9SDimitry Andric } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || 983e8d8bef9SDimitry Andric MI.getOperand(0).isCImm()) { 984e8d8bef9SDimitry Andric VTracker->defVar(MI, MI.getOperand(0)); 985e8d8bef9SDimitry Andric } 986e8d8bef9SDimitry Andric } 987e8d8bef9SDimitry Andric 988e8d8bef9SDimitry Andric // If performing final tracking of transfers, report this variable definition 989e8d8bef9SDimitry Andric // to the TransferTracker too. 990e8d8bef9SDimitry Andric if (TTracker) 991e8d8bef9SDimitry Andric TTracker->redefVar(MI); 992e8d8bef9SDimitry Andric return true; 993e8d8bef9SDimitry Andric } 994e8d8bef9SDimitry Andric 995fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, 996fe6060f1SDimitry Andric ValueIDNum **MLiveOuts, 997fe6060f1SDimitry Andric ValueIDNum **MLiveIns) { 998e8d8bef9SDimitry Andric if (!MI.isDebugRef()) 999e8d8bef9SDimitry Andric return false; 1000e8d8bef9SDimitry Andric 1001e8d8bef9SDimitry Andric // Only handle this instruction when we are building the variable value 1002e8d8bef9SDimitry Andric // transfer function. 1003e8d8bef9SDimitry Andric if (!VTracker) 1004e8d8bef9SDimitry Andric return false; 1005e8d8bef9SDimitry Andric 1006e8d8bef9SDimitry Andric unsigned InstNo = MI.getOperand(0).getImm(); 1007e8d8bef9SDimitry Andric unsigned OpNo = MI.getOperand(1).getImm(); 1008e8d8bef9SDimitry Andric 1009e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 1010e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 1011e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 1012e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1013e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1014e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 1015e8d8bef9SDimitry Andric 1016e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 1017e8d8bef9SDimitry Andric 1018e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1019e8d8bef9SDimitry Andric if (Scope == nullptr) 1020e8d8bef9SDimitry Andric return true; // Handled by doing nothing. This variable is never in scope. 1021e8d8bef9SDimitry Andric 1022e8d8bef9SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent(); 1023e8d8bef9SDimitry Andric 1024e8d8bef9SDimitry Andric // Various optimizations may have happened to the value during codegen, 1025e8d8bef9SDimitry Andric // recorded in the value substitution table. Apply any substitutions to 1026fe6060f1SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect 1027fe6060f1SDimitry Andric // any subregister extractions performed during optimization. 1028fe6060f1SDimitry Andric 1029fe6060f1SDimitry Andric // Create dummy substitution with Src set, for lookup. 1030fe6060f1SDimitry Andric auto SoughtSub = 1031fe6060f1SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0); 1032fe6060f1SDimitry Andric 1033fe6060f1SDimitry Andric SmallVector<unsigned, 4> SeenSubregs; 1034fe6060f1SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1035fe6060f1SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() && 1036fe6060f1SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) { 1037fe6060f1SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest; 1038fe6060f1SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest; 1039fe6060f1SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg) 1040fe6060f1SDimitry Andric SeenSubregs.push_back(Subreg); 1041fe6060f1SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1042e8d8bef9SDimitry Andric } 1043e8d8bef9SDimitry Andric 1044e8d8bef9SDimitry Andric // Default machine value number is <None> -- if no instruction defines 1045e8d8bef9SDimitry Andric // the corresponding value, it must have been optimized out. 1046e8d8bef9SDimitry Andric Optional<ValueIDNum> NewID = None; 1047e8d8bef9SDimitry Andric 1048e8d8bef9SDimitry Andric // Try to lookup the instruction number, and find the machine value number 1049fe6060f1SDimitry Andric // that it defines. It could be an instruction, or a PHI. 1050e8d8bef9SDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo); 1051fe6060f1SDimitry Andric auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), 1052fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstNo); 1053e8d8bef9SDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) { 1054e8d8bef9SDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first; 1055e8d8bef9SDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber(); 1056e8d8bef9SDimitry Andric 1057349cc55cSDimitry Andric // Pick out the designated operand. It might be a memory reference, if 1058349cc55cSDimitry Andric // a register def was folded into a stack store. 1059349cc55cSDimitry Andric if (OpNo == MachineFunction::DebugOperandMemNumber && 1060349cc55cSDimitry Andric TargetInstr.hasOneMemOperand()) { 1061349cc55cSDimitry Andric Optional<LocIdx> L = findLocationForMemOperand(TargetInstr); 1062349cc55cSDimitry Andric if (L) 1063349cc55cSDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L); 1064349cc55cSDimitry Andric } else if (OpNo != MachineFunction::DebugOperandMemNumber) { 1065e8d8bef9SDimitry Andric assert(OpNo < TargetInstr.getNumOperands()); 1066e8d8bef9SDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo); 1067e8d8bef9SDimitry Andric 1068e8d8bef9SDimitry Andric // Today, this can only be a register. 1069e8d8bef9SDimitry Andric assert(MO.isReg() && MO.isDef()); 1070e8d8bef9SDimitry Andric 1071349cc55cSDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg()); 1072e8d8bef9SDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID]; 1073e8d8bef9SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); 1074349cc55cSDimitry Andric } 1075349cc55cSDimitry Andric // else: NewID is left as None. 1076fe6060f1SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { 1077fe6060f1SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use 1078fe6060f1SDimitry Andric // the resolver helper to find out. 1079fe6060f1SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, 1080fe6060f1SDimitry Andric MI, InstNo); 1081fe6060f1SDimitry Andric } 1082fe6060f1SDimitry Andric 1083fe6060f1SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code 1084fe6060f1SDimitry Andric // like this: 1085fe6060f1SDimitry Andric // CALL64 @foo, implicit-def $rax 1086fe6060f1SDimitry Andric // %0:gr64 = COPY $rax 1087fe6060f1SDimitry Andric // %1:gr32 = COPY %0.sub_32bit 1088fe6060f1SDimitry Andric // %2:gr16 = COPY %1.sub_16bit 1089fe6060f1SDimitry Andric // %3:gr8 = COPY %2.sub_8bit 1090fe6060f1SDimitry Andric // In which case each copy would have been recorded as a substitution with 1091fe6060f1SDimitry Andric // a subregister qualifier. Apply those qualifiers now. 1092fe6060f1SDimitry Andric if (NewID && !SeenSubregs.empty()) { 1093fe6060f1SDimitry Andric unsigned Offset = 0; 1094fe6060f1SDimitry Andric unsigned Size = 0; 1095fe6060f1SDimitry Andric 1096fe6060f1SDimitry Andric // Look at each subregister that we passed through, and progressively 1097fe6060f1SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should 1098fe6060f1SDimitry Andric // only ever be the same or narrower width than what they read from; 1099fe6060f1SDimitry Andric // iterate in reverse order so that we go from wide to small. 1100fe6060f1SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) { 1101fe6060f1SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg); 1102fe6060f1SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg); 1103fe6060f1SDimitry Andric Offset += ThisOffset; 1104fe6060f1SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize); 1105fe6060f1SDimitry Andric } 1106fe6060f1SDimitry Andric 1107fe6060f1SDimitry Andric // If that worked, look for an appropriate subregister with the register 1108fe6060f1SDimitry Andric // where the define happens. Don't look at values that were defined during 1109fe6060f1SDimitry Andric // a stack write: we can't currently express register locations within 1110fe6060f1SDimitry Andric // spills. 1111fe6060f1SDimitry Andric LocIdx L = NewID->getLoc(); 1112fe6060f1SDimitry Andric if (NewID && !MTracker->isSpill(L)) { 1113fe6060f1SDimitry Andric // Find the register class for the register where this def happened. 1114fe6060f1SDimitry Andric // FIXME: no index for this? 1115fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L]; 1116fe6060f1SDimitry Andric const TargetRegisterClass *TRC = nullptr; 1117fe6060f1SDimitry Andric for (auto *TRCI : TRI->regclasses()) 1118fe6060f1SDimitry Andric if (TRCI->contains(Reg)) 1119fe6060f1SDimitry Andric TRC = TRCI; 1120fe6060f1SDimitry Andric assert(TRC && "Couldn't find target register class?"); 1121fe6060f1SDimitry Andric 1122fe6060f1SDimitry Andric // If the register we have isn't the right size or in the right place, 1123fe6060f1SDimitry Andric // Try to find a subregister inside it. 1124fe6060f1SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC); 1125fe6060f1SDimitry Andric if (Size != MainRegSize || Offset) { 1126fe6060f1SDimitry Andric // Enumerate all subregisters, searching. 1127fe6060f1SDimitry Andric Register NewReg = 0; 1128fe6060f1SDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1129fe6060f1SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1130fe6060f1SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg); 1131fe6060f1SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg); 1132fe6060f1SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) { 1133fe6060f1SDimitry Andric NewReg = *SRI; 1134fe6060f1SDimitry Andric break; 1135fe6060f1SDimitry Andric } 1136fe6060f1SDimitry Andric } 1137fe6060f1SDimitry Andric 1138fe6060f1SDimitry Andric // If we didn't find anything: there's no way to express our value. 1139fe6060f1SDimitry Andric if (!NewReg) { 1140fe6060f1SDimitry Andric NewID = None; 1141fe6060f1SDimitry Andric } else { 1142fe6060f1SDimitry Andric // Re-state the value as being defined within the subregister 1143fe6060f1SDimitry Andric // that we found. 1144fe6060f1SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg); 1145fe6060f1SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc); 1146fe6060f1SDimitry Andric } 1147fe6060f1SDimitry Andric } 1148fe6060f1SDimitry Andric } else { 1149fe6060f1SDimitry Andric // If we can't handle subregisters, unset the new value. 1150fe6060f1SDimitry Andric NewID = None; 1151fe6060f1SDimitry Andric } 1152e8d8bef9SDimitry Andric } 1153e8d8bef9SDimitry Andric 1154e8d8bef9SDimitry Andric // We, we have a value number or None. Tell the variable value tracker about 1155e8d8bef9SDimitry Andric // it. The rest of this LiveDebugValues implementation acts exactly the same 1156e8d8bef9SDimitry Andric // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that 1157e8d8bef9SDimitry Andric // aren't immediately available). 1158e8d8bef9SDimitry Andric DbgValueProperties Properties(Expr, false); 1159e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, NewID); 1160e8d8bef9SDimitry Andric 1161e8d8bef9SDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF 1162e8d8bef9SDimitry Andric // into a plain DBG_VALUE. 1163e8d8bef9SDimitry Andric if (!TTracker) 1164e8d8bef9SDimitry Andric return true; 1165e8d8bef9SDimitry Andric 1166e8d8bef9SDimitry Andric // Pick a location for the machine value number, if such a location exists. 1167e8d8bef9SDimitry Andric // (This information could be stored in TransferTracker to make it faster). 1168e8d8bef9SDimitry Andric Optional<LocIdx> FoundLoc = None; 1169e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1170e8d8bef9SDimitry Andric LocIdx CurL = Location.Idx; 1171349cc55cSDimitry Andric ValueIDNum ID = MTracker->readMLoc(CurL); 1172e8d8bef9SDimitry Andric if (NewID && ID == NewID) { 1173e8d8bef9SDimitry Andric // If this is the first location with that value, pick it. Otherwise, 1174e8d8bef9SDimitry Andric // consider whether it's a "longer term" location. 1175e8d8bef9SDimitry Andric if (!FoundLoc) { 1176e8d8bef9SDimitry Andric FoundLoc = CurL; 1177e8d8bef9SDimitry Andric continue; 1178e8d8bef9SDimitry Andric } 1179e8d8bef9SDimitry Andric 1180e8d8bef9SDimitry Andric if (MTracker->isSpill(CurL)) 1181e8d8bef9SDimitry Andric FoundLoc = CurL; // Spills are a longer term location. 1182e8d8bef9SDimitry Andric else if (!MTracker->isSpill(*FoundLoc) && 1183e8d8bef9SDimitry Andric !MTracker->isSpill(CurL) && 1184e8d8bef9SDimitry Andric !isCalleeSaved(*FoundLoc) && 1185e8d8bef9SDimitry Andric isCalleeSaved(CurL)) 1186e8d8bef9SDimitry Andric FoundLoc = CurL; // Callee saved regs are longer term than normal. 1187e8d8bef9SDimitry Andric } 1188e8d8bef9SDimitry Andric } 1189e8d8bef9SDimitry Andric 1190e8d8bef9SDimitry Andric // Tell transfer tracker that the variable value has changed. 1191e8d8bef9SDimitry Andric TTracker->redefVar(MI, Properties, FoundLoc); 1192e8d8bef9SDimitry Andric 1193e8d8bef9SDimitry Andric // If there was a value with no location; but the value is defined in a 1194e8d8bef9SDimitry Andric // later instruction in this block, this is a block-local use-before-def. 1195e8d8bef9SDimitry Andric if (!FoundLoc && NewID && NewID->getBlock() == CurBB && 1196e8d8bef9SDimitry Andric NewID->getInst() > CurInst) 1197e8d8bef9SDimitry Andric TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); 1198e8d8bef9SDimitry Andric 1199e8d8bef9SDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. 1200e8d8bef9SDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if 1201e8d8bef9SDimitry Andric // FoundLoc is None. 1202e8d8bef9SDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future). 1203e8d8bef9SDimitry Andric MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); 1204e8d8bef9SDimitry Andric TTracker->PendingDbgValues.push_back(DbgMI); 1205e8d8bef9SDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr); 1206fe6060f1SDimitry Andric return true; 1207fe6060f1SDimitry Andric } 1208fe6060f1SDimitry Andric 1209fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { 1210fe6060f1SDimitry Andric if (!MI.isDebugPHI()) 1211fe6060f1SDimitry Andric return false; 1212fe6060f1SDimitry Andric 1213fe6060f1SDimitry Andric // Analyse these only when solving the machine value location problem. 1214fe6060f1SDimitry Andric if (VTracker || TTracker) 1215fe6060f1SDimitry Andric return true; 1216fe6060f1SDimitry Andric 1217fe6060f1SDimitry Andric // First operand is the value location, either a stack slot or register. 1218fe6060f1SDimitry Andric // Second is the debug instruction number of the original PHI. 1219fe6060f1SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 1220fe6060f1SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm(); 1221fe6060f1SDimitry Andric 1222fe6060f1SDimitry Andric if (MO.isReg()) { 1223fe6060f1SDimitry Andric // The value is whatever's currently in the register. Read and record it, 1224fe6060f1SDimitry Andric // to be analysed later. 1225fe6060f1SDimitry Andric Register Reg = MO.getReg(); 1226fe6060f1SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg); 1227fe6060f1SDimitry Andric auto PHIRec = DebugPHIRecord( 1228fe6060f1SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); 1229fe6060f1SDimitry Andric DebugPHINumToValue.push_back(PHIRec); 1230349cc55cSDimitry Andric 1231349cc55cSDimitry Andric // Ensure this register is tracked. 1232349cc55cSDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1233349cc55cSDimitry Andric MTracker->lookupOrTrackRegister(*RAI); 1234fe6060f1SDimitry Andric } else { 1235fe6060f1SDimitry Andric // The value is whatever's in this stack slot. 1236fe6060f1SDimitry Andric assert(MO.isFI()); 1237fe6060f1SDimitry Andric unsigned FI = MO.getIndex(); 1238fe6060f1SDimitry Andric 1239fe6060f1SDimitry Andric // If the stack slot is dead, then this was optimized away. 1240fe6060f1SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged. 1241fe6060f1SDimitry Andric if (MFI->isDeadObjectIndex(FI)) 1242fe6060f1SDimitry Andric return true; 1243fe6060f1SDimitry Andric 1244349cc55cSDimitry Andric // Identify this spill slot, ensure it's tracked. 1245fe6060f1SDimitry Andric Register Base; 1246fe6060f1SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); 1247fe6060f1SDimitry Andric SpillLoc SL = {Base, Offs}; 1248349cc55cSDimitry Andric SpillLocationNo SpillNo = MTracker->getOrTrackSpillLoc(SL); 1249fe6060f1SDimitry Andric 1250349cc55cSDimitry Andric // Problem: what value should we extract from the stack? LLVM does not 1251349cc55cSDimitry Andric // record what size the last store to the slot was, and it would become 1252349cc55cSDimitry Andric // sketchy after stack slot colouring anyway. Take a look at what values 1253349cc55cSDimitry Andric // are stored on the stack, and pick the largest one that wasn't def'd 1254349cc55cSDimitry Andric // by a spill (i.e., the value most likely to have been def'd in a register 1255349cc55cSDimitry Andric // and then spilt. 1256349cc55cSDimitry Andric std::array<unsigned, 4> CandidateSizes = {64, 32, 16, 8}; 1257349cc55cSDimitry Andric Optional<ValueIDNum> Result = None; 1258349cc55cSDimitry Andric Optional<LocIdx> SpillLoc = None; 12590eae32dcSDimitry Andric for (unsigned CS : CandidateSizes) { 12600eae32dcSDimitry Andric unsigned SpillID = MTracker->getLocID(SpillNo, {CS, 0}); 1261349cc55cSDimitry Andric SpillLoc = MTracker->getSpillMLoc(SpillID); 1262349cc55cSDimitry Andric ValueIDNum Val = MTracker->readMLoc(*SpillLoc); 1263349cc55cSDimitry Andric // If this value was defined in it's own position, then it was probably 1264349cc55cSDimitry Andric // an aliasing index of a small value that was spilt. 1265349cc55cSDimitry Andric if (Val.getLoc() != SpillLoc->asU64()) { 1266349cc55cSDimitry Andric Result = Val; 1267349cc55cSDimitry Andric break; 1268349cc55cSDimitry Andric } 1269349cc55cSDimitry Andric } 1270349cc55cSDimitry Andric 1271349cc55cSDimitry Andric // If we didn't find anything, we're probably looking at a PHI, or a memory 1272349cc55cSDimitry Andric // store folded into an instruction. FIXME: Take a guess that's it's 64 1273349cc55cSDimitry Andric // bits. This isn't ideal, but tracking the size that the spill is 1274349cc55cSDimitry Andric // "supposed" to be is more complex, and benefits a small number of 1275349cc55cSDimitry Andric // locations. 1276349cc55cSDimitry Andric if (!Result) { 1277349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(SpillNo, {64, 0}); 1278349cc55cSDimitry Andric SpillLoc = MTracker->getSpillMLoc(SpillID); 1279349cc55cSDimitry Andric Result = MTracker->readMLoc(*SpillLoc); 1280349cc55cSDimitry Andric } 1281fe6060f1SDimitry Andric 1282fe6060f1SDimitry Andric // Record this DBG_PHI for later analysis. 1283349cc55cSDimitry Andric auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), *Result, *SpillLoc}); 1284fe6060f1SDimitry Andric DebugPHINumToValue.push_back(DbgPHI); 1285fe6060f1SDimitry Andric } 1286e8d8bef9SDimitry Andric 1287e8d8bef9SDimitry Andric return true; 1288e8d8bef9SDimitry Andric } 1289e8d8bef9SDimitry Andric 1290e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { 1291e8d8bef9SDimitry Andric // Meta Instructions do not affect the debug liveness of any register they 1292e8d8bef9SDimitry Andric // define. 1293e8d8bef9SDimitry Andric if (MI.isImplicitDef()) { 1294e8d8bef9SDimitry Andric // Except when there's an implicit def, and the location it's defining has 1295e8d8bef9SDimitry Andric // no value number. The whole point of an implicit def is to announce that 1296e8d8bef9SDimitry Andric // the register is live, without be specific about it's value. So define 1297e8d8bef9SDimitry Andric // a value if there isn't one already. 1298e8d8bef9SDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); 1299e8d8bef9SDimitry Andric // Has a legitimate value -> ignore the implicit def. 1300e8d8bef9SDimitry Andric if (Num.getLoc() != 0) 1301e8d8bef9SDimitry Andric return; 1302e8d8bef9SDimitry Andric // Otherwise, def it here. 1303e8d8bef9SDimitry Andric } else if (MI.isMetaInstruction()) 1304e8d8bef9SDimitry Andric return; 1305e8d8bef9SDimitry Andric 13064824e7fdSDimitry Andric // We always ignore SP defines on call instructions, they don't actually 13074824e7fdSDimitry Andric // change the value of the stack pointer... except for win32's _chkstk. This 13084824e7fdSDimitry Andric // is rare: filter quickly for the common case (no stack adjustments, not a 13094824e7fdSDimitry Andric // call, etc). If it is a call that modifies SP, recognise the SP register 13104824e7fdSDimitry Andric // defs. 13114824e7fdSDimitry Andric bool CallChangesSP = false; 13124824e7fdSDimitry Andric if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() && 13134824e7fdSDimitry Andric !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data())) 13144824e7fdSDimitry Andric CallChangesSP = true; 13154824e7fdSDimitry Andric 13164824e7fdSDimitry Andric // Test whether we should ignore a def of this register due to it being part 13174824e7fdSDimitry Andric // of the stack pointer. 13184824e7fdSDimitry Andric auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool { 13194824e7fdSDimitry Andric if (CallChangesSP) 13204824e7fdSDimitry Andric return false; 13214824e7fdSDimitry Andric return MI.isCall() && MTracker->SPAliases.count(R); 13224824e7fdSDimitry Andric }; 13234824e7fdSDimitry Andric 1324e8d8bef9SDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs. 1325e8d8bef9SDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this 1326e8d8bef9SDimitry Andric // prevents fallback to std::set::count() operations. 1327e8d8bef9SDimitry Andric SmallSet<uint32_t, 32> DeadRegs; 1328e8d8bef9SDimitry Andric SmallVector<const uint32_t *, 4> RegMasks; 1329e8d8bef9SDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs; 1330e8d8bef9SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1331e8d8bef9SDimitry Andric // Determine whether the operand is a register def. 1332e8d8bef9SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() && 1333e8d8bef9SDimitry Andric Register::isPhysicalRegister(MO.getReg()) && 13344824e7fdSDimitry Andric !IgnoreSPAlias(MO.getReg())) { 1335e8d8bef9SDimitry Andric // Remove ranges of all aliased registers. 1336e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1337e8d8bef9SDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs? 1338e8d8bef9SDimitry Andric DeadRegs.insert(*RAI); 1339e8d8bef9SDimitry Andric } else if (MO.isRegMask()) { 1340e8d8bef9SDimitry Andric RegMasks.push_back(MO.getRegMask()); 1341e8d8bef9SDimitry Andric RegMaskPtrs.push_back(&MO); 1342e8d8bef9SDimitry Andric } 1343e8d8bef9SDimitry Andric } 1344e8d8bef9SDimitry Andric 1345e8d8bef9SDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise. 1346e8d8bef9SDimitry Andric for (uint32_t DeadReg : DeadRegs) 1347e8d8bef9SDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst); 1348e8d8bef9SDimitry Andric 1349e8d8bef9SDimitry Andric for (auto *MO : RegMaskPtrs) 1350e8d8bef9SDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst); 1351fe6060f1SDimitry Andric 1352349cc55cSDimitry Andric // If this instruction writes to a spill slot, def that slot. 1353349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1354349cc55cSDimitry Andric SpillLocationNo SpillNo = extractSpillBaseRegAndOffset(MI); 1355349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1356349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(SpillNo, I); 1357349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1358349cc55cSDimitry Andric MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L)); 1359349cc55cSDimitry Andric } 1360349cc55cSDimitry Andric } 1361349cc55cSDimitry Andric 1362fe6060f1SDimitry Andric if (!TTracker) 1363fe6060f1SDimitry Andric return; 1364fe6060f1SDimitry Andric 1365fe6060f1SDimitry Andric // When committing variable values to locations: tell transfer tracker that 1366fe6060f1SDimitry Andric // we've clobbered things. It may be able to recover the variable from a 1367fe6060f1SDimitry Andric // different location. 1368fe6060f1SDimitry Andric 1369fe6060f1SDimitry Andric // Inform TTracker about any direct clobbers. 1370fe6060f1SDimitry Andric for (uint32_t DeadReg : DeadRegs) { 1371fe6060f1SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); 1372fe6060f1SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false); 1373fe6060f1SDimitry Andric } 1374fe6060f1SDimitry Andric 1375fe6060f1SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations 1376fe6060f1SDimitry Andric // that are actually being tracked. 1377fe6060f1SDimitry Andric for (auto L : MTracker->locations()) { 1378fe6060f1SDimitry Andric // Stack locations can't be clobbered by regmasks. 1379fe6060f1SDimitry Andric if (MTracker->isSpill(L.Idx)) 1380fe6060f1SDimitry Andric continue; 1381fe6060f1SDimitry Andric 1382fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx]; 13834824e7fdSDimitry Andric if (IgnoreSPAlias(Reg)) 13844824e7fdSDimitry Andric continue; 13854824e7fdSDimitry Andric 1386fe6060f1SDimitry Andric for (auto *MO : RegMaskPtrs) 1387fe6060f1SDimitry Andric if (MO->clobbersPhysReg(Reg)) 1388fe6060f1SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false); 1389fe6060f1SDimitry Andric } 1390349cc55cSDimitry Andric 1391349cc55cSDimitry Andric // Tell TTracker about any folded stack store. 1392349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1393349cc55cSDimitry Andric SpillLocationNo SpillNo = extractSpillBaseRegAndOffset(MI); 1394349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1395349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(SpillNo, I); 1396349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1397349cc55cSDimitry Andric TTracker->clobberMloc(L, MI.getIterator(), true); 1398349cc55cSDimitry Andric } 1399349cc55cSDimitry Andric } 1400e8d8bef9SDimitry Andric } 1401e8d8bef9SDimitry Andric 1402e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { 1403349cc55cSDimitry Andric // In all circumstances, re-def all aliases. It's definitely a new value now. 1404349cc55cSDimitry Andric for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI) 1405349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1406e8d8bef9SDimitry Andric 1407349cc55cSDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); 1408e8d8bef9SDimitry Andric MTracker->setReg(DstRegNum, SrcValue); 1409e8d8bef9SDimitry Andric 1410349cc55cSDimitry Andric // Copy subregisters from one location to another. 1411e8d8bef9SDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { 1412e8d8bef9SDimitry Andric unsigned SrcSubReg = SRI.getSubReg(); 1413e8d8bef9SDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex(); 1414e8d8bef9SDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); 1415e8d8bef9SDimitry Andric if (!DstSubReg) 1416e8d8bef9SDimitry Andric continue; 1417e8d8bef9SDimitry Andric 1418e8d8bef9SDimitry Andric // Do copy. There are two matching subregisters, the source value should 1419e8d8bef9SDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked 1420e8d8bef9SDimitry Andric // yet. 1421349cc55cSDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet. Will read 1422349cc55cSDimitry Andric // mphi values if it wasn't tracked. 1423349cc55cSDimitry Andric LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg); 1424349cc55cSDimitry Andric LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg); 1425349cc55cSDimitry Andric (void)SrcL; 1426e8d8bef9SDimitry Andric (void)DstL; 1427349cc55cSDimitry Andric ValueIDNum CpyValue = MTracker->readReg(SrcSubReg); 1428e8d8bef9SDimitry Andric 1429e8d8bef9SDimitry Andric MTracker->setReg(DstSubReg, CpyValue); 1430e8d8bef9SDimitry Andric } 1431e8d8bef9SDimitry Andric } 1432e8d8bef9SDimitry Andric 1433e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, 1434e8d8bef9SDimitry Andric MachineFunction *MF) { 1435e8d8bef9SDimitry Andric // TODO: Handle multiple stores folded into one. 1436e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1437e8d8bef9SDimitry Andric return false; 1438e8d8bef9SDimitry Andric 1439349cc55cSDimitry Andric // Reject any memory operand that's aliased -- we can't guarantee its value. 1440349cc55cSDimitry Andric auto MMOI = MI.memoperands_begin(); 1441349cc55cSDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 1442349cc55cSDimitry Andric if (PVal->isAliased(MFI)) 1443349cc55cSDimitry Andric return false; 1444349cc55cSDimitry Andric 1445e8d8bef9SDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 1446e8d8bef9SDimitry Andric return false; // This is not a spill instruction, since no valid size was 1447e8d8bef9SDimitry Andric // returned from either function. 1448e8d8bef9SDimitry Andric 1449e8d8bef9SDimitry Andric return true; 1450e8d8bef9SDimitry Andric } 1451e8d8bef9SDimitry Andric 1452e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, 1453e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1454e8d8bef9SDimitry Andric if (!isSpillInstruction(MI, MF)) 1455e8d8bef9SDimitry Andric return false; 1456e8d8bef9SDimitry Andric 1457e8d8bef9SDimitry Andric int FI; 1458e8d8bef9SDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI); 1459e8d8bef9SDimitry Andric return Reg != 0; 1460e8d8bef9SDimitry Andric } 1461e8d8bef9SDimitry Andric 1462349cc55cSDimitry Andric Optional<SpillLocationNo> 1463e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, 1464e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1465e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1466e8d8bef9SDimitry Andric return None; 1467e8d8bef9SDimitry Andric 1468e8d8bef9SDimitry Andric // FIXME: Handle folded restore instructions with more than one memory 1469e8d8bef9SDimitry Andric // operand. 1470e8d8bef9SDimitry Andric if (MI.getRestoreSize(TII)) { 1471e8d8bef9SDimitry Andric Reg = MI.getOperand(0).getReg(); 1472e8d8bef9SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1473e8d8bef9SDimitry Andric } 1474e8d8bef9SDimitry Andric return None; 1475e8d8bef9SDimitry Andric } 1476e8d8bef9SDimitry Andric 1477e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { 1478e8d8bef9SDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location 1479e8d8bef9SDimitry Andric // limitations under the new model. Therefore, when comparing them, compare 1480e8d8bef9SDimitry Andric // versions that don't attempt spills or restores at all. 1481e8d8bef9SDimitry Andric if (EmulateOldLDV) 1482e8d8bef9SDimitry Andric return false; 1483e8d8bef9SDimitry Andric 1484349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1485349cc55cSDimitry Andric // that can access the stack. 1486349cc55cSDimitry Andric int DummyFI = -1; 1487349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) && 1488349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, DummyFI)) 1489349cc55cSDimitry Andric return false; 1490349cc55cSDimitry Andric 1491e8d8bef9SDimitry Andric MachineFunction *MF = MI.getMF(); 1492e8d8bef9SDimitry Andric unsigned Reg; 1493e8d8bef9SDimitry Andric 1494e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 1495e8d8bef9SDimitry Andric 1496349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1497349cc55cSDimitry Andric // that can access the stack. 1498349cc55cSDimitry Andric int FIDummy; 1499349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) && 1500349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, FIDummy)) 1501349cc55cSDimitry Andric return false; 1502349cc55cSDimitry Andric 1503e8d8bef9SDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is 1504e8d8bef9SDimitry Andric // written to, terminate that variable location. The value in memory 1505e8d8bef9SDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. 1506e8d8bef9SDimitry Andric if (isSpillInstruction(MI, MF)) { 1507349cc55cSDimitry Andric SpillLocationNo Loc = extractSpillBaseRegAndOffset(MI); 1508e8d8bef9SDimitry Andric 1509349cc55cSDimitry Andric // Un-set this location and clobber, so that earlier locations don't 1510349cc55cSDimitry Andric // continue past this store. 1511349cc55cSDimitry Andric for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) { 1512349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Loc, SlotIdx); 1513349cc55cSDimitry Andric Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID); 1514349cc55cSDimitry Andric if (!MLoc) 1515349cc55cSDimitry Andric continue; 1516349cc55cSDimitry Andric 1517349cc55cSDimitry Andric // We need to over-write the stack slot with something (here, a def at 1518349cc55cSDimitry Andric // this instruction) to ensure no values are preserved in this stack slot 1519349cc55cSDimitry Andric // after the spill. It also prevents TTracker from trying to recover the 1520349cc55cSDimitry Andric // location and re-installing it in the same place. 1521349cc55cSDimitry Andric ValueIDNum Def(CurBB, CurInst, *MLoc); 1522349cc55cSDimitry Andric MTracker->setMLoc(*MLoc, Def); 1523349cc55cSDimitry Andric if (TTracker) 1524e8d8bef9SDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator()); 1525e8d8bef9SDimitry Andric } 1526e8d8bef9SDimitry Andric } 1527e8d8bef9SDimitry Andric 1528e8d8bef9SDimitry Andric // Try to recognise spill and restore instructions that may transfer a value. 1529e8d8bef9SDimitry Andric if (isLocationSpill(MI, MF, Reg)) { 1530349cc55cSDimitry Andric SpillLocationNo Loc = extractSpillBaseRegAndOffset(MI); 1531e8d8bef9SDimitry Andric 1532349cc55cSDimitry Andric auto DoTransfer = [&](Register SrcReg, unsigned SpillID) { 1533349cc55cSDimitry Andric auto ReadValue = MTracker->readReg(SrcReg); 1534349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getSpillMLoc(SpillID); 1535349cc55cSDimitry Andric MTracker->setMLoc(DstLoc, ReadValue); 1536e8d8bef9SDimitry Andric 1537349cc55cSDimitry Andric if (TTracker) { 1538349cc55cSDimitry Andric LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg); 1539349cc55cSDimitry Andric TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator()); 1540e8d8bef9SDimitry Andric } 1541349cc55cSDimitry Andric }; 1542349cc55cSDimitry Andric 1543349cc55cSDimitry Andric // Then, transfer subreg bits. 1544349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1545349cc55cSDimitry Andric // Ensure this reg is tracked, 1546349cc55cSDimitry Andric (void)MTracker->lookupOrTrackRegister(*SRI); 1547349cc55cSDimitry Andric unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI); 1548349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, SubregIdx); 1549349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1550349cc55cSDimitry Andric } 1551349cc55cSDimitry Andric 1552349cc55cSDimitry Andric // Directly lookup size of main source reg, and transfer. 1553349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1554349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); 1555349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1556349cc55cSDimitry Andric } else { 1557349cc55cSDimitry Andric Optional<SpillLocationNo> OptLoc = isRestoreInstruction(MI, MF, Reg); 1558349cc55cSDimitry Andric if (!OptLoc) 1559349cc55cSDimitry Andric return false; 1560349cc55cSDimitry Andric SpillLocationNo Loc = *OptLoc; 1561349cc55cSDimitry Andric 1562349cc55cSDimitry Andric // Assumption: we're reading from the base of the stack slot, not some 1563349cc55cSDimitry Andric // offset into it. It seems very unlikely LLVM would ever generate 1564349cc55cSDimitry Andric // restores where this wasn't true. This then becomes a question of what 1565349cc55cSDimitry Andric // subregisters in the destination register line up with positions in the 1566349cc55cSDimitry Andric // stack slot. 1567349cc55cSDimitry Andric 1568349cc55cSDimitry Andric // Def all registers that alias the destination. 1569349cc55cSDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1570349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1571349cc55cSDimitry Andric 1572349cc55cSDimitry Andric // Now find subregisters within the destination register, and load values 1573349cc55cSDimitry Andric // from stack slot positions. 1574349cc55cSDimitry Andric auto DoTransfer = [&](Register DestReg, unsigned SpillID) { 1575349cc55cSDimitry Andric LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID); 1576349cc55cSDimitry Andric auto ReadValue = MTracker->readMLoc(SrcIdx); 1577349cc55cSDimitry Andric MTracker->setReg(DestReg, ReadValue); 1578349cc55cSDimitry Andric 1579349cc55cSDimitry Andric if (TTracker) { 1580349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getRegMLoc(DestReg); 1581349cc55cSDimitry Andric TTracker->transferMlocs(SrcIdx, DstLoc, MI.getIterator()); 1582349cc55cSDimitry Andric } 1583349cc55cSDimitry Andric }; 1584349cc55cSDimitry Andric 1585349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1586349cc55cSDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1587349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, Subreg); 1588349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1589349cc55cSDimitry Andric } 1590349cc55cSDimitry Andric 1591349cc55cSDimitry Andric // Directly look up this registers slot idx by size, and transfer. 1592349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1593349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); 1594349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1595e8d8bef9SDimitry Andric } 1596e8d8bef9SDimitry Andric return true; 1597e8d8bef9SDimitry Andric } 1598e8d8bef9SDimitry Andric 1599e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { 1600e8d8bef9SDimitry Andric auto DestSrc = TII->isCopyInstr(MI); 1601e8d8bef9SDimitry Andric if (!DestSrc) 1602e8d8bef9SDimitry Andric return false; 1603e8d8bef9SDimitry Andric 1604e8d8bef9SDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination; 1605e8d8bef9SDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source; 1606e8d8bef9SDimitry Andric 1607e8d8bef9SDimitry Andric auto isCalleeSavedReg = [&](unsigned Reg) { 1608e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1609e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 1610e8d8bef9SDimitry Andric return true; 1611e8d8bef9SDimitry Andric return false; 1612e8d8bef9SDimitry Andric }; 1613e8d8bef9SDimitry Andric 1614e8d8bef9SDimitry Andric Register SrcReg = SrcRegOp->getReg(); 1615e8d8bef9SDimitry Andric Register DestReg = DestRegOp->getReg(); 1616e8d8bef9SDimitry Andric 1617e8d8bef9SDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues. 1618e8d8bef9SDimitry Andric if (SrcReg == DestReg) 1619e8d8bef9SDimitry Andric return true; 1620e8d8bef9SDimitry Andric 1621e8d8bef9SDimitry Andric // For emulating VarLocBasedImpl: 1622e8d8bef9SDimitry Andric // We want to recognize instructions where destination register is callee 1623e8d8bef9SDimitry Andric // saved register. If register that could be clobbered by the call is 1624e8d8bef9SDimitry Andric // included, there would be a great chance that it is going to be clobbered 1625e8d8bef9SDimitry Andric // soon. It is more likely that previous register, which is callee saved, is 1626e8d8bef9SDimitry Andric // going to stay unclobbered longer, even if it is killed. 1627e8d8bef9SDimitry Andric // 1628e8d8bef9SDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so 1629e8d8bef9SDimitry Andric // ignore this condition. 1630e8d8bef9SDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) 1631e8d8bef9SDimitry Andric return false; 1632e8d8bef9SDimitry Andric 1633e8d8bef9SDimitry Andric // InstrRefBasedImpl only followed killing copies. 1634e8d8bef9SDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill()) 1635e8d8bef9SDimitry Andric return false; 1636e8d8bef9SDimitry Andric 1637e8d8bef9SDimitry Andric // Copy MTracker info, including subregs if available. 1638e8d8bef9SDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg); 1639e8d8bef9SDimitry Andric 1640e8d8bef9SDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV 1641e8d8bef9SDimitry Andric // would have. We might make use of the additional value tracking in some 1642e8d8bef9SDimitry Andric // other way, later. 1643e8d8bef9SDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) 1644e8d8bef9SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), 1645e8d8bef9SDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator()); 1646e8d8bef9SDimitry Andric 1647e8d8bef9SDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying. 1648e8d8bef9SDimitry Andric if (EmulateOldLDV && SrcReg != DestReg) 1649e8d8bef9SDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst); 1650e8d8bef9SDimitry Andric 1651fe6060f1SDimitry Andric // Finally, the copy might have clobbered variables based on the destination 1652fe6060f1SDimitry Andric // register. Tell TTracker about it, in case a backup location exists. 1653fe6060f1SDimitry Andric if (TTracker) { 1654fe6060f1SDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { 1655fe6060f1SDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); 1656fe6060f1SDimitry Andric TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false); 1657fe6060f1SDimitry Andric } 1658fe6060f1SDimitry Andric } 1659fe6060f1SDimitry Andric 1660e8d8bef9SDimitry Andric return true; 1661e8d8bef9SDimitry Andric } 1662e8d8bef9SDimitry Andric 1663e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other 1664e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during 1665e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the 1666e8d8bef9SDimitry Andric /// known-to-overlap fragments are present". 16674824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for 1668e8d8bef9SDimitry Andric /// fragment usage. 1669e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { 16704824e7fdSDimitry Andric assert(MI.isDebugValue() || MI.isDebugRef()); 1671e8d8bef9SDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 1672e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 1673e8d8bef9SDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 1674e8d8bef9SDimitry Andric 1675e8d8bef9SDimitry Andric // If this is the first sighting of this variable, then we are guaranteed 1676e8d8bef9SDimitry Andric // there are currently no overlapping fragments either. Initialize the set 1677e8d8bef9SDimitry Andric // of seen fragments, record no overlaps for the current one, and return. 1678e8d8bef9SDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable()); 1679e8d8bef9SDimitry Andric if (SeenIt == SeenFragments.end()) { 1680e8d8bef9SDimitry Andric SmallSet<FragmentInfo, 4> OneFragment; 1681e8d8bef9SDimitry Andric OneFragment.insert(ThisFragment); 1682e8d8bef9SDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment}); 1683e8d8bef9SDimitry Andric 1684e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1685e8d8bef9SDimitry Andric return; 1686e8d8bef9SDimitry Andric } 1687e8d8bef9SDimitry Andric 1688e8d8bef9SDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap 1689e8d8bef9SDimitry Andric // map, it has already been accounted for. 1690e8d8bef9SDimitry Andric auto IsInOLapMap = 1691e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1692e8d8bef9SDimitry Andric if (!IsInOLapMap.second) 1693e8d8bef9SDimitry Andric return; 1694e8d8bef9SDimitry Andric 1695e8d8bef9SDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 1696e8d8bef9SDimitry Andric auto &AllSeenFragments = SeenIt->second; 1697e8d8bef9SDimitry Andric 1698e8d8bef9SDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this" 1699e8d8bef9SDimitry Andric // fragment being a previously unseen fragment. Record any pair of 1700e8d8bef9SDimitry Andric // overlapping fragments. 1701e8d8bef9SDimitry Andric for (auto &ASeenFragment : AllSeenFragments) { 1702e8d8bef9SDimitry Andric // Does this previously seen fragment overlap? 1703e8d8bef9SDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 1704e8d8bef9SDimitry Andric // Yes: Mark the current fragment as being overlapped. 1705e8d8bef9SDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment); 1706e8d8bef9SDimitry Andric // Mark the previously seen fragment as being overlapped by the current 1707e8d8bef9SDimitry Andric // one. 1708e8d8bef9SDimitry Andric auto ASeenFragmentsOverlaps = 1709e8d8bef9SDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); 1710e8d8bef9SDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() && 1711e8d8bef9SDimitry Andric "Previously seen var fragment has no vector of overlaps"); 1712e8d8bef9SDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment); 1713e8d8bef9SDimitry Andric } 1714e8d8bef9SDimitry Andric } 1715e8d8bef9SDimitry Andric 1716e8d8bef9SDimitry Andric AllSeenFragments.insert(ThisFragment); 1717e8d8bef9SDimitry Andric } 1718e8d8bef9SDimitry Andric 1719fe6060f1SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, ValueIDNum **MLiveOuts, 1720fe6060f1SDimitry Andric ValueIDNum **MLiveIns) { 1721e8d8bef9SDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's 1722e8d8bef9SDimitry Andric // none of these should we interpret it's register defs as new value 1723e8d8bef9SDimitry Andric // definitions. 1724e8d8bef9SDimitry Andric if (transferDebugValue(MI)) 1725e8d8bef9SDimitry Andric return; 1726fe6060f1SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) 1727fe6060f1SDimitry Andric return; 1728fe6060f1SDimitry Andric if (transferDebugPHI(MI)) 1729e8d8bef9SDimitry Andric return; 1730e8d8bef9SDimitry Andric if (transferRegisterCopy(MI)) 1731e8d8bef9SDimitry Andric return; 1732e8d8bef9SDimitry Andric if (transferSpillOrRestoreInst(MI)) 1733e8d8bef9SDimitry Andric return; 1734e8d8bef9SDimitry Andric transferRegisterDef(MI); 1735e8d8bef9SDimitry Andric } 1736e8d8bef9SDimitry Andric 1737e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction( 1738e8d8bef9SDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, 1739e8d8bef9SDimitry Andric unsigned MaxNumBlocks) { 1740e8d8bef9SDimitry Andric // Because we try to optimize around register mask operands by ignoring regs 1741e8d8bef9SDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask 1742e8d8bef9SDimitry Andric // operands that are seen earlier than the first use of a register, still need 1743e8d8bef9SDimitry Andric // to clobber that register in the transfer function. But this information 1744e8d8bef9SDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block, 1745e8d8bef9SDimitry Andric // and accumulated the clobbered but untracked registers in each block into 1746e8d8bef9SDimitry Andric // the following bitvector. Later, if new values are tracked, we can add 1747e8d8bef9SDimitry Andric // appropriate clobbers. 1748e8d8bef9SDimitry Andric SmallVector<BitVector, 32> BlockMasks; 1749e8d8bef9SDimitry Andric BlockMasks.resize(MaxNumBlocks); 1750e8d8bef9SDimitry Andric 1751e8d8bef9SDimitry Andric // Reserve one bit per register for the masks described above. 1752e8d8bef9SDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); 1753e8d8bef9SDimitry Andric for (auto &BV : BlockMasks) 1754e8d8bef9SDimitry Andric BV.resize(TRI->getNumRegs(), true); 1755e8d8bef9SDimitry Andric 1756e8d8bef9SDimitry Andric // Step through all instructions and inhale the transfer function. 1757e8d8bef9SDimitry Andric for (auto &MBB : MF) { 1758e8d8bef9SDimitry Andric // Object fields that are read by trackers to know where we are in the 1759e8d8bef9SDimitry Andric // function. 1760e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 1761e8d8bef9SDimitry Andric CurInst = 1; 1762e8d8bef9SDimitry Andric 1763e8d8bef9SDimitry Andric // Set all machine locations to a PHI value. For transfer function 1764e8d8bef9SDimitry Andric // production only, this signifies the live-in value to the block. 1765e8d8bef9SDimitry Andric MTracker->reset(); 1766e8d8bef9SDimitry Andric MTracker->setMPhis(CurBB); 1767e8d8bef9SDimitry Andric 1768e8d8bef9SDimitry Andric // Step through each instruction in this block. 1769e8d8bef9SDimitry Andric for (auto &MI : MBB) { 1770e8d8bef9SDimitry Andric process(MI); 1771e8d8bef9SDimitry Andric // Also accumulate fragment map. 17724824e7fdSDimitry Andric if (MI.isDebugValue() || MI.isDebugRef()) 1773e8d8bef9SDimitry Andric accumulateFragmentMap(MI); 1774e8d8bef9SDimitry Andric 1775e8d8bef9SDimitry Andric // Create a map from the instruction number (if present) to the 1776e8d8bef9SDimitry Andric // MachineInstr and its position. 1777e8d8bef9SDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 1778e8d8bef9SDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst); 1779e8d8bef9SDimitry Andric auto InsertResult = 1780e8d8bef9SDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 1781e8d8bef9SDimitry Andric 1782e8d8bef9SDimitry Andric // There should never be duplicate instruction numbers. 1783e8d8bef9SDimitry Andric assert(InsertResult.second); 1784e8d8bef9SDimitry Andric (void)InsertResult; 1785e8d8bef9SDimitry Andric } 1786e8d8bef9SDimitry Andric 1787e8d8bef9SDimitry Andric ++CurInst; 1788e8d8bef9SDimitry Andric } 1789e8d8bef9SDimitry Andric 1790e8d8bef9SDimitry Andric // Produce the transfer function, a map of machine location to new value. If 1791e8d8bef9SDimitry Andric // any machine location has the live-in phi value from the start of the 1792e8d8bef9SDimitry Andric // block, it's live-through and doesn't need recording in the transfer 1793e8d8bef9SDimitry Andric // function. 1794e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1795e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1796e8d8bef9SDimitry Andric ValueIDNum &P = Location.Value; 1797e8d8bef9SDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64()) 1798e8d8bef9SDimitry Andric continue; 1799e8d8bef9SDimitry Andric 1800e8d8bef9SDimitry Andric // Insert-or-update. 1801e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[CurBB]; 1802e8d8bef9SDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 1803e8d8bef9SDimitry Andric if (!Result.second) 1804e8d8bef9SDimitry Andric Result.first->second = P; 1805e8d8bef9SDimitry Andric } 1806e8d8bef9SDimitry Andric 1807e8d8bef9SDimitry Andric // Accumulate any bitmask operands into the clobberred reg mask for this 1808e8d8bef9SDimitry Andric // block. 1809e8d8bef9SDimitry Andric for (auto &P : MTracker->Masks) { 1810e8d8bef9SDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 1811e8d8bef9SDimitry Andric } 1812e8d8bef9SDimitry Andric } 1813e8d8bef9SDimitry Andric 1814e8d8bef9SDimitry Andric // Compute a bitvector of all the registers that are tracked in this block. 1815e8d8bef9SDimitry Andric BitVector UsedRegs(TRI->getNumRegs()); 1816e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1817e8d8bef9SDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 1818349cc55cSDimitry Andric // Ignore stack slots, and aliases of the stack pointer. 1819349cc55cSDimitry Andric if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) 1820e8d8bef9SDimitry Andric continue; 1821e8d8bef9SDimitry Andric UsedRegs.set(ID); 1822e8d8bef9SDimitry Andric } 1823e8d8bef9SDimitry Andric 1824e8d8bef9SDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not 1825e8d8bef9SDimitry Andric // live-through in the transfer function. It needs to be clobbered at the 1826e8d8bef9SDimitry Andric // very least. 1827e8d8bef9SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 1828e8d8bef9SDimitry Andric BitVector &BV = BlockMasks[I]; 1829e8d8bef9SDimitry Andric BV.flip(); 1830e8d8bef9SDimitry Andric BV &= UsedRegs; 1831e8d8bef9SDimitry Andric // This produces all the bits that we clobber, but also use. Check that 1832e8d8bef9SDimitry Andric // they're all clobbered or at least set in the designated transfer 1833e8d8bef9SDimitry Andric // elem. 1834e8d8bef9SDimitry Andric for (unsigned Bit : BV.set_bits()) { 1835349cc55cSDimitry Andric unsigned ID = MTracker->getLocID(Bit); 1836e8d8bef9SDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 1837e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[I]; 1838e8d8bef9SDimitry Andric 1839e8d8bef9SDimitry Andric // Install a value representing the fact that this location is effectively 1840e8d8bef9SDimitry Andric // written to in this block. As there's no reserved value, instead use 1841e8d8bef9SDimitry Andric // a value number that is never generated. Pick the value number for the 1842e8d8bef9SDimitry Andric // first instruction in the block, def'ing this location, which we know 1843e8d8bef9SDimitry Andric // this block never used anyway. 1844e8d8bef9SDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 1845e8d8bef9SDimitry Andric auto Result = 1846e8d8bef9SDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 1847e8d8bef9SDimitry Andric if (!Result.second) { 1848e8d8bef9SDimitry Andric ValueIDNum &ValueID = Result.first->second; 1849e8d8bef9SDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI()) 1850e8d8bef9SDimitry Andric // It was left as live-through. Set it to clobbered. 1851e8d8bef9SDimitry Andric ValueID = NotGeneratedNum; 1852e8d8bef9SDimitry Andric } 1853e8d8bef9SDimitry Andric } 1854e8d8bef9SDimitry Andric } 1855e8d8bef9SDimitry Andric } 1856e8d8bef9SDimitry Andric 1857349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin( 1858349cc55cSDimitry Andric MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1859e8d8bef9SDimitry Andric ValueIDNum **OutLocs, ValueIDNum *InLocs) { 1860e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1861e8d8bef9SDimitry Andric bool Changed = false; 1862e8d8bef9SDimitry Andric 1863349cc55cSDimitry Andric // Handle value-propagation when control flow merges on entry to a block. For 1864349cc55cSDimitry Andric // any location without a PHI already placed, the location has the same value 1865349cc55cSDimitry Andric // as its predecessors. If a PHI is placed, test to see whether it's now a 1866349cc55cSDimitry Andric // redundant PHI that we can eliminate. 1867349cc55cSDimitry Andric 1868e8d8bef9SDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders; 1869349cc55cSDimitry Andric for (auto Pred : MBB.predecessors()) 1870e8d8bef9SDimitry Andric BlockOrders.push_back(Pred); 1871e8d8bef9SDimitry Andric 1872e8d8bef9SDimitry Andric // Visit predecessors in RPOT order. 1873e8d8bef9SDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1874e8d8bef9SDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 1875e8d8bef9SDimitry Andric }; 1876e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 1877e8d8bef9SDimitry Andric 1878e8d8bef9SDimitry Andric // Skip entry block. 1879e8d8bef9SDimitry Andric if (BlockOrders.size() == 0) 1880349cc55cSDimitry Andric return false; 1881e8d8bef9SDimitry Andric 1882349cc55cSDimitry Andric // Step through all machine locations, look at each predecessor and test 1883349cc55cSDimitry Andric // whether we can eliminate redundant PHIs. 1884e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1885e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1886349cc55cSDimitry Andric 1887e8d8bef9SDimitry Andric // Pick out the first predecessors live-out value for this location. It's 1888349cc55cSDimitry Andric // guaranteed to not be a backedge, as we order by RPO. 1889349cc55cSDimitry Andric ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 1890e8d8bef9SDimitry Andric 1891349cc55cSDimitry Andric // If we've already eliminated a PHI here, do no further checking, just 1892349cc55cSDimitry Andric // propagate the first live-in value into this block. 1893349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { 1894349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != FirstVal) { 1895349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 1896349cc55cSDimitry Andric Changed |= true; 1897349cc55cSDimitry Andric } 1898349cc55cSDimitry Andric continue; 1899349cc55cSDimitry Andric } 1900349cc55cSDimitry Andric 1901349cc55cSDimitry Andric // We're now examining a PHI to see whether it's un-necessary. Loop around 1902349cc55cSDimitry Andric // the other live-in values and test whether they're all the same. 1903e8d8bef9SDimitry Andric bool Disagree = false; 1904e8d8bef9SDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 1905349cc55cSDimitry Andric const MachineBasicBlock *PredMBB = BlockOrders[I]; 1906349cc55cSDimitry Andric const ValueIDNum &PredLiveOut = 1907349cc55cSDimitry Andric OutLocs[PredMBB->getNumber()][Idx.asU64()]; 1908349cc55cSDimitry Andric 1909349cc55cSDimitry Andric // Incoming values agree, continue trying to eliminate this PHI. 1910349cc55cSDimitry Andric if (FirstVal == PredLiveOut) 1911349cc55cSDimitry Andric continue; 1912349cc55cSDimitry Andric 1913349cc55cSDimitry Andric // We can also accept a PHI value that feeds back into itself. 1914349cc55cSDimitry Andric if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) 1915349cc55cSDimitry Andric continue; 1916349cc55cSDimitry Andric 1917e8d8bef9SDimitry Andric // Live-out of a predecessor disagrees with the first predecessor. 1918e8d8bef9SDimitry Andric Disagree = true; 1919e8d8bef9SDimitry Andric } 1920e8d8bef9SDimitry Andric 1921349cc55cSDimitry Andric // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. 1922349cc55cSDimitry Andric if (!Disagree) { 1923349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 1924e8d8bef9SDimitry Andric Changed |= true; 1925e8d8bef9SDimitry Andric } 1926e8d8bef9SDimitry Andric } 1927e8d8bef9SDimitry Andric 1928e8d8bef9SDimitry Andric // TODO: Reimplement NumInserted and NumRemoved. 1929349cc55cSDimitry Andric return Changed; 1930e8d8bef9SDimitry Andric } 1931e8d8bef9SDimitry Andric 1932349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference( 1933349cc55cSDimitry Andric SmallVectorImpl<unsigned> &Slots) { 1934349cc55cSDimitry Andric // We could spend a bit of time finding the exact, minimal, set of stack 1935349cc55cSDimitry Andric // indexes that interfere with each other, much like reg units. Or, we can 1936349cc55cSDimitry Andric // rely on the fact that: 1937349cc55cSDimitry Andric // * The smallest / lowest index will interfere with everything at zero 1938349cc55cSDimitry Andric // offset, which will be the largest set of registers, 1939349cc55cSDimitry Andric // * Most indexes with non-zero offset will end up being interference units 1940349cc55cSDimitry Andric // anyway. 1941349cc55cSDimitry Andric // So just pick those out and return them. 1942349cc55cSDimitry Andric 1943349cc55cSDimitry Andric // We can rely on a single-byte stack index existing already, because we 1944349cc55cSDimitry Andric // initialize them in MLocTracker. 1945349cc55cSDimitry Andric auto It = MTracker->StackSlotIdxes.find({8, 0}); 1946349cc55cSDimitry Andric assert(It != MTracker->StackSlotIdxes.end()); 1947349cc55cSDimitry Andric Slots.push_back(It->second); 1948349cc55cSDimitry Andric 1949349cc55cSDimitry Andric // Find anything that has a non-zero offset and add that too. 1950349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 1951349cc55cSDimitry Andric // Is offset zero? If so, ignore. 1952349cc55cSDimitry Andric if (!Pair.first.second) 1953349cc55cSDimitry Andric continue; 1954349cc55cSDimitry Andric Slots.push_back(Pair.second); 1955349cc55cSDimitry Andric } 1956349cc55cSDimitry Andric } 1957349cc55cSDimitry Andric 1958349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs( 1959349cc55cSDimitry Andric MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 1960349cc55cSDimitry Andric ValueIDNum **MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 1961349cc55cSDimitry Andric SmallVector<unsigned, 4> StackUnits; 1962349cc55cSDimitry Andric findStackIndexInterference(StackUnits); 1963349cc55cSDimitry Andric 1964349cc55cSDimitry Andric // To avoid repeatedly running the PHI placement algorithm, leverage the 1965349cc55cSDimitry Andric // fact that a def of register MUST also def its register units. Find the 1966349cc55cSDimitry Andric // units for registers, place PHIs for them, and then replicate them for 1967349cc55cSDimitry Andric // aliasing registers. Some inputs that are never def'd (DBG_PHIs of 1968349cc55cSDimitry Andric // arguments) don't lead to register units being tracked, just place PHIs for 1969349cc55cSDimitry Andric // those registers directly. Stack slots have their own form of "unit", 1970349cc55cSDimitry Andric // store them to one side. 1971349cc55cSDimitry Andric SmallSet<Register, 32> RegUnitsToPHIUp; 1972349cc55cSDimitry Andric SmallSet<LocIdx, 32> NormalLocsToPHI; 1973349cc55cSDimitry Andric SmallSet<SpillLocationNo, 32> StackSlots; 1974349cc55cSDimitry Andric for (auto Location : MTracker->locations()) { 1975349cc55cSDimitry Andric LocIdx L = Location.Idx; 1976349cc55cSDimitry Andric if (MTracker->isSpill(L)) { 1977349cc55cSDimitry Andric StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); 1978349cc55cSDimitry Andric continue; 1979349cc55cSDimitry Andric } 1980349cc55cSDimitry Andric 1981349cc55cSDimitry Andric Register R = MTracker->LocIdxToLocID[L]; 1982349cc55cSDimitry Andric SmallSet<Register, 8> FoundRegUnits; 1983349cc55cSDimitry Andric bool AnyIllegal = false; 1984349cc55cSDimitry Andric for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { 1985349cc55cSDimitry Andric for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ 1986349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*URoot)) { 1987349cc55cSDimitry Andric // Not all roots were loaded into the tracking map: this register 1988349cc55cSDimitry Andric // isn't actually def'd anywhere, we only read from it. Generate PHIs 1989349cc55cSDimitry Andric // for this reg, but don't iterate units. 1990349cc55cSDimitry Andric AnyIllegal = true; 1991349cc55cSDimitry Andric } else { 1992349cc55cSDimitry Andric FoundRegUnits.insert(*URoot); 1993349cc55cSDimitry Andric } 1994349cc55cSDimitry Andric } 1995349cc55cSDimitry Andric } 1996349cc55cSDimitry Andric 1997349cc55cSDimitry Andric if (AnyIllegal) { 1998349cc55cSDimitry Andric NormalLocsToPHI.insert(L); 1999349cc55cSDimitry Andric continue; 2000349cc55cSDimitry Andric } 2001349cc55cSDimitry Andric 2002349cc55cSDimitry Andric RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); 2003349cc55cSDimitry Andric } 2004349cc55cSDimitry Andric 2005349cc55cSDimitry Andric // Lambda to fetch PHIs for a given location, and write into the PHIBlocks 2006349cc55cSDimitry Andric // collection. 2007349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2008349cc55cSDimitry Andric auto CollectPHIsForLoc = [&](LocIdx L) { 2009349cc55cSDimitry Andric // Collect the set of defs. 2010349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2011349cc55cSDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 2012349cc55cSDimitry Andric MachineBasicBlock *MBB = OrderToBB[I]; 2013349cc55cSDimitry Andric const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; 2014349cc55cSDimitry Andric if (TransferFunc.find(L) != TransferFunc.end()) 2015349cc55cSDimitry Andric DefBlocks.insert(MBB); 2016349cc55cSDimitry Andric } 2017349cc55cSDimitry Andric 2018349cc55cSDimitry Andric // The entry block defs the location too: it's the live-in / argument value. 2019349cc55cSDimitry Andric // Only insert if there are other defs though; everything is trivially live 2020349cc55cSDimitry Andric // through otherwise. 2021349cc55cSDimitry Andric if (!DefBlocks.empty()) 2022349cc55cSDimitry Andric DefBlocks.insert(&*MF.begin()); 2023349cc55cSDimitry Andric 2024349cc55cSDimitry Andric // Ask the SSA construction algorithm where we should put PHIs. Clear 2025349cc55cSDimitry Andric // anything that might have been hanging around from earlier. 2026349cc55cSDimitry Andric PHIBlocks.clear(); 2027349cc55cSDimitry Andric BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); 2028349cc55cSDimitry Andric }; 2029349cc55cSDimitry Andric 2030349cc55cSDimitry Andric auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { 2031349cc55cSDimitry Andric for (const MachineBasicBlock *MBB : PHIBlocks) 2032349cc55cSDimitry Andric MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); 2033349cc55cSDimitry Andric }; 2034349cc55cSDimitry Andric 2035349cc55cSDimitry Andric // For locations with no reg units, just place PHIs. 2036349cc55cSDimitry Andric for (LocIdx L : NormalLocsToPHI) { 2037349cc55cSDimitry Andric CollectPHIsForLoc(L); 2038349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2039349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2040349cc55cSDimitry Andric } 2041349cc55cSDimitry Andric 2042349cc55cSDimitry Andric // For stack slots, calculate PHIs for the equivalent of the units, then 2043349cc55cSDimitry Andric // install for each index. 2044349cc55cSDimitry Andric for (SpillLocationNo Slot : StackSlots) { 2045349cc55cSDimitry Andric for (unsigned Idx : StackUnits) { 2046349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); 2047349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 2048349cc55cSDimitry Andric CollectPHIsForLoc(L); 2049349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2050349cc55cSDimitry Andric 2051349cc55cSDimitry Andric // Find anything that aliases this stack index, install PHIs for it too. 2052349cc55cSDimitry Andric unsigned Size, Offset; 2053349cc55cSDimitry Andric std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; 2054349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 2055349cc55cSDimitry Andric unsigned ThisSize, ThisOffset; 2056349cc55cSDimitry Andric std::tie(ThisSize, ThisOffset) = Pair.first; 2057349cc55cSDimitry Andric if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) 2058349cc55cSDimitry Andric continue; 2059349cc55cSDimitry Andric 2060349cc55cSDimitry Andric unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); 2061349cc55cSDimitry Andric LocIdx ThisL = MTracker->getSpillMLoc(ThisID); 2062349cc55cSDimitry Andric InstallPHIsAtLoc(ThisL); 2063349cc55cSDimitry Andric } 2064349cc55cSDimitry Andric } 2065349cc55cSDimitry Andric } 2066349cc55cSDimitry Andric 2067349cc55cSDimitry Andric // For reg units, place PHIs, and then place them for any aliasing registers. 2068349cc55cSDimitry Andric for (Register R : RegUnitsToPHIUp) { 2069349cc55cSDimitry Andric LocIdx L = MTracker->lookupOrTrackRegister(R); 2070349cc55cSDimitry Andric CollectPHIsForLoc(L); 2071349cc55cSDimitry Andric 2072349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2073349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2074349cc55cSDimitry Andric 2075349cc55cSDimitry Andric // Now find aliases and install PHIs for those. 2076349cc55cSDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { 2077349cc55cSDimitry Andric // Super-registers that are "above" the largest register read/written by 2078349cc55cSDimitry Andric // the function will alias, but will not be tracked. 2079349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*RAI)) 2080349cc55cSDimitry Andric continue; 2081349cc55cSDimitry Andric 2082349cc55cSDimitry Andric LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); 2083349cc55cSDimitry Andric InstallPHIsAtLoc(AliasLoc); 2084349cc55cSDimitry Andric } 2085349cc55cSDimitry Andric } 2086349cc55cSDimitry Andric } 2087349cc55cSDimitry Andric 2088349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap( 2089349cc55cSDimitry Andric MachineFunction &MF, ValueIDNum **MInLocs, ValueIDNum **MOutLocs, 2090e8d8bef9SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2091e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2092e8d8bef9SDimitry Andric std::greater<unsigned int>> 2093e8d8bef9SDimitry Andric Worklist, Pending; 2094e8d8bef9SDimitry Andric 2095e8d8bef9SDimitry Andric // We track what is on the current and pending worklist to avoid inserting 2096e8d8bef9SDimitry Andric // the same thing twice. We could avoid this with a custom priority queue, 2097e8d8bef9SDimitry Andric // but this is probably not worth it. 2098e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2099e8d8bef9SDimitry Andric 2100349cc55cSDimitry Andric // Initialize worklist with every block to be visited. Also produce list of 2101349cc55cSDimitry Andric // all blocks. 2102349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; 2103e8d8bef9SDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2104e8d8bef9SDimitry Andric Worklist.push(I); 2105e8d8bef9SDimitry Andric OnWorklist.insert(OrderToBB[I]); 2106349cc55cSDimitry Andric AllBlocks.insert(OrderToBB[I]); 2107e8d8bef9SDimitry Andric } 2108e8d8bef9SDimitry Andric 2109349cc55cSDimitry Andric // Initialize entry block to PHIs. These represent arguments. 2110349cc55cSDimitry Andric for (auto Location : MTracker->locations()) 2111349cc55cSDimitry Andric MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); 2112349cc55cSDimitry Andric 2113e8d8bef9SDimitry Andric MTracker->reset(); 2114e8d8bef9SDimitry Andric 2115349cc55cSDimitry Andric // Start by placing PHIs, using the usual SSA constructor algorithm. Consider 2116349cc55cSDimitry Andric // any machine-location that isn't live-through a block to be def'd in that 2117349cc55cSDimitry Andric // block. 2118349cc55cSDimitry Andric placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); 2119e8d8bef9SDimitry Andric 2120349cc55cSDimitry Andric // Propagate values to eliminate redundant PHIs. At the same time, this 2121349cc55cSDimitry Andric // produces the table of Block x Location => Value for the entry to each 2122349cc55cSDimitry Andric // block. 2123349cc55cSDimitry Andric // The kind of PHIs we can eliminate are, for example, where one path in a 2124349cc55cSDimitry Andric // conditional spills and restores a register, and the register still has 2125349cc55cSDimitry Andric // the same value once control flow joins, unbeknowns to the PHI placement 2126349cc55cSDimitry Andric // code. Propagating values allows us to identify such un-necessary PHIs and 2127349cc55cSDimitry Andric // remove them. 2128e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2129e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2130e8d8bef9SDimitry Andric // Vector for storing the evaluated block transfer function. 2131e8d8bef9SDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2132e8d8bef9SDimitry Andric 2133e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2134e8d8bef9SDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2135e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2136e8d8bef9SDimitry Andric Worklist.pop(); 2137e8d8bef9SDimitry Andric 2138e8d8bef9SDimitry Andric // Join the values in all predecessor blocks. 2139349cc55cSDimitry Andric bool InLocsChanged; 2140349cc55cSDimitry Andric InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2141e8d8bef9SDimitry Andric InLocsChanged |= Visited.insert(MBB).second; 2142e8d8bef9SDimitry Andric 2143e8d8bef9SDimitry Andric // Don't examine transfer function if we've visited this loc at least 2144e8d8bef9SDimitry Andric // once, and inlocs haven't changed. 2145e8d8bef9SDimitry Andric if (!InLocsChanged) 2146e8d8bef9SDimitry Andric continue; 2147e8d8bef9SDimitry Andric 2148e8d8bef9SDimitry Andric // Load the current set of live-ins into MLocTracker. 2149e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2150e8d8bef9SDimitry Andric 2151e8d8bef9SDimitry Andric // Each element of the transfer function can be a new def, or a read of 2152e8d8bef9SDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap". 2153e8d8bef9SDimitry Andric ToRemap.clear(); 2154e8d8bef9SDimitry Andric for (auto &P : MLocTransfer[CurBB]) { 2155e8d8bef9SDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2156e8d8bef9SDimitry Andric // This is a movement of whatever was live in. Read it. 2157349cc55cSDimitry Andric ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); 2158e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID)); 2159e8d8bef9SDimitry Andric } else { 2160e8d8bef9SDimitry Andric // It's a def. Just set it. 2161e8d8bef9SDimitry Andric assert(P.second.getBlock() == CurBB); 2162e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second)); 2163e8d8bef9SDimitry Andric } 2164e8d8bef9SDimitry Andric } 2165e8d8bef9SDimitry Andric 2166e8d8bef9SDimitry Andric // Commit the transfer function changes into mloc tracker, which 2167e8d8bef9SDimitry Andric // transforms the contents of the MLocTracker into the live-outs. 2168e8d8bef9SDimitry Andric for (auto &P : ToRemap) 2169e8d8bef9SDimitry Andric MTracker->setMLoc(P.first, P.second); 2170e8d8bef9SDimitry Andric 2171e8d8bef9SDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking 2172e8d8bef9SDimitry Andric // whether changes have occurred. These changes can have come from both 2173e8d8bef9SDimitry Andric // the transfer function, and mlocJoin. 2174e8d8bef9SDimitry Andric bool OLChanged = false; 2175e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 2176e8d8bef9SDimitry Andric OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2177e8d8bef9SDimitry Andric MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2178e8d8bef9SDimitry Andric } 2179e8d8bef9SDimitry Andric 2180e8d8bef9SDimitry Andric MTracker->reset(); 2181e8d8bef9SDimitry Andric 2182e8d8bef9SDimitry Andric // No need to examine successors again if out-locs didn't change. 2183e8d8bef9SDimitry Andric if (!OLChanged) 2184e8d8bef9SDimitry Andric continue; 2185e8d8bef9SDimitry Andric 2186e8d8bef9SDimitry Andric // All successors should be visited: put any back-edges on the pending 2187349cc55cSDimitry Andric // list for the next pass-through, and any other successors to be 2188349cc55cSDimitry Andric // visited this pass, if they're not going to be already. 2189e8d8bef9SDimitry Andric for (auto s : MBB->successors()) { 2190e8d8bef9SDimitry Andric // Does branching to this successor represent a back-edge? 2191e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2192e8d8bef9SDimitry Andric // No: visit it during this dataflow iteration. 2193e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2194e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2195e8d8bef9SDimitry Andric } else { 2196e8d8bef9SDimitry Andric // Yes: visit it on the next iteration. 2197e8d8bef9SDimitry Andric if (OnPending.insert(s).second) 2198e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2199e8d8bef9SDimitry Andric } 2200e8d8bef9SDimitry Andric } 2201e8d8bef9SDimitry Andric } 2202e8d8bef9SDimitry Andric 2203e8d8bef9SDimitry Andric Worklist.swap(Pending); 2204e8d8bef9SDimitry Andric std::swap(OnPending, OnWorklist); 2205e8d8bef9SDimitry Andric OnPending.clear(); 2206e8d8bef9SDimitry Andric // At this point, pending must be empty, since it was just the empty 2207e8d8bef9SDimitry Andric // worklist 2208e8d8bef9SDimitry Andric assert(Pending.empty() && "Pending should be empty"); 2209e8d8bef9SDimitry Andric } 2210e8d8bef9SDimitry Andric 2211349cc55cSDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've eliminated all 2212349cc55cSDimitry Andric // redundant PHIs. 2213e8d8bef9SDimitry Andric } 2214e8d8bef9SDimitry Andric 2215349cc55cSDimitry Andric // Boilerplate for feeding MachineBasicBlocks into IDF calculator. Provide 2216349cc55cSDimitry Andric // template specialisations for graph traits and a successor enumerator. 2217349cc55cSDimitry Andric namespace llvm { 2218349cc55cSDimitry Andric template <> struct GraphTraits<MachineBasicBlock> { 2219349cc55cSDimitry Andric using NodeRef = MachineBasicBlock *; 2220349cc55cSDimitry Andric using ChildIteratorType = MachineBasicBlock::succ_iterator; 2221e8d8bef9SDimitry Andric 2222349cc55cSDimitry Andric static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; } 2223349cc55cSDimitry Andric static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); } 2224349cc55cSDimitry Andric static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); } 2225349cc55cSDimitry Andric }; 2226349cc55cSDimitry Andric 2227349cc55cSDimitry Andric template <> struct GraphTraits<const MachineBasicBlock> { 2228349cc55cSDimitry Andric using NodeRef = const MachineBasicBlock *; 2229349cc55cSDimitry Andric using ChildIteratorType = MachineBasicBlock::const_succ_iterator; 2230349cc55cSDimitry Andric 2231349cc55cSDimitry Andric static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; } 2232349cc55cSDimitry Andric static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); } 2233349cc55cSDimitry Andric static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); } 2234349cc55cSDimitry Andric }; 2235349cc55cSDimitry Andric 2236349cc55cSDimitry Andric using MachineDomTreeBase = DomTreeBase<MachineBasicBlock>::NodeType; 2237349cc55cSDimitry Andric using MachineDomTreeChildGetter = 2238349cc55cSDimitry Andric typename IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false>; 2239349cc55cSDimitry Andric 2240349cc55cSDimitry Andric namespace IDFCalculatorDetail { 2241349cc55cSDimitry Andric template <> 2242349cc55cSDimitry Andric typename MachineDomTreeChildGetter::ChildrenTy 2243349cc55cSDimitry Andric MachineDomTreeChildGetter::get(const NodeRef &N) { 2244349cc55cSDimitry Andric return {N->succ_begin(), N->succ_end()}; 2245349cc55cSDimitry Andric } 2246349cc55cSDimitry Andric } // namespace IDFCalculatorDetail 2247349cc55cSDimitry Andric } // namespace llvm 2248349cc55cSDimitry Andric 2249349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement( 2250349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2251349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 2252349cc55cSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { 2253349cc55cSDimitry Andric // Apply IDF calculator to the designated set of location defs, storing 2254349cc55cSDimitry Andric // required PHIs into PHIBlocks. Uses the dominator tree stored in the 2255349cc55cSDimitry Andric // InstrRefBasedLDV object. 2256349cc55cSDimitry Andric IDFCalculatorDetail::ChildrenGetterTy<MachineDomTreeBase, false> foo; 2257349cc55cSDimitry Andric IDFCalculatorBase<MachineDomTreeBase, false> IDF(DomTree->getBase(), foo); 2258349cc55cSDimitry Andric 2259349cc55cSDimitry Andric IDF.setLiveInBlocks(AllBlocks); 2260349cc55cSDimitry Andric IDF.setDefiningBlocks(DefBlocks); 2261349cc55cSDimitry Andric IDF.calculate(PHIBlocks); 2262e8d8bef9SDimitry Andric } 2263e8d8bef9SDimitry Andric 2264349cc55cSDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( 2265349cc55cSDimitry Andric const MachineBasicBlock &MBB, const DebugVariable &Var, 2266349cc55cSDimitry Andric const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 2267349cc55cSDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { 2268e8d8bef9SDimitry Andric // Collect a set of locations from predecessor where its live-out value can 2269e8d8bef9SDimitry Andric // be found. 2270e8d8bef9SDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2271349cc55cSDimitry Andric SmallVector<const DbgValueProperties *, 4> Properties; 2272e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2273349cc55cSDimitry Andric 2274349cc55cSDimitry Andric // No predecessors means no PHIs. 2275349cc55cSDimitry Andric if (BlockOrders.empty()) 2276349cc55cSDimitry Andric return None; 2277e8d8bef9SDimitry Andric 2278e8d8bef9SDimitry Andric for (auto p : BlockOrders) { 2279e8d8bef9SDimitry Andric unsigned ThisBBNum = p->getNumber(); 2280349cc55cSDimitry Andric auto OutValIt = LiveOuts.find(p); 2281349cc55cSDimitry Andric if (OutValIt == LiveOuts.end()) 2282349cc55cSDimitry Andric // If we have a predecessor not in scope, we'll never find a PHI position. 2283349cc55cSDimitry Andric return None; 2284349cc55cSDimitry Andric const DbgValue &OutVal = *OutValIt->second; 2285e8d8bef9SDimitry Andric 2286e8d8bef9SDimitry Andric if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2287e8d8bef9SDimitry Andric // Consts and no-values cannot have locations we can join on. 2288349cc55cSDimitry Andric return None; 2289e8d8bef9SDimitry Andric 2290349cc55cSDimitry Andric Properties.push_back(&OutVal.Properties); 2291349cc55cSDimitry Andric 2292349cc55cSDimitry Andric // Create new empty vector of locations. 2293349cc55cSDimitry Andric Locs.resize(Locs.size() + 1); 2294349cc55cSDimitry Andric 2295349cc55cSDimitry Andric // If the live-in value is a def, find the locations where that value is 2296349cc55cSDimitry Andric // present. Do the same for VPHIs where we know the VPHI value. 2297349cc55cSDimitry Andric if (OutVal.Kind == DbgValue::Def || 2298349cc55cSDimitry Andric (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && 2299349cc55cSDimitry Andric OutVal.ID != ValueIDNum::EmptyValue)) { 2300e8d8bef9SDimitry Andric ValueIDNum ValToLookFor = OutVal.ID; 2301e8d8bef9SDimitry Andric // Search the live-outs of the predecessor for the specified value. 2302e8d8bef9SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2303e8d8bef9SDimitry Andric if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2304e8d8bef9SDimitry Andric Locs.back().push_back(LocIdx(I)); 2305e8d8bef9SDimitry Andric } 2306349cc55cSDimitry Andric } else { 2307349cc55cSDimitry Andric assert(OutVal.Kind == DbgValue::VPHI); 2308349cc55cSDimitry Andric // For VPHIs where we don't know the location, we definitely can't find 2309349cc55cSDimitry Andric // a join loc. 2310349cc55cSDimitry Andric if (OutVal.BlockNo != MBB.getNumber()) 2311349cc55cSDimitry Andric return None; 2312349cc55cSDimitry Andric 2313349cc55cSDimitry Andric // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. 2314349cc55cSDimitry Andric // a value that's live-through the whole loop. (It has to be a backedge, 2315349cc55cSDimitry Andric // because a block can't dominate itself). We can accept as a PHI location 2316349cc55cSDimitry Andric // any location where the other predecessors agree, _and_ the machine 2317349cc55cSDimitry Andric // locations feed back into themselves. Therefore, add all self-looping 2318349cc55cSDimitry Andric // machine-value PHI locations. 2319349cc55cSDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2320349cc55cSDimitry Andric ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); 2321349cc55cSDimitry Andric if (MOutLocs[ThisBBNum][I] == MPHI) 2322349cc55cSDimitry Andric Locs.back().push_back(LocIdx(I)); 2323349cc55cSDimitry Andric } 2324349cc55cSDimitry Andric } 2325e8d8bef9SDimitry Andric } 2326e8d8bef9SDimitry Andric 2327349cc55cSDimitry Andric // We should have found locations for all predecessors, or returned. 2328349cc55cSDimitry Andric assert(Locs.size() == BlockOrders.size()); 2329e8d8bef9SDimitry Andric 2330349cc55cSDimitry Andric // Check that all properties are the same. We can't pick a location if they're 2331349cc55cSDimitry Andric // not. 2332349cc55cSDimitry Andric const DbgValueProperties *Properties0 = Properties[0]; 2333349cc55cSDimitry Andric for (auto *Prop : Properties) 2334349cc55cSDimitry Andric if (*Prop != *Properties0) 2335349cc55cSDimitry Andric return None; 2336349cc55cSDimitry Andric 2337e8d8bef9SDimitry Andric // Starting with the first set of locations, take the intersection with 2338e8d8bef9SDimitry Andric // subsequent sets. 2339349cc55cSDimitry Andric SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; 2340349cc55cSDimitry Andric for (unsigned int I = 1; I < Locs.size(); ++I) { 2341349cc55cSDimitry Andric auto &LocVec = Locs[I]; 2342349cc55cSDimitry Andric SmallVector<LocIdx, 4> NewCandidates; 2343349cc55cSDimitry Andric std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), 2344349cc55cSDimitry Andric LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); 2345349cc55cSDimitry Andric CandidateLocs = NewCandidates; 2346e8d8bef9SDimitry Andric } 2347349cc55cSDimitry Andric if (CandidateLocs.empty()) 2348e8d8bef9SDimitry Andric return None; 2349e8d8bef9SDimitry Andric 2350e8d8bef9SDimitry Andric // We now have a set of LocIdxes that contain the right output value in 2351e8d8bef9SDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc, 2352e8d8bef9SDimitry Andric // that'll be it. 2353349cc55cSDimitry Andric LocIdx L = *CandidateLocs.begin(); 2354e8d8bef9SDimitry Andric 2355e8d8bef9SDimitry Andric // Return a PHI-value-number for the found location. 2356e8d8bef9SDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2357349cc55cSDimitry Andric return PHIVal; 2358e8d8bef9SDimitry Andric } 2359e8d8bef9SDimitry Andric 2360349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin( 2361349cc55cSDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 2362e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2363349cc55cSDimitry Andric DbgValue &LiveIn) { 2364e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2365e8d8bef9SDimitry Andric bool Changed = false; 2366e8d8bef9SDimitry Andric 2367e8d8bef9SDimitry Andric // Order predecessors by RPOT order, for exploring them in that order. 2368fe6060f1SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2369e8d8bef9SDimitry Andric 2370e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2371e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2372e8d8bef9SDimitry Andric }; 2373e8d8bef9SDimitry Andric 2374e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2375e8d8bef9SDimitry Andric 2376e8d8bef9SDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB]; 2377e8d8bef9SDimitry Andric 2378349cc55cSDimitry Andric // Collect all the incoming DbgValues for this variable, from predecessor 2379349cc55cSDimitry Andric // live-out values. 2380e8d8bef9SDimitry Andric SmallVector<InValueT, 8> Values; 2381e8d8bef9SDimitry Andric bool Bail = false; 2382349cc55cSDimitry Andric int BackEdgesStart = 0; 2383e8d8bef9SDimitry Andric for (auto p : BlockOrders) { 2384e8d8bef9SDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be 2385e8d8bef9SDimitry Andric // able to join any locations. 2386e8d8bef9SDimitry Andric if (!BlocksToExplore.contains(p)) { 2387e8d8bef9SDimitry Andric Bail = true; 2388e8d8bef9SDimitry Andric break; 2389e8d8bef9SDimitry Andric } 2390e8d8bef9SDimitry Andric 2391349cc55cSDimitry Andric // All Live-outs will have been initialized. 2392349cc55cSDimitry Andric DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; 2393e8d8bef9SDimitry Andric 2394e8d8bef9SDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on 2395e8d8bef9SDimitry Andric // BlockOrders being sorted by RPO. 2396e8d8bef9SDimitry Andric unsigned ThisBBRPONum = BBToOrder[p]; 2397e8d8bef9SDimitry Andric if (ThisBBRPONum < CurBlockRPONum) 2398e8d8bef9SDimitry Andric ++BackEdgesStart; 2399e8d8bef9SDimitry Andric 2400349cc55cSDimitry Andric Values.push_back(std::make_pair(p, &OutLoc)); 2401e8d8bef9SDimitry Andric } 2402e8d8bef9SDimitry Andric 2403e8d8bef9SDimitry Andric // If there were no values, or one of the predecessors couldn't have a 2404e8d8bef9SDimitry Andric // value, then give up immediately. It's not safe to produce a live-in 2405349cc55cSDimitry Andric // value. Leave as whatever it was before. 2406e8d8bef9SDimitry Andric if (Bail || Values.size() == 0) 2407349cc55cSDimitry Andric return false; 2408e8d8bef9SDimitry Andric 2409e8d8bef9SDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor. 2410e8d8bef9SDimitry Andric // Pick the variable value from the first of these, to compare against 2411e8d8bef9SDimitry Andric // all others. 2412e8d8bef9SDimitry Andric const DbgValue &FirstVal = *Values[0].second; 2413e8d8bef9SDimitry Andric 2414349cc55cSDimitry Andric // If the old live-in value is not a PHI then either a) no PHI is needed 2415349cc55cSDimitry Andric // here, or b) we eliminated the PHI that was here. If so, we can just 2416349cc55cSDimitry Andric // propagate in the first parent's incoming value. 2417349cc55cSDimitry Andric if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { 2418349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2419349cc55cSDimitry Andric if (Changed) 2420349cc55cSDimitry Andric LiveIn = FirstVal; 2421349cc55cSDimitry Andric return Changed; 2422349cc55cSDimitry Andric } 2423349cc55cSDimitry Andric 2424349cc55cSDimitry Andric // Scan for variable values that can never be resolved: if they have 2425349cc55cSDimitry Andric // different DIExpressions, different indirectness, or are mixed constants / 2426e8d8bef9SDimitry Andric // non-constants. 2427e8d8bef9SDimitry Andric for (auto &V : Values) { 2428e8d8bef9SDimitry Andric if (V.second->Properties != FirstVal.Properties) 2429349cc55cSDimitry Andric return false; 2430349cc55cSDimitry Andric if (V.second->Kind == DbgValue::NoVal) 2431349cc55cSDimitry Andric return false; 2432e8d8bef9SDimitry Andric if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 2433349cc55cSDimitry Andric return false; 2434e8d8bef9SDimitry Andric } 2435e8d8bef9SDimitry Andric 2436349cc55cSDimitry Andric // Try to eliminate this PHI. Do the incoming values all agree? 2437e8d8bef9SDimitry Andric bool Disagree = false; 2438e8d8bef9SDimitry Andric for (auto &V : Values) { 2439e8d8bef9SDimitry Andric if (*V.second == FirstVal) 2440e8d8bef9SDimitry Andric continue; // No disagreement. 2441e8d8bef9SDimitry Andric 2442349cc55cSDimitry Andric // Eliminate if a backedge feeds a VPHI back into itself. 2443349cc55cSDimitry Andric if (V.second->Kind == DbgValue::VPHI && 2444349cc55cSDimitry Andric V.second->BlockNo == MBB.getNumber() && 2445349cc55cSDimitry Andric // Is this a backedge? 2446349cc55cSDimitry Andric std::distance(Values.begin(), &V) >= BackEdgesStart) 2447349cc55cSDimitry Andric continue; 2448349cc55cSDimitry Andric 2449e8d8bef9SDimitry Andric Disagree = true; 2450e8d8bef9SDimitry Andric } 2451e8d8bef9SDimitry Andric 2452349cc55cSDimitry Andric // No disagreement -> live-through value. 2453349cc55cSDimitry Andric if (!Disagree) { 2454349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2455e8d8bef9SDimitry Andric if (Changed) 2456349cc55cSDimitry Andric LiveIn = FirstVal; 2457349cc55cSDimitry Andric return Changed; 2458349cc55cSDimitry Andric } else { 2459349cc55cSDimitry Andric // Otherwise use a VPHI. 2460349cc55cSDimitry Andric DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); 2461349cc55cSDimitry Andric Changed = LiveIn != VPHI; 2462349cc55cSDimitry Andric if (Changed) 2463349cc55cSDimitry Andric LiveIn = VPHI; 2464349cc55cSDimitry Andric return Changed; 2465349cc55cSDimitry Andric } 2466e8d8bef9SDimitry Andric } 2467e8d8bef9SDimitry Andric 2468349cc55cSDimitry Andric void InstrRefBasedLDV::buildVLocValueMap(const DILocation *DILoc, 2469e8d8bef9SDimitry Andric const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 2470e8d8bef9SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 2471e8d8bef9SDimitry Andric ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 2472e8d8bef9SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) { 2473349cc55cSDimitry Andric // This method is much like buildMLocValueMap: but focuses on a single 2474e8d8bef9SDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are 2475e8d8bef9SDimitry Andric // to have their value assignments solved, then run our dataflow algorithm 2476e8d8bef9SDimitry Andric // until a fixedpoint is reached. 2477e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2478e8d8bef9SDimitry Andric std::greater<unsigned int>> 2479e8d8bef9SDimitry Andric Worklist, Pending; 2480e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 2481e8d8bef9SDimitry Andric 2482e8d8bef9SDimitry Andric // The set of blocks we'll be examining. 2483e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2484e8d8bef9SDimitry Andric 2485e8d8bef9SDimitry Andric // The order in which to examine them (RPO). 2486e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders; 2487e8d8bef9SDimitry Andric 2488e8d8bef9SDimitry Andric // RPO ordering function. 2489e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2490e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2491e8d8bef9SDimitry Andric }; 2492e8d8bef9SDimitry Andric 2493e8d8bef9SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 2494e8d8bef9SDimitry Andric 2495e8d8bef9SDimitry Andric // A separate container to distinguish "blocks we're exploring" versus 2496e8d8bef9SDimitry Andric // "blocks that are potentially in scope. See comment at start of vlocJoin. 2497e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore; 2498e8d8bef9SDimitry Andric 24994824e7fdSDimitry Andric // VarLoc LiveDebugValues tracks variable locations that are defined in 25004824e7fdSDimitry Andric // blocks not in scope. This is something we could legitimately ignore, but 25014824e7fdSDimitry Andric // lets allow it for now for the sake of coverage. 2502e8d8bef9SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 2503e8d8bef9SDimitry Andric 2504e8d8bef9SDimitry Andric // We also need to propagate variable values through any artificial blocks 2505e8d8bef9SDimitry Andric // that immediately follow blocks in scope. 2506e8d8bef9SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd; 2507e8d8bef9SDimitry Andric 2508e8d8bef9SDimitry Andric // Helper lambda: For a given block in scope, perform a depth first search 2509e8d8bef9SDimitry Andric // of all the artificial successors, adding them to the ToAdd collection. 2510e8d8bef9SDimitry Andric auto AccumulateArtificialBlocks = 2511e8d8bef9SDimitry Andric [this, &ToAdd, &BlocksToExplore, 2512e8d8bef9SDimitry Andric &InScopeBlocks](const MachineBasicBlock *MBB) { 2513e8d8bef9SDimitry Andric // Depth-first-search state: each node is a block and which successor 2514e8d8bef9SDimitry Andric // we're currently exploring. 2515e8d8bef9SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, 2516e8d8bef9SDimitry Andric MachineBasicBlock::const_succ_iterator>, 2517e8d8bef9SDimitry Andric 8> 2518e8d8bef9SDimitry Andric DFS; 2519e8d8bef9SDimitry Andric 2520e8d8bef9SDimitry Andric // Find any artificial successors not already tracked. 2521e8d8bef9SDimitry Andric for (auto *succ : MBB->successors()) { 2522e8d8bef9SDimitry Andric if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ)) 2523e8d8bef9SDimitry Andric continue; 2524e8d8bef9SDimitry Andric if (!ArtificialBlocks.count(succ)) 2525e8d8bef9SDimitry Andric continue; 2526e8d8bef9SDimitry Andric ToAdd.insert(succ); 2527349cc55cSDimitry Andric DFS.push_back(std::make_pair(succ, succ->succ_begin())); 2528e8d8bef9SDimitry Andric } 2529e8d8bef9SDimitry Andric 2530e8d8bef9SDimitry Andric // Search all those blocks, depth first. 2531e8d8bef9SDimitry Andric while (!DFS.empty()) { 2532e8d8bef9SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first; 2533e8d8bef9SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 2534e8d8bef9SDimitry Andric // Walk back if we've explored this blocks successors to the end. 2535e8d8bef9SDimitry Andric if (CurSucc == CurBB->succ_end()) { 2536e8d8bef9SDimitry Andric DFS.pop_back(); 2537e8d8bef9SDimitry Andric continue; 2538e8d8bef9SDimitry Andric } 2539e8d8bef9SDimitry Andric 2540e8d8bef9SDimitry Andric // If the current successor is artificial and unexplored, descend into 2541e8d8bef9SDimitry Andric // it. 2542e8d8bef9SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 2543e8d8bef9SDimitry Andric ToAdd.insert(*CurSucc); 2544349cc55cSDimitry Andric DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin())); 2545e8d8bef9SDimitry Andric continue; 2546e8d8bef9SDimitry Andric } 2547e8d8bef9SDimitry Andric 2548e8d8bef9SDimitry Andric ++CurSucc; 2549e8d8bef9SDimitry Andric } 2550e8d8bef9SDimitry Andric }; 2551e8d8bef9SDimitry Andric 2552e8d8bef9SDimitry Andric // Search in-scope blocks and those containing a DBG_VALUE from this scope 2553e8d8bef9SDimitry Andric // for artificial successors. 2554e8d8bef9SDimitry Andric for (auto *MBB : BlocksToExplore) 2555e8d8bef9SDimitry Andric AccumulateArtificialBlocks(MBB); 2556e8d8bef9SDimitry Andric for (auto *MBB : InScopeBlocks) 2557e8d8bef9SDimitry Andric AccumulateArtificialBlocks(MBB); 2558e8d8bef9SDimitry Andric 2559e8d8bef9SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 2560e8d8bef9SDimitry Andric InScopeBlocks.insert(ToAdd.begin(), ToAdd.end()); 2561e8d8bef9SDimitry Andric 2562e8d8bef9SDimitry Andric // Single block scope: not interesting! No propagation at all. Note that 2563e8d8bef9SDimitry Andric // this could probably go above ArtificialBlocks without damage, but 2564e8d8bef9SDimitry Andric // that then produces output differences from original-live-debug-values, 2565e8d8bef9SDimitry Andric // which propagates from a single block into many artificial ones. 2566e8d8bef9SDimitry Andric if (BlocksToExplore.size() == 1) 2567e8d8bef9SDimitry Andric return; 2568e8d8bef9SDimitry Andric 2569349cc55cSDimitry Andric // Convert a const set to a non-const set. LexicalScopes 2570349cc55cSDimitry Andric // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. 2571349cc55cSDimitry Andric // (Neither of them mutate anything). 2572349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; 2573349cc55cSDimitry Andric for (const auto *MBB : BlocksToExplore) 2574349cc55cSDimitry Andric MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); 2575349cc55cSDimitry Andric 2576e8d8bef9SDimitry Andric // Picks out relevants blocks RPO order and sort them. 2577e8d8bef9SDimitry Andric for (auto *MBB : BlocksToExplore) 2578e8d8bef9SDimitry Andric BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 2579e8d8bef9SDimitry Andric 2580e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2581e8d8bef9SDimitry Andric unsigned NumBlocks = BlockOrders.size(); 2582e8d8bef9SDimitry Andric 2583e8d8bef9SDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large. 2584349cc55cSDimitry Andric SmallVector<DbgValue, 32> LiveIns, LiveOuts; 2585349cc55cSDimitry Andric LiveIns.reserve(NumBlocks); 2586349cc55cSDimitry Andric LiveOuts.reserve(NumBlocks); 2587349cc55cSDimitry Andric 2588349cc55cSDimitry Andric // Initialize all values to start as NoVals. This signifies "it's live 2589349cc55cSDimitry Andric // through, but we don't know what it is". 2590349cc55cSDimitry Andric DbgValueProperties EmptyProperties(EmptyExpr, false); 2591349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2592349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2593349cc55cSDimitry Andric LiveIns.push_back(EmptyDbgValue); 2594349cc55cSDimitry Andric LiveOuts.push_back(EmptyDbgValue); 2595349cc55cSDimitry Andric } 2596e8d8bef9SDimitry Andric 2597e8d8bef9SDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 2598e8d8bef9SDimitry Andric // vlocJoin. 2599e8d8bef9SDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx; 2600e8d8bef9SDimitry Andric LiveOutIdx.reserve(NumBlocks); 2601e8d8bef9SDimitry Andric LiveInIdx.reserve(NumBlocks); 2602e8d8bef9SDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) { 2603e8d8bef9SDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 2604e8d8bef9SDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 2605e8d8bef9SDimitry Andric } 2606e8d8bef9SDimitry Andric 2607349cc55cSDimitry Andric // Loop over each variable and place PHIs for it, then propagate values 2608349cc55cSDimitry Andric // between blocks. This keeps the locality of working on one lexical scope at 2609349cc55cSDimitry Andric // at time, but avoids re-processing variable values because some other 2610349cc55cSDimitry Andric // variable has been assigned. 2611349cc55cSDimitry Andric for (auto &Var : VarsWeCareAbout) { 2612349cc55cSDimitry Andric // Re-initialize live-ins and live-outs, to clear the remains of previous 2613349cc55cSDimitry Andric // variables live-ins / live-outs. 2614349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2615349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2616349cc55cSDimitry Andric LiveIns[I] = EmptyDbgValue; 2617349cc55cSDimitry Andric LiveOuts[I] = EmptyDbgValue; 2618349cc55cSDimitry Andric } 2619349cc55cSDimitry Andric 2620349cc55cSDimitry Andric // Place PHIs for variable values, using the LLVM IDF calculator. 2621349cc55cSDimitry Andric // Collect the set of blocks where variables are def'd. 2622349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2623349cc55cSDimitry Andric for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { 2624349cc55cSDimitry Andric auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; 2625349cc55cSDimitry Andric if (TransferFunc.find(Var) != TransferFunc.end()) 2626349cc55cSDimitry Andric DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); 2627349cc55cSDimitry Andric } 2628349cc55cSDimitry Andric 2629349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2630349cc55cSDimitry Andric 2631349cc55cSDimitry Andric // Request the set of PHIs we should insert for this variable. 2632349cc55cSDimitry Andric BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); 2633349cc55cSDimitry Andric 2634349cc55cSDimitry Andric // Insert PHIs into the per-block live-in tables for this variable. 2635349cc55cSDimitry Andric for (MachineBasicBlock *PHIMBB : PHIBlocks) { 2636349cc55cSDimitry Andric unsigned BlockNo = PHIMBB->getNumber(); 2637349cc55cSDimitry Andric DbgValue *LiveIn = LiveInIdx[PHIMBB]; 2638349cc55cSDimitry Andric *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); 2639349cc55cSDimitry Andric } 2640349cc55cSDimitry Andric 2641e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2642e8d8bef9SDimitry Andric Worklist.push(BBToOrder[MBB]); 2643e8d8bef9SDimitry Andric OnWorklist.insert(MBB); 2644e8d8bef9SDimitry Andric } 2645e8d8bef9SDimitry Andric 2646349cc55cSDimitry Andric // Iterate over all the blocks we selected, propagating the variables value. 2647349cc55cSDimitry Andric // This loop does two things: 2648349cc55cSDimitry Andric // * Eliminates un-necessary VPHIs in vlocJoin, 2649349cc55cSDimitry Andric // * Evaluates the blocks transfer function (i.e. variable assignments) and 2650349cc55cSDimitry Andric // stores the result to the blocks live-outs. 2651349cc55cSDimitry Andric // Always evaluate the transfer function on the first iteration, and when 2652349cc55cSDimitry Andric // the live-ins change thereafter. 2653e8d8bef9SDimitry Andric bool FirstTrip = true; 2654e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2655e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2656e8d8bef9SDimitry Andric auto *MBB = OrderToBB[Worklist.top()]; 2657e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2658e8d8bef9SDimitry Andric Worklist.pop(); 2659e8d8bef9SDimitry Andric 2660349cc55cSDimitry Andric auto LiveInsIt = LiveInIdx.find(MBB); 2661349cc55cSDimitry Andric assert(LiveInsIt != LiveInIdx.end()); 2662349cc55cSDimitry Andric DbgValue *LiveIn = LiveInsIt->second; 2663e8d8bef9SDimitry Andric 2664e8d8bef9SDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output 2665e8d8bef9SDimitry Andric // into JoinedInLocs. 2666349cc55cSDimitry Andric bool InLocsChanged = 26674824e7fdSDimitry Andric vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); 2668e8d8bef9SDimitry Andric 2669349cc55cSDimitry Andric SmallVector<const MachineBasicBlock *, 8> Preds; 2670349cc55cSDimitry Andric for (const auto *Pred : MBB->predecessors()) 2671349cc55cSDimitry Andric Preds.push_back(Pred); 2672e8d8bef9SDimitry Andric 2673349cc55cSDimitry Andric // If this block's live-in value is a VPHI, try to pick a machine-value 2674349cc55cSDimitry Andric // for it. This makes the machine-value available and propagated 2675349cc55cSDimitry Andric // through all blocks by the time value propagation finishes. We can't 2676349cc55cSDimitry Andric // do this any earlier as it needs to read the block live-outs. 2677349cc55cSDimitry Andric if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { 2678349cc55cSDimitry Andric // There's a small possibility that on a preceeding path, a VPHI is 2679349cc55cSDimitry Andric // eliminated and transitions from VPHI-with-location to 2680349cc55cSDimitry Andric // live-through-value. As a result, the selected location of any VPHI 2681349cc55cSDimitry Andric // might change, so we need to re-compute it on each iteration. 2682349cc55cSDimitry Andric Optional<ValueIDNum> ValueNum = 2683349cc55cSDimitry Andric pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); 2684e8d8bef9SDimitry Andric 2685349cc55cSDimitry Andric if (ValueNum) { 2686349cc55cSDimitry Andric InLocsChanged |= LiveIn->ID != *ValueNum; 2687349cc55cSDimitry Andric LiveIn->ID = *ValueNum; 2688349cc55cSDimitry Andric } 2689349cc55cSDimitry Andric } 2690e8d8bef9SDimitry Andric 2691349cc55cSDimitry Andric if (!InLocsChanged && !FirstTrip) 2692e8d8bef9SDimitry Andric continue; 2693e8d8bef9SDimitry Andric 2694349cc55cSDimitry Andric DbgValue *LiveOut = LiveOutIdx[MBB]; 2695349cc55cSDimitry Andric bool OLChanged = false; 2696349cc55cSDimitry Andric 2697e8d8bef9SDimitry Andric // Do transfer function. 2698e8d8bef9SDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()]; 2699349cc55cSDimitry Andric auto TransferIt = VTracker.Vars.find(Var); 2700349cc55cSDimitry Andric if (TransferIt != VTracker.Vars.end()) { 2701e8d8bef9SDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg). 2702349cc55cSDimitry Andric if (TransferIt->second.Kind == DbgValue::Undef) { 2703349cc55cSDimitry Andric DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); 2704349cc55cSDimitry Andric if (*LiveOut != NewVal) { 2705349cc55cSDimitry Andric *LiveOut = NewVal; 2706349cc55cSDimitry Andric OLChanged = true; 2707349cc55cSDimitry Andric } 2708e8d8bef9SDimitry Andric } else { 2709e8d8bef9SDimitry Andric // Insert new variable value; or overwrite. 2710349cc55cSDimitry Andric if (*LiveOut != TransferIt->second) { 2711349cc55cSDimitry Andric *LiveOut = TransferIt->second; 2712349cc55cSDimitry Andric OLChanged = true; 2713e8d8bef9SDimitry Andric } 2714e8d8bef9SDimitry Andric } 2715349cc55cSDimitry Andric } else { 2716349cc55cSDimitry Andric // Just copy live-ins to live-outs, for anything not transferred. 2717349cc55cSDimitry Andric if (*LiveOut != *LiveIn) { 2718349cc55cSDimitry Andric *LiveOut = *LiveIn; 2719349cc55cSDimitry Andric OLChanged = true; 2720349cc55cSDimitry Andric } 2721e8d8bef9SDimitry Andric } 2722e8d8bef9SDimitry Andric 2723349cc55cSDimitry Andric // If no live-out value changed, there's no need to explore further. 2724e8d8bef9SDimitry Andric if (!OLChanged) 2725e8d8bef9SDimitry Andric continue; 2726e8d8bef9SDimitry Andric 2727e8d8bef9SDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge 2728e8d8bef9SDimitry Andric // successors during this dataflow iteration; book backedge successors 2729e8d8bef9SDimitry Andric // to be visited next time around. 2730e8d8bef9SDimitry Andric for (auto s : MBB->successors()) { 2731e8d8bef9SDimitry Andric // Ignore out of scope / not-to-be-explored successors. 2732e8d8bef9SDimitry Andric if (LiveInIdx.find(s) == LiveInIdx.end()) 2733e8d8bef9SDimitry Andric continue; 2734e8d8bef9SDimitry Andric 2735e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2736e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2737e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2738e8d8bef9SDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 2739e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2740e8d8bef9SDimitry Andric } 2741e8d8bef9SDimitry Andric } 2742e8d8bef9SDimitry Andric } 2743e8d8bef9SDimitry Andric Worklist.swap(Pending); 2744e8d8bef9SDimitry Andric std::swap(OnWorklist, OnPending); 2745e8d8bef9SDimitry Andric OnPending.clear(); 2746e8d8bef9SDimitry Andric assert(Pending.empty()); 2747e8d8bef9SDimitry Andric FirstTrip = false; 2748e8d8bef9SDimitry Andric } 2749e8d8bef9SDimitry Andric 2750349cc55cSDimitry Andric // Save live-ins to output vector. Ignore any that are still marked as being 2751349cc55cSDimitry Andric // VPHIs with no location -- those are variables that we know the value of, 2752349cc55cSDimitry Andric // but are not actually available in the register file. 2753e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2754349cc55cSDimitry Andric DbgValue *BlockLiveIn = LiveInIdx[MBB]; 2755349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::NoVal) 2756e8d8bef9SDimitry Andric continue; 2757349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI && 2758349cc55cSDimitry Andric BlockLiveIn->ID == ValueIDNum::EmptyValue) 2759349cc55cSDimitry Andric continue; 2760349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI) 2761349cc55cSDimitry Andric BlockLiveIn->Kind = DbgValue::Def; 27624824e7fdSDimitry Andric assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == 27634824e7fdSDimitry Andric Var.getFragment() && "Fragment info missing during value prop"); 2764349cc55cSDimitry Andric Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); 2765e8d8bef9SDimitry Andric } 2766349cc55cSDimitry Andric } // Per-variable loop. 2767e8d8bef9SDimitry Andric 2768e8d8bef9SDimitry Andric BlockOrders.clear(); 2769e8d8bef9SDimitry Andric BlocksToExplore.clear(); 2770e8d8bef9SDimitry Andric } 2771e8d8bef9SDimitry Andric 2772e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2773e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer( 2774e8d8bef9SDimitry Andric const MLocTransferMap &mloc_transfer) const { 2775e8d8bef9SDimitry Andric for (auto &P : mloc_transfer) { 2776e8d8bef9SDimitry Andric std::string foo = MTracker->LocIdxToName(P.first); 2777e8d8bef9SDimitry Andric std::string bar = MTracker->IDAsString(P.second); 2778e8d8bef9SDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n"; 2779e8d8bef9SDimitry Andric } 2780e8d8bef9SDimitry Andric } 2781e8d8bef9SDimitry Andric #endif 2782e8d8bef9SDimitry Andric 2783e8d8bef9SDimitry Andric void InstrRefBasedLDV::emitLocations( 2784fe6060f1SDimitry Andric MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MOutLocs, 2785fe6060f1SDimitry Andric ValueIDNum **MInLocs, DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 2786fe6060f1SDimitry Andric const TargetPassConfig &TPC) { 2787fe6060f1SDimitry Andric TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 2788e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2789e8d8bef9SDimitry Andric 2790e8d8bef9SDimitry Andric // For each block, load in the machine value locations and variable value 2791e8d8bef9SDimitry Andric // live-ins, then step through each instruction in the block. New DBG_VALUEs 2792e8d8bef9SDimitry Andric // to be inserted will be created along the way. 2793e8d8bef9SDimitry Andric for (MachineBasicBlock &MBB : MF) { 2794e8d8bef9SDimitry Andric unsigned bbnum = MBB.getNumber(); 2795e8d8bef9SDimitry Andric MTracker->reset(); 2796e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[bbnum], bbnum); 2797e8d8bef9SDimitry Andric TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()], 2798e8d8bef9SDimitry Andric NumLocs); 2799e8d8bef9SDimitry Andric 2800e8d8bef9SDimitry Andric CurBB = bbnum; 2801e8d8bef9SDimitry Andric CurInst = 1; 2802e8d8bef9SDimitry Andric for (auto &MI : MBB) { 2803fe6060f1SDimitry Andric process(MI, MOutLocs, MInLocs); 2804e8d8bef9SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 2805e8d8bef9SDimitry Andric ++CurInst; 2806e8d8bef9SDimitry Andric } 2807e8d8bef9SDimitry Andric } 2808e8d8bef9SDimitry Andric 2809e8d8bef9SDimitry Andric // Go through all the transfers recorded in the TransferTracker -- this is 2810e8d8bef9SDimitry Andric // both the live-ins to a block, and any movements of values that happen 2811e8d8bef9SDimitry Andric // in the middle. 2812*04eeddc0SDimitry Andric for (const auto &P : TTracker->Transfers) { 2813*04eeddc0SDimitry Andric // We have to insert DBG_VALUEs in a consistent order, otherwise they 2814*04eeddc0SDimitry Andric // appear in DWARF in different orders. Use the order that they appear 2815*04eeddc0SDimitry Andric // when walking through each block / each instruction, stored in 2816*04eeddc0SDimitry Andric // AllVarsNumbering. 2817*04eeddc0SDimitry Andric SmallVector<std::pair<unsigned, MachineInstr *>> Insts; 2818*04eeddc0SDimitry Andric for (MachineInstr *MI : P.Insts) { 2819*04eeddc0SDimitry Andric DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(), 2820*04eeddc0SDimitry Andric MI->getDebugLoc()->getInlinedAt()); 2821*04eeddc0SDimitry Andric Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI); 2822*04eeddc0SDimitry Andric } 2823*04eeddc0SDimitry Andric llvm::sort(Insts, 2824*04eeddc0SDimitry Andric [](const auto &A, const auto &B) { return A.first < B.first; }); 2825*04eeddc0SDimitry Andric 2826e8d8bef9SDimitry Andric // Insert either before or after the designated point... 2827e8d8bef9SDimitry Andric if (P.MBB) { 2828e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *P.MBB; 2829*04eeddc0SDimitry Andric for (const auto &Pair : Insts) 2830*04eeddc0SDimitry Andric MBB.insert(P.Pos, Pair.second); 2831e8d8bef9SDimitry Andric } else { 2832fe6060f1SDimitry Andric // Terminators, like tail calls, can clobber things. Don't try and place 2833fe6060f1SDimitry Andric // transfers after them. 2834fe6060f1SDimitry Andric if (P.Pos->isTerminator()) 2835fe6060f1SDimitry Andric continue; 2836fe6060f1SDimitry Andric 2837e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *P.Pos->getParent(); 2838*04eeddc0SDimitry Andric for (const auto &Pair : Insts) 2839*04eeddc0SDimitry Andric MBB.insertAfterBundle(P.Pos, Pair.second); 2840e8d8bef9SDimitry Andric } 2841e8d8bef9SDimitry Andric } 2842e8d8bef9SDimitry Andric } 2843e8d8bef9SDimitry Andric 2844e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 2845e8d8bef9SDimitry Andric // Build some useful data structures. 2846349cc55cSDimitry Andric 2847349cc55cSDimitry Andric LLVMContext &Context = MF.getFunction().getContext(); 2848349cc55cSDimitry Andric EmptyExpr = DIExpression::get(Context, {}); 2849349cc55cSDimitry Andric 2850e8d8bef9SDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 2851e8d8bef9SDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc()) 2852e8d8bef9SDimitry Andric return DL.getLine() != 0; 2853e8d8bef9SDimitry Andric return false; 2854e8d8bef9SDimitry Andric }; 2855e8d8bef9SDimitry Andric // Collect a set of all the artificial blocks. 2856e8d8bef9SDimitry Andric for (auto &MBB : MF) 2857e8d8bef9SDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation)) 2858e8d8bef9SDimitry Andric ArtificialBlocks.insert(&MBB); 2859e8d8bef9SDimitry Andric 2860e8d8bef9SDimitry Andric // Compute mappings of block <=> RPO order. 2861e8d8bef9SDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 2862e8d8bef9SDimitry Andric unsigned int RPONumber = 0; 2863fe6060f1SDimitry Andric for (MachineBasicBlock *MBB : RPOT) { 2864fe6060f1SDimitry Andric OrderToBB[RPONumber] = MBB; 2865fe6060f1SDimitry Andric BBToOrder[MBB] = RPONumber; 2866fe6060f1SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber; 2867e8d8bef9SDimitry Andric ++RPONumber; 2868e8d8bef9SDimitry Andric } 2869fe6060f1SDimitry Andric 2870fe6060f1SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup. 2871fe6060f1SDimitry Andric llvm::sort(MF.DebugValueSubstitutions); 2872fe6060f1SDimitry Andric 2873fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS 2874fe6060f1SDimitry Andric // As an expensive check, test whether there are any duplicate substitution 2875fe6060f1SDimitry Andric // sources in the collection. 2876fe6060f1SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) { 2877fe6060f1SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin(); 2878fe6060f1SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { 2879fe6060f1SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location " 2880fe6060f1SDimitry Andric "substitution seen"); 2881fe6060f1SDimitry Andric } 2882fe6060f1SDimitry Andric } 2883fe6060f1SDimitry Andric #endif 2884e8d8bef9SDimitry Andric } 2885e8d8bef9SDimitry Andric 2886e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and 2887e8d8bef9SDimitry Andric /// extend ranges across basic blocks. 2888e8d8bef9SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 2889349cc55cSDimitry Andric MachineDominatorTree *DomTree, 2890349cc55cSDimitry Andric TargetPassConfig *TPC, 2891349cc55cSDimitry Andric unsigned InputBBLimit, 2892349cc55cSDimitry Andric unsigned InputDbgValLimit) { 2893e8d8bef9SDimitry Andric // No subprogram means this function contains no debuginfo. 2894e8d8bef9SDimitry Andric if (!MF.getFunction().getSubprogram()) 2895e8d8bef9SDimitry Andric return false; 2896e8d8bef9SDimitry Andric 2897e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 2898e8d8bef9SDimitry Andric this->TPC = TPC; 2899e8d8bef9SDimitry Andric 2900349cc55cSDimitry Andric this->DomTree = DomTree; 2901e8d8bef9SDimitry Andric TRI = MF.getSubtarget().getRegisterInfo(); 2902349cc55cSDimitry Andric MRI = &MF.getRegInfo(); 2903e8d8bef9SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 2904e8d8bef9SDimitry Andric TFI = MF.getSubtarget().getFrameLowering(); 2905e8d8bef9SDimitry Andric TFI->getCalleeSaves(MF, CalleeSavedRegs); 2906fe6060f1SDimitry Andric MFI = &MF.getFrameInfo(); 2907e8d8bef9SDimitry Andric LS.initialize(MF); 2908e8d8bef9SDimitry Andric 29094824e7fdSDimitry Andric const auto &STI = MF.getSubtarget(); 29104824e7fdSDimitry Andric AdjustsStackInCalls = MFI->adjustsStack() && 29114824e7fdSDimitry Andric STI.getFrameLowering()->stackProbeFunctionModifiesSP(); 29124824e7fdSDimitry Andric if (AdjustsStackInCalls) 29134824e7fdSDimitry Andric StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); 29144824e7fdSDimitry Andric 2915e8d8bef9SDimitry Andric MTracker = 2916e8d8bef9SDimitry Andric new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 2917e8d8bef9SDimitry Andric VTracker = nullptr; 2918e8d8bef9SDimitry Andric TTracker = nullptr; 2919e8d8bef9SDimitry Andric 2920e8d8bef9SDimitry Andric SmallVector<MLocTransferMap, 32> MLocTransfer; 2921e8d8bef9SDimitry Andric SmallVector<VLocTracker, 8> vlocs; 2922e8d8bef9SDimitry Andric LiveInsT SavedLiveIns; 2923e8d8bef9SDimitry Andric 2924e8d8bef9SDimitry Andric int MaxNumBlocks = -1; 2925e8d8bef9SDimitry Andric for (auto &MBB : MF) 2926e8d8bef9SDimitry Andric MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 2927e8d8bef9SDimitry Andric assert(MaxNumBlocks >= 0); 2928e8d8bef9SDimitry Andric ++MaxNumBlocks; 2929e8d8bef9SDimitry Andric 2930e8d8bef9SDimitry Andric MLocTransfer.resize(MaxNumBlocks); 29314824e7fdSDimitry Andric vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); 2932e8d8bef9SDimitry Andric SavedLiveIns.resize(MaxNumBlocks); 2933e8d8bef9SDimitry Andric 2934e8d8bef9SDimitry Andric initialSetup(MF); 2935e8d8bef9SDimitry Andric 2936e8d8bef9SDimitry Andric produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 2937e8d8bef9SDimitry Andric 2938e8d8bef9SDimitry Andric // Allocate and initialize two array-of-arrays for the live-in and live-out 2939e8d8bef9SDimitry Andric // machine values. The outer dimension is the block number; while the inner 2940e8d8bef9SDimitry Andric // dimension is a LocIdx from MLocTracker. 2941e8d8bef9SDimitry Andric ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks]; 2942e8d8bef9SDimitry Andric ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks]; 2943e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2944e8d8bef9SDimitry Andric for (int i = 0; i < MaxNumBlocks; ++i) { 2945349cc55cSDimitry Andric // These all auto-initialize to ValueIDNum::EmptyValue 2946e8d8bef9SDimitry Andric MOutLocs[i] = new ValueIDNum[NumLocs]; 2947e8d8bef9SDimitry Andric MInLocs[i] = new ValueIDNum[NumLocs]; 2948e8d8bef9SDimitry Andric } 2949e8d8bef9SDimitry Andric 2950e8d8bef9SDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function, 2951e8d8bef9SDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use 2952e8d8bef9SDimitry Andric // both live-ins and live-outs for decision making in the variable value 2953e8d8bef9SDimitry Andric // dataflow problem. 2954349cc55cSDimitry Andric buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); 2955e8d8bef9SDimitry Andric 2956fe6060f1SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into 2957fe6060f1SDimitry Andric // either live-through machine values, or PHIs. 2958fe6060f1SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) { 2959fe6060f1SDimitry Andric // Identify unresolved block-live-ins. 2960fe6060f1SDimitry Andric ValueIDNum &Num = DBG_PHI.ValueRead; 2961fe6060f1SDimitry Andric if (!Num.isPHI()) 2962fe6060f1SDimitry Andric continue; 2963fe6060f1SDimitry Andric 2964fe6060f1SDimitry Andric unsigned BlockNo = Num.getBlock(); 2965fe6060f1SDimitry Andric LocIdx LocNo = Num.getLoc(); 2966fe6060f1SDimitry Andric Num = MInLocs[BlockNo][LocNo.asU64()]; 2967fe6060f1SDimitry Andric } 2968fe6060f1SDimitry Andric // Later, we'll be looking up ranges of instruction numbers. 2969fe6060f1SDimitry Andric llvm::sort(DebugPHINumToValue); 2970fe6060f1SDimitry Andric 2971e8d8bef9SDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE 2972e8d8bef9SDimitry Andric // instructions and recording what machine value their operands refer to. 2973e8d8bef9SDimitry Andric for (auto &OrderPair : OrderToBB) { 2974e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *OrderPair.second; 2975e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 2976e8d8bef9SDimitry Andric VTracker = &vlocs[CurBB]; 2977e8d8bef9SDimitry Andric VTracker->MBB = &MBB; 2978e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2979e8d8bef9SDimitry Andric CurInst = 1; 2980e8d8bef9SDimitry Andric for (auto &MI : MBB) { 2981fe6060f1SDimitry Andric process(MI, MOutLocs, MInLocs); 2982e8d8bef9SDimitry Andric ++CurInst; 2983e8d8bef9SDimitry Andric } 2984e8d8bef9SDimitry Andric MTracker->reset(); 2985e8d8bef9SDimitry Andric } 2986e8d8bef9SDimitry Andric 2987e8d8bef9SDimitry Andric // Number all variables in the order that they appear, to be used as a stable 2988e8d8bef9SDimitry Andric // insertion order later. 2989e8d8bef9SDimitry Andric DenseMap<DebugVariable, unsigned> AllVarsNumbering; 2990e8d8bef9SDimitry Andric 2991e8d8bef9SDimitry Andric // Map from one LexicalScope to all the variables in that scope. 2992e8d8bef9SDimitry Andric DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars; 2993e8d8bef9SDimitry Andric 2994e8d8bef9SDimitry Andric // Map from One lexical scope to all blocks in that scope. 2995e8d8bef9SDimitry Andric DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>> 2996e8d8bef9SDimitry Andric ScopeToBlocks; 2997e8d8bef9SDimitry Andric 2998e8d8bef9SDimitry Andric // Store a DILocation that describes a scope. 2999e8d8bef9SDimitry Andric DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation; 3000e8d8bef9SDimitry Andric 3001e8d8bef9SDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3002e8d8bef9SDimitry Andric // the order is unimportant, it just has to be stable. 3003349cc55cSDimitry Andric unsigned VarAssignCount = 0; 3004e8d8bef9SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3005e8d8bef9SDimitry Andric auto *MBB = OrderToBB[I]; 3006e8d8bef9SDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()]; 3007e8d8bef9SDimitry Andric // Collect each variable with a DBG_VALUE in this block. 3008e8d8bef9SDimitry Andric for (auto &idx : VTracker->Vars) { 3009e8d8bef9SDimitry Andric const auto &Var = idx.first; 3010e8d8bef9SDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3011e8d8bef9SDimitry Andric assert(ScopeLoc != nullptr); 3012e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc); 3013e8d8bef9SDimitry Andric 3014e8d8bef9SDimitry Andric // No insts in scope -> shouldn't have been recorded. 3015e8d8bef9SDimitry Andric assert(Scope != nullptr); 3016e8d8bef9SDimitry Andric 3017e8d8bef9SDimitry Andric AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3018e8d8bef9SDimitry Andric ScopeToVars[Scope].insert(Var); 3019e8d8bef9SDimitry Andric ScopeToBlocks[Scope].insert(VTracker->MBB); 3020e8d8bef9SDimitry Andric ScopeToDILocation[Scope] = ScopeLoc; 3021349cc55cSDimitry Andric ++VarAssignCount; 3022e8d8bef9SDimitry Andric } 3023e8d8bef9SDimitry Andric } 3024e8d8bef9SDimitry Andric 3025349cc55cSDimitry Andric bool Changed = false; 3026349cc55cSDimitry Andric 3027349cc55cSDimitry Andric // If we have an extremely large number of variable assignments and blocks, 3028349cc55cSDimitry Andric // bail out at this point. We've burnt some time doing analysis already, 3029349cc55cSDimitry Andric // however we should cut our losses. 3030349cc55cSDimitry Andric if ((unsigned)MaxNumBlocks > InputBBLimit && 3031349cc55cSDimitry Andric VarAssignCount > InputDbgValLimit) { 3032349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() 3033349cc55cSDimitry Andric << " has " << MaxNumBlocks << " basic blocks and " 3034349cc55cSDimitry Andric << VarAssignCount 3035349cc55cSDimitry Andric << " variable assignments, exceeding limits.\n"); 3036349cc55cSDimitry Andric } else { 3037349cc55cSDimitry Andric // Compute the extended ranges, iterating over scopes. There might be 3038349cc55cSDimitry Andric // something to be said for ordering them by size/locality, but that's for 3039349cc55cSDimitry Andric // the future. For each scope, solve the variable value problem, producing 3040349cc55cSDimitry Andric // a map of variables to values in SavedLiveIns. 3041e8d8bef9SDimitry Andric for (auto &P : ScopeToVars) { 3042349cc55cSDimitry Andric buildVLocValueMap(ScopeToDILocation[P.first], P.second, 3043e8d8bef9SDimitry Andric ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs, 3044e8d8bef9SDimitry Andric vlocs); 3045e8d8bef9SDimitry Andric } 3046e8d8bef9SDimitry Andric 3047e8d8bef9SDimitry Andric // Using the computed value locations and variable values for each block, 3048e8d8bef9SDimitry Andric // create the DBG_VALUE instructions representing the extended variable 3049e8d8bef9SDimitry Andric // locations. 3050fe6060f1SDimitry Andric emitLocations(MF, SavedLiveIns, MOutLocs, MInLocs, AllVarsNumbering, *TPC); 3051e8d8bef9SDimitry Andric 3052349cc55cSDimitry Andric // Did we actually make any changes? If we created any DBG_VALUEs, then yes. 3053349cc55cSDimitry Andric Changed = TTracker->Transfers.size() != 0; 3054349cc55cSDimitry Andric } 3055349cc55cSDimitry Andric 3056349cc55cSDimitry Andric // Common clean-up of memory. 3057e8d8bef9SDimitry Andric for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) { 3058e8d8bef9SDimitry Andric delete[] MOutLocs[Idx]; 3059e8d8bef9SDimitry Andric delete[] MInLocs[Idx]; 3060e8d8bef9SDimitry Andric } 3061e8d8bef9SDimitry Andric delete[] MOutLocs; 3062e8d8bef9SDimitry Andric delete[] MInLocs; 3063e8d8bef9SDimitry Andric 3064e8d8bef9SDimitry Andric delete MTracker; 3065e8d8bef9SDimitry Andric delete TTracker; 3066e8d8bef9SDimitry Andric MTracker = nullptr; 3067e8d8bef9SDimitry Andric VTracker = nullptr; 3068e8d8bef9SDimitry Andric TTracker = nullptr; 3069e8d8bef9SDimitry Andric 3070e8d8bef9SDimitry Andric ArtificialBlocks.clear(); 3071e8d8bef9SDimitry Andric OrderToBB.clear(); 3072e8d8bef9SDimitry Andric BBToOrder.clear(); 3073e8d8bef9SDimitry Andric BBNumToRPO.clear(); 3074e8d8bef9SDimitry Andric DebugInstrNumToInstr.clear(); 3075fe6060f1SDimitry Andric DebugPHINumToValue.clear(); 30764824e7fdSDimitry Andric OverlapFragments.clear(); 30774824e7fdSDimitry Andric SeenFragments.clear(); 3078e8d8bef9SDimitry Andric 3079e8d8bef9SDimitry Andric return Changed; 3080e8d8bef9SDimitry Andric } 3081e8d8bef9SDimitry Andric 3082e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3083e8d8bef9SDimitry Andric return new InstrRefBasedLDV(); 3084e8d8bef9SDimitry Andric } 3085fe6060f1SDimitry Andric 3086fe6060f1SDimitry Andric namespace { 3087fe6060f1SDimitry Andric class LDVSSABlock; 3088fe6060f1SDimitry Andric class LDVSSAUpdater; 3089fe6060f1SDimitry Andric 3090fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We 3091fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater 3092fe6060f1SDimitry Andric // expects to zero-initialize the type. 3093fe6060f1SDimitry Andric typedef uint64_t BlockValueNum; 3094fe6060f1SDimitry Andric 3095fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block 3096fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming 3097fe6060f1SDimitry Andric /// values from parent blocks. 3098fe6060f1SDimitry Andric class LDVSSAPhi { 3099fe6060f1SDimitry Andric public: 3100fe6060f1SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3101fe6060f1SDimitry Andric LDVSSABlock *ParentBlock; 3102fe6060f1SDimitry Andric BlockValueNum PHIValNum; 3103fe6060f1SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3104fe6060f1SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3105fe6060f1SDimitry Andric 3106fe6060f1SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; } 3107fe6060f1SDimitry Andric }; 3108fe6060f1SDimitry Andric 3109fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a 3110fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock. 3111fe6060f1SDimitry Andric class LDVSSABlockIterator { 3112fe6060f1SDimitry Andric public: 3113fe6060f1SDimitry Andric MachineBasicBlock::pred_iterator PredIt; 3114fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3115fe6060f1SDimitry Andric 3116fe6060f1SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3117fe6060f1SDimitry Andric LDVSSAUpdater &Updater) 3118fe6060f1SDimitry Andric : PredIt(PredIt), Updater(Updater) {} 3119fe6060f1SDimitry Andric 3120fe6060f1SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3121fe6060f1SDimitry Andric return OtherIt.PredIt != PredIt; 3122fe6060f1SDimitry Andric } 3123fe6060f1SDimitry Andric 3124fe6060f1SDimitry Andric LDVSSABlockIterator &operator++() { 3125fe6060f1SDimitry Andric ++PredIt; 3126fe6060f1SDimitry Andric return *this; 3127fe6060f1SDimitry Andric } 3128fe6060f1SDimitry Andric 3129fe6060f1SDimitry Andric LDVSSABlock *operator*(); 3130fe6060f1SDimitry Andric }; 3131fe6060f1SDimitry Andric 3132fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because 3133fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary 3134fe6060f1SDimitry Andric /// in this block. 3135fe6060f1SDimitry Andric class LDVSSABlock { 3136fe6060f1SDimitry Andric public: 3137fe6060f1SDimitry Andric MachineBasicBlock &BB; 3138fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3139fe6060f1SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>; 3140fe6060f1SDimitry Andric /// List of PHIs in this block. There should only ever be one. 3141fe6060f1SDimitry Andric PHIListT PHIList; 3142fe6060f1SDimitry Andric 3143fe6060f1SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3144fe6060f1SDimitry Andric : BB(BB), Updater(Updater) {} 3145fe6060f1SDimitry Andric 3146fe6060f1SDimitry Andric LDVSSABlockIterator succ_begin() { 3147fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater); 3148fe6060f1SDimitry Andric } 3149fe6060f1SDimitry Andric 3150fe6060f1SDimitry Andric LDVSSABlockIterator succ_end() { 3151fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater); 3152fe6060f1SDimitry Andric } 3153fe6060f1SDimitry Andric 3154fe6060f1SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record. 3155fe6060f1SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) { 3156fe6060f1SDimitry Andric PHIList.emplace_back(Value, this); 3157fe6060f1SDimitry Andric return &PHIList.back(); 3158fe6060f1SDimitry Andric } 3159fe6060f1SDimitry Andric 3160fe6060f1SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block. 3161fe6060f1SDimitry Andric PHIListT &phis() { return PHIList; } 3162fe6060f1SDimitry Andric }; 3163fe6060f1SDimitry Andric 3164fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3165fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3166fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>. 3167fe6060f1SDimitry Andric class LDVSSAUpdater { 3168fe6060f1SDimitry Andric public: 3169fe6060f1SDimitry Andric /// Map of value numbers to PHI records. 3170fe6060f1SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3171fe6060f1SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not 3172fe6060f1SDimitry Andric /// dominated by any Def. 3173fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3174fe6060f1SDimitry Andric /// Map of machine blocks to our own records of them. 3175fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3176fe6060f1SDimitry Andric /// Machine location where any PHI must occur. 3177fe6060f1SDimitry Andric LocIdx Loc; 3178fe6060f1SDimitry Andric /// Table of live-in machine value numbers for blocks / locations. 3179fe6060f1SDimitry Andric ValueIDNum **MLiveIns; 3180fe6060f1SDimitry Andric 3181fe6060f1SDimitry Andric LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {} 3182fe6060f1SDimitry Andric 3183fe6060f1SDimitry Andric void reset() { 3184fe6060f1SDimitry Andric for (auto &Block : BlockMap) 3185fe6060f1SDimitry Andric delete Block.second; 3186fe6060f1SDimitry Andric 3187fe6060f1SDimitry Andric PHIs.clear(); 3188fe6060f1SDimitry Andric UndefMap.clear(); 3189fe6060f1SDimitry Andric BlockMap.clear(); 3190fe6060f1SDimitry Andric } 3191fe6060f1SDimitry Andric 3192fe6060f1SDimitry Andric ~LDVSSAUpdater() { reset(); } 3193fe6060f1SDimitry Andric 3194fe6060f1SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the 3195fe6060f1SDimitry Andric /// LDVSSAUpdater block map. 3196fe6060f1SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3197fe6060f1SDimitry Andric auto it = BlockMap.find(BB); 3198fe6060f1SDimitry Andric if (it == BlockMap.end()) { 3199fe6060f1SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this); 3200fe6060f1SDimitry Andric it = BlockMap.find(BB); 3201fe6060f1SDimitry Andric } 3202fe6060f1SDimitry Andric return it->second; 3203fe6060f1SDimitry Andric } 3204fe6060f1SDimitry Andric 3205fe6060f1SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at 3206fe6060f1SDimitry Andric /// the PHI location on entry. 3207fe6060f1SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) { 3208fe6060f1SDimitry Andric return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3209fe6060f1SDimitry Andric } 3210fe6060f1SDimitry Andric }; 3211fe6060f1SDimitry Andric 3212fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() { 3213fe6060f1SDimitry Andric return Updater.getSSALDVBlock(*PredIt); 3214fe6060f1SDimitry Andric } 3215fe6060f1SDimitry Andric 3216fe6060f1SDimitry Andric #ifndef NDEBUG 3217fe6060f1SDimitry Andric 3218fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3219fe6060f1SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum; 3220fe6060f1SDimitry Andric return out; 3221fe6060f1SDimitry Andric } 3222fe6060f1SDimitry Andric 3223fe6060f1SDimitry Andric #endif 3224fe6060f1SDimitry Andric 3225fe6060f1SDimitry Andric } // namespace 3226fe6060f1SDimitry Andric 3227fe6060f1SDimitry Andric namespace llvm { 3228fe6060f1SDimitry Andric 3229fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value 3230fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the 3231fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define. 3232fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them. 3233fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3234fe6060f1SDimitry Andric public: 3235fe6060f1SDimitry Andric using BlkT = LDVSSABlock; 3236fe6060f1SDimitry Andric using ValT = BlockValueNum; 3237fe6060f1SDimitry Andric using PhiT = LDVSSAPhi; 3238fe6060f1SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator; 3239fe6060f1SDimitry Andric 3240fe6060f1SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class. 3241fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3242fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3243fe6060f1SDimitry Andric 3244fe6060f1SDimitry Andric /// Iterator for PHI operands. 3245fe6060f1SDimitry Andric class PHI_iterator { 3246fe6060f1SDimitry Andric private: 3247fe6060f1SDimitry Andric LDVSSAPhi *PHI; 3248fe6060f1SDimitry Andric unsigned Idx; 3249fe6060f1SDimitry Andric 3250fe6060f1SDimitry Andric public: 3251fe6060f1SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3252fe6060f1SDimitry Andric : PHI(P), Idx(0) {} 3253fe6060f1SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3254fe6060f1SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {} 3255fe6060f1SDimitry Andric 3256fe6060f1SDimitry Andric PHI_iterator &operator++() { 3257fe6060f1SDimitry Andric Idx++; 3258fe6060f1SDimitry Andric return *this; 3259fe6060f1SDimitry Andric } 3260fe6060f1SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3261fe6060f1SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3262fe6060f1SDimitry Andric 3263fe6060f1SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3264fe6060f1SDimitry Andric 3265fe6060f1SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3266fe6060f1SDimitry Andric }; 3267fe6060f1SDimitry Andric 3268fe6060f1SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3269fe6060f1SDimitry Andric 3270fe6060f1SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) { 3271fe6060f1SDimitry Andric return PHI_iterator(PHI, true); 3272fe6060f1SDimitry Andric } 3273fe6060f1SDimitry Andric 3274fe6060f1SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3275fe6060f1SDimitry Andric /// vector. 3276fe6060f1SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB, 3277fe6060f1SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) { 3278349cc55cSDimitry Andric for (MachineBasicBlock *Pred : BB->BB.predecessors()) 3279349cc55cSDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); 3280fe6060f1SDimitry Andric } 3281fe6060f1SDimitry Andric 3282fe6060f1SDimitry Andric /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3283fe6060f1SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having 3284fe6060f1SDimitry Andric /// any DBG_PHI predecessors. 3285fe6060f1SDimitry Andric static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3286fe6060f1SDimitry Andric // Create a value number for this block -- it needs to be unique and in the 3287fe6060f1SDimitry Andric // "undef" collection, so that we know it's not real. Use a number 3288fe6060f1SDimitry Andric // representing a PHI into this block. 3289fe6060f1SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3290fe6060f1SDimitry Andric Updater->UndefMap[&BB->BB] = Num; 3291fe6060f1SDimitry Andric return Num; 3292fe6060f1SDimitry Andric } 3293fe6060f1SDimitry Andric 3294fe6060f1SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3295fe6060f1SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The 3296fe6060f1SDimitry Andric /// value number of this PHI is whatever the machine value number problem 3297fe6060f1SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater 3298fe6060f1SDimitry Andric /// tries to create a PHI where the incoming values are identical. 3299fe6060f1SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3300fe6060f1SDimitry Andric LDVSSAUpdater *Updater) { 3301fe6060f1SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB); 3302fe6060f1SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3303fe6060f1SDimitry Andric Updater->PHIs[PHIValNum] = PHI; 3304fe6060f1SDimitry Andric return PHIValNum; 3305fe6060f1SDimitry Andric } 3306fe6060f1SDimitry Andric 3307fe6060f1SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for 3308fe6060f1SDimitry Andric /// the specified predecessor block. 3309fe6060f1SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3310fe6060f1SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3311fe6060f1SDimitry Andric } 3312fe6060f1SDimitry Andric 3313fe6060f1SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value 3314fe6060f1SDimitry Andric /// is a PHI instruction. 3315fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3316fe6060f1SDimitry Andric auto PHIIt = Updater->PHIs.find(Val); 3317fe6060f1SDimitry Andric if (PHIIt == Updater->PHIs.end()) 3318fe6060f1SDimitry Andric return nullptr; 3319fe6060f1SDimitry Andric return PHIIt->second; 3320fe6060f1SDimitry Andric } 3321fe6060f1SDimitry Andric 3322fe6060f1SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3323fe6060f1SDimitry Andric /// operands, i.e., it was just added. 3324fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3325fe6060f1SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3326fe6060f1SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0) 3327fe6060f1SDimitry Andric return PHI; 3328fe6060f1SDimitry Andric return nullptr; 3329fe6060f1SDimitry Andric } 3330fe6060f1SDimitry Andric 3331fe6060f1SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value 3332fe6060f1SDimitry Andric /// that it defines. 3333fe6060f1SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3334fe6060f1SDimitry Andric }; 3335fe6060f1SDimitry Andric 3336fe6060f1SDimitry Andric } // end namespace llvm 3337fe6060f1SDimitry Andric 3338fe6060f1SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF, 3339fe6060f1SDimitry Andric ValueIDNum **MLiveOuts, 3340fe6060f1SDimitry Andric ValueIDNum **MLiveIns, 3341fe6060f1SDimitry Andric MachineInstr &Here, 3342fe6060f1SDimitry Andric uint64_t InstrNum) { 3343fe6060f1SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there 3344fe6060f1SDimitry Andric // are none, then we cannot compute a value number. 3345fe6060f1SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3346fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstrNum); 3347fe6060f1SDimitry Andric auto LowerIt = RangePair.first; 3348fe6060f1SDimitry Andric auto UpperIt = RangePair.second; 3349fe6060f1SDimitry Andric 3350fe6060f1SDimitry Andric // No DBG_PHI means there can be no location. 3351fe6060f1SDimitry Andric if (LowerIt == UpperIt) 3352fe6060f1SDimitry Andric return None; 3353fe6060f1SDimitry Andric 3354fe6060f1SDimitry Andric // If there's only one DBG_PHI, then that is our value number. 3355fe6060f1SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1) 3356fe6060f1SDimitry Andric return LowerIt->ValueRead; 3357fe6060f1SDimitry Andric 3358fe6060f1SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt); 3359fe6060f1SDimitry Andric 3360fe6060f1SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's 3361fe6060f1SDimitry Andric // technically possible for us to merge values in different registers in each 3362fe6060f1SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register 3363fe6060f1SDimitry Andric // allocation. 3364fe6060f1SDimitry Andric LocIdx Loc = LowerIt->ReadLoc; 3365fe6060f1SDimitry Andric 3366fe6060f1SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each 3367fe6060f1SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each 3368fe6060f1SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3369fe6060f1SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3370fe6060f1SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along 3371fe6060f1SDimitry Andric // the way. 3372fe6060f1SDimitry Andric // Adapted LLVM SSA Updater: 3373fe6060f1SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns); 3374fe6060f1SDimitry Andric // Map of which Def or PHI is the current value in each block. 3375fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3376fe6060f1SDimitry Andric // Set of PHIs that we have created along the way. 3377fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3378fe6060f1SDimitry Andric 3379fe6060f1SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3380fe6060f1SDimitry Andric // for the SSAUpdater. 3381fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3382fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3383fe6060f1SDimitry Andric const ValueIDNum &Num = DBG_PHI.ValueRead; 3384fe6060f1SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3385fe6060f1SDimitry Andric } 3386fe6060f1SDimitry Andric 3387fe6060f1SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3388fe6060f1SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock); 3389fe6060f1SDimitry Andric if (AvailIt != AvailableValues.end()) { 3390fe6060f1SDimitry Andric // Actually, we already know what the value is -- the Use is in the same 3391fe6060f1SDimitry Andric // block as the Def. 3392fe6060f1SDimitry Andric return ValueIDNum::fromU64(AvailIt->second); 3393fe6060f1SDimitry Andric } 3394fe6060f1SDimitry Andric 3395fe6060f1SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number 3396fe6060f1SDimitry Andric // that we are to use, and the PHIs that must happen along the way. 3397fe6060f1SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3398fe6060f1SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3399fe6060f1SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3400fe6060f1SDimitry Andric 3401fe6060f1SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used 3402fe6060f1SDimitry Andric // at this Use. There are a number of things we have to check about it though: 3403fe6060f1SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3404fe6060f1SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort. 3405fe6060f1SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3406fe6060f1SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the 3407fe6060f1SDimitry Andric // expected values. 3408fe6060f1SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the 3409fe6060f1SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number? 3410fe6060f1SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3411fe6060f1SDimitry Andric // the ValidatedValues collection below to sort this out. 3412fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3413fe6060f1SDimitry Andric 3414fe6060f1SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues. 3415fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3416fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3417fe6060f1SDimitry Andric const ValueIDNum &Num = DBG_PHI.ValueRead; 3418fe6060f1SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num)); 3419fe6060f1SDimitry Andric } 3420fe6060f1SDimitry Andric 3421fe6060f1SDimitry Andric // Sort PHIs to validate into RPO-order. 3422fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3423fe6060f1SDimitry Andric for (auto &PHI : CreatedPHIs) 3424fe6060f1SDimitry Andric SortedPHIs.push_back(PHI); 3425fe6060f1SDimitry Andric 3426fe6060f1SDimitry Andric std::sort( 3427fe6060f1SDimitry Andric SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3428fe6060f1SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3429fe6060f1SDimitry Andric }); 3430fe6060f1SDimitry Andric 3431fe6060f1SDimitry Andric for (auto &PHI : SortedPHIs) { 3432fe6060f1SDimitry Andric ValueIDNum ThisBlockValueNum = 3433fe6060f1SDimitry Andric MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3434fe6060f1SDimitry Andric 3435fe6060f1SDimitry Andric // Are all these things actually defined? 3436fe6060f1SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) { 3437fe6060f1SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point. 3438fe6060f1SDimitry Andric if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3439fe6060f1SDimitry Andric return None; 3440fe6060f1SDimitry Andric 3441fe6060f1SDimitry Andric ValueIDNum ValueToCheck; 3442fe6060f1SDimitry Andric ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 3443fe6060f1SDimitry Andric 3444fe6060f1SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first); 3445fe6060f1SDimitry Andric if (VVal == ValidatedValues.end()) { 3446fe6060f1SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication 3447fe6060f1SDimitry Andric // happens so late that DBG_PHI instructions should not be able to 3448fe6060f1SDimitry Andric // migrate into loops -- meaning we can only be live-through this 3449fe6060f1SDimitry Andric // loop. 3450fe6060f1SDimitry Andric ValueToCheck = ThisBlockValueNum; 3451fe6060f1SDimitry Andric } else { 3452fe6060f1SDimitry Andric // Does the block have as a live-out, in the location we're examining, 3453fe6060f1SDimitry Andric // the value that we expect? If not, it's been moved or clobbered. 3454fe6060f1SDimitry Andric ValueToCheck = VVal->second; 3455fe6060f1SDimitry Andric } 3456fe6060f1SDimitry Andric 3457fe6060f1SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 3458fe6060f1SDimitry Andric return None; 3459fe6060f1SDimitry Andric } 3460fe6060f1SDimitry Andric 3461fe6060f1SDimitry Andric // Record this value as validated. 3462fe6060f1SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 3463fe6060f1SDimitry Andric } 3464fe6060f1SDimitry Andric 3465fe6060f1SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value 3466fe6060f1SDimitry Andric // number was. 3467fe6060f1SDimitry Andric return Result; 3468fe6060f1SDimitry Andric } 3469