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" 87*81ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h" 88e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h" 89e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 90349cc55cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 91e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h" 92e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 93e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 94e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 95fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h" 96e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h" 97e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 98e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h" 99e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h" 100e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 101e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h" 102e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 103e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 104e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 105e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 106e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 107e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h" 108e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 109e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h" 110e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 111e8d8bef9SDimitry Andric #include "llvm/Support/Compiler.h" 112e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 113*81ad6265SDimitry Andric #include "llvm/Support/GenericIteratedDominanceFrontier.h" 114e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h" 115e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 116fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h" 117fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 118e8d8bef9SDimitry Andric #include <algorithm> 119e8d8bef9SDimitry Andric #include <cassert> 120*81ad6265SDimitry Andric #include <climits> 121e8d8bef9SDimitry Andric #include <cstdint> 122e8d8bef9SDimitry Andric #include <functional> 123e8d8bef9SDimitry Andric #include <queue> 124e8d8bef9SDimitry Andric #include <tuple> 125e8d8bef9SDimitry Andric #include <utility> 126e8d8bef9SDimitry Andric #include <vector> 127e8d8bef9SDimitry Andric 128349cc55cSDimitry Andric #include "InstrRefBasedImpl.h" 129e8d8bef9SDimitry Andric #include "LiveDebugValues.h" 130e8d8bef9SDimitry Andric 131e8d8bef9SDimitry Andric using namespace llvm; 132349cc55cSDimitry Andric using namespace LiveDebugValues; 133e8d8bef9SDimitry Andric 134fe6060f1SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it. 135fe6060f1SDimitry Andric #undef DEBUG_TYPE 136e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues" 137e8d8bef9SDimitry Andric 138e8d8bef9SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too 139e8d8bef9SDimitry Andric // far and ignoring some transfers. 140e8d8bef9SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, 141e8d8bef9SDimitry Andric cl::desc("Act like old LiveDebugValues did"), 142e8d8bef9SDimitry Andric cl::init(false)); 143e8d8bef9SDimitry Andric 144d56accc7SDimitry Andric // Limit for the maximum number of stack slots we should track, past which we 145d56accc7SDimitry Andric // will ignore any spills. InstrRefBasedLDV gathers detailed information on all 146d56accc7SDimitry Andric // stack slots which leads to high memory consumption, and in some scenarios 147d56accc7SDimitry Andric // (such as asan with very many locals) the working set of the function can be 148d56accc7SDimitry Andric // very large, causing many spills. In these scenarios, it is very unlikely that 149d56accc7SDimitry Andric // the developer has hundreds of variables live at the same time that they're 150d56accc7SDimitry Andric // carefully thinking about -- instead, they probably autogenerated the code. 151d56accc7SDimitry Andric // When this happens, gracefully stop tracking excess spill slots, rather than 152d56accc7SDimitry Andric // consuming all the developer's memory. 153d56accc7SDimitry Andric static cl::opt<unsigned> 154d56accc7SDimitry Andric StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden, 155d56accc7SDimitry Andric cl::desc("livedebugvalues-stack-ws-limit"), 156d56accc7SDimitry Andric cl::init(250)); 157d56accc7SDimitry Andric 158e8d8bef9SDimitry Andric /// Tracker for converting machine value locations and variable values into 159e8d8bef9SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs 160e8d8bef9SDimitry Andric /// specifying block live-in locations and transfers within blocks. 161e8d8bef9SDimitry Andric /// 162e8d8bef9SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker 163e8d8bef9SDimitry Andric /// and must be initialized with the set of variable values that are live-in to 164e8d8bef9SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks 165e8d8bef9SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a 166e8d8bef9SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is 167e8d8bef9SDimitry Andric /// stepped through, transfers of values between machine locations are 168e8d8bef9SDimitry Andric /// identified and if profitable, a DBG_VALUE created. 169e8d8bef9SDimitry Andric /// 170e8d8bef9SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an 171e8d8bef9SDimitry Andric /// unavailable value could materialize in the middle of a block, when the 172e8d8bef9SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the 173e8d8bef9SDimitry Andric /// variable in a backup location. (XXX these are unimplemented). 174e8d8bef9SDimitry Andric class TransferTracker { 175e8d8bef9SDimitry Andric public: 176e8d8bef9SDimitry Andric const TargetInstrInfo *TII; 177fe6060f1SDimitry Andric const TargetLowering *TLI; 178e8d8bef9SDimitry Andric /// This machine location tracker is assumed to always contain the up-to-date 179e8d8bef9SDimitry Andric /// value mapping for all machine locations. TransferTracker only reads 180e8d8bef9SDimitry Andric /// information from it. (XXX make it const?) 181e8d8bef9SDimitry Andric MLocTracker *MTracker; 182e8d8bef9SDimitry Andric MachineFunction &MF; 183fe6060f1SDimitry Andric bool ShouldEmitDebugEntryValues; 184e8d8bef9SDimitry Andric 185e8d8bef9SDimitry Andric /// Record of all changes in variable locations at a block position. Awkwardly 186e8d8bef9SDimitry Andric /// we allow inserting either before or after the point: MBB != nullptr 187e8d8bef9SDimitry Andric /// indicates it's before, otherwise after. 188e8d8bef9SDimitry Andric struct Transfer { 189fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes 190e8d8bef9SDimitry Andric MachineBasicBlock *MBB; /// non-null if we should insert after. 191e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. 192e8d8bef9SDimitry Andric }; 193e8d8bef9SDimitry Andric 194fe6060f1SDimitry Andric struct LocAndProperties { 195e8d8bef9SDimitry Andric LocIdx Loc; 196e8d8bef9SDimitry Andric DbgValueProperties Properties; 197fe6060f1SDimitry Andric }; 198e8d8bef9SDimitry Andric 199e8d8bef9SDimitry Andric /// Collection of transfers (DBG_VALUEs) to be inserted. 200e8d8bef9SDimitry Andric SmallVector<Transfer, 32> Transfers; 201e8d8bef9SDimitry Andric 202e8d8bef9SDimitry Andric /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences 203e8d8bef9SDimitry Andric /// between TransferTrackers view of variable locations and MLocTrackers. For 204e8d8bef9SDimitry Andric /// example, MLocTracker observes all clobbers, but TransferTracker lazily 205e8d8bef9SDimitry Andric /// does not. 206349cc55cSDimitry Andric SmallVector<ValueIDNum, 32> VarLocs; 207e8d8bef9SDimitry Andric 208e8d8bef9SDimitry Andric /// Map from LocIdxes to which DebugVariables are based that location. 209e8d8bef9SDimitry Andric /// Mantained while stepping through the block. Not accurate if 210e8d8bef9SDimitry Andric /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. 211349cc55cSDimitry Andric DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; 212e8d8bef9SDimitry Andric 213e8d8bef9SDimitry Andric /// Map from DebugVariable to it's current location and qualifying meta 214e8d8bef9SDimitry Andric /// information. To be used in conjunction with ActiveMLocs to construct 215e8d8bef9SDimitry Andric /// enough information for the DBG_VALUEs for a particular LocIdx. 216e8d8bef9SDimitry Andric DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; 217e8d8bef9SDimitry Andric 218e8d8bef9SDimitry Andric /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. 219e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> PendingDbgValues; 220e8d8bef9SDimitry Andric 221e8d8bef9SDimitry Andric /// Record of a use-before-def: created when a value that's live-in to the 222e8d8bef9SDimitry Andric /// current block isn't available in any machine location, but it will be 223e8d8bef9SDimitry Andric /// defined in this block. 224e8d8bef9SDimitry Andric struct UseBeforeDef { 225e8d8bef9SDimitry Andric /// Value of this variable, def'd in block. 226e8d8bef9SDimitry Andric ValueIDNum ID; 227e8d8bef9SDimitry Andric /// Identity of this variable. 228e8d8bef9SDimitry Andric DebugVariable Var; 229e8d8bef9SDimitry Andric /// Additional variable properties. 230e8d8bef9SDimitry Andric DbgValueProperties Properties; 231e8d8bef9SDimitry Andric }; 232e8d8bef9SDimitry Andric 233e8d8bef9SDimitry Andric /// Map from instruction index (within the block) to the set of UseBeforeDefs 234e8d8bef9SDimitry Andric /// that become defined at that instruction. 235e8d8bef9SDimitry Andric DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; 236e8d8bef9SDimitry Andric 237e8d8bef9SDimitry Andric /// The set of variables that are in UseBeforeDefs and can become a location 238e8d8bef9SDimitry Andric /// once the relevant value is defined. An element being erased from this 239e8d8bef9SDimitry Andric /// collection prevents the use-before-def materializing. 240e8d8bef9SDimitry Andric DenseSet<DebugVariable> UseBeforeDefVariables; 241e8d8bef9SDimitry Andric 242e8d8bef9SDimitry Andric const TargetRegisterInfo &TRI; 243e8d8bef9SDimitry Andric const BitVector &CalleeSavedRegs; 244e8d8bef9SDimitry Andric 245e8d8bef9SDimitry Andric TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, 246e8d8bef9SDimitry Andric MachineFunction &MF, const TargetRegisterInfo &TRI, 247fe6060f1SDimitry Andric const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) 248e8d8bef9SDimitry Andric : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), 249fe6060f1SDimitry Andric CalleeSavedRegs(CalleeSavedRegs) { 250fe6060f1SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 251fe6060f1SDimitry Andric auto &TM = TPC.getTM<TargetMachine>(); 252fe6060f1SDimitry Andric ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); 253fe6060f1SDimitry Andric } 254e8d8bef9SDimitry Andric 255e8d8bef9SDimitry Andric /// Load object with live-in variable values. \p mlocs contains the live-in 256e8d8bef9SDimitry Andric /// values in each machine location, while \p vlocs the live-in variable 257e8d8bef9SDimitry Andric /// values. This method picks variable locations for the live-in variables, 258e8d8bef9SDimitry Andric /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other 259e8d8bef9SDimitry Andric /// object fields to track variable locations as we step through the block. 260e8d8bef9SDimitry Andric /// FIXME: could just examine mloctracker instead of passing in \p mlocs? 26104eeddc0SDimitry Andric void 262*81ad6265SDimitry Andric loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, 26304eeddc0SDimitry Andric const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, 264e8d8bef9SDimitry Andric unsigned NumLocs) { 265e8d8bef9SDimitry Andric ActiveMLocs.clear(); 266e8d8bef9SDimitry Andric ActiveVLocs.clear(); 267e8d8bef9SDimitry Andric VarLocs.clear(); 268e8d8bef9SDimitry Andric VarLocs.reserve(NumLocs); 269e8d8bef9SDimitry Andric UseBeforeDefs.clear(); 270e8d8bef9SDimitry Andric UseBeforeDefVariables.clear(); 271e8d8bef9SDimitry Andric 272e8d8bef9SDimitry Andric auto isCalleeSaved = [&](LocIdx L) { 273e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 274e8d8bef9SDimitry Andric if (Reg >= MTracker->NumRegs) 275e8d8bef9SDimitry Andric return false; 276e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) 277e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 278e8d8bef9SDimitry Andric return true; 279e8d8bef9SDimitry Andric return false; 280e8d8bef9SDimitry Andric }; 281e8d8bef9SDimitry Andric 282e8d8bef9SDimitry Andric // Map of the preferred location for each value. 28304eeddc0SDimitry Andric DenseMap<ValueIDNum, LocIdx> ValueToLoc; 2841fd87a68SDimitry Andric 2851fd87a68SDimitry Andric // Initialized the preferred-location map with illegal locations, to be 2861fd87a68SDimitry Andric // filled in later. 2871fd87a68SDimitry Andric for (auto &VLoc : VLocs) 2881fd87a68SDimitry Andric if (VLoc.second.Kind == DbgValue::Def) 2891fd87a68SDimitry Andric ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()}); 2901fd87a68SDimitry Andric 291349cc55cSDimitry Andric ActiveMLocs.reserve(VLocs.size()); 292349cc55cSDimitry Andric ActiveVLocs.reserve(VLocs.size()); 293e8d8bef9SDimitry Andric 294e8d8bef9SDimitry Andric // Produce a map of value numbers to the current machine locs they live 295e8d8bef9SDimitry Andric // in. When emulating VarLocBasedImpl, there should only be one 296e8d8bef9SDimitry Andric // location; when not, we get to pick. 297e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 298e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 299e8d8bef9SDimitry Andric ValueIDNum &VNum = MLocs[Idx.asU64()]; 300e8d8bef9SDimitry Andric VarLocs.push_back(VNum); 30104eeddc0SDimitry Andric 3021fd87a68SDimitry Andric // Is there a variable that wants a location for this value? If not, skip. 3031fd87a68SDimitry Andric auto VIt = ValueToLoc.find(VNum); 3041fd87a68SDimitry Andric if (VIt == ValueToLoc.end()) 30504eeddc0SDimitry Andric continue; 30604eeddc0SDimitry Andric 3071fd87a68SDimitry Andric LocIdx CurLoc = VIt->second; 308e8d8bef9SDimitry Andric // In order of preference, pick: 309e8d8bef9SDimitry Andric // * Callee saved registers, 310e8d8bef9SDimitry Andric // * Other registers, 311e8d8bef9SDimitry Andric // * Spill slots. 3121fd87a68SDimitry Andric if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) || 3131fd87a68SDimitry Andric (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) { 314e8d8bef9SDimitry Andric // Insert, or overwrite if insertion failed. 3151fd87a68SDimitry Andric VIt->second = Idx; 316e8d8bef9SDimitry Andric } 317e8d8bef9SDimitry Andric } 318e8d8bef9SDimitry Andric 319e8d8bef9SDimitry Andric // Now map variables to their picked LocIdxes. 32004eeddc0SDimitry Andric for (const auto &Var : VLocs) { 321e8d8bef9SDimitry Andric if (Var.second.Kind == DbgValue::Const) { 322e8d8bef9SDimitry Andric PendingDbgValues.push_back( 323349cc55cSDimitry Andric emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties)); 324e8d8bef9SDimitry Andric continue; 325e8d8bef9SDimitry Andric } 326e8d8bef9SDimitry Andric 327e8d8bef9SDimitry Andric // If the value has no location, we can't make a variable location. 328e8d8bef9SDimitry Andric const ValueIDNum &Num = Var.second.ID; 329e8d8bef9SDimitry Andric auto ValuesPreferredLoc = ValueToLoc.find(Num); 3301fd87a68SDimitry Andric if (ValuesPreferredLoc->second.isIllegal()) { 331e8d8bef9SDimitry Andric // If it's a def that occurs in this block, register it as a 332e8d8bef9SDimitry Andric // use-before-def to be resolved as we step through the block. 333e8d8bef9SDimitry Andric if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) 334e8d8bef9SDimitry Andric addUseBeforeDef(Var.first, Var.second.Properties, Num); 335fe6060f1SDimitry Andric else 336fe6060f1SDimitry Andric recoverAsEntryValue(Var.first, Var.second.Properties, Num); 337e8d8bef9SDimitry Andric continue; 338e8d8bef9SDimitry Andric } 339e8d8bef9SDimitry Andric 340e8d8bef9SDimitry Andric LocIdx M = ValuesPreferredLoc->second; 341e8d8bef9SDimitry Andric auto NewValue = LocAndProperties{M, Var.second.Properties}; 342e8d8bef9SDimitry Andric auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); 343e8d8bef9SDimitry Andric if (!Result.second) 344e8d8bef9SDimitry Andric Result.first->second = NewValue; 345e8d8bef9SDimitry Andric ActiveMLocs[M].insert(Var.first); 346e8d8bef9SDimitry Andric PendingDbgValues.push_back( 347e8d8bef9SDimitry Andric MTracker->emitLoc(M, Var.first, Var.second.Properties)); 348e8d8bef9SDimitry Andric } 349e8d8bef9SDimitry Andric flushDbgValues(MBB.begin(), &MBB); 350e8d8bef9SDimitry Andric } 351e8d8bef9SDimitry Andric 352e8d8bef9SDimitry Andric /// Record that \p Var has value \p ID, a value that becomes available 353e8d8bef9SDimitry Andric /// later in the function. 354e8d8bef9SDimitry Andric void addUseBeforeDef(const DebugVariable &Var, 355e8d8bef9SDimitry Andric const DbgValueProperties &Properties, ValueIDNum ID) { 356e8d8bef9SDimitry Andric UseBeforeDef UBD = {ID, Var, Properties}; 357e8d8bef9SDimitry Andric UseBeforeDefs[ID.getInst()].push_back(UBD); 358e8d8bef9SDimitry Andric UseBeforeDefVariables.insert(Var); 359e8d8bef9SDimitry Andric } 360e8d8bef9SDimitry Andric 361e8d8bef9SDimitry Andric /// After the instruction at index \p Inst and position \p pos has been 362e8d8bef9SDimitry Andric /// processed, check whether it defines a variable value in a use-before-def. 363e8d8bef9SDimitry Andric /// If so, and the variable value hasn't changed since the start of the 364e8d8bef9SDimitry Andric /// block, create a DBG_VALUE. 365e8d8bef9SDimitry Andric void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { 366e8d8bef9SDimitry Andric auto MIt = UseBeforeDefs.find(Inst); 367e8d8bef9SDimitry Andric if (MIt == UseBeforeDefs.end()) 368e8d8bef9SDimitry Andric return; 369e8d8bef9SDimitry Andric 370e8d8bef9SDimitry Andric for (auto &Use : MIt->second) { 371e8d8bef9SDimitry Andric LocIdx L = Use.ID.getLoc(); 372e8d8bef9SDimitry Andric 373e8d8bef9SDimitry Andric // If something goes very wrong, we might end up labelling a COPY 374e8d8bef9SDimitry Andric // instruction or similar with an instruction number, where it doesn't 375e8d8bef9SDimitry Andric // actually define a new value, instead it moves a value. In case this 376e8d8bef9SDimitry Andric // happens, discard. 377349cc55cSDimitry Andric if (MTracker->readMLoc(L) != Use.ID) 378e8d8bef9SDimitry Andric continue; 379e8d8bef9SDimitry Andric 380e8d8bef9SDimitry Andric // If a different debug instruction defined the variable value / location 381e8d8bef9SDimitry Andric // since the start of the block, don't materialize this use-before-def. 382e8d8bef9SDimitry Andric if (!UseBeforeDefVariables.count(Use.Var)) 383e8d8bef9SDimitry Andric continue; 384e8d8bef9SDimitry Andric 385e8d8bef9SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); 386e8d8bef9SDimitry Andric } 387e8d8bef9SDimitry Andric flushDbgValues(pos, nullptr); 388e8d8bef9SDimitry Andric } 389e8d8bef9SDimitry Andric 390e8d8bef9SDimitry Andric /// Helper to move created DBG_VALUEs into Transfers collection. 391e8d8bef9SDimitry Andric void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { 392fe6060f1SDimitry Andric if (PendingDbgValues.size() == 0) 393fe6060f1SDimitry Andric return; 394fe6060f1SDimitry Andric 395fe6060f1SDimitry Andric // Pick out the instruction start position. 396fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator BundleStart; 397fe6060f1SDimitry Andric if (MBB && Pos == MBB->begin()) 398fe6060f1SDimitry Andric BundleStart = MBB->instr_begin(); 399fe6060f1SDimitry Andric else 400fe6060f1SDimitry Andric BundleStart = getBundleStart(Pos->getIterator()); 401fe6060f1SDimitry Andric 402fe6060f1SDimitry Andric Transfers.push_back({BundleStart, MBB, PendingDbgValues}); 403e8d8bef9SDimitry Andric PendingDbgValues.clear(); 404e8d8bef9SDimitry Andric } 405fe6060f1SDimitry Andric 406fe6060f1SDimitry Andric bool isEntryValueVariable(const DebugVariable &Var, 407fe6060f1SDimitry Andric const DIExpression *Expr) const { 408fe6060f1SDimitry Andric if (!Var.getVariable()->isParameter()) 409fe6060f1SDimitry Andric return false; 410fe6060f1SDimitry Andric 411fe6060f1SDimitry Andric if (Var.getInlinedAt()) 412fe6060f1SDimitry Andric return false; 413fe6060f1SDimitry Andric 414fe6060f1SDimitry Andric if (Expr->getNumElements() > 0) 415fe6060f1SDimitry Andric return false; 416fe6060f1SDimitry Andric 417fe6060f1SDimitry Andric return true; 418fe6060f1SDimitry Andric } 419fe6060f1SDimitry Andric 420fe6060f1SDimitry Andric bool isEntryValueValue(const ValueIDNum &Val) const { 421fe6060f1SDimitry Andric // Must be in entry block (block number zero), and be a PHI / live-in value. 422fe6060f1SDimitry Andric if (Val.getBlock() || !Val.isPHI()) 423fe6060f1SDimitry Andric return false; 424fe6060f1SDimitry Andric 425fe6060f1SDimitry Andric // Entry values must enter in a register. 426fe6060f1SDimitry Andric if (MTracker->isSpill(Val.getLoc())) 427fe6060f1SDimitry Andric return false; 428fe6060f1SDimitry Andric 429fe6060f1SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore(); 430fe6060f1SDimitry Andric Register FP = TRI.getFrameRegister(MF); 431fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; 432fe6060f1SDimitry Andric return Reg != SP && Reg != FP; 433fe6060f1SDimitry Andric } 434fe6060f1SDimitry Andric 43504eeddc0SDimitry Andric bool recoverAsEntryValue(const DebugVariable &Var, 43604eeddc0SDimitry Andric const DbgValueProperties &Prop, 437fe6060f1SDimitry Andric const ValueIDNum &Num) { 438fe6060f1SDimitry Andric // Is this variable location a candidate to be an entry value. First, 439fe6060f1SDimitry Andric // should we be trying this at all? 440fe6060f1SDimitry Andric if (!ShouldEmitDebugEntryValues) 441fe6060f1SDimitry Andric return false; 442fe6060f1SDimitry Andric 443fe6060f1SDimitry Andric // Is the variable appropriate for entry values (i.e., is a parameter). 444fe6060f1SDimitry Andric if (!isEntryValueVariable(Var, Prop.DIExpr)) 445fe6060f1SDimitry Andric return false; 446fe6060f1SDimitry Andric 447fe6060f1SDimitry Andric // Is the value assigned to this variable still the entry value? 448fe6060f1SDimitry Andric if (!isEntryValueValue(Num)) 449fe6060f1SDimitry Andric return false; 450fe6060f1SDimitry Andric 451fe6060f1SDimitry Andric // Emit a variable location using an entry value expression. 452fe6060f1SDimitry Andric DIExpression *NewExpr = 453fe6060f1SDimitry Andric DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); 454fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; 455fe6060f1SDimitry Andric MachineOperand MO = MachineOperand::CreateReg(Reg, false); 456fe6060f1SDimitry Andric 457fe6060f1SDimitry Andric PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); 458fe6060f1SDimitry Andric return true; 459e8d8bef9SDimitry Andric } 460e8d8bef9SDimitry Andric 461e8d8bef9SDimitry Andric /// Change a variable value after encountering a DBG_VALUE inside a block. 462e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI) { 463e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 464e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 465e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 466e8d8bef9SDimitry Andric 467e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 468e8d8bef9SDimitry Andric 469e8d8bef9SDimitry Andric // Ignore non-register locations, we don't transfer those. 470e8d8bef9SDimitry Andric if (!MO.isReg() || MO.getReg() == 0) { 471e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 472e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) { 473e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 474e8d8bef9SDimitry Andric ActiveVLocs.erase(It); 475e8d8bef9SDimitry Andric } 476e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 477e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 478e8d8bef9SDimitry Andric return; 479e8d8bef9SDimitry Andric } 480e8d8bef9SDimitry Andric 481e8d8bef9SDimitry Andric Register Reg = MO.getReg(); 482e8d8bef9SDimitry Andric LocIdx NewLoc = MTracker->getRegMLoc(Reg); 483e8d8bef9SDimitry Andric redefVar(MI, Properties, NewLoc); 484e8d8bef9SDimitry Andric } 485e8d8bef9SDimitry Andric 486e8d8bef9SDimitry Andric /// Handle a change in variable location within a block. Terminate the 487e8d8bef9SDimitry Andric /// variables current location, and record the value it now refers to, so 488e8d8bef9SDimitry Andric /// that we can detect location transfers later on. 489e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, 490e8d8bef9SDimitry Andric Optional<LocIdx> OptNewLoc) { 491e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 492e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 493e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 494e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 495e8d8bef9SDimitry Andric 496e8d8bef9SDimitry Andric // Erase any previous location, 497e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 498e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) 499e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 500e8d8bef9SDimitry Andric 501e8d8bef9SDimitry Andric // If there _is_ no new location, all we had to do was erase. 502e8d8bef9SDimitry Andric if (!OptNewLoc) 503e8d8bef9SDimitry Andric return; 504e8d8bef9SDimitry Andric LocIdx NewLoc = *OptNewLoc; 505e8d8bef9SDimitry Andric 506e8d8bef9SDimitry Andric // Check whether our local copy of values-by-location in #VarLocs is out of 507e8d8bef9SDimitry Andric // date. Wipe old tracking data for the location if it's been clobbered in 508e8d8bef9SDimitry Andric // the meantime. 509349cc55cSDimitry Andric if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) { 510e8d8bef9SDimitry Andric for (auto &P : ActiveMLocs[NewLoc]) { 511e8d8bef9SDimitry Andric ActiveVLocs.erase(P); 512e8d8bef9SDimitry Andric } 513e8d8bef9SDimitry Andric ActiveMLocs[NewLoc.asU64()].clear(); 514349cc55cSDimitry Andric VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc); 515e8d8bef9SDimitry Andric } 516e8d8bef9SDimitry Andric 517e8d8bef9SDimitry Andric ActiveMLocs[NewLoc].insert(Var); 518e8d8bef9SDimitry Andric if (It == ActiveVLocs.end()) { 519e8d8bef9SDimitry Andric ActiveVLocs.insert( 520e8d8bef9SDimitry Andric std::make_pair(Var, LocAndProperties{NewLoc, Properties})); 521e8d8bef9SDimitry Andric } else { 522e8d8bef9SDimitry Andric It->second.Loc = NewLoc; 523e8d8bef9SDimitry Andric It->second.Properties = Properties; 524e8d8bef9SDimitry Andric } 525e8d8bef9SDimitry Andric } 526e8d8bef9SDimitry Andric 527fe6060f1SDimitry Andric /// Account for a location \p mloc being clobbered. Examine the variable 528fe6060f1SDimitry Andric /// locations that will be terminated: and try to recover them by using 529fe6060f1SDimitry Andric /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to 530fe6060f1SDimitry Andric /// explicitly terminate a location if it can't be recovered. 531fe6060f1SDimitry Andric void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, 532fe6060f1SDimitry Andric bool MakeUndef = true) { 533e8d8bef9SDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc); 534e8d8bef9SDimitry Andric if (ActiveMLocIt == ActiveMLocs.end()) 535e8d8bef9SDimitry Andric return; 536e8d8bef9SDimitry Andric 537fe6060f1SDimitry Andric // What was the old variable value? 538fe6060f1SDimitry Andric ValueIDNum OldValue = VarLocs[MLoc.asU64()]; 539e8d8bef9SDimitry Andric VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; 540e8d8bef9SDimitry Andric 541fe6060f1SDimitry Andric // Examine the remaining variable locations: if we can find the same value 542fe6060f1SDimitry Andric // again, we can recover the location. 543fe6060f1SDimitry Andric Optional<LocIdx> NewLoc = None; 544fe6060f1SDimitry Andric for (auto Loc : MTracker->locations()) 545fe6060f1SDimitry Andric if (Loc.Value == OldValue) 546fe6060f1SDimitry Andric NewLoc = Loc.Idx; 547fe6060f1SDimitry Andric 548fe6060f1SDimitry Andric // If there is no location, and we weren't asked to make the variable 549fe6060f1SDimitry Andric // explicitly undef, then stop here. 550fe6060f1SDimitry Andric if (!NewLoc && !MakeUndef) { 551fe6060f1SDimitry Andric // Try and recover a few more locations with entry values. 552fe6060f1SDimitry Andric for (auto &Var : ActiveMLocIt->second) { 553fe6060f1SDimitry Andric auto &Prop = ActiveVLocs.find(Var)->second.Properties; 554fe6060f1SDimitry Andric recoverAsEntryValue(Var, Prop, OldValue); 555fe6060f1SDimitry Andric } 556fe6060f1SDimitry Andric flushDbgValues(Pos, nullptr); 557fe6060f1SDimitry Andric return; 558fe6060f1SDimitry Andric } 559fe6060f1SDimitry Andric 560fe6060f1SDimitry Andric // Examine all the variables based on this location. 561fe6060f1SDimitry Andric DenseSet<DebugVariable> NewMLocs; 562e8d8bef9SDimitry Andric for (auto &Var : ActiveMLocIt->second) { 563e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 564fe6060f1SDimitry Andric // Re-state the variable location: if there's no replacement then NewLoc 565fe6060f1SDimitry Andric // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE 566fe6060f1SDimitry Andric // identifying the alternative location will be emitted. 5674824e7fdSDimitry Andric const DbgValueProperties &Properties = ActiveVLocIt->second.Properties; 568fe6060f1SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); 569fe6060f1SDimitry Andric 570fe6060f1SDimitry Andric // Update machine locations <=> variable locations maps. Defer updating 571fe6060f1SDimitry Andric // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. 572fe6060f1SDimitry Andric if (!NewLoc) { 573e8d8bef9SDimitry Andric ActiveVLocs.erase(ActiveVLocIt); 574fe6060f1SDimitry Andric } else { 575fe6060f1SDimitry Andric ActiveVLocIt->second.Loc = *NewLoc; 576fe6060f1SDimitry Andric NewMLocs.insert(Var); 577e8d8bef9SDimitry Andric } 578fe6060f1SDimitry Andric } 579fe6060f1SDimitry Andric 580fe6060f1SDimitry Andric // Commit any deferred ActiveMLoc changes. 581fe6060f1SDimitry Andric if (!NewMLocs.empty()) 582fe6060f1SDimitry Andric for (auto &Var : NewMLocs) 583fe6060f1SDimitry Andric ActiveMLocs[*NewLoc].insert(Var); 584fe6060f1SDimitry Andric 585fe6060f1SDimitry Andric // We lazily track what locations have which values; if we've found a new 586fe6060f1SDimitry Andric // location for the clobbered value, remember it. 587fe6060f1SDimitry Andric if (NewLoc) 588fe6060f1SDimitry Andric VarLocs[NewLoc->asU64()] = OldValue; 589fe6060f1SDimitry Andric 590e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 591e8d8bef9SDimitry Andric 592349cc55cSDimitry Andric // Re-find ActiveMLocIt, iterator could have been invalidated. 593349cc55cSDimitry Andric ActiveMLocIt = ActiveMLocs.find(MLoc); 594e8d8bef9SDimitry Andric ActiveMLocIt->second.clear(); 595e8d8bef9SDimitry Andric } 596e8d8bef9SDimitry Andric 597e8d8bef9SDimitry Andric /// Transfer variables based on \p Src to be based on \p Dst. This handles 598e8d8bef9SDimitry Andric /// both register copies as well as spills and restores. Creates DBG_VALUEs 599e8d8bef9SDimitry Andric /// describing the movement. 600e8d8bef9SDimitry Andric void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { 601e8d8bef9SDimitry Andric // Does Src still contain the value num we expect? If not, it's been 602e8d8bef9SDimitry Andric // clobbered in the meantime, and our variable locations are stale. 603349cc55cSDimitry Andric if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src)) 604e8d8bef9SDimitry Andric return; 605e8d8bef9SDimitry Andric 606e8d8bef9SDimitry Andric // assert(ActiveMLocs[Dst].size() == 0); 607e8d8bef9SDimitry Andric //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? 608349cc55cSDimitry Andric 609349cc55cSDimitry Andric // Move set of active variables from one location to another. 610349cc55cSDimitry Andric auto MovingVars = ActiveMLocs[Src]; 611349cc55cSDimitry Andric ActiveMLocs[Dst] = MovingVars; 612e8d8bef9SDimitry Andric VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; 613e8d8bef9SDimitry Andric 614e8d8bef9SDimitry Andric // For each variable based on Src; create a location at Dst. 615349cc55cSDimitry Andric for (auto &Var : MovingVars) { 616e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 617e8d8bef9SDimitry Andric assert(ActiveVLocIt != ActiveVLocs.end()); 618e8d8bef9SDimitry Andric ActiveVLocIt->second.Loc = Dst; 619e8d8bef9SDimitry Andric 620e8d8bef9SDimitry Andric MachineInstr *MI = 621e8d8bef9SDimitry Andric MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); 622e8d8bef9SDimitry Andric PendingDbgValues.push_back(MI); 623e8d8bef9SDimitry Andric } 624e8d8bef9SDimitry Andric ActiveMLocs[Src].clear(); 625e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 626e8d8bef9SDimitry Andric 627e8d8bef9SDimitry Andric // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data 628e8d8bef9SDimitry Andric // about the old location. 629e8d8bef9SDimitry Andric if (EmulateOldLDV) 630e8d8bef9SDimitry Andric VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; 631e8d8bef9SDimitry Andric } 632e8d8bef9SDimitry Andric 633e8d8bef9SDimitry Andric MachineInstrBuilder emitMOLoc(const MachineOperand &MO, 634e8d8bef9SDimitry Andric const DebugVariable &Var, 635e8d8bef9SDimitry Andric const DbgValueProperties &Properties) { 636e8d8bef9SDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 637e8d8bef9SDimitry Andric Var.getVariable()->getScope(), 638e8d8bef9SDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 639e8d8bef9SDimitry Andric auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 640e8d8bef9SDimitry Andric MIB.add(MO); 641e8d8bef9SDimitry Andric if (Properties.Indirect) 642e8d8bef9SDimitry Andric MIB.addImm(0); 643e8d8bef9SDimitry Andric else 644e8d8bef9SDimitry Andric MIB.addReg(0); 645e8d8bef9SDimitry Andric MIB.addMetadata(Var.getVariable()); 646e8d8bef9SDimitry Andric MIB.addMetadata(Properties.DIExpr); 647e8d8bef9SDimitry Andric return MIB; 648e8d8bef9SDimitry Andric } 649e8d8bef9SDimitry Andric }; 650e8d8bef9SDimitry Andric 651349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 652349cc55cSDimitry Andric // Implementation 653349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 654e8d8bef9SDimitry Andric 655349cc55cSDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; 656349cc55cSDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1}; 657e8d8bef9SDimitry Andric 658349cc55cSDimitry Andric #ifndef NDEBUG 659349cc55cSDimitry Andric void DbgValue::dump(const MLocTracker *MTrack) const { 660349cc55cSDimitry Andric if (Kind == Const) { 661349cc55cSDimitry Andric MO->dump(); 662349cc55cSDimitry Andric } else if (Kind == NoVal) { 663349cc55cSDimitry Andric dbgs() << "NoVal(" << BlockNo << ")"; 664349cc55cSDimitry Andric } else if (Kind == VPHI) { 665349cc55cSDimitry Andric dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")"; 666349cc55cSDimitry Andric } else { 667349cc55cSDimitry Andric assert(Kind == Def); 668349cc55cSDimitry Andric dbgs() << MTrack->IDAsString(ID); 669349cc55cSDimitry Andric } 670349cc55cSDimitry Andric if (Properties.Indirect) 671349cc55cSDimitry Andric dbgs() << " indir"; 672349cc55cSDimitry Andric if (Properties.DIExpr) 673349cc55cSDimitry Andric dbgs() << " " << *Properties.DIExpr; 674349cc55cSDimitry Andric } 675349cc55cSDimitry Andric #endif 676e8d8bef9SDimitry Andric 677349cc55cSDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 678349cc55cSDimitry Andric const TargetRegisterInfo &TRI, 679349cc55cSDimitry Andric const TargetLowering &TLI) 680349cc55cSDimitry Andric : MF(MF), TII(TII), TRI(TRI), TLI(TLI), 681349cc55cSDimitry Andric LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) { 682349cc55cSDimitry Andric NumRegs = TRI.getNumRegs(); 683349cc55cSDimitry Andric reset(); 684349cc55cSDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 685349cc55cSDimitry Andric assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure 686e8d8bef9SDimitry Andric 687349cc55cSDimitry Andric // Always track SP. This avoids the implicit clobbering caused by regmasks 688349cc55cSDimitry Andric // from affectings its values. (LiveDebugValues disbelieves calls and 689349cc55cSDimitry Andric // regmasks that claim to clobber SP). 690349cc55cSDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore(); 691349cc55cSDimitry Andric if (SP) { 692349cc55cSDimitry Andric unsigned ID = getLocID(SP); 693349cc55cSDimitry Andric (void)lookupOrTrackRegister(ID); 694e8d8bef9SDimitry Andric 695349cc55cSDimitry Andric for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI) 696349cc55cSDimitry Andric SPAliases.insert(*RAI); 697349cc55cSDimitry Andric } 698e8d8bef9SDimitry Andric 699349cc55cSDimitry Andric // Build some common stack positions -- full registers being spilt to the 700349cc55cSDimitry Andric // stack. 701349cc55cSDimitry Andric StackSlotIdxes.insert({{8, 0}, 0}); 702349cc55cSDimitry Andric StackSlotIdxes.insert({{16, 0}, 1}); 703349cc55cSDimitry Andric StackSlotIdxes.insert({{32, 0}, 2}); 704349cc55cSDimitry Andric StackSlotIdxes.insert({{64, 0}, 3}); 705349cc55cSDimitry Andric StackSlotIdxes.insert({{128, 0}, 4}); 706349cc55cSDimitry Andric StackSlotIdxes.insert({{256, 0}, 5}); 707349cc55cSDimitry Andric StackSlotIdxes.insert({{512, 0}, 6}); 708e8d8bef9SDimitry Andric 709349cc55cSDimitry Andric // Traverse all the subregister idxes, and ensure there's an index for them. 710349cc55cSDimitry Andric // Duplicates are no problem: we're interested in their position in the 711349cc55cSDimitry Andric // stack slot, we don't want to type the slot. 712349cc55cSDimitry Andric for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) { 713349cc55cSDimitry Andric unsigned Size = TRI.getSubRegIdxSize(I); 714349cc55cSDimitry Andric unsigned Offs = TRI.getSubRegIdxOffset(I); 715349cc55cSDimitry Andric unsigned Idx = StackSlotIdxes.size(); 716e8d8bef9SDimitry Andric 717349cc55cSDimitry Andric // Some subregs have -1, -2 and so forth fed into their fields, to mean 718349cc55cSDimitry Andric // special backend things. Ignore those. 719349cc55cSDimitry Andric if (Size > 60000 || Offs > 60000) 720349cc55cSDimitry Andric continue; 721e8d8bef9SDimitry Andric 722349cc55cSDimitry Andric StackSlotIdxes.insert({{Size, Offs}, Idx}); 723349cc55cSDimitry Andric } 724e8d8bef9SDimitry Andric 725*81ad6265SDimitry Andric // There may also be strange register class sizes (think x86 fp80s). 726*81ad6265SDimitry Andric for (const TargetRegisterClass *RC : TRI.regclasses()) { 727*81ad6265SDimitry Andric unsigned Size = TRI.getRegSizeInBits(*RC); 728*81ad6265SDimitry Andric 729*81ad6265SDimitry Andric // We might see special reserved values as sizes, and classes for other 730*81ad6265SDimitry Andric // stuff the machine tries to model. If it's more than 512 bits, then it 731*81ad6265SDimitry Andric // is very unlikely to be a register than can be spilt. 732*81ad6265SDimitry Andric if (Size > 512) 733*81ad6265SDimitry Andric continue; 734*81ad6265SDimitry Andric 735*81ad6265SDimitry Andric unsigned Idx = StackSlotIdxes.size(); 736*81ad6265SDimitry Andric StackSlotIdxes.insert({{Size, 0}, Idx}); 737*81ad6265SDimitry Andric } 738*81ad6265SDimitry Andric 739349cc55cSDimitry Andric for (auto &Idx : StackSlotIdxes) 740349cc55cSDimitry Andric StackIdxesToPos[Idx.second] = Idx.first; 741e8d8bef9SDimitry Andric 742349cc55cSDimitry Andric NumSlotIdxes = StackSlotIdxes.size(); 743349cc55cSDimitry Andric } 744e8d8bef9SDimitry Andric 745349cc55cSDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) { 746349cc55cSDimitry Andric assert(ID != 0); 747349cc55cSDimitry Andric LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); 748349cc55cSDimitry Andric LocIdxToIDNum.grow(NewIdx); 749349cc55cSDimitry Andric LocIdxToLocID.grow(NewIdx); 750e8d8bef9SDimitry Andric 751349cc55cSDimitry Andric // Default: it's an mphi. 752349cc55cSDimitry Andric ValueIDNum ValNum = {CurBB, 0, NewIdx}; 753349cc55cSDimitry Andric // Was this reg ever touched by a regmask? 754349cc55cSDimitry Andric for (const auto &MaskPair : reverse(Masks)) { 755349cc55cSDimitry Andric if (MaskPair.first->clobbersPhysReg(ID)) { 756349cc55cSDimitry Andric // There was an earlier def we skipped. 757349cc55cSDimitry Andric ValNum = {CurBB, MaskPair.second, NewIdx}; 758349cc55cSDimitry Andric break; 759349cc55cSDimitry Andric } 760349cc55cSDimitry Andric } 761e8d8bef9SDimitry Andric 762349cc55cSDimitry Andric LocIdxToIDNum[NewIdx] = ValNum; 763349cc55cSDimitry Andric LocIdxToLocID[NewIdx] = ID; 764349cc55cSDimitry Andric return NewIdx; 765349cc55cSDimitry Andric } 766e8d8bef9SDimitry Andric 767349cc55cSDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB, 768349cc55cSDimitry Andric unsigned InstID) { 769349cc55cSDimitry Andric // Def any register we track have that isn't preserved. The regmask 770349cc55cSDimitry Andric // terminates the liveness of a register, meaning its value can't be 771349cc55cSDimitry Andric // relied upon -- we represent this by giving it a new value. 772349cc55cSDimitry Andric for (auto Location : locations()) { 773349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Location.Idx]; 774349cc55cSDimitry Andric // Don't clobber SP, even if the mask says it's clobbered. 775349cc55cSDimitry Andric if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID)) 776349cc55cSDimitry Andric defReg(ID, CurBB, InstID); 777349cc55cSDimitry Andric } 778349cc55cSDimitry Andric Masks.push_back(std::make_pair(MO, InstID)); 779349cc55cSDimitry Andric } 780e8d8bef9SDimitry Andric 781d56accc7SDimitry Andric Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) { 782349cc55cSDimitry Andric SpillLocationNo SpillID(SpillLocs.idFor(L)); 783d56accc7SDimitry Andric 784349cc55cSDimitry Andric if (SpillID.id() == 0) { 785d56accc7SDimitry Andric // If there is no location, and we have reached the limit of how many stack 786d56accc7SDimitry Andric // slots to track, then don't track this one. 787d56accc7SDimitry Andric if (SpillLocs.size() >= StackWorkingSetLimit) 788d56accc7SDimitry Andric return None; 789d56accc7SDimitry Andric 790349cc55cSDimitry Andric // Spill location is untracked: create record for this one, and all 791349cc55cSDimitry Andric // subregister slots too. 792349cc55cSDimitry Andric SpillID = SpillLocationNo(SpillLocs.insert(L)); 793349cc55cSDimitry Andric for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) { 794349cc55cSDimitry Andric unsigned L = getSpillIDWithIdx(SpillID, StackIdx); 795349cc55cSDimitry Andric LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx 796349cc55cSDimitry Andric LocIdxToIDNum.grow(Idx); 797349cc55cSDimitry Andric LocIdxToLocID.grow(Idx); 798349cc55cSDimitry Andric LocIDToLocIdx.push_back(Idx); 799349cc55cSDimitry Andric LocIdxToLocID[Idx] = L; 800349cc55cSDimitry Andric // Initialize to PHI value; corresponds to the location's live-in value 801349cc55cSDimitry Andric // during transfer function construction. 802349cc55cSDimitry Andric LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx); 803349cc55cSDimitry Andric } 804349cc55cSDimitry Andric } 805349cc55cSDimitry Andric return SpillID; 806349cc55cSDimitry Andric } 807fe6060f1SDimitry Andric 808349cc55cSDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const { 809349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Idx]; 810349cc55cSDimitry Andric if (ID >= NumRegs) { 811349cc55cSDimitry Andric StackSlotPos Pos = locIDToSpillIdx(ID); 812349cc55cSDimitry Andric ID -= NumRegs; 813349cc55cSDimitry Andric unsigned Slot = ID / NumSlotIdxes; 814349cc55cSDimitry Andric return Twine("slot ") 815349cc55cSDimitry Andric .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first) 816349cc55cSDimitry Andric .concat(Twine(" offs ").concat(Twine(Pos.second)))))) 817349cc55cSDimitry Andric .str(); 818349cc55cSDimitry Andric } else { 819349cc55cSDimitry Andric return TRI.getRegAsmName(ID).str(); 820349cc55cSDimitry Andric } 821349cc55cSDimitry Andric } 822fe6060f1SDimitry Andric 823349cc55cSDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const { 824349cc55cSDimitry Andric std::string DefName = LocIdxToName(Num.getLoc()); 825349cc55cSDimitry Andric return Num.asString(DefName); 826349cc55cSDimitry Andric } 827fe6060f1SDimitry Andric 828349cc55cSDimitry Andric #ifndef NDEBUG 829349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() { 830349cc55cSDimitry Andric for (auto Location : locations()) { 831349cc55cSDimitry Andric std::string MLocName = LocIdxToName(Location.Value.getLoc()); 832349cc55cSDimitry Andric std::string DefName = Location.Value.asString(MLocName); 833349cc55cSDimitry Andric dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; 834349cc55cSDimitry Andric } 835349cc55cSDimitry Andric } 836e8d8bef9SDimitry Andric 837349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() { 838349cc55cSDimitry Andric for (auto Location : locations()) { 839349cc55cSDimitry Andric std::string foo = LocIdxToName(Location.Idx); 840349cc55cSDimitry Andric dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; 841349cc55cSDimitry Andric } 842349cc55cSDimitry Andric } 843349cc55cSDimitry Andric #endif 844e8d8bef9SDimitry Andric 845349cc55cSDimitry Andric MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc, 846349cc55cSDimitry Andric const DebugVariable &Var, 847349cc55cSDimitry Andric const DbgValueProperties &Properties) { 848349cc55cSDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 849349cc55cSDimitry Andric Var.getVariable()->getScope(), 850349cc55cSDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 851349cc55cSDimitry Andric auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); 852e8d8bef9SDimitry Andric 853349cc55cSDimitry Andric const DIExpression *Expr = Properties.DIExpr; 854349cc55cSDimitry Andric if (!MLoc) { 855349cc55cSDimitry Andric // No location -> DBG_VALUE $noreg 856349cc55cSDimitry Andric MIB.addReg(0); 857349cc55cSDimitry Andric MIB.addReg(0); 858349cc55cSDimitry Andric } else if (LocIdxToLocID[*MLoc] >= NumRegs) { 859349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 860349cc55cSDimitry Andric SpillLocationNo SpillID = locIDToSpill(LocID); 861349cc55cSDimitry Andric StackSlotPos StackIdx = locIDToSpillIdx(LocID); 862349cc55cSDimitry Andric unsigned short Offset = StackIdx.second; 863e8d8bef9SDimitry Andric 864349cc55cSDimitry Andric // TODO: support variables that are located in spill slots, with non-zero 865349cc55cSDimitry Andric // offsets from the start of the spill slot. It would require some more 866349cc55cSDimitry Andric // complex DIExpression calculations. This doesn't seem to be produced by 867349cc55cSDimitry Andric // LLVM right now, so don't try and support it. 868349cc55cSDimitry Andric // Accept no-subregister slots and subregisters where the offset is zero. 869349cc55cSDimitry Andric // The consumer should already have type information to work out how large 870349cc55cSDimitry Andric // the variable is. 871349cc55cSDimitry Andric if (Offset == 0) { 872349cc55cSDimitry Andric const SpillLoc &Spill = SpillLocs[SpillID.id()]; 873349cc55cSDimitry Andric unsigned Base = Spill.SpillBase; 874349cc55cSDimitry Andric MIB.addReg(Base); 8754824e7fdSDimitry Andric 876*81ad6265SDimitry Andric // There are several ways we can dereference things, and several inputs 877*81ad6265SDimitry Andric // to consider: 878*81ad6265SDimitry Andric // * NRVO variables will appear with IsIndirect set, but should have 879*81ad6265SDimitry Andric // nothing else in their DIExpressions, 880*81ad6265SDimitry Andric // * Variables with DW_OP_stack_value in their expr already need an 881*81ad6265SDimitry Andric // explicit dereference of the stack location, 882*81ad6265SDimitry Andric // * Values that don't match the variable size need DW_OP_deref_size, 883*81ad6265SDimitry Andric // * Everything else can just become a simple location expression. 884*81ad6265SDimitry Andric 885*81ad6265SDimitry Andric // We need to use deref_size whenever there's a mismatch between the 886*81ad6265SDimitry Andric // size of value and the size of variable portion being read. 887*81ad6265SDimitry Andric // Additionally, we should use it whenever dealing with stack_value 888*81ad6265SDimitry Andric // fragments, to avoid the consumer having to determine the deref size 889*81ad6265SDimitry Andric // from DW_OP_piece. 890*81ad6265SDimitry Andric bool UseDerefSize = false; 891*81ad6265SDimitry Andric unsigned ValueSizeInBits = getLocSizeInBits(*MLoc); 892*81ad6265SDimitry Andric unsigned DerefSizeInBytes = ValueSizeInBits / 8; 893*81ad6265SDimitry Andric if (auto Fragment = Var.getFragment()) { 894*81ad6265SDimitry Andric unsigned VariableSizeInBits = Fragment->SizeInBits; 895*81ad6265SDimitry Andric if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex()) 896*81ad6265SDimitry Andric UseDerefSize = true; 897*81ad6265SDimitry Andric } else if (auto Size = Var.getVariable()->getSizeInBits()) { 898*81ad6265SDimitry Andric if (*Size != ValueSizeInBits) { 899*81ad6265SDimitry Andric UseDerefSize = true; 900*81ad6265SDimitry Andric } 901*81ad6265SDimitry Andric } 902*81ad6265SDimitry Andric 9034824e7fdSDimitry Andric if (Properties.Indirect) { 904*81ad6265SDimitry Andric // This is something like an NRVO variable, where the pointer has been 905*81ad6265SDimitry Andric // spilt to the stack, or a dbg.addr pointing at a coroutine frame 906*81ad6265SDimitry Andric // field. It should end up being a memory location, with the pointer 907*81ad6265SDimitry Andric // to the variable loaded off the stack with a deref. It can't be a 908*81ad6265SDimitry Andric // DW_OP_stack_value expression. 909*81ad6265SDimitry Andric assert(!Expr->isImplicit()); 910*81ad6265SDimitry Andric Expr = TRI.prependOffsetExpression( 911*81ad6265SDimitry Andric Expr, DIExpression::ApplyOffset | DIExpression::DerefAfter, 912*81ad6265SDimitry Andric Spill.SpillOffset); 913*81ad6265SDimitry Andric MIB.addImm(0); 914*81ad6265SDimitry Andric } else if (UseDerefSize) { 915*81ad6265SDimitry Andric // We're loading a value off the stack that's not the same size as the 916*81ad6265SDimitry Andric // variable. Add / subtract stack offset, explicitly deref with a size, 917*81ad6265SDimitry Andric // and add DW_OP_stack_value if not already present. 918*81ad6265SDimitry Andric SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, 919*81ad6265SDimitry Andric DerefSizeInBytes}; 920*81ad6265SDimitry Andric Expr = DIExpression::prependOpcodes(Expr, Ops, true); 921*81ad6265SDimitry Andric unsigned Flags = DIExpression::StackValue | DIExpression::ApplyOffset; 922*81ad6265SDimitry Andric Expr = TRI.prependOffsetExpression(Expr, Flags, Spill.SpillOffset); 923*81ad6265SDimitry Andric MIB.addReg(0); 924*81ad6265SDimitry Andric } else if (Expr->isComplex()) { 925*81ad6265SDimitry Andric // A variable with no size ambiguity, but with extra elements in it's 926*81ad6265SDimitry Andric // expression. Manually dereference the stack location. 927*81ad6265SDimitry Andric assert(Expr->isComplex()); 928*81ad6265SDimitry Andric Expr = TRI.prependOffsetExpression( 929*81ad6265SDimitry Andric Expr, DIExpression::ApplyOffset | DIExpression::DerefAfter, 930*81ad6265SDimitry Andric Spill.SpillOffset); 931*81ad6265SDimitry Andric MIB.addReg(0); 932*81ad6265SDimitry Andric } else { 933*81ad6265SDimitry Andric // A plain value that has been spilt to the stack, with no further 934*81ad6265SDimitry Andric // context. Request a location expression, marking the DBG_VALUE as 935*81ad6265SDimitry Andric // IsIndirect. 936*81ad6265SDimitry Andric Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset, 937*81ad6265SDimitry Andric Spill.SpillOffset); 938*81ad6265SDimitry Andric MIB.addImm(0); 9394824e7fdSDimitry Andric } 940349cc55cSDimitry Andric } else { 941349cc55cSDimitry Andric // This is a stack location with a weird subregister offset: emit an undef 942349cc55cSDimitry Andric // DBG_VALUE instead. 943349cc55cSDimitry Andric MIB.addReg(0); 944349cc55cSDimitry Andric MIB.addReg(0); 945349cc55cSDimitry Andric } 946349cc55cSDimitry Andric } else { 947349cc55cSDimitry Andric // Non-empty, non-stack slot, must be a plain register. 948349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 949349cc55cSDimitry Andric MIB.addReg(LocID); 950349cc55cSDimitry Andric if (Properties.Indirect) 951349cc55cSDimitry Andric MIB.addImm(0); 952349cc55cSDimitry Andric else 953349cc55cSDimitry Andric MIB.addReg(0); 954349cc55cSDimitry Andric } 955e8d8bef9SDimitry Andric 956349cc55cSDimitry Andric MIB.addMetadata(Var.getVariable()); 957349cc55cSDimitry Andric MIB.addMetadata(Expr); 958349cc55cSDimitry Andric return MIB; 959349cc55cSDimitry Andric } 960e8d8bef9SDimitry Andric 961e8d8bef9SDimitry Andric /// Default construct and initialize the pass. 962*81ad6265SDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() = default; 963e8d8bef9SDimitry Andric 964349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const { 965e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 966e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 967e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 968e8d8bef9SDimitry Andric return true; 969e8d8bef9SDimitry Andric return false; 970e8d8bef9SDimitry Andric } 971e8d8bef9SDimitry Andric 972e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 973e8d8bef9SDimitry Andric // Debug Range Extension Implementation 974e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 975e8d8bef9SDimitry Andric 976e8d8bef9SDimitry Andric #ifndef NDEBUG 977e8d8bef9SDimitry Andric // Something to restore in the future. 978e8d8bef9SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..) 979e8d8bef9SDimitry Andric #endif 980e8d8bef9SDimitry Andric 981d56accc7SDimitry Andric Optional<SpillLocationNo> 982e8d8bef9SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 983e8d8bef9SDimitry Andric assert(MI.hasOneMemOperand() && 984e8d8bef9SDimitry Andric "Spill instruction does not have exactly one memory operand?"); 985e8d8bef9SDimitry Andric auto MMOI = MI.memoperands_begin(); 986e8d8bef9SDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 987e8d8bef9SDimitry Andric assert(PVal->kind() == PseudoSourceValue::FixedStack && 988e8d8bef9SDimitry Andric "Inconsistent memory operand in spill instruction"); 989e8d8bef9SDimitry Andric int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 990e8d8bef9SDimitry Andric const MachineBasicBlock *MBB = MI.getParent(); 991e8d8bef9SDimitry Andric Register Reg; 992e8d8bef9SDimitry Andric StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 993349cc55cSDimitry Andric return MTracker->getOrTrackSpillLoc({Reg, Offset}); 994349cc55cSDimitry Andric } 995349cc55cSDimitry Andric 996d56accc7SDimitry Andric Optional<LocIdx> 997d56accc7SDimitry Andric InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) { 998d56accc7SDimitry Andric Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI); 999d56accc7SDimitry Andric if (!SpillLoc) 1000d56accc7SDimitry Andric return None; 1001349cc55cSDimitry Andric 1002349cc55cSDimitry Andric // Where in the stack slot is this value defined -- i.e., what size of value 1003349cc55cSDimitry Andric // is this? An important question, because it could be loaded into a register 1004349cc55cSDimitry Andric // from the stack at some point. Happily the memory operand will tell us 1005349cc55cSDimitry Andric // the size written to the stack. 1006349cc55cSDimitry Andric auto *MemOperand = *MI.memoperands_begin(); 1007349cc55cSDimitry Andric unsigned SizeInBits = MemOperand->getSizeInBits(); 1008349cc55cSDimitry Andric 1009349cc55cSDimitry Andric // Find that position in the stack indexes we're tracking. 1010349cc55cSDimitry Andric auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0}); 1011349cc55cSDimitry Andric if (IdxIt == MTracker->StackSlotIdxes.end()) 1012349cc55cSDimitry Andric // That index is not tracked. This is suprising, and unlikely to ever 1013349cc55cSDimitry Andric // occur, but the safe action is to indicate the variable is optimised out. 1014349cc55cSDimitry Andric return None; 1015349cc55cSDimitry Andric 1016d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second); 1017349cc55cSDimitry Andric return MTracker->getSpillMLoc(SpillID); 1018e8d8bef9SDimitry Andric } 1019e8d8bef9SDimitry Andric 1020e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI 1021e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr. 1022e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { 1023e8d8bef9SDimitry Andric if (!MI.isDebugValue()) 1024e8d8bef9SDimitry Andric return false; 1025e8d8bef9SDimitry Andric 1026e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 1027e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 1028e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 1029e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1030e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1031e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 1032e8d8bef9SDimitry Andric 1033e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 1034e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 1035e8d8bef9SDimitry Andric 1036e8d8bef9SDimitry Andric // If there are no instructions in this lexical scope, do no location tracking 1037e8d8bef9SDimitry Andric // at all, this variable shouldn't get a legitimate location range. 1038e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1039e8d8bef9SDimitry Andric if (Scope == nullptr) 1040e8d8bef9SDimitry Andric return true; // handled it; by doing nothing 1041e8d8bef9SDimitry Andric 1042349cc55cSDimitry Andric // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to 1043349cc55cSDimitry Andric // contribute to locations in this block, but don't propagate further. 1044349cc55cSDimitry Andric // Interpret it like a DBG_VALUE $noreg. 1045349cc55cSDimitry Andric if (MI.isDebugValueList()) { 1046349cc55cSDimitry Andric if (VTracker) 1047349cc55cSDimitry Andric VTracker->defVar(MI, Properties, None); 1048349cc55cSDimitry Andric if (TTracker) 1049349cc55cSDimitry Andric TTracker->redefVar(MI, Properties, None); 1050349cc55cSDimitry Andric return true; 1051349cc55cSDimitry Andric } 1052349cc55cSDimitry Andric 1053e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 1054e8d8bef9SDimitry Andric 1055e8d8bef9SDimitry Andric // MLocTracker needs to know that this register is read, even if it's only 1056e8d8bef9SDimitry Andric // read by a debug inst. 1057e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg() != 0) 1058e8d8bef9SDimitry Andric (void)MTracker->readReg(MO.getReg()); 1059e8d8bef9SDimitry Andric 1060e8d8bef9SDimitry Andric // If we're preparing for the second analysis (variables), the machine value 1061e8d8bef9SDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value 1062e8d8bef9SDimitry Andric // it refers to to VLocTracker. 1063e8d8bef9SDimitry Andric if (VTracker) { 1064e8d8bef9SDimitry Andric if (MO.isReg()) { 1065e8d8bef9SDimitry Andric // Feed defVar the new variable location, or if this is a 1066e8d8bef9SDimitry Andric // DBG_VALUE $noreg, feed defVar None. 1067e8d8bef9SDimitry Andric if (MO.getReg()) 1068e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); 1069e8d8bef9SDimitry Andric else 1070e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, None); 1071e8d8bef9SDimitry Andric } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || 1072e8d8bef9SDimitry Andric MI.getOperand(0).isCImm()) { 1073e8d8bef9SDimitry Andric VTracker->defVar(MI, MI.getOperand(0)); 1074e8d8bef9SDimitry Andric } 1075e8d8bef9SDimitry Andric } 1076e8d8bef9SDimitry Andric 1077e8d8bef9SDimitry Andric // If performing final tracking of transfers, report this variable definition 1078e8d8bef9SDimitry Andric // to the TransferTracker too. 1079e8d8bef9SDimitry Andric if (TTracker) 1080e8d8bef9SDimitry Andric TTracker->redefVar(MI); 1081e8d8bef9SDimitry Andric return true; 1082e8d8bef9SDimitry Andric } 1083e8d8bef9SDimitry Andric 1084fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, 1085*81ad6265SDimitry Andric const ValueTable *MLiveOuts, 1086*81ad6265SDimitry Andric const ValueTable *MLiveIns) { 1087e8d8bef9SDimitry Andric if (!MI.isDebugRef()) 1088e8d8bef9SDimitry Andric return false; 1089e8d8bef9SDimitry Andric 1090e8d8bef9SDimitry Andric // Only handle this instruction when we are building the variable value 1091e8d8bef9SDimitry Andric // transfer function. 1092d56accc7SDimitry Andric if (!VTracker && !TTracker) 1093e8d8bef9SDimitry Andric return false; 1094e8d8bef9SDimitry Andric 1095e8d8bef9SDimitry Andric unsigned InstNo = MI.getOperand(0).getImm(); 1096e8d8bef9SDimitry Andric unsigned OpNo = MI.getOperand(1).getImm(); 1097e8d8bef9SDimitry Andric 1098e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 1099e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 1100e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 1101e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1102e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1103e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 1104e8d8bef9SDimitry Andric 1105e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 1106e8d8bef9SDimitry Andric 1107e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1108e8d8bef9SDimitry Andric if (Scope == nullptr) 1109e8d8bef9SDimitry Andric return true; // Handled by doing nothing. This variable is never in scope. 1110e8d8bef9SDimitry Andric 1111e8d8bef9SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent(); 1112e8d8bef9SDimitry Andric 1113e8d8bef9SDimitry Andric // Various optimizations may have happened to the value during codegen, 1114e8d8bef9SDimitry Andric // recorded in the value substitution table. Apply any substitutions to 1115fe6060f1SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect 1116fe6060f1SDimitry Andric // any subregister extractions performed during optimization. 1117fe6060f1SDimitry Andric 1118fe6060f1SDimitry Andric // Create dummy substitution with Src set, for lookup. 1119fe6060f1SDimitry Andric auto SoughtSub = 1120fe6060f1SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0); 1121fe6060f1SDimitry Andric 1122fe6060f1SDimitry Andric SmallVector<unsigned, 4> SeenSubregs; 1123fe6060f1SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1124fe6060f1SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() && 1125fe6060f1SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) { 1126fe6060f1SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest; 1127fe6060f1SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest; 1128fe6060f1SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg) 1129fe6060f1SDimitry Andric SeenSubregs.push_back(Subreg); 1130fe6060f1SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1131e8d8bef9SDimitry Andric } 1132e8d8bef9SDimitry Andric 1133e8d8bef9SDimitry Andric // Default machine value number is <None> -- if no instruction defines 1134e8d8bef9SDimitry Andric // the corresponding value, it must have been optimized out. 1135e8d8bef9SDimitry Andric Optional<ValueIDNum> NewID = None; 1136e8d8bef9SDimitry Andric 1137e8d8bef9SDimitry Andric // Try to lookup the instruction number, and find the machine value number 1138fe6060f1SDimitry Andric // that it defines. It could be an instruction, or a PHI. 1139e8d8bef9SDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo); 1140fe6060f1SDimitry Andric auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), 1141fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstNo); 1142e8d8bef9SDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) { 1143e8d8bef9SDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first; 1144e8d8bef9SDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber(); 1145e8d8bef9SDimitry Andric 1146349cc55cSDimitry Andric // Pick out the designated operand. It might be a memory reference, if 1147349cc55cSDimitry Andric // a register def was folded into a stack store. 1148349cc55cSDimitry Andric if (OpNo == MachineFunction::DebugOperandMemNumber && 1149349cc55cSDimitry Andric TargetInstr.hasOneMemOperand()) { 1150349cc55cSDimitry Andric Optional<LocIdx> L = findLocationForMemOperand(TargetInstr); 1151349cc55cSDimitry Andric if (L) 1152349cc55cSDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L); 1153349cc55cSDimitry Andric } else if (OpNo != MachineFunction::DebugOperandMemNumber) { 1154*81ad6265SDimitry Andric // Permit the debug-info to be completely wrong: identifying a nonexistant 1155*81ad6265SDimitry Andric // operand, or one that is not a register definition, means something 1156*81ad6265SDimitry Andric // unexpected happened during optimisation. Broken debug-info, however, 1157*81ad6265SDimitry Andric // shouldn't crash the compiler -- instead leave the variable value as 1158*81ad6265SDimitry Andric // None, which will make it appear "optimised out". 1159*81ad6265SDimitry Andric if (OpNo < TargetInstr.getNumOperands()) { 1160e8d8bef9SDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo); 1161e8d8bef9SDimitry Andric 1162*81ad6265SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg()) { 1163349cc55cSDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg()); 1164e8d8bef9SDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID]; 1165e8d8bef9SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); 1166349cc55cSDimitry Andric } 1167*81ad6265SDimitry Andric } 1168*81ad6265SDimitry Andric 1169*81ad6265SDimitry Andric if (!NewID) { 1170*81ad6265SDimitry Andric LLVM_DEBUG( 1171*81ad6265SDimitry Andric { dbgs() << "Seen instruction reference to illegal operand\n"; }); 1172*81ad6265SDimitry Andric } 1173*81ad6265SDimitry Andric } 1174349cc55cSDimitry Andric // else: NewID is left as None. 1175fe6060f1SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { 1176fe6060f1SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use 1177fe6060f1SDimitry Andric // the resolver helper to find out. 1178fe6060f1SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, 1179fe6060f1SDimitry Andric MI, InstNo); 1180fe6060f1SDimitry Andric } 1181fe6060f1SDimitry Andric 1182fe6060f1SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code 1183fe6060f1SDimitry Andric // like this: 1184fe6060f1SDimitry Andric // CALL64 @foo, implicit-def $rax 1185fe6060f1SDimitry Andric // %0:gr64 = COPY $rax 1186fe6060f1SDimitry Andric // %1:gr32 = COPY %0.sub_32bit 1187fe6060f1SDimitry Andric // %2:gr16 = COPY %1.sub_16bit 1188fe6060f1SDimitry Andric // %3:gr8 = COPY %2.sub_8bit 1189fe6060f1SDimitry Andric // In which case each copy would have been recorded as a substitution with 1190fe6060f1SDimitry Andric // a subregister qualifier. Apply those qualifiers now. 1191fe6060f1SDimitry Andric if (NewID && !SeenSubregs.empty()) { 1192fe6060f1SDimitry Andric unsigned Offset = 0; 1193fe6060f1SDimitry Andric unsigned Size = 0; 1194fe6060f1SDimitry Andric 1195fe6060f1SDimitry Andric // Look at each subregister that we passed through, and progressively 1196fe6060f1SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should 1197fe6060f1SDimitry Andric // only ever be the same or narrower width than what they read from; 1198fe6060f1SDimitry Andric // iterate in reverse order so that we go from wide to small. 1199fe6060f1SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) { 1200fe6060f1SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg); 1201fe6060f1SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg); 1202fe6060f1SDimitry Andric Offset += ThisOffset; 1203fe6060f1SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize); 1204fe6060f1SDimitry Andric } 1205fe6060f1SDimitry Andric 1206fe6060f1SDimitry Andric // If that worked, look for an appropriate subregister with the register 1207fe6060f1SDimitry Andric // where the define happens. Don't look at values that were defined during 1208fe6060f1SDimitry Andric // a stack write: we can't currently express register locations within 1209fe6060f1SDimitry Andric // spills. 1210fe6060f1SDimitry Andric LocIdx L = NewID->getLoc(); 1211fe6060f1SDimitry Andric if (NewID && !MTracker->isSpill(L)) { 1212fe6060f1SDimitry Andric // Find the register class for the register where this def happened. 1213fe6060f1SDimitry Andric // FIXME: no index for this? 1214fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L]; 1215fe6060f1SDimitry Andric const TargetRegisterClass *TRC = nullptr; 1216fe6060f1SDimitry Andric for (auto *TRCI : TRI->regclasses()) 1217fe6060f1SDimitry Andric if (TRCI->contains(Reg)) 1218fe6060f1SDimitry Andric TRC = TRCI; 1219fe6060f1SDimitry Andric assert(TRC && "Couldn't find target register class?"); 1220fe6060f1SDimitry Andric 1221fe6060f1SDimitry Andric // If the register we have isn't the right size or in the right place, 1222fe6060f1SDimitry Andric // Try to find a subregister inside it. 1223fe6060f1SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC); 1224fe6060f1SDimitry Andric if (Size != MainRegSize || Offset) { 1225fe6060f1SDimitry Andric // Enumerate all subregisters, searching. 1226fe6060f1SDimitry Andric Register NewReg = 0; 1227fe6060f1SDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1228fe6060f1SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1229fe6060f1SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg); 1230fe6060f1SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg); 1231fe6060f1SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) { 1232fe6060f1SDimitry Andric NewReg = *SRI; 1233fe6060f1SDimitry Andric break; 1234fe6060f1SDimitry Andric } 1235fe6060f1SDimitry Andric } 1236fe6060f1SDimitry Andric 1237fe6060f1SDimitry Andric // If we didn't find anything: there's no way to express our value. 1238fe6060f1SDimitry Andric if (!NewReg) { 1239fe6060f1SDimitry Andric NewID = None; 1240fe6060f1SDimitry Andric } else { 1241fe6060f1SDimitry Andric // Re-state the value as being defined within the subregister 1242fe6060f1SDimitry Andric // that we found. 1243fe6060f1SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg); 1244fe6060f1SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc); 1245fe6060f1SDimitry Andric } 1246fe6060f1SDimitry Andric } 1247fe6060f1SDimitry Andric } else { 1248fe6060f1SDimitry Andric // If we can't handle subregisters, unset the new value. 1249fe6060f1SDimitry Andric NewID = None; 1250fe6060f1SDimitry Andric } 1251e8d8bef9SDimitry Andric } 1252e8d8bef9SDimitry Andric 1253e8d8bef9SDimitry Andric // We, we have a value number or None. Tell the variable value tracker about 1254e8d8bef9SDimitry Andric // it. The rest of this LiveDebugValues implementation acts exactly the same 1255e8d8bef9SDimitry Andric // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that 1256e8d8bef9SDimitry Andric // aren't immediately available). 1257e8d8bef9SDimitry Andric DbgValueProperties Properties(Expr, false); 1258d56accc7SDimitry Andric if (VTracker) 1259e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, NewID); 1260e8d8bef9SDimitry Andric 1261e8d8bef9SDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF 1262e8d8bef9SDimitry Andric // into a plain DBG_VALUE. 1263e8d8bef9SDimitry Andric if (!TTracker) 1264e8d8bef9SDimitry Andric return true; 1265e8d8bef9SDimitry Andric 1266e8d8bef9SDimitry Andric // Pick a location for the machine value number, if such a location exists. 1267e8d8bef9SDimitry Andric // (This information could be stored in TransferTracker to make it faster). 1268e8d8bef9SDimitry Andric Optional<LocIdx> FoundLoc = None; 1269e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1270e8d8bef9SDimitry Andric LocIdx CurL = Location.Idx; 1271349cc55cSDimitry Andric ValueIDNum ID = MTracker->readMLoc(CurL); 1272e8d8bef9SDimitry Andric if (NewID && ID == NewID) { 1273e8d8bef9SDimitry Andric // If this is the first location with that value, pick it. Otherwise, 1274e8d8bef9SDimitry Andric // consider whether it's a "longer term" location. 1275e8d8bef9SDimitry Andric if (!FoundLoc) { 1276e8d8bef9SDimitry Andric FoundLoc = CurL; 1277e8d8bef9SDimitry Andric continue; 1278e8d8bef9SDimitry Andric } 1279e8d8bef9SDimitry Andric 1280e8d8bef9SDimitry Andric if (MTracker->isSpill(CurL)) 1281e8d8bef9SDimitry Andric FoundLoc = CurL; // Spills are a longer term location. 1282e8d8bef9SDimitry Andric else if (!MTracker->isSpill(*FoundLoc) && 1283e8d8bef9SDimitry Andric !MTracker->isSpill(CurL) && 1284e8d8bef9SDimitry Andric !isCalleeSaved(*FoundLoc) && 1285e8d8bef9SDimitry Andric isCalleeSaved(CurL)) 1286e8d8bef9SDimitry Andric FoundLoc = CurL; // Callee saved regs are longer term than normal. 1287e8d8bef9SDimitry Andric } 1288e8d8bef9SDimitry Andric } 1289e8d8bef9SDimitry Andric 1290e8d8bef9SDimitry Andric // Tell transfer tracker that the variable value has changed. 1291e8d8bef9SDimitry Andric TTracker->redefVar(MI, Properties, FoundLoc); 1292e8d8bef9SDimitry Andric 1293e8d8bef9SDimitry Andric // If there was a value with no location; but the value is defined in a 1294e8d8bef9SDimitry Andric // later instruction in this block, this is a block-local use-before-def. 1295e8d8bef9SDimitry Andric if (!FoundLoc && NewID && NewID->getBlock() == CurBB && 1296e8d8bef9SDimitry Andric NewID->getInst() > CurInst) 1297e8d8bef9SDimitry Andric TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); 1298e8d8bef9SDimitry Andric 1299e8d8bef9SDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. 1300e8d8bef9SDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if 1301e8d8bef9SDimitry Andric // FoundLoc is None. 1302e8d8bef9SDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future). 1303e8d8bef9SDimitry Andric MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); 1304e8d8bef9SDimitry Andric TTracker->PendingDbgValues.push_back(DbgMI); 1305e8d8bef9SDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr); 1306fe6060f1SDimitry Andric return true; 1307fe6060f1SDimitry Andric } 1308fe6060f1SDimitry Andric 1309fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { 1310fe6060f1SDimitry Andric if (!MI.isDebugPHI()) 1311fe6060f1SDimitry Andric return false; 1312fe6060f1SDimitry Andric 1313fe6060f1SDimitry Andric // Analyse these only when solving the machine value location problem. 1314fe6060f1SDimitry Andric if (VTracker || TTracker) 1315fe6060f1SDimitry Andric return true; 1316fe6060f1SDimitry Andric 1317fe6060f1SDimitry Andric // First operand is the value location, either a stack slot or register. 1318fe6060f1SDimitry Andric // Second is the debug instruction number of the original PHI. 1319fe6060f1SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 1320fe6060f1SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm(); 1321fe6060f1SDimitry Andric 1322*81ad6265SDimitry Andric auto EmitBadPHI = [this, &MI, InstrNum](void) -> bool { 1323*81ad6265SDimitry Andric // Helper lambda to do any accounting when we fail to find a location for 1324*81ad6265SDimitry Andric // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a 1325*81ad6265SDimitry Andric // dead stack slot, for example. 1326*81ad6265SDimitry Andric // Record a DebugPHIRecord with an empty value + location. 1327*81ad6265SDimitry Andric DebugPHINumToValue.push_back({InstrNum, MI.getParent(), None, None}); 1328*81ad6265SDimitry Andric return true; 1329*81ad6265SDimitry Andric }; 1330*81ad6265SDimitry Andric 1331*81ad6265SDimitry Andric if (MO.isReg() && MO.getReg()) { 1332fe6060f1SDimitry Andric // The value is whatever's currently in the register. Read and record it, 1333fe6060f1SDimitry Andric // to be analysed later. 1334fe6060f1SDimitry Andric Register Reg = MO.getReg(); 1335fe6060f1SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg); 1336fe6060f1SDimitry Andric auto PHIRec = DebugPHIRecord( 1337fe6060f1SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); 1338fe6060f1SDimitry Andric DebugPHINumToValue.push_back(PHIRec); 1339349cc55cSDimitry Andric 1340349cc55cSDimitry Andric // Ensure this register is tracked. 1341349cc55cSDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1342349cc55cSDimitry Andric MTracker->lookupOrTrackRegister(*RAI); 1343*81ad6265SDimitry Andric } else if (MO.isFI()) { 1344fe6060f1SDimitry Andric // The value is whatever's in this stack slot. 1345fe6060f1SDimitry Andric unsigned FI = MO.getIndex(); 1346fe6060f1SDimitry Andric 1347fe6060f1SDimitry Andric // If the stack slot is dead, then this was optimized away. 1348fe6060f1SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged. 1349fe6060f1SDimitry Andric if (MFI->isDeadObjectIndex(FI)) 1350*81ad6265SDimitry Andric return EmitBadPHI(); 1351fe6060f1SDimitry Andric 1352349cc55cSDimitry Andric // Identify this spill slot, ensure it's tracked. 1353fe6060f1SDimitry Andric Register Base; 1354fe6060f1SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); 1355fe6060f1SDimitry Andric SpillLoc SL = {Base, Offs}; 1356d56accc7SDimitry Andric Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL); 1357d56accc7SDimitry Andric 1358d56accc7SDimitry Andric // We might be able to find a value, but have chosen not to, to avoid 1359d56accc7SDimitry Andric // tracking too much stack information. 1360d56accc7SDimitry Andric if (!SpillNo) 1361*81ad6265SDimitry Andric return EmitBadPHI(); 1362fe6060f1SDimitry Andric 1363*81ad6265SDimitry Andric // Any stack location DBG_PHI should have an associate bit-size. 1364*81ad6265SDimitry Andric assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?"); 1365*81ad6265SDimitry Andric unsigned slotBitSize = MI.getOperand(2).getImm(); 1366349cc55cSDimitry Andric 1367*81ad6265SDimitry Andric unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0}); 1368*81ad6265SDimitry Andric LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID); 1369*81ad6265SDimitry Andric ValueIDNum Result = MTracker->readMLoc(SpillLoc); 1370fe6060f1SDimitry Andric 1371fe6060f1SDimitry Andric // Record this DBG_PHI for later analysis. 1372*81ad6265SDimitry Andric auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc}); 1373fe6060f1SDimitry Andric DebugPHINumToValue.push_back(DbgPHI); 1374*81ad6265SDimitry Andric } else { 1375*81ad6265SDimitry Andric // Else: if the operand is neither a legal register or a stack slot, then 1376*81ad6265SDimitry Andric // we're being fed illegal debug-info. Record an empty PHI, so that any 1377*81ad6265SDimitry Andric // debug users trying to read this number will be put off trying to 1378*81ad6265SDimitry Andric // interpret the value. 1379*81ad6265SDimitry Andric LLVM_DEBUG( 1380*81ad6265SDimitry Andric { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; }); 1381*81ad6265SDimitry Andric return EmitBadPHI(); 1382fe6060f1SDimitry Andric } 1383e8d8bef9SDimitry Andric 1384e8d8bef9SDimitry Andric return true; 1385e8d8bef9SDimitry Andric } 1386e8d8bef9SDimitry Andric 1387e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { 1388e8d8bef9SDimitry Andric // Meta Instructions do not affect the debug liveness of any register they 1389e8d8bef9SDimitry Andric // define. 1390e8d8bef9SDimitry Andric if (MI.isImplicitDef()) { 1391e8d8bef9SDimitry Andric // Except when there's an implicit def, and the location it's defining has 1392e8d8bef9SDimitry Andric // no value number. The whole point of an implicit def is to announce that 1393e8d8bef9SDimitry Andric // the register is live, without be specific about it's value. So define 1394e8d8bef9SDimitry Andric // a value if there isn't one already. 1395e8d8bef9SDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); 1396e8d8bef9SDimitry Andric // Has a legitimate value -> ignore the implicit def. 1397e8d8bef9SDimitry Andric if (Num.getLoc() != 0) 1398e8d8bef9SDimitry Andric return; 1399e8d8bef9SDimitry Andric // Otherwise, def it here. 1400e8d8bef9SDimitry Andric } else if (MI.isMetaInstruction()) 1401e8d8bef9SDimitry Andric return; 1402e8d8bef9SDimitry Andric 14034824e7fdSDimitry Andric // We always ignore SP defines on call instructions, they don't actually 14044824e7fdSDimitry Andric // change the value of the stack pointer... except for win32's _chkstk. This 14054824e7fdSDimitry Andric // is rare: filter quickly for the common case (no stack adjustments, not a 14064824e7fdSDimitry Andric // call, etc). If it is a call that modifies SP, recognise the SP register 14074824e7fdSDimitry Andric // defs. 14084824e7fdSDimitry Andric bool CallChangesSP = false; 14094824e7fdSDimitry Andric if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() && 14104824e7fdSDimitry Andric !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data())) 14114824e7fdSDimitry Andric CallChangesSP = true; 14124824e7fdSDimitry Andric 14134824e7fdSDimitry Andric // Test whether we should ignore a def of this register due to it being part 14144824e7fdSDimitry Andric // of the stack pointer. 14154824e7fdSDimitry Andric auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool { 14164824e7fdSDimitry Andric if (CallChangesSP) 14174824e7fdSDimitry Andric return false; 14184824e7fdSDimitry Andric return MI.isCall() && MTracker->SPAliases.count(R); 14194824e7fdSDimitry Andric }; 14204824e7fdSDimitry Andric 1421e8d8bef9SDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs. 1422e8d8bef9SDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this 1423e8d8bef9SDimitry Andric // prevents fallback to std::set::count() operations. 1424e8d8bef9SDimitry Andric SmallSet<uint32_t, 32> DeadRegs; 1425e8d8bef9SDimitry Andric SmallVector<const uint32_t *, 4> RegMasks; 1426e8d8bef9SDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs; 1427e8d8bef9SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1428e8d8bef9SDimitry Andric // Determine whether the operand is a register def. 1429e8d8bef9SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() && 1430e8d8bef9SDimitry Andric Register::isPhysicalRegister(MO.getReg()) && 14314824e7fdSDimitry Andric !IgnoreSPAlias(MO.getReg())) { 1432e8d8bef9SDimitry Andric // Remove ranges of all aliased registers. 1433e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1434e8d8bef9SDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs? 1435e8d8bef9SDimitry Andric DeadRegs.insert(*RAI); 1436e8d8bef9SDimitry Andric } else if (MO.isRegMask()) { 1437e8d8bef9SDimitry Andric RegMasks.push_back(MO.getRegMask()); 1438e8d8bef9SDimitry Andric RegMaskPtrs.push_back(&MO); 1439e8d8bef9SDimitry Andric } 1440e8d8bef9SDimitry Andric } 1441e8d8bef9SDimitry Andric 1442e8d8bef9SDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise. 1443e8d8bef9SDimitry Andric for (uint32_t DeadReg : DeadRegs) 1444e8d8bef9SDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst); 1445e8d8bef9SDimitry Andric 1446e8d8bef9SDimitry Andric for (auto *MO : RegMaskPtrs) 1447e8d8bef9SDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst); 1448fe6060f1SDimitry Andric 1449349cc55cSDimitry Andric // If this instruction writes to a spill slot, def that slot. 1450349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1451d56accc7SDimitry Andric if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1452349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1453d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1454349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1455349cc55cSDimitry Andric MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L)); 1456349cc55cSDimitry Andric } 1457349cc55cSDimitry Andric } 1458d56accc7SDimitry Andric } 1459349cc55cSDimitry Andric 1460fe6060f1SDimitry Andric if (!TTracker) 1461fe6060f1SDimitry Andric return; 1462fe6060f1SDimitry Andric 1463fe6060f1SDimitry Andric // When committing variable values to locations: tell transfer tracker that 1464fe6060f1SDimitry Andric // we've clobbered things. It may be able to recover the variable from a 1465fe6060f1SDimitry Andric // different location. 1466fe6060f1SDimitry Andric 1467fe6060f1SDimitry Andric // Inform TTracker about any direct clobbers. 1468fe6060f1SDimitry Andric for (uint32_t DeadReg : DeadRegs) { 1469fe6060f1SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); 1470fe6060f1SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false); 1471fe6060f1SDimitry Andric } 1472fe6060f1SDimitry Andric 1473fe6060f1SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations 1474fe6060f1SDimitry Andric // that are actually being tracked. 14751fd87a68SDimitry Andric if (!RegMaskPtrs.empty()) { 1476fe6060f1SDimitry Andric for (auto L : MTracker->locations()) { 1477fe6060f1SDimitry Andric // Stack locations can't be clobbered by regmasks. 1478fe6060f1SDimitry Andric if (MTracker->isSpill(L.Idx)) 1479fe6060f1SDimitry Andric continue; 1480fe6060f1SDimitry Andric 1481fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx]; 14824824e7fdSDimitry Andric if (IgnoreSPAlias(Reg)) 14834824e7fdSDimitry Andric continue; 14844824e7fdSDimitry Andric 1485fe6060f1SDimitry Andric for (auto *MO : RegMaskPtrs) 1486fe6060f1SDimitry Andric if (MO->clobbersPhysReg(Reg)) 1487fe6060f1SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false); 1488fe6060f1SDimitry Andric } 14891fd87a68SDimitry Andric } 1490349cc55cSDimitry Andric 1491349cc55cSDimitry Andric // Tell TTracker about any folded stack store. 1492349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1493d56accc7SDimitry Andric if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1494349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1495d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1496349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1497349cc55cSDimitry Andric TTracker->clobberMloc(L, MI.getIterator(), true); 1498349cc55cSDimitry Andric } 1499349cc55cSDimitry Andric } 1500e8d8bef9SDimitry Andric } 1501d56accc7SDimitry Andric } 1502e8d8bef9SDimitry Andric 1503e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { 1504349cc55cSDimitry Andric // In all circumstances, re-def all aliases. It's definitely a new value now. 1505349cc55cSDimitry Andric for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI) 1506349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1507e8d8bef9SDimitry Andric 1508349cc55cSDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); 1509e8d8bef9SDimitry Andric MTracker->setReg(DstRegNum, SrcValue); 1510e8d8bef9SDimitry Andric 1511349cc55cSDimitry Andric // Copy subregisters from one location to another. 1512e8d8bef9SDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { 1513e8d8bef9SDimitry Andric unsigned SrcSubReg = SRI.getSubReg(); 1514e8d8bef9SDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex(); 1515e8d8bef9SDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); 1516e8d8bef9SDimitry Andric if (!DstSubReg) 1517e8d8bef9SDimitry Andric continue; 1518e8d8bef9SDimitry Andric 1519e8d8bef9SDimitry Andric // Do copy. There are two matching subregisters, the source value should 1520e8d8bef9SDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked 1521e8d8bef9SDimitry Andric // yet. 1522349cc55cSDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet. Will read 1523349cc55cSDimitry Andric // mphi values if it wasn't tracked. 1524349cc55cSDimitry Andric LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg); 1525349cc55cSDimitry Andric LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg); 1526349cc55cSDimitry Andric (void)SrcL; 1527e8d8bef9SDimitry Andric (void)DstL; 1528349cc55cSDimitry Andric ValueIDNum CpyValue = MTracker->readReg(SrcSubReg); 1529e8d8bef9SDimitry Andric 1530e8d8bef9SDimitry Andric MTracker->setReg(DstSubReg, CpyValue); 1531e8d8bef9SDimitry Andric } 1532e8d8bef9SDimitry Andric } 1533e8d8bef9SDimitry Andric 1534d56accc7SDimitry Andric Optional<SpillLocationNo> 1535d56accc7SDimitry Andric InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, 1536e8d8bef9SDimitry Andric MachineFunction *MF) { 1537e8d8bef9SDimitry Andric // TODO: Handle multiple stores folded into one. 1538e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1539d56accc7SDimitry Andric return None; 1540e8d8bef9SDimitry Andric 1541349cc55cSDimitry Andric // Reject any memory operand that's aliased -- we can't guarantee its value. 1542349cc55cSDimitry Andric auto MMOI = MI.memoperands_begin(); 1543349cc55cSDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 1544349cc55cSDimitry Andric if (PVal->isAliased(MFI)) 1545d56accc7SDimitry Andric return None; 1546349cc55cSDimitry Andric 1547e8d8bef9SDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 1548d56accc7SDimitry Andric return None; // This is not a spill instruction, since no valid size was 1549e8d8bef9SDimitry Andric // returned from either function. 1550e8d8bef9SDimitry Andric 1551d56accc7SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1552e8d8bef9SDimitry Andric } 1553e8d8bef9SDimitry Andric 1554e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, 1555e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1556e8d8bef9SDimitry Andric if (!isSpillInstruction(MI, MF)) 1557e8d8bef9SDimitry Andric return false; 1558e8d8bef9SDimitry Andric 1559e8d8bef9SDimitry Andric int FI; 1560e8d8bef9SDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI); 1561e8d8bef9SDimitry Andric return Reg != 0; 1562e8d8bef9SDimitry Andric } 1563e8d8bef9SDimitry Andric 1564349cc55cSDimitry Andric Optional<SpillLocationNo> 1565e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, 1566e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1567e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1568e8d8bef9SDimitry Andric return None; 1569e8d8bef9SDimitry Andric 1570e8d8bef9SDimitry Andric // FIXME: Handle folded restore instructions with more than one memory 1571e8d8bef9SDimitry Andric // operand. 1572e8d8bef9SDimitry Andric if (MI.getRestoreSize(TII)) { 1573e8d8bef9SDimitry Andric Reg = MI.getOperand(0).getReg(); 1574e8d8bef9SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1575e8d8bef9SDimitry Andric } 1576e8d8bef9SDimitry Andric return None; 1577e8d8bef9SDimitry Andric } 1578e8d8bef9SDimitry Andric 1579e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { 1580e8d8bef9SDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location 1581e8d8bef9SDimitry Andric // limitations under the new model. Therefore, when comparing them, compare 1582e8d8bef9SDimitry Andric // versions that don't attempt spills or restores at all. 1583e8d8bef9SDimitry Andric if (EmulateOldLDV) 1584e8d8bef9SDimitry Andric return false; 1585e8d8bef9SDimitry Andric 1586349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1587349cc55cSDimitry Andric // that can access the stack. 1588349cc55cSDimitry Andric int DummyFI = -1; 1589349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) && 1590349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, DummyFI)) 1591349cc55cSDimitry Andric return false; 1592349cc55cSDimitry Andric 1593e8d8bef9SDimitry Andric MachineFunction *MF = MI.getMF(); 1594e8d8bef9SDimitry Andric unsigned Reg; 1595e8d8bef9SDimitry Andric 1596e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 1597e8d8bef9SDimitry Andric 1598349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1599349cc55cSDimitry Andric // that can access the stack. 1600349cc55cSDimitry Andric int FIDummy; 1601349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) && 1602349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, FIDummy)) 1603349cc55cSDimitry Andric return false; 1604349cc55cSDimitry Andric 1605e8d8bef9SDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is 1606e8d8bef9SDimitry Andric // written to, terminate that variable location. The value in memory 1607e8d8bef9SDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. 1608d56accc7SDimitry Andric if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) { 1609349cc55cSDimitry Andric // Un-set this location and clobber, so that earlier locations don't 1610349cc55cSDimitry Andric // continue past this store. 1611349cc55cSDimitry Andric for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) { 1612d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx); 1613349cc55cSDimitry Andric Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID); 1614349cc55cSDimitry Andric if (!MLoc) 1615349cc55cSDimitry Andric continue; 1616349cc55cSDimitry Andric 1617349cc55cSDimitry Andric // We need to over-write the stack slot with something (here, a def at 1618349cc55cSDimitry Andric // this instruction) to ensure no values are preserved in this stack slot 1619349cc55cSDimitry Andric // after the spill. It also prevents TTracker from trying to recover the 1620349cc55cSDimitry Andric // location and re-installing it in the same place. 1621349cc55cSDimitry Andric ValueIDNum Def(CurBB, CurInst, *MLoc); 1622349cc55cSDimitry Andric MTracker->setMLoc(*MLoc, Def); 1623349cc55cSDimitry Andric if (TTracker) 1624e8d8bef9SDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator()); 1625e8d8bef9SDimitry Andric } 1626e8d8bef9SDimitry Andric } 1627e8d8bef9SDimitry Andric 1628e8d8bef9SDimitry Andric // Try to recognise spill and restore instructions that may transfer a value. 1629e8d8bef9SDimitry Andric if (isLocationSpill(MI, MF, Reg)) { 1630d56accc7SDimitry Andric // isLocationSpill returning true should guarantee we can extract a 1631d56accc7SDimitry Andric // location. 1632d56accc7SDimitry Andric SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI); 1633e8d8bef9SDimitry Andric 1634349cc55cSDimitry Andric auto DoTransfer = [&](Register SrcReg, unsigned SpillID) { 1635349cc55cSDimitry Andric auto ReadValue = MTracker->readReg(SrcReg); 1636349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getSpillMLoc(SpillID); 1637349cc55cSDimitry Andric MTracker->setMLoc(DstLoc, ReadValue); 1638e8d8bef9SDimitry Andric 1639349cc55cSDimitry Andric if (TTracker) { 1640349cc55cSDimitry Andric LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg); 1641349cc55cSDimitry Andric TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator()); 1642e8d8bef9SDimitry Andric } 1643349cc55cSDimitry Andric }; 1644349cc55cSDimitry Andric 1645349cc55cSDimitry Andric // Then, transfer subreg bits. 1646349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1647349cc55cSDimitry Andric // Ensure this reg is tracked, 1648349cc55cSDimitry Andric (void)MTracker->lookupOrTrackRegister(*SRI); 1649349cc55cSDimitry Andric unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI); 1650349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, SubregIdx); 1651349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1652349cc55cSDimitry Andric } 1653349cc55cSDimitry Andric 1654349cc55cSDimitry Andric // Directly lookup size of main source reg, and transfer. 1655349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1656349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); 1657349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1658349cc55cSDimitry Andric } else { 1659d56accc7SDimitry Andric Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg); 1660d56accc7SDimitry Andric if (!Loc) 1661349cc55cSDimitry Andric return false; 1662349cc55cSDimitry Andric 1663349cc55cSDimitry Andric // Assumption: we're reading from the base of the stack slot, not some 1664349cc55cSDimitry Andric // offset into it. It seems very unlikely LLVM would ever generate 1665349cc55cSDimitry Andric // restores where this wasn't true. This then becomes a question of what 1666349cc55cSDimitry Andric // subregisters in the destination register line up with positions in the 1667349cc55cSDimitry Andric // stack slot. 1668349cc55cSDimitry Andric 1669349cc55cSDimitry Andric // Def all registers that alias the destination. 1670349cc55cSDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1671349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1672349cc55cSDimitry Andric 1673349cc55cSDimitry Andric // Now find subregisters within the destination register, and load values 1674349cc55cSDimitry Andric // from stack slot positions. 1675349cc55cSDimitry Andric auto DoTransfer = [&](Register DestReg, unsigned SpillID) { 1676349cc55cSDimitry Andric LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID); 1677349cc55cSDimitry Andric auto ReadValue = MTracker->readMLoc(SrcIdx); 1678349cc55cSDimitry Andric MTracker->setReg(DestReg, ReadValue); 1679349cc55cSDimitry Andric }; 1680349cc55cSDimitry Andric 1681349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1682349cc55cSDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1683d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, Subreg); 1684349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1685349cc55cSDimitry Andric } 1686349cc55cSDimitry Andric 1687349cc55cSDimitry Andric // Directly look up this registers slot idx by size, and transfer. 1688349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1689d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0}); 1690349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1691e8d8bef9SDimitry Andric } 1692e8d8bef9SDimitry Andric return true; 1693e8d8bef9SDimitry Andric } 1694e8d8bef9SDimitry Andric 1695e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { 1696e8d8bef9SDimitry Andric auto DestSrc = TII->isCopyInstr(MI); 1697e8d8bef9SDimitry Andric if (!DestSrc) 1698e8d8bef9SDimitry Andric return false; 1699e8d8bef9SDimitry Andric 1700e8d8bef9SDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination; 1701e8d8bef9SDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source; 1702e8d8bef9SDimitry Andric 1703e8d8bef9SDimitry Andric auto isCalleeSavedReg = [&](unsigned Reg) { 1704e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1705e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 1706e8d8bef9SDimitry Andric return true; 1707e8d8bef9SDimitry Andric return false; 1708e8d8bef9SDimitry Andric }; 1709e8d8bef9SDimitry Andric 1710e8d8bef9SDimitry Andric Register SrcReg = SrcRegOp->getReg(); 1711e8d8bef9SDimitry Andric Register DestReg = DestRegOp->getReg(); 1712e8d8bef9SDimitry Andric 1713e8d8bef9SDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues. 1714e8d8bef9SDimitry Andric if (SrcReg == DestReg) 1715e8d8bef9SDimitry Andric return true; 1716e8d8bef9SDimitry Andric 1717e8d8bef9SDimitry Andric // For emulating VarLocBasedImpl: 1718e8d8bef9SDimitry Andric // We want to recognize instructions where destination register is callee 1719e8d8bef9SDimitry Andric // saved register. If register that could be clobbered by the call is 1720e8d8bef9SDimitry Andric // included, there would be a great chance that it is going to be clobbered 1721e8d8bef9SDimitry Andric // soon. It is more likely that previous register, which is callee saved, is 1722e8d8bef9SDimitry Andric // going to stay unclobbered longer, even if it is killed. 1723e8d8bef9SDimitry Andric // 1724e8d8bef9SDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so 1725e8d8bef9SDimitry Andric // ignore this condition. 1726e8d8bef9SDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) 1727e8d8bef9SDimitry Andric return false; 1728e8d8bef9SDimitry Andric 1729e8d8bef9SDimitry Andric // InstrRefBasedImpl only followed killing copies. 1730e8d8bef9SDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill()) 1731e8d8bef9SDimitry Andric return false; 1732e8d8bef9SDimitry Andric 1733e8d8bef9SDimitry Andric // Copy MTracker info, including subregs if available. 1734e8d8bef9SDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg); 1735e8d8bef9SDimitry Andric 1736e8d8bef9SDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV 1737e8d8bef9SDimitry Andric // would have. We might make use of the additional value tracking in some 1738e8d8bef9SDimitry Andric // other way, later. 1739e8d8bef9SDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) 1740e8d8bef9SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), 1741e8d8bef9SDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator()); 1742e8d8bef9SDimitry Andric 1743e8d8bef9SDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying. 1744e8d8bef9SDimitry Andric if (EmulateOldLDV && SrcReg != DestReg) 1745e8d8bef9SDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst); 1746e8d8bef9SDimitry Andric 1747fe6060f1SDimitry Andric // Finally, the copy might have clobbered variables based on the destination 1748fe6060f1SDimitry Andric // register. Tell TTracker about it, in case a backup location exists. 1749fe6060f1SDimitry Andric if (TTracker) { 1750fe6060f1SDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { 1751fe6060f1SDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); 1752fe6060f1SDimitry Andric TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false); 1753fe6060f1SDimitry Andric } 1754fe6060f1SDimitry Andric } 1755fe6060f1SDimitry Andric 1756e8d8bef9SDimitry Andric return true; 1757e8d8bef9SDimitry Andric } 1758e8d8bef9SDimitry Andric 1759e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other 1760e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during 1761e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the 1762e8d8bef9SDimitry Andric /// known-to-overlap fragments are present". 17634824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for 1764e8d8bef9SDimitry Andric /// fragment usage. 1765e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { 17664824e7fdSDimitry Andric assert(MI.isDebugValue() || MI.isDebugRef()); 1767e8d8bef9SDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 1768e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 1769e8d8bef9SDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 1770e8d8bef9SDimitry Andric 1771e8d8bef9SDimitry Andric // If this is the first sighting of this variable, then we are guaranteed 1772e8d8bef9SDimitry Andric // there are currently no overlapping fragments either. Initialize the set 1773e8d8bef9SDimitry Andric // of seen fragments, record no overlaps for the current one, and return. 1774e8d8bef9SDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable()); 1775e8d8bef9SDimitry Andric if (SeenIt == SeenFragments.end()) { 1776e8d8bef9SDimitry Andric SmallSet<FragmentInfo, 4> OneFragment; 1777e8d8bef9SDimitry Andric OneFragment.insert(ThisFragment); 1778e8d8bef9SDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment}); 1779e8d8bef9SDimitry Andric 1780e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1781e8d8bef9SDimitry Andric return; 1782e8d8bef9SDimitry Andric } 1783e8d8bef9SDimitry Andric 1784e8d8bef9SDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap 1785e8d8bef9SDimitry Andric // map, it has already been accounted for. 1786e8d8bef9SDimitry Andric auto IsInOLapMap = 1787e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1788e8d8bef9SDimitry Andric if (!IsInOLapMap.second) 1789e8d8bef9SDimitry Andric return; 1790e8d8bef9SDimitry Andric 1791e8d8bef9SDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 1792e8d8bef9SDimitry Andric auto &AllSeenFragments = SeenIt->second; 1793e8d8bef9SDimitry Andric 1794e8d8bef9SDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this" 1795e8d8bef9SDimitry Andric // fragment being a previously unseen fragment. Record any pair of 1796e8d8bef9SDimitry Andric // overlapping fragments. 1797e8d8bef9SDimitry Andric for (auto &ASeenFragment : AllSeenFragments) { 1798e8d8bef9SDimitry Andric // Does this previously seen fragment overlap? 1799e8d8bef9SDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 1800e8d8bef9SDimitry Andric // Yes: Mark the current fragment as being overlapped. 1801e8d8bef9SDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment); 1802e8d8bef9SDimitry Andric // Mark the previously seen fragment as being overlapped by the current 1803e8d8bef9SDimitry Andric // one. 1804e8d8bef9SDimitry Andric auto ASeenFragmentsOverlaps = 1805e8d8bef9SDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); 1806e8d8bef9SDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() && 1807e8d8bef9SDimitry Andric "Previously seen var fragment has no vector of overlaps"); 1808e8d8bef9SDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment); 1809e8d8bef9SDimitry Andric } 1810e8d8bef9SDimitry Andric } 1811e8d8bef9SDimitry Andric 1812e8d8bef9SDimitry Andric AllSeenFragments.insert(ThisFragment); 1813e8d8bef9SDimitry Andric } 1814e8d8bef9SDimitry Andric 1815*81ad6265SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts, 1816*81ad6265SDimitry Andric const ValueTable *MLiveIns) { 1817e8d8bef9SDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's 1818e8d8bef9SDimitry Andric // none of these should we interpret it's register defs as new value 1819e8d8bef9SDimitry Andric // definitions. 1820e8d8bef9SDimitry Andric if (transferDebugValue(MI)) 1821e8d8bef9SDimitry Andric return; 1822fe6060f1SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) 1823fe6060f1SDimitry Andric return; 1824fe6060f1SDimitry Andric if (transferDebugPHI(MI)) 1825e8d8bef9SDimitry Andric return; 1826e8d8bef9SDimitry Andric if (transferRegisterCopy(MI)) 1827e8d8bef9SDimitry Andric return; 1828e8d8bef9SDimitry Andric if (transferSpillOrRestoreInst(MI)) 1829e8d8bef9SDimitry Andric return; 1830e8d8bef9SDimitry Andric transferRegisterDef(MI); 1831e8d8bef9SDimitry Andric } 1832e8d8bef9SDimitry Andric 1833e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction( 1834e8d8bef9SDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, 1835e8d8bef9SDimitry Andric unsigned MaxNumBlocks) { 1836e8d8bef9SDimitry Andric // Because we try to optimize around register mask operands by ignoring regs 1837e8d8bef9SDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask 1838e8d8bef9SDimitry Andric // operands that are seen earlier than the first use of a register, still need 1839e8d8bef9SDimitry Andric // to clobber that register in the transfer function. But this information 1840e8d8bef9SDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block, 1841e8d8bef9SDimitry Andric // and accumulated the clobbered but untracked registers in each block into 1842e8d8bef9SDimitry Andric // the following bitvector. Later, if new values are tracked, we can add 1843e8d8bef9SDimitry Andric // appropriate clobbers. 1844e8d8bef9SDimitry Andric SmallVector<BitVector, 32> BlockMasks; 1845e8d8bef9SDimitry Andric BlockMasks.resize(MaxNumBlocks); 1846e8d8bef9SDimitry Andric 1847e8d8bef9SDimitry Andric // Reserve one bit per register for the masks described above. 1848e8d8bef9SDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); 1849e8d8bef9SDimitry Andric for (auto &BV : BlockMasks) 1850e8d8bef9SDimitry Andric BV.resize(TRI->getNumRegs(), true); 1851e8d8bef9SDimitry Andric 1852e8d8bef9SDimitry Andric // Step through all instructions and inhale the transfer function. 1853e8d8bef9SDimitry Andric for (auto &MBB : MF) { 1854e8d8bef9SDimitry Andric // Object fields that are read by trackers to know where we are in the 1855e8d8bef9SDimitry Andric // function. 1856e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 1857e8d8bef9SDimitry Andric CurInst = 1; 1858e8d8bef9SDimitry Andric 1859e8d8bef9SDimitry Andric // Set all machine locations to a PHI value. For transfer function 1860e8d8bef9SDimitry Andric // production only, this signifies the live-in value to the block. 1861e8d8bef9SDimitry Andric MTracker->reset(); 1862e8d8bef9SDimitry Andric MTracker->setMPhis(CurBB); 1863e8d8bef9SDimitry Andric 1864e8d8bef9SDimitry Andric // Step through each instruction in this block. 1865e8d8bef9SDimitry Andric for (auto &MI : MBB) { 1866*81ad6265SDimitry Andric // Pass in an empty unique_ptr for the value tables when accumulating the 1867*81ad6265SDimitry Andric // machine transfer function. 1868*81ad6265SDimitry Andric process(MI, nullptr, nullptr); 1869*81ad6265SDimitry Andric 1870e8d8bef9SDimitry Andric // Also accumulate fragment map. 18714824e7fdSDimitry Andric if (MI.isDebugValue() || MI.isDebugRef()) 1872e8d8bef9SDimitry Andric accumulateFragmentMap(MI); 1873e8d8bef9SDimitry Andric 1874e8d8bef9SDimitry Andric // Create a map from the instruction number (if present) to the 1875e8d8bef9SDimitry Andric // MachineInstr and its position. 1876e8d8bef9SDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 1877e8d8bef9SDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst); 1878e8d8bef9SDimitry Andric auto InsertResult = 1879e8d8bef9SDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 1880e8d8bef9SDimitry Andric 1881e8d8bef9SDimitry Andric // There should never be duplicate instruction numbers. 1882e8d8bef9SDimitry Andric assert(InsertResult.second); 1883e8d8bef9SDimitry Andric (void)InsertResult; 1884e8d8bef9SDimitry Andric } 1885e8d8bef9SDimitry Andric 1886e8d8bef9SDimitry Andric ++CurInst; 1887e8d8bef9SDimitry Andric } 1888e8d8bef9SDimitry Andric 1889e8d8bef9SDimitry Andric // Produce the transfer function, a map of machine location to new value. If 1890e8d8bef9SDimitry Andric // any machine location has the live-in phi value from the start of the 1891e8d8bef9SDimitry Andric // block, it's live-through and doesn't need recording in the transfer 1892e8d8bef9SDimitry Andric // function. 1893e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1894e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1895e8d8bef9SDimitry Andric ValueIDNum &P = Location.Value; 1896e8d8bef9SDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64()) 1897e8d8bef9SDimitry Andric continue; 1898e8d8bef9SDimitry Andric 1899e8d8bef9SDimitry Andric // Insert-or-update. 1900e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[CurBB]; 1901e8d8bef9SDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 1902e8d8bef9SDimitry Andric if (!Result.second) 1903e8d8bef9SDimitry Andric Result.first->second = P; 1904e8d8bef9SDimitry Andric } 1905e8d8bef9SDimitry Andric 1906e8d8bef9SDimitry Andric // Accumulate any bitmask operands into the clobberred reg mask for this 1907e8d8bef9SDimitry Andric // block. 1908e8d8bef9SDimitry Andric for (auto &P : MTracker->Masks) { 1909e8d8bef9SDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 1910e8d8bef9SDimitry Andric } 1911e8d8bef9SDimitry Andric } 1912e8d8bef9SDimitry Andric 1913e8d8bef9SDimitry Andric // Compute a bitvector of all the registers that are tracked in this block. 1914e8d8bef9SDimitry Andric BitVector UsedRegs(TRI->getNumRegs()); 1915e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1916e8d8bef9SDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 1917349cc55cSDimitry Andric // Ignore stack slots, and aliases of the stack pointer. 1918349cc55cSDimitry Andric if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) 1919e8d8bef9SDimitry Andric continue; 1920e8d8bef9SDimitry Andric UsedRegs.set(ID); 1921e8d8bef9SDimitry Andric } 1922e8d8bef9SDimitry Andric 1923e8d8bef9SDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not 1924e8d8bef9SDimitry Andric // live-through in the transfer function. It needs to be clobbered at the 1925e8d8bef9SDimitry Andric // very least. 1926e8d8bef9SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 1927e8d8bef9SDimitry Andric BitVector &BV = BlockMasks[I]; 1928e8d8bef9SDimitry Andric BV.flip(); 1929e8d8bef9SDimitry Andric BV &= UsedRegs; 1930e8d8bef9SDimitry Andric // This produces all the bits that we clobber, but also use. Check that 1931e8d8bef9SDimitry Andric // they're all clobbered or at least set in the designated transfer 1932e8d8bef9SDimitry Andric // elem. 1933e8d8bef9SDimitry Andric for (unsigned Bit : BV.set_bits()) { 1934349cc55cSDimitry Andric unsigned ID = MTracker->getLocID(Bit); 1935e8d8bef9SDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 1936e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[I]; 1937e8d8bef9SDimitry Andric 1938e8d8bef9SDimitry Andric // Install a value representing the fact that this location is effectively 1939e8d8bef9SDimitry Andric // written to in this block. As there's no reserved value, instead use 1940e8d8bef9SDimitry Andric // a value number that is never generated. Pick the value number for the 1941e8d8bef9SDimitry Andric // first instruction in the block, def'ing this location, which we know 1942e8d8bef9SDimitry Andric // this block never used anyway. 1943e8d8bef9SDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 1944e8d8bef9SDimitry Andric auto Result = 1945e8d8bef9SDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 1946e8d8bef9SDimitry Andric if (!Result.second) { 1947e8d8bef9SDimitry Andric ValueIDNum &ValueID = Result.first->second; 1948e8d8bef9SDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI()) 1949e8d8bef9SDimitry Andric // It was left as live-through. Set it to clobbered. 1950e8d8bef9SDimitry Andric ValueID = NotGeneratedNum; 1951e8d8bef9SDimitry Andric } 1952e8d8bef9SDimitry Andric } 1953e8d8bef9SDimitry Andric } 1954e8d8bef9SDimitry Andric } 1955e8d8bef9SDimitry Andric 1956349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin( 1957349cc55cSDimitry Andric MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1958*81ad6265SDimitry Andric FuncValueTable &OutLocs, ValueTable &InLocs) { 1959e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1960e8d8bef9SDimitry Andric bool Changed = false; 1961e8d8bef9SDimitry Andric 1962349cc55cSDimitry Andric // Handle value-propagation when control flow merges on entry to a block. For 1963349cc55cSDimitry Andric // any location without a PHI already placed, the location has the same value 1964349cc55cSDimitry Andric // as its predecessors. If a PHI is placed, test to see whether it's now a 1965349cc55cSDimitry Andric // redundant PHI that we can eliminate. 1966349cc55cSDimitry Andric 1967e8d8bef9SDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders; 1968349cc55cSDimitry Andric for (auto Pred : MBB.predecessors()) 1969e8d8bef9SDimitry Andric BlockOrders.push_back(Pred); 1970e8d8bef9SDimitry Andric 1971e8d8bef9SDimitry Andric // Visit predecessors in RPOT order. 1972e8d8bef9SDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1973e8d8bef9SDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 1974e8d8bef9SDimitry Andric }; 1975e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 1976e8d8bef9SDimitry Andric 1977e8d8bef9SDimitry Andric // Skip entry block. 1978e8d8bef9SDimitry Andric if (BlockOrders.size() == 0) 1979349cc55cSDimitry Andric return false; 1980e8d8bef9SDimitry Andric 1981349cc55cSDimitry Andric // Step through all machine locations, look at each predecessor and test 1982349cc55cSDimitry Andric // whether we can eliminate redundant PHIs. 1983e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1984e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1985349cc55cSDimitry Andric 1986e8d8bef9SDimitry Andric // Pick out the first predecessors live-out value for this location. It's 1987349cc55cSDimitry Andric // guaranteed to not be a backedge, as we order by RPO. 1988349cc55cSDimitry Andric ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 1989e8d8bef9SDimitry Andric 1990349cc55cSDimitry Andric // If we've already eliminated a PHI here, do no further checking, just 1991349cc55cSDimitry Andric // propagate the first live-in value into this block. 1992349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { 1993349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != FirstVal) { 1994349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 1995349cc55cSDimitry Andric Changed |= true; 1996349cc55cSDimitry Andric } 1997349cc55cSDimitry Andric continue; 1998349cc55cSDimitry Andric } 1999349cc55cSDimitry Andric 2000349cc55cSDimitry Andric // We're now examining a PHI to see whether it's un-necessary. Loop around 2001349cc55cSDimitry Andric // the other live-in values and test whether they're all the same. 2002e8d8bef9SDimitry Andric bool Disagree = false; 2003e8d8bef9SDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 2004349cc55cSDimitry Andric const MachineBasicBlock *PredMBB = BlockOrders[I]; 2005349cc55cSDimitry Andric const ValueIDNum &PredLiveOut = 2006349cc55cSDimitry Andric OutLocs[PredMBB->getNumber()][Idx.asU64()]; 2007349cc55cSDimitry Andric 2008349cc55cSDimitry Andric // Incoming values agree, continue trying to eliminate this PHI. 2009349cc55cSDimitry Andric if (FirstVal == PredLiveOut) 2010349cc55cSDimitry Andric continue; 2011349cc55cSDimitry Andric 2012349cc55cSDimitry Andric // We can also accept a PHI value that feeds back into itself. 2013349cc55cSDimitry Andric if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) 2014349cc55cSDimitry Andric continue; 2015349cc55cSDimitry Andric 2016e8d8bef9SDimitry Andric // Live-out of a predecessor disagrees with the first predecessor. 2017e8d8bef9SDimitry Andric Disagree = true; 2018e8d8bef9SDimitry Andric } 2019e8d8bef9SDimitry Andric 2020349cc55cSDimitry Andric // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. 2021349cc55cSDimitry Andric if (!Disagree) { 2022349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 2023e8d8bef9SDimitry Andric Changed |= true; 2024e8d8bef9SDimitry Andric } 2025e8d8bef9SDimitry Andric } 2026e8d8bef9SDimitry Andric 2027e8d8bef9SDimitry Andric // TODO: Reimplement NumInserted and NumRemoved. 2028349cc55cSDimitry Andric return Changed; 2029e8d8bef9SDimitry Andric } 2030e8d8bef9SDimitry Andric 2031349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference( 2032349cc55cSDimitry Andric SmallVectorImpl<unsigned> &Slots) { 2033349cc55cSDimitry Andric // We could spend a bit of time finding the exact, minimal, set of stack 2034349cc55cSDimitry Andric // indexes that interfere with each other, much like reg units. Or, we can 2035349cc55cSDimitry Andric // rely on the fact that: 2036349cc55cSDimitry Andric // * The smallest / lowest index will interfere with everything at zero 2037349cc55cSDimitry Andric // offset, which will be the largest set of registers, 2038349cc55cSDimitry Andric // * Most indexes with non-zero offset will end up being interference units 2039349cc55cSDimitry Andric // anyway. 2040349cc55cSDimitry Andric // So just pick those out and return them. 2041349cc55cSDimitry Andric 2042349cc55cSDimitry Andric // We can rely on a single-byte stack index existing already, because we 2043349cc55cSDimitry Andric // initialize them in MLocTracker. 2044349cc55cSDimitry Andric auto It = MTracker->StackSlotIdxes.find({8, 0}); 2045349cc55cSDimitry Andric assert(It != MTracker->StackSlotIdxes.end()); 2046349cc55cSDimitry Andric Slots.push_back(It->second); 2047349cc55cSDimitry Andric 2048349cc55cSDimitry Andric // Find anything that has a non-zero offset and add that too. 2049349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 2050349cc55cSDimitry Andric // Is offset zero? If so, ignore. 2051349cc55cSDimitry Andric if (!Pair.first.second) 2052349cc55cSDimitry Andric continue; 2053349cc55cSDimitry Andric Slots.push_back(Pair.second); 2054349cc55cSDimitry Andric } 2055349cc55cSDimitry Andric } 2056349cc55cSDimitry Andric 2057349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs( 2058349cc55cSDimitry Andric MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2059*81ad6265SDimitry Andric FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2060349cc55cSDimitry Andric SmallVector<unsigned, 4> StackUnits; 2061349cc55cSDimitry Andric findStackIndexInterference(StackUnits); 2062349cc55cSDimitry Andric 2063349cc55cSDimitry Andric // To avoid repeatedly running the PHI placement algorithm, leverage the 2064349cc55cSDimitry Andric // fact that a def of register MUST also def its register units. Find the 2065349cc55cSDimitry Andric // units for registers, place PHIs for them, and then replicate them for 2066349cc55cSDimitry Andric // aliasing registers. Some inputs that are never def'd (DBG_PHIs of 2067349cc55cSDimitry Andric // arguments) don't lead to register units being tracked, just place PHIs for 2068349cc55cSDimitry Andric // those registers directly. Stack slots have their own form of "unit", 2069349cc55cSDimitry Andric // store them to one side. 2070349cc55cSDimitry Andric SmallSet<Register, 32> RegUnitsToPHIUp; 2071349cc55cSDimitry Andric SmallSet<LocIdx, 32> NormalLocsToPHI; 2072349cc55cSDimitry Andric SmallSet<SpillLocationNo, 32> StackSlots; 2073349cc55cSDimitry Andric for (auto Location : MTracker->locations()) { 2074349cc55cSDimitry Andric LocIdx L = Location.Idx; 2075349cc55cSDimitry Andric if (MTracker->isSpill(L)) { 2076349cc55cSDimitry Andric StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); 2077349cc55cSDimitry Andric continue; 2078349cc55cSDimitry Andric } 2079349cc55cSDimitry Andric 2080349cc55cSDimitry Andric Register R = MTracker->LocIdxToLocID[L]; 2081349cc55cSDimitry Andric SmallSet<Register, 8> FoundRegUnits; 2082349cc55cSDimitry Andric bool AnyIllegal = false; 2083349cc55cSDimitry Andric for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { 2084349cc55cSDimitry Andric for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ 2085349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*URoot)) { 2086349cc55cSDimitry Andric // Not all roots were loaded into the tracking map: this register 2087349cc55cSDimitry Andric // isn't actually def'd anywhere, we only read from it. Generate PHIs 2088349cc55cSDimitry Andric // for this reg, but don't iterate units. 2089349cc55cSDimitry Andric AnyIllegal = true; 2090349cc55cSDimitry Andric } else { 2091349cc55cSDimitry Andric FoundRegUnits.insert(*URoot); 2092349cc55cSDimitry Andric } 2093349cc55cSDimitry Andric } 2094349cc55cSDimitry Andric } 2095349cc55cSDimitry Andric 2096349cc55cSDimitry Andric if (AnyIllegal) { 2097349cc55cSDimitry Andric NormalLocsToPHI.insert(L); 2098349cc55cSDimitry Andric continue; 2099349cc55cSDimitry Andric } 2100349cc55cSDimitry Andric 2101349cc55cSDimitry Andric RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); 2102349cc55cSDimitry Andric } 2103349cc55cSDimitry Andric 2104349cc55cSDimitry Andric // Lambda to fetch PHIs for a given location, and write into the PHIBlocks 2105349cc55cSDimitry Andric // collection. 2106349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2107349cc55cSDimitry Andric auto CollectPHIsForLoc = [&](LocIdx L) { 2108349cc55cSDimitry Andric // Collect the set of defs. 2109349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2110349cc55cSDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 2111349cc55cSDimitry Andric MachineBasicBlock *MBB = OrderToBB[I]; 2112349cc55cSDimitry Andric const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; 2113349cc55cSDimitry Andric if (TransferFunc.find(L) != TransferFunc.end()) 2114349cc55cSDimitry Andric DefBlocks.insert(MBB); 2115349cc55cSDimitry Andric } 2116349cc55cSDimitry Andric 2117349cc55cSDimitry Andric // The entry block defs the location too: it's the live-in / argument value. 2118349cc55cSDimitry Andric // Only insert if there are other defs though; everything is trivially live 2119349cc55cSDimitry Andric // through otherwise. 2120349cc55cSDimitry Andric if (!DefBlocks.empty()) 2121349cc55cSDimitry Andric DefBlocks.insert(&*MF.begin()); 2122349cc55cSDimitry Andric 2123349cc55cSDimitry Andric // Ask the SSA construction algorithm where we should put PHIs. Clear 2124349cc55cSDimitry Andric // anything that might have been hanging around from earlier. 2125349cc55cSDimitry Andric PHIBlocks.clear(); 2126349cc55cSDimitry Andric BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); 2127349cc55cSDimitry Andric }; 2128349cc55cSDimitry Andric 2129349cc55cSDimitry Andric auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { 2130349cc55cSDimitry Andric for (const MachineBasicBlock *MBB : PHIBlocks) 2131349cc55cSDimitry Andric MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); 2132349cc55cSDimitry Andric }; 2133349cc55cSDimitry Andric 2134349cc55cSDimitry Andric // For locations with no reg units, just place PHIs. 2135349cc55cSDimitry Andric for (LocIdx L : NormalLocsToPHI) { 2136349cc55cSDimitry Andric CollectPHIsForLoc(L); 2137349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2138349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2139349cc55cSDimitry Andric } 2140349cc55cSDimitry Andric 2141349cc55cSDimitry Andric // For stack slots, calculate PHIs for the equivalent of the units, then 2142349cc55cSDimitry Andric // install for each index. 2143349cc55cSDimitry Andric for (SpillLocationNo Slot : StackSlots) { 2144349cc55cSDimitry Andric for (unsigned Idx : StackUnits) { 2145349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); 2146349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 2147349cc55cSDimitry Andric CollectPHIsForLoc(L); 2148349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2149349cc55cSDimitry Andric 2150349cc55cSDimitry Andric // Find anything that aliases this stack index, install PHIs for it too. 2151349cc55cSDimitry Andric unsigned Size, Offset; 2152349cc55cSDimitry Andric std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; 2153349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 2154349cc55cSDimitry Andric unsigned ThisSize, ThisOffset; 2155349cc55cSDimitry Andric std::tie(ThisSize, ThisOffset) = Pair.first; 2156349cc55cSDimitry Andric if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) 2157349cc55cSDimitry Andric continue; 2158349cc55cSDimitry Andric 2159349cc55cSDimitry Andric unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); 2160349cc55cSDimitry Andric LocIdx ThisL = MTracker->getSpillMLoc(ThisID); 2161349cc55cSDimitry Andric InstallPHIsAtLoc(ThisL); 2162349cc55cSDimitry Andric } 2163349cc55cSDimitry Andric } 2164349cc55cSDimitry Andric } 2165349cc55cSDimitry Andric 2166349cc55cSDimitry Andric // For reg units, place PHIs, and then place them for any aliasing registers. 2167349cc55cSDimitry Andric for (Register R : RegUnitsToPHIUp) { 2168349cc55cSDimitry Andric LocIdx L = MTracker->lookupOrTrackRegister(R); 2169349cc55cSDimitry Andric CollectPHIsForLoc(L); 2170349cc55cSDimitry Andric 2171349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2172349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2173349cc55cSDimitry Andric 2174349cc55cSDimitry Andric // Now find aliases and install PHIs for those. 2175349cc55cSDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { 2176349cc55cSDimitry Andric // Super-registers that are "above" the largest register read/written by 2177349cc55cSDimitry Andric // the function will alias, but will not be tracked. 2178349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*RAI)) 2179349cc55cSDimitry Andric continue; 2180349cc55cSDimitry Andric 2181349cc55cSDimitry Andric LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); 2182349cc55cSDimitry Andric InstallPHIsAtLoc(AliasLoc); 2183349cc55cSDimitry Andric } 2184349cc55cSDimitry Andric } 2185349cc55cSDimitry Andric } 2186349cc55cSDimitry Andric 2187349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap( 2188*81ad6265SDimitry Andric MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs, 2189e8d8bef9SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2190e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2191e8d8bef9SDimitry Andric std::greater<unsigned int>> 2192e8d8bef9SDimitry Andric Worklist, Pending; 2193e8d8bef9SDimitry Andric 2194e8d8bef9SDimitry Andric // We track what is on the current and pending worklist to avoid inserting 2195e8d8bef9SDimitry Andric // the same thing twice. We could avoid this with a custom priority queue, 2196e8d8bef9SDimitry Andric // but this is probably not worth it. 2197e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2198e8d8bef9SDimitry Andric 2199349cc55cSDimitry Andric // Initialize worklist with every block to be visited. Also produce list of 2200349cc55cSDimitry Andric // all blocks. 2201349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; 2202e8d8bef9SDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2203e8d8bef9SDimitry Andric Worklist.push(I); 2204e8d8bef9SDimitry Andric OnWorklist.insert(OrderToBB[I]); 2205349cc55cSDimitry Andric AllBlocks.insert(OrderToBB[I]); 2206e8d8bef9SDimitry Andric } 2207e8d8bef9SDimitry Andric 2208349cc55cSDimitry Andric // Initialize entry block to PHIs. These represent arguments. 2209349cc55cSDimitry Andric for (auto Location : MTracker->locations()) 2210349cc55cSDimitry Andric MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); 2211349cc55cSDimitry Andric 2212e8d8bef9SDimitry Andric MTracker->reset(); 2213e8d8bef9SDimitry Andric 2214349cc55cSDimitry Andric // Start by placing PHIs, using the usual SSA constructor algorithm. Consider 2215349cc55cSDimitry Andric // any machine-location that isn't live-through a block to be def'd in that 2216349cc55cSDimitry Andric // block. 2217349cc55cSDimitry Andric placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); 2218e8d8bef9SDimitry Andric 2219349cc55cSDimitry Andric // Propagate values to eliminate redundant PHIs. At the same time, this 2220349cc55cSDimitry Andric // produces the table of Block x Location => Value for the entry to each 2221349cc55cSDimitry Andric // block. 2222349cc55cSDimitry Andric // The kind of PHIs we can eliminate are, for example, where one path in a 2223349cc55cSDimitry Andric // conditional spills and restores a register, and the register still has 2224349cc55cSDimitry Andric // the same value once control flow joins, unbeknowns to the PHI placement 2225349cc55cSDimitry Andric // code. Propagating values allows us to identify such un-necessary PHIs and 2226349cc55cSDimitry Andric // remove them. 2227e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2228e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2229e8d8bef9SDimitry Andric // Vector for storing the evaluated block transfer function. 2230e8d8bef9SDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2231e8d8bef9SDimitry Andric 2232e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2233e8d8bef9SDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2234e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2235e8d8bef9SDimitry Andric Worklist.pop(); 2236e8d8bef9SDimitry Andric 2237e8d8bef9SDimitry Andric // Join the values in all predecessor blocks. 2238349cc55cSDimitry Andric bool InLocsChanged; 2239349cc55cSDimitry Andric InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2240e8d8bef9SDimitry Andric InLocsChanged |= Visited.insert(MBB).second; 2241e8d8bef9SDimitry Andric 2242e8d8bef9SDimitry Andric // Don't examine transfer function if we've visited this loc at least 2243e8d8bef9SDimitry Andric // once, and inlocs haven't changed. 2244e8d8bef9SDimitry Andric if (!InLocsChanged) 2245e8d8bef9SDimitry Andric continue; 2246e8d8bef9SDimitry Andric 2247e8d8bef9SDimitry Andric // Load the current set of live-ins into MLocTracker. 2248e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2249e8d8bef9SDimitry Andric 2250e8d8bef9SDimitry Andric // Each element of the transfer function can be a new def, or a read of 2251e8d8bef9SDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap". 2252e8d8bef9SDimitry Andric ToRemap.clear(); 2253e8d8bef9SDimitry Andric for (auto &P : MLocTransfer[CurBB]) { 2254e8d8bef9SDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2255e8d8bef9SDimitry Andric // This is a movement of whatever was live in. Read it. 2256349cc55cSDimitry Andric ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); 2257e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID)); 2258e8d8bef9SDimitry Andric } else { 2259e8d8bef9SDimitry Andric // It's a def. Just set it. 2260e8d8bef9SDimitry Andric assert(P.second.getBlock() == CurBB); 2261e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second)); 2262e8d8bef9SDimitry Andric } 2263e8d8bef9SDimitry Andric } 2264e8d8bef9SDimitry Andric 2265e8d8bef9SDimitry Andric // Commit the transfer function changes into mloc tracker, which 2266e8d8bef9SDimitry Andric // transforms the contents of the MLocTracker into the live-outs. 2267e8d8bef9SDimitry Andric for (auto &P : ToRemap) 2268e8d8bef9SDimitry Andric MTracker->setMLoc(P.first, P.second); 2269e8d8bef9SDimitry Andric 2270e8d8bef9SDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking 2271e8d8bef9SDimitry Andric // whether changes have occurred. These changes can have come from both 2272e8d8bef9SDimitry Andric // the transfer function, and mlocJoin. 2273e8d8bef9SDimitry Andric bool OLChanged = false; 2274e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 2275e8d8bef9SDimitry Andric OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2276e8d8bef9SDimitry Andric MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2277e8d8bef9SDimitry Andric } 2278e8d8bef9SDimitry Andric 2279e8d8bef9SDimitry Andric MTracker->reset(); 2280e8d8bef9SDimitry Andric 2281e8d8bef9SDimitry Andric // No need to examine successors again if out-locs didn't change. 2282e8d8bef9SDimitry Andric if (!OLChanged) 2283e8d8bef9SDimitry Andric continue; 2284e8d8bef9SDimitry Andric 2285e8d8bef9SDimitry Andric // All successors should be visited: put any back-edges on the pending 2286349cc55cSDimitry Andric // list for the next pass-through, and any other successors to be 2287349cc55cSDimitry Andric // visited this pass, if they're not going to be already. 2288e8d8bef9SDimitry Andric for (auto s : MBB->successors()) { 2289e8d8bef9SDimitry Andric // Does branching to this successor represent a back-edge? 2290e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2291e8d8bef9SDimitry Andric // No: visit it during this dataflow iteration. 2292e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2293e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2294e8d8bef9SDimitry Andric } else { 2295e8d8bef9SDimitry Andric // Yes: visit it on the next iteration. 2296e8d8bef9SDimitry Andric if (OnPending.insert(s).second) 2297e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2298e8d8bef9SDimitry Andric } 2299e8d8bef9SDimitry Andric } 2300e8d8bef9SDimitry Andric } 2301e8d8bef9SDimitry Andric 2302e8d8bef9SDimitry Andric Worklist.swap(Pending); 2303e8d8bef9SDimitry Andric std::swap(OnPending, OnWorklist); 2304e8d8bef9SDimitry Andric OnPending.clear(); 2305e8d8bef9SDimitry Andric // At this point, pending must be empty, since it was just the empty 2306e8d8bef9SDimitry Andric // worklist 2307e8d8bef9SDimitry Andric assert(Pending.empty() && "Pending should be empty"); 2308e8d8bef9SDimitry Andric } 2309e8d8bef9SDimitry Andric 2310349cc55cSDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've eliminated all 2311349cc55cSDimitry Andric // redundant PHIs. 2312e8d8bef9SDimitry Andric } 2313e8d8bef9SDimitry Andric 2314349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement( 2315349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2316349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 2317349cc55cSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { 2318349cc55cSDimitry Andric // Apply IDF calculator to the designated set of location defs, storing 2319349cc55cSDimitry Andric // required PHIs into PHIBlocks. Uses the dominator tree stored in the 2320349cc55cSDimitry Andric // InstrRefBasedLDV object. 23211fd87a68SDimitry Andric IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase()); 2322349cc55cSDimitry Andric 2323349cc55cSDimitry Andric IDF.setLiveInBlocks(AllBlocks); 2324349cc55cSDimitry Andric IDF.setDefiningBlocks(DefBlocks); 2325349cc55cSDimitry Andric IDF.calculate(PHIBlocks); 2326e8d8bef9SDimitry Andric } 2327e8d8bef9SDimitry Andric 2328349cc55cSDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( 2329349cc55cSDimitry Andric const MachineBasicBlock &MBB, const DebugVariable &Var, 2330*81ad6265SDimitry Andric const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs, 2331349cc55cSDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { 2332e8d8bef9SDimitry Andric // Collect a set of locations from predecessor where its live-out value can 2333e8d8bef9SDimitry Andric // be found. 2334e8d8bef9SDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2335349cc55cSDimitry Andric SmallVector<const DbgValueProperties *, 4> Properties; 2336e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2337349cc55cSDimitry Andric 2338349cc55cSDimitry Andric // No predecessors means no PHIs. 2339349cc55cSDimitry Andric if (BlockOrders.empty()) 2340349cc55cSDimitry Andric return None; 2341e8d8bef9SDimitry Andric 2342e8d8bef9SDimitry Andric for (auto p : BlockOrders) { 2343e8d8bef9SDimitry Andric unsigned ThisBBNum = p->getNumber(); 2344349cc55cSDimitry Andric auto OutValIt = LiveOuts.find(p); 2345349cc55cSDimitry Andric if (OutValIt == LiveOuts.end()) 2346349cc55cSDimitry Andric // If we have a predecessor not in scope, we'll never find a PHI position. 2347349cc55cSDimitry Andric return None; 2348349cc55cSDimitry Andric const DbgValue &OutVal = *OutValIt->second; 2349e8d8bef9SDimitry Andric 2350e8d8bef9SDimitry Andric if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2351e8d8bef9SDimitry Andric // Consts and no-values cannot have locations we can join on. 2352349cc55cSDimitry Andric return None; 2353e8d8bef9SDimitry Andric 2354349cc55cSDimitry Andric Properties.push_back(&OutVal.Properties); 2355349cc55cSDimitry Andric 2356349cc55cSDimitry Andric // Create new empty vector of locations. 2357349cc55cSDimitry Andric Locs.resize(Locs.size() + 1); 2358349cc55cSDimitry Andric 2359349cc55cSDimitry Andric // If the live-in value is a def, find the locations where that value is 2360349cc55cSDimitry Andric // present. Do the same for VPHIs where we know the VPHI value. 2361349cc55cSDimitry Andric if (OutVal.Kind == DbgValue::Def || 2362349cc55cSDimitry Andric (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && 2363349cc55cSDimitry Andric OutVal.ID != ValueIDNum::EmptyValue)) { 2364e8d8bef9SDimitry Andric ValueIDNum ValToLookFor = OutVal.ID; 2365e8d8bef9SDimitry Andric // Search the live-outs of the predecessor for the specified value. 2366e8d8bef9SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2367e8d8bef9SDimitry Andric if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2368e8d8bef9SDimitry Andric Locs.back().push_back(LocIdx(I)); 2369e8d8bef9SDimitry Andric } 2370349cc55cSDimitry Andric } else { 2371349cc55cSDimitry Andric assert(OutVal.Kind == DbgValue::VPHI); 2372349cc55cSDimitry Andric // For VPHIs where we don't know the location, we definitely can't find 2373349cc55cSDimitry Andric // a join loc. 2374349cc55cSDimitry Andric if (OutVal.BlockNo != MBB.getNumber()) 2375349cc55cSDimitry Andric return None; 2376349cc55cSDimitry Andric 2377349cc55cSDimitry Andric // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. 2378349cc55cSDimitry Andric // a value that's live-through the whole loop. (It has to be a backedge, 2379349cc55cSDimitry Andric // because a block can't dominate itself). We can accept as a PHI location 2380349cc55cSDimitry Andric // any location where the other predecessors agree, _and_ the machine 2381349cc55cSDimitry Andric // locations feed back into themselves. Therefore, add all self-looping 2382349cc55cSDimitry Andric // machine-value PHI locations. 2383349cc55cSDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2384349cc55cSDimitry Andric ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); 2385349cc55cSDimitry Andric if (MOutLocs[ThisBBNum][I] == MPHI) 2386349cc55cSDimitry Andric Locs.back().push_back(LocIdx(I)); 2387349cc55cSDimitry Andric } 2388349cc55cSDimitry Andric } 2389e8d8bef9SDimitry Andric } 2390e8d8bef9SDimitry Andric 2391349cc55cSDimitry Andric // We should have found locations for all predecessors, or returned. 2392349cc55cSDimitry Andric assert(Locs.size() == BlockOrders.size()); 2393e8d8bef9SDimitry Andric 2394349cc55cSDimitry Andric // Check that all properties are the same. We can't pick a location if they're 2395349cc55cSDimitry Andric // not. 2396349cc55cSDimitry Andric const DbgValueProperties *Properties0 = Properties[0]; 2397349cc55cSDimitry Andric for (auto *Prop : Properties) 2398349cc55cSDimitry Andric if (*Prop != *Properties0) 2399349cc55cSDimitry Andric return None; 2400349cc55cSDimitry Andric 2401e8d8bef9SDimitry Andric // Starting with the first set of locations, take the intersection with 2402e8d8bef9SDimitry Andric // subsequent sets. 2403349cc55cSDimitry Andric SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; 2404349cc55cSDimitry Andric for (unsigned int I = 1; I < Locs.size(); ++I) { 2405349cc55cSDimitry Andric auto &LocVec = Locs[I]; 2406349cc55cSDimitry Andric SmallVector<LocIdx, 4> NewCandidates; 2407349cc55cSDimitry Andric std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), 2408349cc55cSDimitry Andric LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); 2409349cc55cSDimitry Andric CandidateLocs = NewCandidates; 2410e8d8bef9SDimitry Andric } 2411349cc55cSDimitry Andric if (CandidateLocs.empty()) 2412e8d8bef9SDimitry Andric return None; 2413e8d8bef9SDimitry Andric 2414e8d8bef9SDimitry Andric // We now have a set of LocIdxes that contain the right output value in 2415e8d8bef9SDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc, 2416e8d8bef9SDimitry Andric // that'll be it. 2417349cc55cSDimitry Andric LocIdx L = *CandidateLocs.begin(); 2418e8d8bef9SDimitry Andric 2419e8d8bef9SDimitry Andric // Return a PHI-value-number for the found location. 2420e8d8bef9SDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2421349cc55cSDimitry Andric return PHIVal; 2422e8d8bef9SDimitry Andric } 2423e8d8bef9SDimitry Andric 2424349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin( 2425349cc55cSDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 2426e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2427349cc55cSDimitry Andric DbgValue &LiveIn) { 2428e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2429e8d8bef9SDimitry Andric bool Changed = false; 2430e8d8bef9SDimitry Andric 2431e8d8bef9SDimitry Andric // Order predecessors by RPOT order, for exploring them in that order. 2432fe6060f1SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2433e8d8bef9SDimitry Andric 2434e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2435e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2436e8d8bef9SDimitry Andric }; 2437e8d8bef9SDimitry Andric 2438e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2439e8d8bef9SDimitry Andric 2440e8d8bef9SDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB]; 2441e8d8bef9SDimitry Andric 2442349cc55cSDimitry Andric // Collect all the incoming DbgValues for this variable, from predecessor 2443349cc55cSDimitry Andric // live-out values. 2444e8d8bef9SDimitry Andric SmallVector<InValueT, 8> Values; 2445e8d8bef9SDimitry Andric bool Bail = false; 2446349cc55cSDimitry Andric int BackEdgesStart = 0; 2447e8d8bef9SDimitry Andric for (auto p : BlockOrders) { 2448e8d8bef9SDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be 2449e8d8bef9SDimitry Andric // able to join any locations. 2450e8d8bef9SDimitry Andric if (!BlocksToExplore.contains(p)) { 2451e8d8bef9SDimitry Andric Bail = true; 2452e8d8bef9SDimitry Andric break; 2453e8d8bef9SDimitry Andric } 2454e8d8bef9SDimitry Andric 2455349cc55cSDimitry Andric // All Live-outs will have been initialized. 2456349cc55cSDimitry Andric DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; 2457e8d8bef9SDimitry Andric 2458e8d8bef9SDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on 2459e8d8bef9SDimitry Andric // BlockOrders being sorted by RPO. 2460e8d8bef9SDimitry Andric unsigned ThisBBRPONum = BBToOrder[p]; 2461e8d8bef9SDimitry Andric if (ThisBBRPONum < CurBlockRPONum) 2462e8d8bef9SDimitry Andric ++BackEdgesStart; 2463e8d8bef9SDimitry Andric 2464349cc55cSDimitry Andric Values.push_back(std::make_pair(p, &OutLoc)); 2465e8d8bef9SDimitry Andric } 2466e8d8bef9SDimitry Andric 2467e8d8bef9SDimitry Andric // If there were no values, or one of the predecessors couldn't have a 2468e8d8bef9SDimitry Andric // value, then give up immediately. It's not safe to produce a live-in 2469349cc55cSDimitry Andric // value. Leave as whatever it was before. 2470e8d8bef9SDimitry Andric if (Bail || Values.size() == 0) 2471349cc55cSDimitry Andric return false; 2472e8d8bef9SDimitry Andric 2473e8d8bef9SDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor. 2474e8d8bef9SDimitry Andric // Pick the variable value from the first of these, to compare against 2475e8d8bef9SDimitry Andric // all others. 2476e8d8bef9SDimitry Andric const DbgValue &FirstVal = *Values[0].second; 2477e8d8bef9SDimitry Andric 2478349cc55cSDimitry Andric // If the old live-in value is not a PHI then either a) no PHI is needed 2479349cc55cSDimitry Andric // here, or b) we eliminated the PHI that was here. If so, we can just 2480349cc55cSDimitry Andric // propagate in the first parent's incoming value. 2481349cc55cSDimitry Andric if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { 2482349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2483349cc55cSDimitry Andric if (Changed) 2484349cc55cSDimitry Andric LiveIn = FirstVal; 2485349cc55cSDimitry Andric return Changed; 2486349cc55cSDimitry Andric } 2487349cc55cSDimitry Andric 2488349cc55cSDimitry Andric // Scan for variable values that can never be resolved: if they have 2489349cc55cSDimitry Andric // different DIExpressions, different indirectness, or are mixed constants / 2490e8d8bef9SDimitry Andric // non-constants. 2491e8d8bef9SDimitry Andric for (auto &V : Values) { 2492e8d8bef9SDimitry Andric if (V.second->Properties != FirstVal.Properties) 2493349cc55cSDimitry Andric return false; 2494349cc55cSDimitry Andric if (V.second->Kind == DbgValue::NoVal) 2495349cc55cSDimitry Andric return false; 2496e8d8bef9SDimitry Andric if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 2497349cc55cSDimitry Andric return false; 2498e8d8bef9SDimitry Andric } 2499e8d8bef9SDimitry Andric 2500349cc55cSDimitry Andric // Try to eliminate this PHI. Do the incoming values all agree? 2501e8d8bef9SDimitry Andric bool Disagree = false; 2502e8d8bef9SDimitry Andric for (auto &V : Values) { 2503e8d8bef9SDimitry Andric if (*V.second == FirstVal) 2504e8d8bef9SDimitry Andric continue; // No disagreement. 2505e8d8bef9SDimitry Andric 2506349cc55cSDimitry Andric // Eliminate if a backedge feeds a VPHI back into itself. 2507349cc55cSDimitry Andric if (V.second->Kind == DbgValue::VPHI && 2508349cc55cSDimitry Andric V.second->BlockNo == MBB.getNumber() && 2509349cc55cSDimitry Andric // Is this a backedge? 2510349cc55cSDimitry Andric std::distance(Values.begin(), &V) >= BackEdgesStart) 2511349cc55cSDimitry Andric continue; 2512349cc55cSDimitry Andric 2513e8d8bef9SDimitry Andric Disagree = true; 2514e8d8bef9SDimitry Andric } 2515e8d8bef9SDimitry Andric 2516349cc55cSDimitry Andric // No disagreement -> live-through value. 2517349cc55cSDimitry Andric if (!Disagree) { 2518349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2519e8d8bef9SDimitry Andric if (Changed) 2520349cc55cSDimitry Andric LiveIn = FirstVal; 2521349cc55cSDimitry Andric return Changed; 2522349cc55cSDimitry Andric } else { 2523349cc55cSDimitry Andric // Otherwise use a VPHI. 2524349cc55cSDimitry Andric DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); 2525349cc55cSDimitry Andric Changed = LiveIn != VPHI; 2526349cc55cSDimitry Andric if (Changed) 2527349cc55cSDimitry Andric LiveIn = VPHI; 2528349cc55cSDimitry Andric return Changed; 2529349cc55cSDimitry Andric } 2530e8d8bef9SDimitry Andric } 2531e8d8bef9SDimitry Andric 25321fd87a68SDimitry Andric void InstrRefBasedLDV::getBlocksForScope( 25331fd87a68SDimitry Andric const DILocation *DILoc, 25341fd87a68SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore, 25351fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) { 25361fd87a68SDimitry Andric // Get the set of "normal" in-lexical-scope blocks. 25371fd87a68SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 25381fd87a68SDimitry Andric 25391fd87a68SDimitry Andric // VarLoc LiveDebugValues tracks variable locations that are defined in 25401fd87a68SDimitry Andric // blocks not in scope. This is something we could legitimately ignore, but 25411fd87a68SDimitry Andric // lets allow it for now for the sake of coverage. 25421fd87a68SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 25431fd87a68SDimitry Andric 25441fd87a68SDimitry Andric // Storage for artificial blocks we intend to add to BlocksToExplore. 25451fd87a68SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd; 25461fd87a68SDimitry Andric 25471fd87a68SDimitry Andric // To avoid needlessly dropping large volumes of variable locations, propagate 25481fd87a68SDimitry Andric // variables through aritifical blocks, i.e. those that don't have any 25491fd87a68SDimitry Andric // instructions in scope at all. To accurately replicate VarLoc 25501fd87a68SDimitry Andric // LiveDebugValues, this means exploring all artificial successors too. 25511fd87a68SDimitry Andric // Perform a depth-first-search to enumerate those blocks. 25521fd87a68SDimitry Andric for (auto *MBB : BlocksToExplore) { 25531fd87a68SDimitry Andric // Depth-first-search state: each node is a block and which successor 25541fd87a68SDimitry Andric // we're currently exploring. 25551fd87a68SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, 25561fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator>, 25571fd87a68SDimitry Andric 8> 25581fd87a68SDimitry Andric DFS; 25591fd87a68SDimitry Andric 25601fd87a68SDimitry Andric // Find any artificial successors not already tracked. 25611fd87a68SDimitry Andric for (auto *succ : MBB->successors()) { 25621fd87a68SDimitry Andric if (BlocksToExplore.count(succ)) 25631fd87a68SDimitry Andric continue; 25641fd87a68SDimitry Andric if (!ArtificialBlocks.count(succ)) 25651fd87a68SDimitry Andric continue; 25661fd87a68SDimitry Andric ToAdd.insert(succ); 25671fd87a68SDimitry Andric DFS.push_back({succ, succ->succ_begin()}); 25681fd87a68SDimitry Andric } 25691fd87a68SDimitry Andric 25701fd87a68SDimitry Andric // Search all those blocks, depth first. 25711fd87a68SDimitry Andric while (!DFS.empty()) { 25721fd87a68SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first; 25731fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 25741fd87a68SDimitry Andric // Walk back if we've explored this blocks successors to the end. 25751fd87a68SDimitry Andric if (CurSucc == CurBB->succ_end()) { 25761fd87a68SDimitry Andric DFS.pop_back(); 25771fd87a68SDimitry Andric continue; 25781fd87a68SDimitry Andric } 25791fd87a68SDimitry Andric 25801fd87a68SDimitry Andric // If the current successor is artificial and unexplored, descend into 25811fd87a68SDimitry Andric // it. 25821fd87a68SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 25831fd87a68SDimitry Andric ToAdd.insert(*CurSucc); 25841fd87a68SDimitry Andric DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()}); 25851fd87a68SDimitry Andric continue; 25861fd87a68SDimitry Andric } 25871fd87a68SDimitry Andric 25881fd87a68SDimitry Andric ++CurSucc; 25891fd87a68SDimitry Andric } 25901fd87a68SDimitry Andric }; 25911fd87a68SDimitry Andric 25921fd87a68SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 25931fd87a68SDimitry Andric } 25941fd87a68SDimitry Andric 25951fd87a68SDimitry Andric void InstrRefBasedLDV::buildVLocValueMap( 25961fd87a68SDimitry Andric const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 2597e8d8bef9SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 2598*81ad6265SDimitry Andric FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2599e8d8bef9SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) { 2600349cc55cSDimitry Andric // This method is much like buildMLocValueMap: but focuses on a single 2601e8d8bef9SDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are 2602e8d8bef9SDimitry Andric // to have their value assignments solved, then run our dataflow algorithm 2603e8d8bef9SDimitry Andric // until a fixedpoint is reached. 2604e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2605e8d8bef9SDimitry Andric std::greater<unsigned int>> 2606e8d8bef9SDimitry Andric Worklist, Pending; 2607e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 2608e8d8bef9SDimitry Andric 2609e8d8bef9SDimitry Andric // The set of blocks we'll be examining. 2610e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2611e8d8bef9SDimitry Andric 2612e8d8bef9SDimitry Andric // The order in which to examine them (RPO). 2613e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders; 2614e8d8bef9SDimitry Andric 2615e8d8bef9SDimitry Andric // RPO ordering function. 2616e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2617e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2618e8d8bef9SDimitry Andric }; 2619e8d8bef9SDimitry Andric 26201fd87a68SDimitry Andric getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks); 2621e8d8bef9SDimitry Andric 2622e8d8bef9SDimitry Andric // Single block scope: not interesting! No propagation at all. Note that 2623e8d8bef9SDimitry Andric // this could probably go above ArtificialBlocks without damage, but 2624e8d8bef9SDimitry Andric // that then produces output differences from original-live-debug-values, 2625e8d8bef9SDimitry Andric // which propagates from a single block into many artificial ones. 2626e8d8bef9SDimitry Andric if (BlocksToExplore.size() == 1) 2627e8d8bef9SDimitry Andric return; 2628e8d8bef9SDimitry Andric 2629349cc55cSDimitry Andric // Convert a const set to a non-const set. LexicalScopes 2630349cc55cSDimitry Andric // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. 2631349cc55cSDimitry Andric // (Neither of them mutate anything). 2632349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; 2633349cc55cSDimitry Andric for (const auto *MBB : BlocksToExplore) 2634349cc55cSDimitry Andric MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); 2635349cc55cSDimitry Andric 2636e8d8bef9SDimitry Andric // Picks out relevants blocks RPO order and sort them. 2637e8d8bef9SDimitry Andric for (auto *MBB : BlocksToExplore) 2638e8d8bef9SDimitry Andric BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 2639e8d8bef9SDimitry Andric 2640e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2641e8d8bef9SDimitry Andric unsigned NumBlocks = BlockOrders.size(); 2642e8d8bef9SDimitry Andric 2643e8d8bef9SDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large. 2644349cc55cSDimitry Andric SmallVector<DbgValue, 32> LiveIns, LiveOuts; 2645349cc55cSDimitry Andric LiveIns.reserve(NumBlocks); 2646349cc55cSDimitry Andric LiveOuts.reserve(NumBlocks); 2647349cc55cSDimitry Andric 2648349cc55cSDimitry Andric // Initialize all values to start as NoVals. This signifies "it's live 2649349cc55cSDimitry Andric // through, but we don't know what it is". 2650349cc55cSDimitry Andric DbgValueProperties EmptyProperties(EmptyExpr, false); 2651349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2652349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2653349cc55cSDimitry Andric LiveIns.push_back(EmptyDbgValue); 2654349cc55cSDimitry Andric LiveOuts.push_back(EmptyDbgValue); 2655349cc55cSDimitry Andric } 2656e8d8bef9SDimitry Andric 2657e8d8bef9SDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 2658e8d8bef9SDimitry Andric // vlocJoin. 2659e8d8bef9SDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx; 2660e8d8bef9SDimitry Andric LiveOutIdx.reserve(NumBlocks); 2661e8d8bef9SDimitry Andric LiveInIdx.reserve(NumBlocks); 2662e8d8bef9SDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) { 2663e8d8bef9SDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 2664e8d8bef9SDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 2665e8d8bef9SDimitry Andric } 2666e8d8bef9SDimitry Andric 2667349cc55cSDimitry Andric // Loop over each variable and place PHIs for it, then propagate values 2668349cc55cSDimitry Andric // between blocks. This keeps the locality of working on one lexical scope at 2669349cc55cSDimitry Andric // at time, but avoids re-processing variable values because some other 2670349cc55cSDimitry Andric // variable has been assigned. 2671349cc55cSDimitry Andric for (auto &Var : VarsWeCareAbout) { 2672349cc55cSDimitry Andric // Re-initialize live-ins and live-outs, to clear the remains of previous 2673349cc55cSDimitry Andric // variables live-ins / live-outs. 2674349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2675349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2676349cc55cSDimitry Andric LiveIns[I] = EmptyDbgValue; 2677349cc55cSDimitry Andric LiveOuts[I] = EmptyDbgValue; 2678349cc55cSDimitry Andric } 2679349cc55cSDimitry Andric 2680349cc55cSDimitry Andric // Place PHIs for variable values, using the LLVM IDF calculator. 2681349cc55cSDimitry Andric // Collect the set of blocks where variables are def'd. 2682349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2683349cc55cSDimitry Andric for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { 2684349cc55cSDimitry Andric auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; 2685349cc55cSDimitry Andric if (TransferFunc.find(Var) != TransferFunc.end()) 2686349cc55cSDimitry Andric DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); 2687349cc55cSDimitry Andric } 2688349cc55cSDimitry Andric 2689349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2690349cc55cSDimitry Andric 26911fd87a68SDimitry Andric // Request the set of PHIs we should insert for this variable. If there's 26921fd87a68SDimitry Andric // only one value definition, things are very simple. 26931fd87a68SDimitry Andric if (DefBlocks.size() == 1) { 26941fd87a68SDimitry Andric placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(), 26951fd87a68SDimitry Andric AllTheVLocs, Var, Output); 26961fd87a68SDimitry Andric continue; 26971fd87a68SDimitry Andric } 26981fd87a68SDimitry Andric 26991fd87a68SDimitry Andric // Otherwise: we need to place PHIs through SSA and propagate values. 2700349cc55cSDimitry Andric BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); 2701349cc55cSDimitry Andric 2702349cc55cSDimitry Andric // Insert PHIs into the per-block live-in tables for this variable. 2703349cc55cSDimitry Andric for (MachineBasicBlock *PHIMBB : PHIBlocks) { 2704349cc55cSDimitry Andric unsigned BlockNo = PHIMBB->getNumber(); 2705349cc55cSDimitry Andric DbgValue *LiveIn = LiveInIdx[PHIMBB]; 2706349cc55cSDimitry Andric *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); 2707349cc55cSDimitry Andric } 2708349cc55cSDimitry Andric 2709e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2710e8d8bef9SDimitry Andric Worklist.push(BBToOrder[MBB]); 2711e8d8bef9SDimitry Andric OnWorklist.insert(MBB); 2712e8d8bef9SDimitry Andric } 2713e8d8bef9SDimitry Andric 2714349cc55cSDimitry Andric // Iterate over all the blocks we selected, propagating the variables value. 2715349cc55cSDimitry Andric // This loop does two things: 2716349cc55cSDimitry Andric // * Eliminates un-necessary VPHIs in vlocJoin, 2717349cc55cSDimitry Andric // * Evaluates the blocks transfer function (i.e. variable assignments) and 2718349cc55cSDimitry Andric // stores the result to the blocks live-outs. 2719349cc55cSDimitry Andric // Always evaluate the transfer function on the first iteration, and when 2720349cc55cSDimitry Andric // the live-ins change thereafter. 2721e8d8bef9SDimitry Andric bool FirstTrip = true; 2722e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2723e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2724e8d8bef9SDimitry Andric auto *MBB = OrderToBB[Worklist.top()]; 2725e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2726e8d8bef9SDimitry Andric Worklist.pop(); 2727e8d8bef9SDimitry Andric 2728349cc55cSDimitry Andric auto LiveInsIt = LiveInIdx.find(MBB); 2729349cc55cSDimitry Andric assert(LiveInsIt != LiveInIdx.end()); 2730349cc55cSDimitry Andric DbgValue *LiveIn = LiveInsIt->second; 2731e8d8bef9SDimitry Andric 2732e8d8bef9SDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output 2733e8d8bef9SDimitry Andric // into JoinedInLocs. 2734349cc55cSDimitry Andric bool InLocsChanged = 27354824e7fdSDimitry Andric vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); 2736e8d8bef9SDimitry Andric 2737349cc55cSDimitry Andric SmallVector<const MachineBasicBlock *, 8> Preds; 2738349cc55cSDimitry Andric for (const auto *Pred : MBB->predecessors()) 2739349cc55cSDimitry Andric Preds.push_back(Pred); 2740e8d8bef9SDimitry Andric 2741349cc55cSDimitry Andric // If this block's live-in value is a VPHI, try to pick a machine-value 2742349cc55cSDimitry Andric // for it. This makes the machine-value available and propagated 2743349cc55cSDimitry Andric // through all blocks by the time value propagation finishes. We can't 2744349cc55cSDimitry Andric // do this any earlier as it needs to read the block live-outs. 2745349cc55cSDimitry Andric if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { 2746349cc55cSDimitry Andric // There's a small possibility that on a preceeding path, a VPHI is 2747349cc55cSDimitry Andric // eliminated and transitions from VPHI-with-location to 2748349cc55cSDimitry Andric // live-through-value. As a result, the selected location of any VPHI 2749349cc55cSDimitry Andric // might change, so we need to re-compute it on each iteration. 2750349cc55cSDimitry Andric Optional<ValueIDNum> ValueNum = 2751349cc55cSDimitry Andric pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); 2752e8d8bef9SDimitry Andric 2753349cc55cSDimitry Andric if (ValueNum) { 2754349cc55cSDimitry Andric InLocsChanged |= LiveIn->ID != *ValueNum; 2755349cc55cSDimitry Andric LiveIn->ID = *ValueNum; 2756349cc55cSDimitry Andric } 2757349cc55cSDimitry Andric } 2758e8d8bef9SDimitry Andric 2759349cc55cSDimitry Andric if (!InLocsChanged && !FirstTrip) 2760e8d8bef9SDimitry Andric continue; 2761e8d8bef9SDimitry Andric 2762349cc55cSDimitry Andric DbgValue *LiveOut = LiveOutIdx[MBB]; 2763349cc55cSDimitry Andric bool OLChanged = false; 2764349cc55cSDimitry Andric 2765e8d8bef9SDimitry Andric // Do transfer function. 2766e8d8bef9SDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()]; 2767349cc55cSDimitry Andric auto TransferIt = VTracker.Vars.find(Var); 2768349cc55cSDimitry Andric if (TransferIt != VTracker.Vars.end()) { 2769e8d8bef9SDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg). 2770349cc55cSDimitry Andric if (TransferIt->second.Kind == DbgValue::Undef) { 2771349cc55cSDimitry Andric DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); 2772349cc55cSDimitry Andric if (*LiveOut != NewVal) { 2773349cc55cSDimitry Andric *LiveOut = NewVal; 2774349cc55cSDimitry Andric OLChanged = true; 2775349cc55cSDimitry Andric } 2776e8d8bef9SDimitry Andric } else { 2777e8d8bef9SDimitry Andric // Insert new variable value; or overwrite. 2778349cc55cSDimitry Andric if (*LiveOut != TransferIt->second) { 2779349cc55cSDimitry Andric *LiveOut = TransferIt->second; 2780349cc55cSDimitry Andric OLChanged = true; 2781e8d8bef9SDimitry Andric } 2782e8d8bef9SDimitry Andric } 2783349cc55cSDimitry Andric } else { 2784349cc55cSDimitry Andric // Just copy live-ins to live-outs, for anything not transferred. 2785349cc55cSDimitry Andric if (*LiveOut != *LiveIn) { 2786349cc55cSDimitry Andric *LiveOut = *LiveIn; 2787349cc55cSDimitry Andric OLChanged = true; 2788349cc55cSDimitry Andric } 2789e8d8bef9SDimitry Andric } 2790e8d8bef9SDimitry Andric 2791349cc55cSDimitry Andric // If no live-out value changed, there's no need to explore further. 2792e8d8bef9SDimitry Andric if (!OLChanged) 2793e8d8bef9SDimitry Andric continue; 2794e8d8bef9SDimitry Andric 2795e8d8bef9SDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge 2796e8d8bef9SDimitry Andric // successors during this dataflow iteration; book backedge successors 2797e8d8bef9SDimitry Andric // to be visited next time around. 2798e8d8bef9SDimitry Andric for (auto s : MBB->successors()) { 2799e8d8bef9SDimitry Andric // Ignore out of scope / not-to-be-explored successors. 2800e8d8bef9SDimitry Andric if (LiveInIdx.find(s) == LiveInIdx.end()) 2801e8d8bef9SDimitry Andric continue; 2802e8d8bef9SDimitry Andric 2803e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2804e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2805e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2806e8d8bef9SDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 2807e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2808e8d8bef9SDimitry Andric } 2809e8d8bef9SDimitry Andric } 2810e8d8bef9SDimitry Andric } 2811e8d8bef9SDimitry Andric Worklist.swap(Pending); 2812e8d8bef9SDimitry Andric std::swap(OnWorklist, OnPending); 2813e8d8bef9SDimitry Andric OnPending.clear(); 2814e8d8bef9SDimitry Andric assert(Pending.empty()); 2815e8d8bef9SDimitry Andric FirstTrip = false; 2816e8d8bef9SDimitry Andric } 2817e8d8bef9SDimitry Andric 2818349cc55cSDimitry Andric // Save live-ins to output vector. Ignore any that are still marked as being 2819349cc55cSDimitry Andric // VPHIs with no location -- those are variables that we know the value of, 2820349cc55cSDimitry Andric // but are not actually available in the register file. 2821e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2822349cc55cSDimitry Andric DbgValue *BlockLiveIn = LiveInIdx[MBB]; 2823349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::NoVal) 2824e8d8bef9SDimitry Andric continue; 2825349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI && 2826349cc55cSDimitry Andric BlockLiveIn->ID == ValueIDNum::EmptyValue) 2827349cc55cSDimitry Andric continue; 2828349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI) 2829349cc55cSDimitry Andric BlockLiveIn->Kind = DbgValue::Def; 28304824e7fdSDimitry Andric assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == 28314824e7fdSDimitry Andric Var.getFragment() && "Fragment info missing during value prop"); 2832349cc55cSDimitry Andric Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); 2833e8d8bef9SDimitry Andric } 2834349cc55cSDimitry Andric } // Per-variable loop. 2835e8d8bef9SDimitry Andric 2836e8d8bef9SDimitry Andric BlockOrders.clear(); 2837e8d8bef9SDimitry Andric BlocksToExplore.clear(); 2838e8d8bef9SDimitry Andric } 2839e8d8bef9SDimitry Andric 28401fd87a68SDimitry Andric void InstrRefBasedLDV::placePHIsForSingleVarDefinition( 28411fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks, 28421fd87a68SDimitry Andric MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs, 28431fd87a68SDimitry Andric const DebugVariable &Var, LiveInsT &Output) { 28441fd87a68SDimitry Andric // If there is a single definition of the variable, then working out it's 28451fd87a68SDimitry Andric // value everywhere is very simple: it's every block dominated by the 28461fd87a68SDimitry Andric // definition. At the dominance frontier, the usual algorithm would: 28471fd87a68SDimitry Andric // * Place PHIs, 28481fd87a68SDimitry Andric // * Propagate values into them, 28491fd87a68SDimitry Andric // * Find there's no incoming variable value from the other incoming branches 28501fd87a68SDimitry Andric // of the dominance frontier, 28511fd87a68SDimitry Andric // * Specify there's no variable value in blocks past the frontier. 28521fd87a68SDimitry Andric // This is a common case, hence it's worth special-casing it. 28531fd87a68SDimitry Andric 28541fd87a68SDimitry Andric // Pick out the variables value from the block transfer function. 28551fd87a68SDimitry Andric VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()]; 28561fd87a68SDimitry Andric auto ValueIt = VLocs.Vars.find(Var); 28571fd87a68SDimitry Andric const DbgValue &Value = ValueIt->second; 28581fd87a68SDimitry Andric 2859d56accc7SDimitry Andric // If it's an explicit assignment of "undef", that means there is no location 2860d56accc7SDimitry Andric // anyway, anywhere. 2861d56accc7SDimitry Andric if (Value.Kind == DbgValue::Undef) 2862d56accc7SDimitry Andric return; 2863d56accc7SDimitry Andric 28641fd87a68SDimitry Andric // Assign the variable value to entry to each dominated block that's in scope. 28651fd87a68SDimitry Andric // Skip the definition block -- it's assigned the variable value in the middle 28661fd87a68SDimitry Andric // of the block somewhere. 28671fd87a68SDimitry Andric for (auto *ScopeBlock : InScopeBlocks) { 28681fd87a68SDimitry Andric if (!DomTree->properlyDominates(AssignMBB, ScopeBlock)) 28691fd87a68SDimitry Andric continue; 28701fd87a68SDimitry Andric 28711fd87a68SDimitry Andric Output[ScopeBlock->getNumber()].push_back({Var, Value}); 28721fd87a68SDimitry Andric } 28731fd87a68SDimitry Andric 28741fd87a68SDimitry Andric // All blocks that aren't dominated have no live-in value, thus no variable 28751fd87a68SDimitry Andric // value will be given to them. 28761fd87a68SDimitry Andric } 28771fd87a68SDimitry Andric 2878e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2879e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer( 2880e8d8bef9SDimitry Andric const MLocTransferMap &mloc_transfer) const { 2881e8d8bef9SDimitry Andric for (auto &P : mloc_transfer) { 2882e8d8bef9SDimitry Andric std::string foo = MTracker->LocIdxToName(P.first); 2883e8d8bef9SDimitry Andric std::string bar = MTracker->IDAsString(P.second); 2884e8d8bef9SDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n"; 2885e8d8bef9SDimitry Andric } 2886e8d8bef9SDimitry Andric } 2887e8d8bef9SDimitry Andric #endif 2888e8d8bef9SDimitry Andric 2889e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 2890e8d8bef9SDimitry Andric // Build some useful data structures. 2891349cc55cSDimitry Andric 2892349cc55cSDimitry Andric LLVMContext &Context = MF.getFunction().getContext(); 2893349cc55cSDimitry Andric EmptyExpr = DIExpression::get(Context, {}); 2894349cc55cSDimitry Andric 2895e8d8bef9SDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 2896e8d8bef9SDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc()) 2897e8d8bef9SDimitry Andric return DL.getLine() != 0; 2898e8d8bef9SDimitry Andric return false; 2899e8d8bef9SDimitry Andric }; 2900e8d8bef9SDimitry Andric // Collect a set of all the artificial blocks. 2901e8d8bef9SDimitry Andric for (auto &MBB : MF) 2902e8d8bef9SDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation)) 2903e8d8bef9SDimitry Andric ArtificialBlocks.insert(&MBB); 2904e8d8bef9SDimitry Andric 2905e8d8bef9SDimitry Andric // Compute mappings of block <=> RPO order. 2906e8d8bef9SDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 2907e8d8bef9SDimitry Andric unsigned int RPONumber = 0; 2908fe6060f1SDimitry Andric for (MachineBasicBlock *MBB : RPOT) { 2909fe6060f1SDimitry Andric OrderToBB[RPONumber] = MBB; 2910fe6060f1SDimitry Andric BBToOrder[MBB] = RPONumber; 2911fe6060f1SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber; 2912e8d8bef9SDimitry Andric ++RPONumber; 2913e8d8bef9SDimitry Andric } 2914fe6060f1SDimitry Andric 2915fe6060f1SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup. 2916fe6060f1SDimitry Andric llvm::sort(MF.DebugValueSubstitutions); 2917fe6060f1SDimitry Andric 2918fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS 2919fe6060f1SDimitry Andric // As an expensive check, test whether there are any duplicate substitution 2920fe6060f1SDimitry Andric // sources in the collection. 2921fe6060f1SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) { 2922fe6060f1SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin(); 2923fe6060f1SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { 2924fe6060f1SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location " 2925fe6060f1SDimitry Andric "substitution seen"); 2926fe6060f1SDimitry Andric } 2927fe6060f1SDimitry Andric } 2928fe6060f1SDimitry Andric #endif 2929e8d8bef9SDimitry Andric } 2930e8d8bef9SDimitry Andric 2931d56accc7SDimitry Andric // Produce an "ejection map" for blocks, i.e., what's the highest-numbered 2932d56accc7SDimitry Andric // lexical scope it's used in. When exploring in DFS order and we pass that 2933d56accc7SDimitry Andric // scope, the block can be processed and any tracking information freed. 2934d56accc7SDimitry Andric void InstrRefBasedLDV::makeDepthFirstEjectionMap( 2935d56accc7SDimitry Andric SmallVectorImpl<unsigned> &EjectionMap, 2936d56accc7SDimitry Andric const ScopeToDILocT &ScopeToDILocation, 2937d56accc7SDimitry Andric ScopeToAssignBlocksT &ScopeToAssignBlocks) { 2938d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2939d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2940d56accc7SDimitry Andric auto *TopScope = LS.getCurrentFunctionScope(); 2941d56accc7SDimitry Andric 2942d56accc7SDimitry Andric // Unlike lexical scope explorers, we explore in reverse order, to find the 2943d56accc7SDimitry Andric // "last" lexical scope used for each block early. 2944d56accc7SDimitry Andric WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1}); 2945d56accc7SDimitry Andric 2946d56accc7SDimitry Andric while (!WorkStack.empty()) { 2947d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back(); 2948d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first; 2949d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second--; 2950d56accc7SDimitry Andric 2951d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 2952d56accc7SDimitry Andric if (ChildNum >= 0) { 2953d56accc7SDimitry Andric // If ChildNum is positive, there are remaining children to explore. 2954d56accc7SDimitry Andric // Push the child and its children-count onto the stack. 2955d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum]; 2956d56accc7SDimitry Andric WorkStack.push_back( 2957d56accc7SDimitry Andric std::make_pair(ChildScope, ChildScope->getChildren().size() - 1)); 2958d56accc7SDimitry Andric } else { 2959d56accc7SDimitry Andric WorkStack.pop_back(); 2960d56accc7SDimitry Andric 2961d56accc7SDimitry Andric // We've explored all children and any later blocks: examine all blocks 2962d56accc7SDimitry Andric // in our scope. If they haven't yet had an ejection number set, then 2963d56accc7SDimitry Andric // this scope will be the last to use that block. 2964d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS); 2965d56accc7SDimitry Andric if (DILocationIt != ScopeToDILocation.end()) { 2966d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore, 2967d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second); 2968d56accc7SDimitry Andric for (auto *MBB : BlocksToExplore) { 2969d56accc7SDimitry Andric unsigned BBNum = MBB->getNumber(); 2970d56accc7SDimitry Andric if (EjectionMap[BBNum] == 0) 2971d56accc7SDimitry Andric EjectionMap[BBNum] = WS->getDFSOut(); 2972d56accc7SDimitry Andric } 2973d56accc7SDimitry Andric 2974d56accc7SDimitry Andric BlocksToExplore.clear(); 2975d56accc7SDimitry Andric } 2976d56accc7SDimitry Andric } 2977d56accc7SDimitry Andric } 2978d56accc7SDimitry Andric } 2979d56accc7SDimitry Andric 2980d56accc7SDimitry Andric bool InstrRefBasedLDV::depthFirstVLocAndEmit( 2981d56accc7SDimitry Andric unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation, 2982d56accc7SDimitry Andric const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks, 2983*81ad6265SDimitry Andric LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2984d56accc7SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF, 2985d56accc7SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 2986d56accc7SDimitry Andric const TargetPassConfig &TPC) { 2987d56accc7SDimitry Andric TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 2988d56accc7SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2989d56accc7SDimitry Andric VTracker = nullptr; 2990d56accc7SDimitry Andric 2991d56accc7SDimitry Andric // No scopes? No variable locations. 2992*81ad6265SDimitry Andric if (!LS.getCurrentFunctionScope()) 2993d56accc7SDimitry Andric return false; 2994d56accc7SDimitry Andric 2995d56accc7SDimitry Andric // Build map from block number to the last scope that uses the block. 2996d56accc7SDimitry Andric SmallVector<unsigned, 16> EjectionMap; 2997d56accc7SDimitry Andric EjectionMap.resize(MaxNumBlocks, 0); 2998d56accc7SDimitry Andric makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation, 2999d56accc7SDimitry Andric ScopeToAssignBlocks); 3000d56accc7SDimitry Andric 3001d56accc7SDimitry Andric // Helper lambda for ejecting a block -- if nothing is going to use the block, 3002d56accc7SDimitry Andric // we can translate the variable location information into DBG_VALUEs and then 3003d56accc7SDimitry Andric // free all of InstrRefBasedLDV's data structures. 3004d56accc7SDimitry Andric auto EjectBlock = [&](MachineBasicBlock &MBB) -> void { 3005d56accc7SDimitry Andric unsigned BBNum = MBB.getNumber(); 3006d56accc7SDimitry Andric AllTheVLocs[BBNum].clear(); 3007d56accc7SDimitry Andric 3008d56accc7SDimitry Andric // Prime the transfer-tracker, and then step through all the block 3009d56accc7SDimitry Andric // instructions, installing transfers. 3010d56accc7SDimitry Andric MTracker->reset(); 3011d56accc7SDimitry Andric MTracker->loadFromArray(MInLocs[BBNum], BBNum); 3012d56accc7SDimitry Andric TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs); 3013d56accc7SDimitry Andric 3014d56accc7SDimitry Andric CurBB = BBNum; 3015d56accc7SDimitry Andric CurInst = 1; 3016d56accc7SDimitry Andric for (auto &MI : MBB) { 3017*81ad6265SDimitry Andric process(MI, MOutLocs.get(), MInLocs.get()); 3018d56accc7SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 3019d56accc7SDimitry Andric ++CurInst; 3020d56accc7SDimitry Andric } 3021d56accc7SDimitry Andric 3022d56accc7SDimitry Andric // Free machine-location tables for this block. 3023*81ad6265SDimitry Andric MInLocs[BBNum].reset(); 3024*81ad6265SDimitry Andric MOutLocs[BBNum].reset(); 3025d56accc7SDimitry Andric // We don't need live-in variable values for this block either. 3026d56accc7SDimitry Andric Output[BBNum].clear(); 3027d56accc7SDimitry Andric AllTheVLocs[BBNum].clear(); 3028d56accc7SDimitry Andric }; 3029d56accc7SDimitry Andric 3030d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 3031d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 3032d56accc7SDimitry Andric WorkStack.push_back({LS.getCurrentFunctionScope(), 0}); 3033d56accc7SDimitry Andric unsigned HighestDFSIn = 0; 3034d56accc7SDimitry Andric 3035d56accc7SDimitry Andric // Proceed to explore in depth first order. 3036d56accc7SDimitry Andric while (!WorkStack.empty()) { 3037d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back(); 3038d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first; 3039d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second++; 3040d56accc7SDimitry Andric 3041d56accc7SDimitry Andric // We obesrve scopes with children twice here, once descending in, once 3042d56accc7SDimitry Andric // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure 3043d56accc7SDimitry Andric // we don't process a scope twice. Additionally, ignore scopes that don't 3044d56accc7SDimitry Andric // have a DILocation -- by proxy, this means we never tracked any variable 3045d56accc7SDimitry Andric // assignments in that scope. 3046d56accc7SDimitry Andric auto DILocIt = ScopeToDILocation.find(WS); 3047d56accc7SDimitry Andric if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) { 3048d56accc7SDimitry Andric const DILocation *DILoc = DILocIt->second; 3049d56accc7SDimitry Andric auto &VarsWeCareAbout = ScopeToVars.find(WS)->second; 3050d56accc7SDimitry Andric auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second; 3051d56accc7SDimitry Andric 3052d56accc7SDimitry Andric buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs, 3053d56accc7SDimitry Andric MInLocs, AllTheVLocs); 3054d56accc7SDimitry Andric } 3055d56accc7SDimitry Andric 3056d56accc7SDimitry Andric HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn()); 3057d56accc7SDimitry Andric 3058d56accc7SDimitry Andric // Descend into any scope nests. 3059d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 3060d56accc7SDimitry Andric if (ChildNum < (ssize_t)Children.size()) { 3061d56accc7SDimitry Andric // There are children to explore -- push onto stack and continue. 3062d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum]; 3063d56accc7SDimitry Andric WorkStack.push_back(std::make_pair(ChildScope, 0)); 3064d56accc7SDimitry Andric } else { 3065d56accc7SDimitry Andric WorkStack.pop_back(); 3066d56accc7SDimitry Andric 3067d56accc7SDimitry Andric // We've explored a leaf, or have explored all the children of a scope. 3068d56accc7SDimitry Andric // Try to eject any blocks where this is the last scope it's relevant to. 3069d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS); 3070d56accc7SDimitry Andric if (DILocationIt == ScopeToDILocation.end()) 3071d56accc7SDimitry Andric continue; 3072d56accc7SDimitry Andric 3073d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore, 3074d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second); 3075d56accc7SDimitry Andric for (auto *MBB : BlocksToExplore) 3076d56accc7SDimitry Andric if (WS->getDFSOut() == EjectionMap[MBB->getNumber()]) 3077d56accc7SDimitry Andric EjectBlock(const_cast<MachineBasicBlock &>(*MBB)); 3078d56accc7SDimitry Andric 3079d56accc7SDimitry Andric BlocksToExplore.clear(); 3080d56accc7SDimitry Andric } 3081d56accc7SDimitry Andric } 3082d56accc7SDimitry Andric 3083d56accc7SDimitry Andric // Some artificial blocks may not have been ejected, meaning they're not 3084d56accc7SDimitry Andric // connected to an actual legitimate scope. This can technically happen 3085d56accc7SDimitry Andric // with things like the entry block. In theory, we shouldn't need to do 3086d56accc7SDimitry Andric // anything for such out-of-scope blocks, but for the sake of being similar 3087d56accc7SDimitry Andric // to VarLocBasedLDV, eject these too. 3088d56accc7SDimitry Andric for (auto *MBB : ArtificialBlocks) 3089d56accc7SDimitry Andric if (MOutLocs[MBB->getNumber()]) 3090d56accc7SDimitry Andric EjectBlock(*MBB); 3091d56accc7SDimitry Andric 3092d56accc7SDimitry Andric return emitTransfers(AllVarsNumbering); 3093d56accc7SDimitry Andric } 3094d56accc7SDimitry Andric 30951fd87a68SDimitry Andric bool InstrRefBasedLDV::emitTransfers( 30961fd87a68SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering) { 30971fd87a68SDimitry Andric // Go through all the transfers recorded in the TransferTracker -- this is 30981fd87a68SDimitry Andric // both the live-ins to a block, and any movements of values that happen 30991fd87a68SDimitry Andric // in the middle. 31001fd87a68SDimitry Andric for (const auto &P : TTracker->Transfers) { 31011fd87a68SDimitry Andric // We have to insert DBG_VALUEs in a consistent order, otherwise they 31021fd87a68SDimitry Andric // appear in DWARF in different orders. Use the order that they appear 31031fd87a68SDimitry Andric // when walking through each block / each instruction, stored in 31041fd87a68SDimitry Andric // AllVarsNumbering. 31051fd87a68SDimitry Andric SmallVector<std::pair<unsigned, MachineInstr *>> Insts; 31061fd87a68SDimitry Andric for (MachineInstr *MI : P.Insts) { 31071fd87a68SDimitry Andric DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(), 31081fd87a68SDimitry Andric MI->getDebugLoc()->getInlinedAt()); 31091fd87a68SDimitry Andric Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI); 31101fd87a68SDimitry Andric } 31111fd87a68SDimitry Andric llvm::sort(Insts, 31121fd87a68SDimitry Andric [](const auto &A, const auto &B) { return A.first < B.first; }); 31131fd87a68SDimitry Andric 31141fd87a68SDimitry Andric // Insert either before or after the designated point... 31151fd87a68SDimitry Andric if (P.MBB) { 31161fd87a68SDimitry Andric MachineBasicBlock &MBB = *P.MBB; 31171fd87a68SDimitry Andric for (const auto &Pair : Insts) 31181fd87a68SDimitry Andric MBB.insert(P.Pos, Pair.second); 31191fd87a68SDimitry Andric } else { 31201fd87a68SDimitry Andric // Terminators, like tail calls, can clobber things. Don't try and place 31211fd87a68SDimitry Andric // transfers after them. 31221fd87a68SDimitry Andric if (P.Pos->isTerminator()) 31231fd87a68SDimitry Andric continue; 31241fd87a68SDimitry Andric 31251fd87a68SDimitry Andric MachineBasicBlock &MBB = *P.Pos->getParent(); 31261fd87a68SDimitry Andric for (const auto &Pair : Insts) 31271fd87a68SDimitry Andric MBB.insertAfterBundle(P.Pos, Pair.second); 31281fd87a68SDimitry Andric } 31291fd87a68SDimitry Andric } 31301fd87a68SDimitry Andric 31311fd87a68SDimitry Andric return TTracker->Transfers.size() != 0; 31321fd87a68SDimitry Andric } 31331fd87a68SDimitry Andric 3134e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and 3135e8d8bef9SDimitry Andric /// extend ranges across basic blocks. 3136e8d8bef9SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 3137349cc55cSDimitry Andric MachineDominatorTree *DomTree, 3138349cc55cSDimitry Andric TargetPassConfig *TPC, 3139349cc55cSDimitry Andric unsigned InputBBLimit, 3140349cc55cSDimitry Andric unsigned InputDbgValLimit) { 3141e8d8bef9SDimitry Andric // No subprogram means this function contains no debuginfo. 3142e8d8bef9SDimitry Andric if (!MF.getFunction().getSubprogram()) 3143e8d8bef9SDimitry Andric return false; 3144e8d8bef9SDimitry Andric 3145e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 3146e8d8bef9SDimitry Andric this->TPC = TPC; 3147e8d8bef9SDimitry Andric 3148349cc55cSDimitry Andric this->DomTree = DomTree; 3149e8d8bef9SDimitry Andric TRI = MF.getSubtarget().getRegisterInfo(); 3150349cc55cSDimitry Andric MRI = &MF.getRegInfo(); 3151e8d8bef9SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 3152e8d8bef9SDimitry Andric TFI = MF.getSubtarget().getFrameLowering(); 3153e8d8bef9SDimitry Andric TFI->getCalleeSaves(MF, CalleeSavedRegs); 3154fe6060f1SDimitry Andric MFI = &MF.getFrameInfo(); 3155e8d8bef9SDimitry Andric LS.initialize(MF); 3156e8d8bef9SDimitry Andric 31574824e7fdSDimitry Andric const auto &STI = MF.getSubtarget(); 31584824e7fdSDimitry Andric AdjustsStackInCalls = MFI->adjustsStack() && 31594824e7fdSDimitry Andric STI.getFrameLowering()->stackProbeFunctionModifiesSP(); 31604824e7fdSDimitry Andric if (AdjustsStackInCalls) 31614824e7fdSDimitry Andric StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); 31624824e7fdSDimitry Andric 3163e8d8bef9SDimitry Andric MTracker = 3164e8d8bef9SDimitry Andric new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 3165e8d8bef9SDimitry Andric VTracker = nullptr; 3166e8d8bef9SDimitry Andric TTracker = nullptr; 3167e8d8bef9SDimitry Andric 3168e8d8bef9SDimitry Andric SmallVector<MLocTransferMap, 32> MLocTransfer; 3169e8d8bef9SDimitry Andric SmallVector<VLocTracker, 8> vlocs; 3170e8d8bef9SDimitry Andric LiveInsT SavedLiveIns; 3171e8d8bef9SDimitry Andric 3172e8d8bef9SDimitry Andric int MaxNumBlocks = -1; 3173e8d8bef9SDimitry Andric for (auto &MBB : MF) 3174e8d8bef9SDimitry Andric MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 3175e8d8bef9SDimitry Andric assert(MaxNumBlocks >= 0); 3176e8d8bef9SDimitry Andric ++MaxNumBlocks; 3177e8d8bef9SDimitry Andric 3178*81ad6265SDimitry Andric initialSetup(MF); 3179*81ad6265SDimitry Andric 3180e8d8bef9SDimitry Andric MLocTransfer.resize(MaxNumBlocks); 31814824e7fdSDimitry Andric vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); 3182e8d8bef9SDimitry Andric SavedLiveIns.resize(MaxNumBlocks); 3183e8d8bef9SDimitry Andric 3184e8d8bef9SDimitry Andric produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 3185e8d8bef9SDimitry Andric 3186e8d8bef9SDimitry Andric // Allocate and initialize two array-of-arrays for the live-in and live-out 3187e8d8bef9SDimitry Andric // machine values. The outer dimension is the block number; while the inner 3188e8d8bef9SDimitry Andric // dimension is a LocIdx from MLocTracker. 3189*81ad6265SDimitry Andric FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3190*81ad6265SDimitry Andric FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3191e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 3192e8d8bef9SDimitry Andric for (int i = 0; i < MaxNumBlocks; ++i) { 3193349cc55cSDimitry Andric // These all auto-initialize to ValueIDNum::EmptyValue 3194*81ad6265SDimitry Andric MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3195*81ad6265SDimitry Andric MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3196e8d8bef9SDimitry Andric } 3197e8d8bef9SDimitry Andric 3198e8d8bef9SDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function, 3199e8d8bef9SDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use 3200e8d8bef9SDimitry Andric // both live-ins and live-outs for decision making in the variable value 3201e8d8bef9SDimitry Andric // dataflow problem. 3202349cc55cSDimitry Andric buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); 3203e8d8bef9SDimitry Andric 3204fe6060f1SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into 3205fe6060f1SDimitry Andric // either live-through machine values, or PHIs. 3206fe6060f1SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) { 3207fe6060f1SDimitry Andric // Identify unresolved block-live-ins. 3208*81ad6265SDimitry Andric if (!DBG_PHI.ValueRead) 3209*81ad6265SDimitry Andric continue; 3210*81ad6265SDimitry Andric 3211*81ad6265SDimitry Andric ValueIDNum &Num = *DBG_PHI.ValueRead; 3212fe6060f1SDimitry Andric if (!Num.isPHI()) 3213fe6060f1SDimitry Andric continue; 3214fe6060f1SDimitry Andric 3215fe6060f1SDimitry Andric unsigned BlockNo = Num.getBlock(); 3216fe6060f1SDimitry Andric LocIdx LocNo = Num.getLoc(); 3217fe6060f1SDimitry Andric Num = MInLocs[BlockNo][LocNo.asU64()]; 3218fe6060f1SDimitry Andric } 3219fe6060f1SDimitry Andric // Later, we'll be looking up ranges of instruction numbers. 3220fe6060f1SDimitry Andric llvm::sort(DebugPHINumToValue); 3221fe6060f1SDimitry Andric 3222e8d8bef9SDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE 3223e8d8bef9SDimitry Andric // instructions and recording what machine value their operands refer to. 3224e8d8bef9SDimitry Andric for (auto &OrderPair : OrderToBB) { 3225e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *OrderPair.second; 3226e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 3227e8d8bef9SDimitry Andric VTracker = &vlocs[CurBB]; 3228e8d8bef9SDimitry Andric VTracker->MBB = &MBB; 3229e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 3230e8d8bef9SDimitry Andric CurInst = 1; 3231e8d8bef9SDimitry Andric for (auto &MI : MBB) { 3232*81ad6265SDimitry Andric process(MI, MOutLocs.get(), MInLocs.get()); 3233e8d8bef9SDimitry Andric ++CurInst; 3234e8d8bef9SDimitry Andric } 3235e8d8bef9SDimitry Andric MTracker->reset(); 3236e8d8bef9SDimitry Andric } 3237e8d8bef9SDimitry Andric 3238e8d8bef9SDimitry Andric // Number all variables in the order that they appear, to be used as a stable 3239e8d8bef9SDimitry Andric // insertion order later. 3240e8d8bef9SDimitry Andric DenseMap<DebugVariable, unsigned> AllVarsNumbering; 3241e8d8bef9SDimitry Andric 3242e8d8bef9SDimitry Andric // Map from one LexicalScope to all the variables in that scope. 32431fd87a68SDimitry Andric ScopeToVarsT ScopeToVars; 3244e8d8bef9SDimitry Andric 32451fd87a68SDimitry Andric // Map from One lexical scope to all blocks where assignments happen for 32461fd87a68SDimitry Andric // that scope. 32471fd87a68SDimitry Andric ScopeToAssignBlocksT ScopeToAssignBlocks; 3248e8d8bef9SDimitry Andric 32491fd87a68SDimitry Andric // Store map of DILocations that describes scopes. 32501fd87a68SDimitry Andric ScopeToDILocT ScopeToDILocation; 3251e8d8bef9SDimitry Andric 3252e8d8bef9SDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3253e8d8bef9SDimitry Andric // the order is unimportant, it just has to be stable. 3254349cc55cSDimitry Andric unsigned VarAssignCount = 0; 3255e8d8bef9SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3256e8d8bef9SDimitry Andric auto *MBB = OrderToBB[I]; 3257e8d8bef9SDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()]; 3258e8d8bef9SDimitry Andric // Collect each variable with a DBG_VALUE in this block. 3259e8d8bef9SDimitry Andric for (auto &idx : VTracker->Vars) { 3260e8d8bef9SDimitry Andric const auto &Var = idx.first; 3261e8d8bef9SDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3262e8d8bef9SDimitry Andric assert(ScopeLoc != nullptr); 3263e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc); 3264e8d8bef9SDimitry Andric 3265e8d8bef9SDimitry Andric // No insts in scope -> shouldn't have been recorded. 3266e8d8bef9SDimitry Andric assert(Scope != nullptr); 3267e8d8bef9SDimitry Andric 3268e8d8bef9SDimitry Andric AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3269e8d8bef9SDimitry Andric ScopeToVars[Scope].insert(Var); 32701fd87a68SDimitry Andric ScopeToAssignBlocks[Scope].insert(VTracker->MBB); 3271e8d8bef9SDimitry Andric ScopeToDILocation[Scope] = ScopeLoc; 3272349cc55cSDimitry Andric ++VarAssignCount; 3273e8d8bef9SDimitry Andric } 3274e8d8bef9SDimitry Andric } 3275e8d8bef9SDimitry Andric 3276349cc55cSDimitry Andric bool Changed = false; 3277349cc55cSDimitry Andric 3278349cc55cSDimitry Andric // If we have an extremely large number of variable assignments and blocks, 3279349cc55cSDimitry Andric // bail out at this point. We've burnt some time doing analysis already, 3280349cc55cSDimitry Andric // however we should cut our losses. 3281349cc55cSDimitry Andric if ((unsigned)MaxNumBlocks > InputBBLimit && 3282349cc55cSDimitry Andric VarAssignCount > InputDbgValLimit) { 3283349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() 3284349cc55cSDimitry Andric << " has " << MaxNumBlocks << " basic blocks and " 3285349cc55cSDimitry Andric << VarAssignCount 3286349cc55cSDimitry Andric << " variable assignments, exceeding limits.\n"); 3287d56accc7SDimitry Andric } else { 3288d56accc7SDimitry Andric // Optionally, solve the variable value problem and emit to blocks by using 3289d56accc7SDimitry Andric // a lexical-scope-depth search. It should be functionally identical to 3290d56accc7SDimitry Andric // the "else" block of this condition. 3291d56accc7SDimitry Andric Changed = depthFirstVLocAndEmit( 3292d56accc7SDimitry Andric MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks, 3293d56accc7SDimitry Andric SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC); 3294d56accc7SDimitry Andric } 3295d56accc7SDimitry Andric 3296e8d8bef9SDimitry Andric delete MTracker; 3297e8d8bef9SDimitry Andric delete TTracker; 3298e8d8bef9SDimitry Andric MTracker = nullptr; 3299e8d8bef9SDimitry Andric VTracker = nullptr; 3300e8d8bef9SDimitry Andric TTracker = nullptr; 3301e8d8bef9SDimitry Andric 3302e8d8bef9SDimitry Andric ArtificialBlocks.clear(); 3303e8d8bef9SDimitry Andric OrderToBB.clear(); 3304e8d8bef9SDimitry Andric BBToOrder.clear(); 3305e8d8bef9SDimitry Andric BBNumToRPO.clear(); 3306e8d8bef9SDimitry Andric DebugInstrNumToInstr.clear(); 3307fe6060f1SDimitry Andric DebugPHINumToValue.clear(); 33084824e7fdSDimitry Andric OverlapFragments.clear(); 33094824e7fdSDimitry Andric SeenFragments.clear(); 3310d56accc7SDimitry Andric SeenDbgPHIs.clear(); 3311e8d8bef9SDimitry Andric 3312e8d8bef9SDimitry Andric return Changed; 3313e8d8bef9SDimitry Andric } 3314e8d8bef9SDimitry Andric 3315e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3316e8d8bef9SDimitry Andric return new InstrRefBasedLDV(); 3317e8d8bef9SDimitry Andric } 3318fe6060f1SDimitry Andric 3319fe6060f1SDimitry Andric namespace { 3320fe6060f1SDimitry Andric class LDVSSABlock; 3321fe6060f1SDimitry Andric class LDVSSAUpdater; 3322fe6060f1SDimitry Andric 3323fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We 3324fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater 3325fe6060f1SDimitry Andric // expects to zero-initialize the type. 3326fe6060f1SDimitry Andric typedef uint64_t BlockValueNum; 3327fe6060f1SDimitry Andric 3328fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block 3329fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming 3330fe6060f1SDimitry Andric /// values from parent blocks. 3331fe6060f1SDimitry Andric class LDVSSAPhi { 3332fe6060f1SDimitry Andric public: 3333fe6060f1SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3334fe6060f1SDimitry Andric LDVSSABlock *ParentBlock; 3335fe6060f1SDimitry Andric BlockValueNum PHIValNum; 3336fe6060f1SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3337fe6060f1SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3338fe6060f1SDimitry Andric 3339fe6060f1SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; } 3340fe6060f1SDimitry Andric }; 3341fe6060f1SDimitry Andric 3342fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a 3343fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock. 3344fe6060f1SDimitry Andric class LDVSSABlockIterator { 3345fe6060f1SDimitry Andric public: 3346fe6060f1SDimitry Andric MachineBasicBlock::pred_iterator PredIt; 3347fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3348fe6060f1SDimitry Andric 3349fe6060f1SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3350fe6060f1SDimitry Andric LDVSSAUpdater &Updater) 3351fe6060f1SDimitry Andric : PredIt(PredIt), Updater(Updater) {} 3352fe6060f1SDimitry Andric 3353fe6060f1SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3354fe6060f1SDimitry Andric return OtherIt.PredIt != PredIt; 3355fe6060f1SDimitry Andric } 3356fe6060f1SDimitry Andric 3357fe6060f1SDimitry Andric LDVSSABlockIterator &operator++() { 3358fe6060f1SDimitry Andric ++PredIt; 3359fe6060f1SDimitry Andric return *this; 3360fe6060f1SDimitry Andric } 3361fe6060f1SDimitry Andric 3362fe6060f1SDimitry Andric LDVSSABlock *operator*(); 3363fe6060f1SDimitry Andric }; 3364fe6060f1SDimitry Andric 3365fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because 3366fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary 3367fe6060f1SDimitry Andric /// in this block. 3368fe6060f1SDimitry Andric class LDVSSABlock { 3369fe6060f1SDimitry Andric public: 3370fe6060f1SDimitry Andric MachineBasicBlock &BB; 3371fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3372fe6060f1SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>; 3373fe6060f1SDimitry Andric /// List of PHIs in this block. There should only ever be one. 3374fe6060f1SDimitry Andric PHIListT PHIList; 3375fe6060f1SDimitry Andric 3376fe6060f1SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3377fe6060f1SDimitry Andric : BB(BB), Updater(Updater) {} 3378fe6060f1SDimitry Andric 3379fe6060f1SDimitry Andric LDVSSABlockIterator succ_begin() { 3380fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater); 3381fe6060f1SDimitry Andric } 3382fe6060f1SDimitry Andric 3383fe6060f1SDimitry Andric LDVSSABlockIterator succ_end() { 3384fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater); 3385fe6060f1SDimitry Andric } 3386fe6060f1SDimitry Andric 3387fe6060f1SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record. 3388fe6060f1SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) { 3389fe6060f1SDimitry Andric PHIList.emplace_back(Value, this); 3390fe6060f1SDimitry Andric return &PHIList.back(); 3391fe6060f1SDimitry Andric } 3392fe6060f1SDimitry Andric 3393fe6060f1SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block. 3394fe6060f1SDimitry Andric PHIListT &phis() { return PHIList; } 3395fe6060f1SDimitry Andric }; 3396fe6060f1SDimitry Andric 3397fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3398fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3399fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>. 3400fe6060f1SDimitry Andric class LDVSSAUpdater { 3401fe6060f1SDimitry Andric public: 3402fe6060f1SDimitry Andric /// Map of value numbers to PHI records. 3403fe6060f1SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3404fe6060f1SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not 3405fe6060f1SDimitry Andric /// dominated by any Def. 3406fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3407fe6060f1SDimitry Andric /// Map of machine blocks to our own records of them. 3408fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3409fe6060f1SDimitry Andric /// Machine location where any PHI must occur. 3410fe6060f1SDimitry Andric LocIdx Loc; 3411fe6060f1SDimitry Andric /// Table of live-in machine value numbers for blocks / locations. 3412*81ad6265SDimitry Andric const ValueTable *MLiveIns; 3413fe6060f1SDimitry Andric 3414*81ad6265SDimitry Andric LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns) 3415*81ad6265SDimitry Andric : Loc(L), MLiveIns(MLiveIns) {} 3416fe6060f1SDimitry Andric 3417fe6060f1SDimitry Andric void reset() { 3418fe6060f1SDimitry Andric for (auto &Block : BlockMap) 3419fe6060f1SDimitry Andric delete Block.second; 3420fe6060f1SDimitry Andric 3421fe6060f1SDimitry Andric PHIs.clear(); 3422fe6060f1SDimitry Andric UndefMap.clear(); 3423fe6060f1SDimitry Andric BlockMap.clear(); 3424fe6060f1SDimitry Andric } 3425fe6060f1SDimitry Andric 3426fe6060f1SDimitry Andric ~LDVSSAUpdater() { reset(); } 3427fe6060f1SDimitry Andric 3428fe6060f1SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the 3429fe6060f1SDimitry Andric /// LDVSSAUpdater block map. 3430fe6060f1SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3431fe6060f1SDimitry Andric auto it = BlockMap.find(BB); 3432fe6060f1SDimitry Andric if (it == BlockMap.end()) { 3433fe6060f1SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this); 3434fe6060f1SDimitry Andric it = BlockMap.find(BB); 3435fe6060f1SDimitry Andric } 3436fe6060f1SDimitry Andric return it->second; 3437fe6060f1SDimitry Andric } 3438fe6060f1SDimitry Andric 3439fe6060f1SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at 3440fe6060f1SDimitry Andric /// the PHI location on entry. 3441fe6060f1SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) { 3442fe6060f1SDimitry Andric return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3443fe6060f1SDimitry Andric } 3444fe6060f1SDimitry Andric }; 3445fe6060f1SDimitry Andric 3446fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() { 3447fe6060f1SDimitry Andric return Updater.getSSALDVBlock(*PredIt); 3448fe6060f1SDimitry Andric } 3449fe6060f1SDimitry Andric 3450fe6060f1SDimitry Andric #ifndef NDEBUG 3451fe6060f1SDimitry Andric 3452fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3453fe6060f1SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum; 3454fe6060f1SDimitry Andric return out; 3455fe6060f1SDimitry Andric } 3456fe6060f1SDimitry Andric 3457fe6060f1SDimitry Andric #endif 3458fe6060f1SDimitry Andric 3459fe6060f1SDimitry Andric } // namespace 3460fe6060f1SDimitry Andric 3461fe6060f1SDimitry Andric namespace llvm { 3462fe6060f1SDimitry Andric 3463fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value 3464fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the 3465fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define. 3466fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them. 3467fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3468fe6060f1SDimitry Andric public: 3469fe6060f1SDimitry Andric using BlkT = LDVSSABlock; 3470fe6060f1SDimitry Andric using ValT = BlockValueNum; 3471fe6060f1SDimitry Andric using PhiT = LDVSSAPhi; 3472fe6060f1SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator; 3473fe6060f1SDimitry Andric 3474fe6060f1SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class. 3475fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3476fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3477fe6060f1SDimitry Andric 3478fe6060f1SDimitry Andric /// Iterator for PHI operands. 3479fe6060f1SDimitry Andric class PHI_iterator { 3480fe6060f1SDimitry Andric private: 3481fe6060f1SDimitry Andric LDVSSAPhi *PHI; 3482fe6060f1SDimitry Andric unsigned Idx; 3483fe6060f1SDimitry Andric 3484fe6060f1SDimitry Andric public: 3485fe6060f1SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3486fe6060f1SDimitry Andric : PHI(P), Idx(0) {} 3487fe6060f1SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3488fe6060f1SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {} 3489fe6060f1SDimitry Andric 3490fe6060f1SDimitry Andric PHI_iterator &operator++() { 3491fe6060f1SDimitry Andric Idx++; 3492fe6060f1SDimitry Andric return *this; 3493fe6060f1SDimitry Andric } 3494fe6060f1SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3495fe6060f1SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3496fe6060f1SDimitry Andric 3497fe6060f1SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3498fe6060f1SDimitry Andric 3499fe6060f1SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3500fe6060f1SDimitry Andric }; 3501fe6060f1SDimitry Andric 3502fe6060f1SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3503fe6060f1SDimitry Andric 3504fe6060f1SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) { 3505fe6060f1SDimitry Andric return PHI_iterator(PHI, true); 3506fe6060f1SDimitry Andric } 3507fe6060f1SDimitry Andric 3508fe6060f1SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3509fe6060f1SDimitry Andric /// vector. 3510fe6060f1SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB, 3511fe6060f1SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) { 3512349cc55cSDimitry Andric for (MachineBasicBlock *Pred : BB->BB.predecessors()) 3513349cc55cSDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); 3514fe6060f1SDimitry Andric } 3515fe6060f1SDimitry Andric 3516fe6060f1SDimitry Andric /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3517fe6060f1SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having 3518fe6060f1SDimitry Andric /// any DBG_PHI predecessors. 3519fe6060f1SDimitry Andric static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3520fe6060f1SDimitry Andric // Create a value number for this block -- it needs to be unique and in the 3521fe6060f1SDimitry Andric // "undef" collection, so that we know it's not real. Use a number 3522fe6060f1SDimitry Andric // representing a PHI into this block. 3523fe6060f1SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3524fe6060f1SDimitry Andric Updater->UndefMap[&BB->BB] = Num; 3525fe6060f1SDimitry Andric return Num; 3526fe6060f1SDimitry Andric } 3527fe6060f1SDimitry Andric 3528fe6060f1SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3529fe6060f1SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The 3530fe6060f1SDimitry Andric /// value number of this PHI is whatever the machine value number problem 3531fe6060f1SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater 3532fe6060f1SDimitry Andric /// tries to create a PHI where the incoming values are identical. 3533fe6060f1SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3534fe6060f1SDimitry Andric LDVSSAUpdater *Updater) { 3535fe6060f1SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB); 3536fe6060f1SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3537fe6060f1SDimitry Andric Updater->PHIs[PHIValNum] = PHI; 3538fe6060f1SDimitry Andric return PHIValNum; 3539fe6060f1SDimitry Andric } 3540fe6060f1SDimitry Andric 3541fe6060f1SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for 3542fe6060f1SDimitry Andric /// the specified predecessor block. 3543fe6060f1SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3544fe6060f1SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3545fe6060f1SDimitry Andric } 3546fe6060f1SDimitry Andric 3547fe6060f1SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value 3548fe6060f1SDimitry Andric /// is a PHI instruction. 3549fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3550fe6060f1SDimitry Andric auto PHIIt = Updater->PHIs.find(Val); 3551fe6060f1SDimitry Andric if (PHIIt == Updater->PHIs.end()) 3552fe6060f1SDimitry Andric return nullptr; 3553fe6060f1SDimitry Andric return PHIIt->second; 3554fe6060f1SDimitry Andric } 3555fe6060f1SDimitry Andric 3556fe6060f1SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3557fe6060f1SDimitry Andric /// operands, i.e., it was just added. 3558fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3559fe6060f1SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3560fe6060f1SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0) 3561fe6060f1SDimitry Andric return PHI; 3562fe6060f1SDimitry Andric return nullptr; 3563fe6060f1SDimitry Andric } 3564fe6060f1SDimitry Andric 3565fe6060f1SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value 3566fe6060f1SDimitry Andric /// that it defines. 3567fe6060f1SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3568fe6060f1SDimitry Andric }; 3569fe6060f1SDimitry Andric 3570fe6060f1SDimitry Andric } // end namespace llvm 3571fe6060f1SDimitry Andric 3572*81ad6265SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs( 3573*81ad6265SDimitry Andric MachineFunction &MF, const ValueTable *MLiveOuts, 3574*81ad6265SDimitry Andric const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3575*81ad6265SDimitry Andric assert(MLiveOuts && MLiveIns && 3576*81ad6265SDimitry Andric "Tried to resolve DBG_PHI before location " 3577*81ad6265SDimitry Andric "tables allocated?"); 3578*81ad6265SDimitry Andric 3579d56accc7SDimitry Andric // This function will be called twice per DBG_INSTR_REF, and might end up 3580d56accc7SDimitry Andric // computing lots of SSA information: memoize it. 3581d56accc7SDimitry Andric auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here); 3582d56accc7SDimitry Andric if (SeenDbgPHIIt != SeenDbgPHIs.end()) 3583d56accc7SDimitry Andric return SeenDbgPHIIt->second; 3584d56accc7SDimitry Andric 3585d56accc7SDimitry Andric Optional<ValueIDNum> Result = 3586d56accc7SDimitry Andric resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum); 3587d56accc7SDimitry Andric SeenDbgPHIs.insert({&Here, Result}); 3588d56accc7SDimitry Andric return Result; 3589d56accc7SDimitry Andric } 3590d56accc7SDimitry Andric 3591d56accc7SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl( 3592*81ad6265SDimitry Andric MachineFunction &MF, const ValueTable *MLiveOuts, 3593*81ad6265SDimitry Andric const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3594fe6060f1SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there 3595fe6060f1SDimitry Andric // are none, then we cannot compute a value number. 3596fe6060f1SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3597fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstrNum); 3598fe6060f1SDimitry Andric auto LowerIt = RangePair.first; 3599fe6060f1SDimitry Andric auto UpperIt = RangePair.second; 3600fe6060f1SDimitry Andric 3601fe6060f1SDimitry Andric // No DBG_PHI means there can be no location. 3602fe6060f1SDimitry Andric if (LowerIt == UpperIt) 3603fe6060f1SDimitry Andric return None; 3604fe6060f1SDimitry Andric 3605*81ad6265SDimitry Andric // If any DBG_PHIs referred to a location we didn't understand, don't try to 3606*81ad6265SDimitry Andric // compute a value. There might be scenarios where we could recover a value 3607*81ad6265SDimitry Andric // for some range of DBG_INSTR_REFs, but at this point we can have high 3608*81ad6265SDimitry Andric // confidence that we've seen a bug. 3609*81ad6265SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt); 3610*81ad6265SDimitry Andric for (const DebugPHIRecord &DBG_PHI : DBGPHIRange) 3611*81ad6265SDimitry Andric if (!DBG_PHI.ValueRead) 3612*81ad6265SDimitry Andric return None; 3613*81ad6265SDimitry Andric 3614fe6060f1SDimitry Andric // If there's only one DBG_PHI, then that is our value number. 3615fe6060f1SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1) 3616*81ad6265SDimitry Andric return *LowerIt->ValueRead; 3617fe6060f1SDimitry Andric 3618fe6060f1SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's 3619fe6060f1SDimitry Andric // technically possible for us to merge values in different registers in each 3620fe6060f1SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register 3621fe6060f1SDimitry Andric // allocation. 3622*81ad6265SDimitry Andric LocIdx Loc = *LowerIt->ReadLoc; 3623fe6060f1SDimitry Andric 3624fe6060f1SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each 3625fe6060f1SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each 3626fe6060f1SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3627fe6060f1SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3628fe6060f1SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along 3629fe6060f1SDimitry Andric // the way. 3630fe6060f1SDimitry Andric // Adapted LLVM SSA Updater: 3631fe6060f1SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns); 3632fe6060f1SDimitry Andric // Map of which Def or PHI is the current value in each block. 3633fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3634fe6060f1SDimitry Andric // Set of PHIs that we have created along the way. 3635fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3636fe6060f1SDimitry Andric 3637fe6060f1SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3638fe6060f1SDimitry Andric // for the SSAUpdater. 3639fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3640fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3641*81ad6265SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead; 3642fe6060f1SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3643fe6060f1SDimitry Andric } 3644fe6060f1SDimitry Andric 3645fe6060f1SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3646fe6060f1SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock); 3647fe6060f1SDimitry Andric if (AvailIt != AvailableValues.end()) { 3648fe6060f1SDimitry Andric // Actually, we already know what the value is -- the Use is in the same 3649fe6060f1SDimitry Andric // block as the Def. 3650fe6060f1SDimitry Andric return ValueIDNum::fromU64(AvailIt->second); 3651fe6060f1SDimitry Andric } 3652fe6060f1SDimitry Andric 3653fe6060f1SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number 3654fe6060f1SDimitry Andric // that we are to use, and the PHIs that must happen along the way. 3655fe6060f1SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3656fe6060f1SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3657fe6060f1SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3658fe6060f1SDimitry Andric 3659fe6060f1SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used 3660fe6060f1SDimitry Andric // at this Use. There are a number of things we have to check about it though: 3661fe6060f1SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3662fe6060f1SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort. 3663fe6060f1SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3664fe6060f1SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the 3665fe6060f1SDimitry Andric // expected values. 3666fe6060f1SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the 3667fe6060f1SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number? 3668fe6060f1SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3669fe6060f1SDimitry Andric // the ValidatedValues collection below to sort this out. 3670fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3671fe6060f1SDimitry Andric 3672fe6060f1SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues. 3673fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3674fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3675*81ad6265SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead; 3676fe6060f1SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num)); 3677fe6060f1SDimitry Andric } 3678fe6060f1SDimitry Andric 3679fe6060f1SDimitry Andric // Sort PHIs to validate into RPO-order. 3680fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3681fe6060f1SDimitry Andric for (auto &PHI : CreatedPHIs) 3682fe6060f1SDimitry Andric SortedPHIs.push_back(PHI); 3683fe6060f1SDimitry Andric 3684fe6060f1SDimitry Andric std::sort( 3685fe6060f1SDimitry Andric SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3686fe6060f1SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3687fe6060f1SDimitry Andric }); 3688fe6060f1SDimitry Andric 3689fe6060f1SDimitry Andric for (auto &PHI : SortedPHIs) { 3690fe6060f1SDimitry Andric ValueIDNum ThisBlockValueNum = 3691fe6060f1SDimitry Andric MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3692fe6060f1SDimitry Andric 3693fe6060f1SDimitry Andric // Are all these things actually defined? 3694fe6060f1SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) { 3695fe6060f1SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point. 3696fe6060f1SDimitry Andric if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3697fe6060f1SDimitry Andric return None; 3698fe6060f1SDimitry Andric 3699fe6060f1SDimitry Andric ValueIDNum ValueToCheck; 3700*81ad6265SDimitry Andric const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 3701fe6060f1SDimitry Andric 3702fe6060f1SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first); 3703fe6060f1SDimitry Andric if (VVal == ValidatedValues.end()) { 3704fe6060f1SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication 3705fe6060f1SDimitry Andric // happens so late that DBG_PHI instructions should not be able to 3706fe6060f1SDimitry Andric // migrate into loops -- meaning we can only be live-through this 3707fe6060f1SDimitry Andric // loop. 3708fe6060f1SDimitry Andric ValueToCheck = ThisBlockValueNum; 3709fe6060f1SDimitry Andric } else { 3710fe6060f1SDimitry Andric // Does the block have as a live-out, in the location we're examining, 3711fe6060f1SDimitry Andric // the value that we expect? If not, it's been moved or clobbered. 3712fe6060f1SDimitry Andric ValueToCheck = VVal->second; 3713fe6060f1SDimitry Andric } 3714fe6060f1SDimitry Andric 3715fe6060f1SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 3716fe6060f1SDimitry Andric return None; 3717fe6060f1SDimitry Andric } 3718fe6060f1SDimitry Andric 3719fe6060f1SDimitry Andric // Record this value as validated. 3720fe6060f1SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 3721fe6060f1SDimitry Andric } 3722fe6060f1SDimitry Andric 3723fe6060f1SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value 3724fe6060f1SDimitry Andric // number was. 3725fe6060f1SDimitry Andric return Result; 3726fe6060f1SDimitry Andric } 3727