1e8d8bef9SDimitry Andric //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric /// \file InstrRefBasedImpl.cpp 9e8d8bef9SDimitry Andric /// 10e8d8bef9SDimitry Andric /// This is a separate implementation of LiveDebugValues, see 11e8d8bef9SDimitry Andric /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information. 12e8d8bef9SDimitry Andric /// 13e8d8bef9SDimitry Andric /// This pass propagates variable locations between basic blocks, resolving 14349cc55cSDimitry Andric /// control flow conflicts between them. The problem is SSA construction, where 15349cc55cSDimitry Andric /// each debug instruction assigns the *value* that a variable has, and every 16349cc55cSDimitry Andric /// instruction where the variable is in scope uses that variable. The resulting 17349cc55cSDimitry Andric /// map of instruction-to-value is then translated into a register (or spill) 18349cc55cSDimitry Andric /// location for each variable over each instruction. 19e8d8bef9SDimitry Andric /// 20349cc55cSDimitry Andric /// The primary difference from normal SSA construction is that we cannot 21349cc55cSDimitry Andric /// _create_ PHI values that contain variable values. CodeGen has already 22349cc55cSDimitry Andric /// completed, and we can't alter it just to make debug-info complete. Thus: 23349cc55cSDimitry Andric /// we can identify function positions where we would like a PHI value for a 24349cc55cSDimitry Andric /// variable, but must search the MachineFunction to see whether such a PHI is 25349cc55cSDimitry Andric /// available. If no such PHI exists, the variable location must be dropped. 26e8d8bef9SDimitry Andric /// 27349cc55cSDimitry Andric /// To achieve this, we perform two kinds of analysis. First, we identify 28e8d8bef9SDimitry Andric /// every value defined by every instruction (ignoring those that only move 29349cc55cSDimitry Andric /// another value), then re-compute an SSA-form representation of the 30349cc55cSDimitry Andric /// MachineFunction, using value propagation to eliminate any un-necessary 31349cc55cSDimitry Andric /// PHI values. This gives us a map of every value computed in the function, 32349cc55cSDimitry Andric /// and its location within the register file / stack. 33e8d8bef9SDimitry Andric /// 34349cc55cSDimitry Andric /// Secondly, for each variable we perform the same analysis, where each debug 35349cc55cSDimitry Andric /// instruction is considered a def, and every instruction where the variable 36349cc55cSDimitry Andric /// is in lexical scope as a use. Value propagation is used again to eliminate 37349cc55cSDimitry Andric /// any un-necessary PHIs. This gives us a map of each variable to the value 38349cc55cSDimitry Andric /// it should have in a block. 39e8d8bef9SDimitry Andric /// 40349cc55cSDimitry Andric /// Once both are complete, we have two maps for each block: 41349cc55cSDimitry Andric /// * Variables to the values they should have, 42349cc55cSDimitry Andric /// * Values to the register / spill slot they are located in. 43349cc55cSDimitry Andric /// After which we can marry-up variable values with a location, and emit 44349cc55cSDimitry Andric /// DBG_VALUE instructions specifying those locations. Variable locations may 45349cc55cSDimitry Andric /// be dropped in this process due to the desired variable value not being 46349cc55cSDimitry Andric /// resident in any machine location, or because there is no PHI value in any 47349cc55cSDimitry Andric /// location that accurately represents the desired value. The building of 48349cc55cSDimitry Andric /// location lists for each block is left to DbgEntityHistoryCalculator. 49e8d8bef9SDimitry Andric /// 50349cc55cSDimitry Andric /// This pass is kept efficient because the size of the first SSA problem 51349cc55cSDimitry Andric /// is proportional to the working-set size of the function, which the compiler 52349cc55cSDimitry Andric /// tries to keep small. (It's also proportional to the number of blocks). 53349cc55cSDimitry Andric /// Additionally, we repeatedly perform the second SSA problem analysis with 54349cc55cSDimitry Andric /// only the variables and blocks in a single lexical scope, exploiting their 55349cc55cSDimitry Andric /// locality. 56e8d8bef9SDimitry Andric /// 57e8d8bef9SDimitry Andric /// ### Terminology 58e8d8bef9SDimitry Andric /// 59e8d8bef9SDimitry Andric /// A machine location is a register or spill slot, a value is something that's 60e8d8bef9SDimitry Andric /// defined by an instruction or PHI node, while a variable value is the value 61e8d8bef9SDimitry Andric /// assigned to a variable. A variable location is a machine location, that must 62e8d8bef9SDimitry Andric /// contain the appropriate variable value. A value that is a PHI node is 63e8d8bef9SDimitry Andric /// occasionally called an mphi. 64e8d8bef9SDimitry Andric /// 65349cc55cSDimitry Andric /// The first SSA problem is the "machine value location" problem, 66e8d8bef9SDimitry Andric /// because we're determining which machine locations contain which values. 67e8d8bef9SDimitry Andric /// The "locations" are constant: what's unknown is what value they contain. 68e8d8bef9SDimitry Andric /// 69349cc55cSDimitry Andric /// The second SSA problem (the one for variables) is the "variable value 70e8d8bef9SDimitry Andric /// problem", because it's determining what values a variable has, rather than 71349cc55cSDimitry Andric /// what location those values are placed in. 72e8d8bef9SDimitry Andric /// 73e8d8bef9SDimitry Andric /// TODO: 74e8d8bef9SDimitry Andric /// Overlapping fragments 75e8d8bef9SDimitry Andric /// Entry values 76e8d8bef9SDimitry Andric /// Add back DEBUG statements for debugging this 77e8d8bef9SDimitry Andric /// Collect statistics 78e8d8bef9SDimitry Andric /// 79e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 80e8d8bef9SDimitry Andric 81e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h" 82e8d8bef9SDimitry Andric #include "llvm/ADT/PostOrderIterator.h" 83fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h" 84e8d8bef9SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 85e8d8bef9SDimitry Andric #include "llvm/ADT/SmallSet.h" 86e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 87e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h" 88349cc55cSDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h" 89e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h" 90e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 91349cc55cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 92e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h" 93e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 94e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 95e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 96e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 97fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h" 98e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h" 99e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 100e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h" 101e8d8bef9SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h" 102e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h" 103e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 104e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h" 105e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 106e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 107e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 108e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 109e8d8bef9SDimitry Andric #include "llvm/IR/DIBuilder.h" 110e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 111e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h" 112e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 113e8d8bef9SDimitry Andric #include "llvm/IR/Module.h" 114e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h" 115e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h" 116e8d8bef9SDimitry Andric #include "llvm/Pass.h" 117e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 118e8d8bef9SDimitry Andric #include "llvm/Support/Compiler.h" 119e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 120e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h" 121e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 122fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h" 123fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 124e8d8bef9SDimitry Andric #include <algorithm> 125e8d8bef9SDimitry Andric #include <cassert> 126e8d8bef9SDimitry Andric #include <cstdint> 127e8d8bef9SDimitry Andric #include <functional> 128349cc55cSDimitry Andric #include <limits.h> 129349cc55cSDimitry Andric #include <limits> 130e8d8bef9SDimitry Andric #include <queue> 131e8d8bef9SDimitry Andric #include <tuple> 132e8d8bef9SDimitry Andric #include <utility> 133e8d8bef9SDimitry Andric #include <vector> 134e8d8bef9SDimitry Andric 135349cc55cSDimitry Andric #include "InstrRefBasedImpl.h" 136e8d8bef9SDimitry Andric #include "LiveDebugValues.h" 137e8d8bef9SDimitry Andric 138e8d8bef9SDimitry Andric using namespace llvm; 139349cc55cSDimitry Andric using namespace LiveDebugValues; 140e8d8bef9SDimitry Andric 141fe6060f1SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it. 142fe6060f1SDimitry Andric #undef DEBUG_TYPE 143e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues" 144e8d8bef9SDimitry Andric 145e8d8bef9SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too 146e8d8bef9SDimitry Andric // far and ignoring some transfers. 147e8d8bef9SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, 148e8d8bef9SDimitry Andric cl::desc("Act like old LiveDebugValues did"), 149e8d8bef9SDimitry Andric cl::init(false)); 150e8d8bef9SDimitry Andric 151*d56accc7SDimitry Andric // Limit for the maximum number of stack slots we should track, past which we 152*d56accc7SDimitry Andric // will ignore any spills. InstrRefBasedLDV gathers detailed information on all 153*d56accc7SDimitry Andric // stack slots which leads to high memory consumption, and in some scenarios 154*d56accc7SDimitry Andric // (such as asan with very many locals) the working set of the function can be 155*d56accc7SDimitry Andric // very large, causing many spills. In these scenarios, it is very unlikely that 156*d56accc7SDimitry Andric // the developer has hundreds of variables live at the same time that they're 157*d56accc7SDimitry Andric // carefully thinking about -- instead, they probably autogenerated the code. 158*d56accc7SDimitry Andric // When this happens, gracefully stop tracking excess spill slots, rather than 159*d56accc7SDimitry Andric // consuming all the developer's memory. 160*d56accc7SDimitry Andric static cl::opt<unsigned> 161*d56accc7SDimitry Andric StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden, 162*d56accc7SDimitry Andric cl::desc("livedebugvalues-stack-ws-limit"), 163*d56accc7SDimitry Andric cl::init(250)); 164*d56accc7SDimitry Andric 165e8d8bef9SDimitry Andric /// Tracker for converting machine value locations and variable values into 166e8d8bef9SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs 167e8d8bef9SDimitry Andric /// specifying block live-in locations and transfers within blocks. 168e8d8bef9SDimitry Andric /// 169e8d8bef9SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker 170e8d8bef9SDimitry Andric /// and must be initialized with the set of variable values that are live-in to 171e8d8bef9SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks 172e8d8bef9SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a 173e8d8bef9SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is 174e8d8bef9SDimitry Andric /// stepped through, transfers of values between machine locations are 175e8d8bef9SDimitry Andric /// identified and if profitable, a DBG_VALUE created. 176e8d8bef9SDimitry Andric /// 177e8d8bef9SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an 178e8d8bef9SDimitry Andric /// unavailable value could materialize in the middle of a block, when the 179e8d8bef9SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the 180e8d8bef9SDimitry Andric /// variable in a backup location. (XXX these are unimplemented). 181e8d8bef9SDimitry Andric class TransferTracker { 182e8d8bef9SDimitry Andric public: 183e8d8bef9SDimitry Andric const TargetInstrInfo *TII; 184fe6060f1SDimitry Andric const TargetLowering *TLI; 185e8d8bef9SDimitry Andric /// This machine location tracker is assumed to always contain the up-to-date 186e8d8bef9SDimitry Andric /// value mapping for all machine locations. TransferTracker only reads 187e8d8bef9SDimitry Andric /// information from it. (XXX make it const?) 188e8d8bef9SDimitry Andric MLocTracker *MTracker; 189e8d8bef9SDimitry Andric MachineFunction &MF; 190fe6060f1SDimitry Andric bool ShouldEmitDebugEntryValues; 191e8d8bef9SDimitry Andric 192e8d8bef9SDimitry Andric /// Record of all changes in variable locations at a block position. Awkwardly 193e8d8bef9SDimitry Andric /// we allow inserting either before or after the point: MBB != nullptr 194e8d8bef9SDimitry Andric /// indicates it's before, otherwise after. 195e8d8bef9SDimitry Andric struct Transfer { 196fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes 197e8d8bef9SDimitry Andric MachineBasicBlock *MBB; /// non-null if we should insert after. 198e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. 199e8d8bef9SDimitry Andric }; 200e8d8bef9SDimitry Andric 201fe6060f1SDimitry Andric struct LocAndProperties { 202e8d8bef9SDimitry Andric LocIdx Loc; 203e8d8bef9SDimitry Andric DbgValueProperties Properties; 204fe6060f1SDimitry Andric }; 205e8d8bef9SDimitry Andric 206e8d8bef9SDimitry Andric /// Collection of transfers (DBG_VALUEs) to be inserted. 207e8d8bef9SDimitry Andric SmallVector<Transfer, 32> Transfers; 208e8d8bef9SDimitry Andric 209e8d8bef9SDimitry Andric /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences 210e8d8bef9SDimitry Andric /// between TransferTrackers view of variable locations and MLocTrackers. For 211e8d8bef9SDimitry Andric /// example, MLocTracker observes all clobbers, but TransferTracker lazily 212e8d8bef9SDimitry Andric /// does not. 213349cc55cSDimitry Andric SmallVector<ValueIDNum, 32> VarLocs; 214e8d8bef9SDimitry Andric 215e8d8bef9SDimitry Andric /// Map from LocIdxes to which DebugVariables are based that location. 216e8d8bef9SDimitry Andric /// Mantained while stepping through the block. Not accurate if 217e8d8bef9SDimitry Andric /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. 218349cc55cSDimitry Andric DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; 219e8d8bef9SDimitry Andric 220e8d8bef9SDimitry Andric /// Map from DebugVariable to it's current location and qualifying meta 221e8d8bef9SDimitry Andric /// information. To be used in conjunction with ActiveMLocs to construct 222e8d8bef9SDimitry Andric /// enough information for the DBG_VALUEs for a particular LocIdx. 223e8d8bef9SDimitry Andric DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; 224e8d8bef9SDimitry Andric 225e8d8bef9SDimitry Andric /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. 226e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> PendingDbgValues; 227e8d8bef9SDimitry Andric 228e8d8bef9SDimitry Andric /// Record of a use-before-def: created when a value that's live-in to the 229e8d8bef9SDimitry Andric /// current block isn't available in any machine location, but it will be 230e8d8bef9SDimitry Andric /// defined in this block. 231e8d8bef9SDimitry Andric struct UseBeforeDef { 232e8d8bef9SDimitry Andric /// Value of this variable, def'd in block. 233e8d8bef9SDimitry Andric ValueIDNum ID; 234e8d8bef9SDimitry Andric /// Identity of this variable. 235e8d8bef9SDimitry Andric DebugVariable Var; 236e8d8bef9SDimitry Andric /// Additional variable properties. 237e8d8bef9SDimitry Andric DbgValueProperties Properties; 238e8d8bef9SDimitry Andric }; 239e8d8bef9SDimitry Andric 240e8d8bef9SDimitry Andric /// Map from instruction index (within the block) to the set of UseBeforeDefs 241e8d8bef9SDimitry Andric /// that become defined at that instruction. 242e8d8bef9SDimitry Andric DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; 243e8d8bef9SDimitry Andric 244e8d8bef9SDimitry Andric /// The set of variables that are in UseBeforeDefs and can become a location 245e8d8bef9SDimitry Andric /// once the relevant value is defined. An element being erased from this 246e8d8bef9SDimitry Andric /// collection prevents the use-before-def materializing. 247e8d8bef9SDimitry Andric DenseSet<DebugVariable> UseBeforeDefVariables; 248e8d8bef9SDimitry Andric 249e8d8bef9SDimitry Andric const TargetRegisterInfo &TRI; 250e8d8bef9SDimitry Andric const BitVector &CalleeSavedRegs; 251e8d8bef9SDimitry Andric 252e8d8bef9SDimitry Andric TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, 253e8d8bef9SDimitry Andric MachineFunction &MF, const TargetRegisterInfo &TRI, 254fe6060f1SDimitry Andric const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) 255e8d8bef9SDimitry Andric : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), 256fe6060f1SDimitry Andric CalleeSavedRegs(CalleeSavedRegs) { 257fe6060f1SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 258fe6060f1SDimitry Andric auto &TM = TPC.getTM<TargetMachine>(); 259fe6060f1SDimitry Andric ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); 260fe6060f1SDimitry Andric } 261e8d8bef9SDimitry Andric 262e8d8bef9SDimitry Andric /// Load object with live-in variable values. \p mlocs contains the live-in 263e8d8bef9SDimitry Andric /// values in each machine location, while \p vlocs the live-in variable 264e8d8bef9SDimitry Andric /// values. This method picks variable locations for the live-in variables, 265e8d8bef9SDimitry Andric /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other 266e8d8bef9SDimitry Andric /// object fields to track variable locations as we step through the block. 267e8d8bef9SDimitry Andric /// FIXME: could just examine mloctracker instead of passing in \p mlocs? 26804eeddc0SDimitry Andric void 26904eeddc0SDimitry Andric loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs, 27004eeddc0SDimitry Andric const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, 271e8d8bef9SDimitry Andric unsigned NumLocs) { 272e8d8bef9SDimitry Andric ActiveMLocs.clear(); 273e8d8bef9SDimitry Andric ActiveVLocs.clear(); 274e8d8bef9SDimitry Andric VarLocs.clear(); 275e8d8bef9SDimitry Andric VarLocs.reserve(NumLocs); 276e8d8bef9SDimitry Andric UseBeforeDefs.clear(); 277e8d8bef9SDimitry Andric UseBeforeDefVariables.clear(); 278e8d8bef9SDimitry Andric 279e8d8bef9SDimitry Andric auto isCalleeSaved = [&](LocIdx L) { 280e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 281e8d8bef9SDimitry Andric if (Reg >= MTracker->NumRegs) 282e8d8bef9SDimitry Andric return false; 283e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) 284e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 285e8d8bef9SDimitry Andric return true; 286e8d8bef9SDimitry Andric return false; 287e8d8bef9SDimitry Andric }; 288e8d8bef9SDimitry Andric 289e8d8bef9SDimitry Andric // Map of the preferred location for each value. 29004eeddc0SDimitry Andric DenseMap<ValueIDNum, LocIdx> ValueToLoc; 2911fd87a68SDimitry Andric 2921fd87a68SDimitry Andric // Initialized the preferred-location map with illegal locations, to be 2931fd87a68SDimitry Andric // filled in later. 2941fd87a68SDimitry Andric for (auto &VLoc : VLocs) 2951fd87a68SDimitry Andric if (VLoc.second.Kind == DbgValue::Def) 2961fd87a68SDimitry Andric ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()}); 2971fd87a68SDimitry Andric 298349cc55cSDimitry Andric ActiveMLocs.reserve(VLocs.size()); 299349cc55cSDimitry Andric ActiveVLocs.reserve(VLocs.size()); 300e8d8bef9SDimitry Andric 301e8d8bef9SDimitry Andric // Produce a map of value numbers to the current machine locs they live 302e8d8bef9SDimitry Andric // in. When emulating VarLocBasedImpl, there should only be one 303e8d8bef9SDimitry Andric // location; when not, we get to pick. 304e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 305e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 306e8d8bef9SDimitry Andric ValueIDNum &VNum = MLocs[Idx.asU64()]; 307e8d8bef9SDimitry Andric VarLocs.push_back(VNum); 30804eeddc0SDimitry Andric 3091fd87a68SDimitry Andric // Is there a variable that wants a location for this value? If not, skip. 3101fd87a68SDimitry Andric auto VIt = ValueToLoc.find(VNum); 3111fd87a68SDimitry Andric if (VIt == ValueToLoc.end()) 31204eeddc0SDimitry Andric continue; 31304eeddc0SDimitry Andric 3141fd87a68SDimitry Andric LocIdx CurLoc = VIt->second; 315e8d8bef9SDimitry Andric // In order of preference, pick: 316e8d8bef9SDimitry Andric // * Callee saved registers, 317e8d8bef9SDimitry Andric // * Other registers, 318e8d8bef9SDimitry Andric // * Spill slots. 3191fd87a68SDimitry Andric if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) || 3201fd87a68SDimitry Andric (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) { 321e8d8bef9SDimitry Andric // Insert, or overwrite if insertion failed. 3221fd87a68SDimitry Andric VIt->second = Idx; 323e8d8bef9SDimitry Andric } 324e8d8bef9SDimitry Andric } 325e8d8bef9SDimitry Andric 326e8d8bef9SDimitry Andric // Now map variables to their picked LocIdxes. 32704eeddc0SDimitry Andric for (const auto &Var : VLocs) { 328e8d8bef9SDimitry Andric if (Var.second.Kind == DbgValue::Const) { 329e8d8bef9SDimitry Andric PendingDbgValues.push_back( 330349cc55cSDimitry Andric emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties)); 331e8d8bef9SDimitry Andric continue; 332e8d8bef9SDimitry Andric } 333e8d8bef9SDimitry Andric 334e8d8bef9SDimitry Andric // If the value has no location, we can't make a variable location. 335e8d8bef9SDimitry Andric const ValueIDNum &Num = Var.second.ID; 336e8d8bef9SDimitry Andric auto ValuesPreferredLoc = ValueToLoc.find(Num); 3371fd87a68SDimitry Andric if (ValuesPreferredLoc->second.isIllegal()) { 338e8d8bef9SDimitry Andric // If it's a def that occurs in this block, register it as a 339e8d8bef9SDimitry Andric // use-before-def to be resolved as we step through the block. 340e8d8bef9SDimitry Andric if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) 341e8d8bef9SDimitry Andric addUseBeforeDef(Var.first, Var.second.Properties, Num); 342fe6060f1SDimitry Andric else 343fe6060f1SDimitry Andric recoverAsEntryValue(Var.first, Var.second.Properties, Num); 344e8d8bef9SDimitry Andric continue; 345e8d8bef9SDimitry Andric } 346e8d8bef9SDimitry Andric 347e8d8bef9SDimitry Andric LocIdx M = ValuesPreferredLoc->second; 348e8d8bef9SDimitry Andric auto NewValue = LocAndProperties{M, Var.second.Properties}; 349e8d8bef9SDimitry Andric auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); 350e8d8bef9SDimitry Andric if (!Result.second) 351e8d8bef9SDimitry Andric Result.first->second = NewValue; 352e8d8bef9SDimitry Andric ActiveMLocs[M].insert(Var.first); 353e8d8bef9SDimitry Andric PendingDbgValues.push_back( 354e8d8bef9SDimitry Andric MTracker->emitLoc(M, Var.first, Var.second.Properties)); 355e8d8bef9SDimitry Andric } 356e8d8bef9SDimitry Andric flushDbgValues(MBB.begin(), &MBB); 357e8d8bef9SDimitry Andric } 358e8d8bef9SDimitry Andric 359e8d8bef9SDimitry Andric /// Record that \p Var has value \p ID, a value that becomes available 360e8d8bef9SDimitry Andric /// later in the function. 361e8d8bef9SDimitry Andric void addUseBeforeDef(const DebugVariable &Var, 362e8d8bef9SDimitry Andric const DbgValueProperties &Properties, ValueIDNum ID) { 363e8d8bef9SDimitry Andric UseBeforeDef UBD = {ID, Var, Properties}; 364e8d8bef9SDimitry Andric UseBeforeDefs[ID.getInst()].push_back(UBD); 365e8d8bef9SDimitry Andric UseBeforeDefVariables.insert(Var); 366e8d8bef9SDimitry Andric } 367e8d8bef9SDimitry Andric 368e8d8bef9SDimitry Andric /// After the instruction at index \p Inst and position \p pos has been 369e8d8bef9SDimitry Andric /// processed, check whether it defines a variable value in a use-before-def. 370e8d8bef9SDimitry Andric /// If so, and the variable value hasn't changed since the start of the 371e8d8bef9SDimitry Andric /// block, create a DBG_VALUE. 372e8d8bef9SDimitry Andric void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { 373e8d8bef9SDimitry Andric auto MIt = UseBeforeDefs.find(Inst); 374e8d8bef9SDimitry Andric if (MIt == UseBeforeDefs.end()) 375e8d8bef9SDimitry Andric return; 376e8d8bef9SDimitry Andric 377e8d8bef9SDimitry Andric for (auto &Use : MIt->second) { 378e8d8bef9SDimitry Andric LocIdx L = Use.ID.getLoc(); 379e8d8bef9SDimitry Andric 380e8d8bef9SDimitry Andric // If something goes very wrong, we might end up labelling a COPY 381e8d8bef9SDimitry Andric // instruction or similar with an instruction number, where it doesn't 382e8d8bef9SDimitry Andric // actually define a new value, instead it moves a value. In case this 383e8d8bef9SDimitry Andric // happens, discard. 384349cc55cSDimitry Andric if (MTracker->readMLoc(L) != Use.ID) 385e8d8bef9SDimitry Andric continue; 386e8d8bef9SDimitry Andric 387e8d8bef9SDimitry Andric // If a different debug instruction defined the variable value / location 388e8d8bef9SDimitry Andric // since the start of the block, don't materialize this use-before-def. 389e8d8bef9SDimitry Andric if (!UseBeforeDefVariables.count(Use.Var)) 390e8d8bef9SDimitry Andric continue; 391e8d8bef9SDimitry Andric 392e8d8bef9SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); 393e8d8bef9SDimitry Andric } 394e8d8bef9SDimitry Andric flushDbgValues(pos, nullptr); 395e8d8bef9SDimitry Andric } 396e8d8bef9SDimitry Andric 397e8d8bef9SDimitry Andric /// Helper to move created DBG_VALUEs into Transfers collection. 398e8d8bef9SDimitry Andric void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { 399fe6060f1SDimitry Andric if (PendingDbgValues.size() == 0) 400fe6060f1SDimitry Andric return; 401fe6060f1SDimitry Andric 402fe6060f1SDimitry Andric // Pick out the instruction start position. 403fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator BundleStart; 404fe6060f1SDimitry Andric if (MBB && Pos == MBB->begin()) 405fe6060f1SDimitry Andric BundleStart = MBB->instr_begin(); 406fe6060f1SDimitry Andric else 407fe6060f1SDimitry Andric BundleStart = getBundleStart(Pos->getIterator()); 408fe6060f1SDimitry Andric 409fe6060f1SDimitry Andric Transfers.push_back({BundleStart, MBB, PendingDbgValues}); 410e8d8bef9SDimitry Andric PendingDbgValues.clear(); 411e8d8bef9SDimitry Andric } 412fe6060f1SDimitry Andric 413fe6060f1SDimitry Andric bool isEntryValueVariable(const DebugVariable &Var, 414fe6060f1SDimitry Andric const DIExpression *Expr) const { 415fe6060f1SDimitry Andric if (!Var.getVariable()->isParameter()) 416fe6060f1SDimitry Andric return false; 417fe6060f1SDimitry Andric 418fe6060f1SDimitry Andric if (Var.getInlinedAt()) 419fe6060f1SDimitry Andric return false; 420fe6060f1SDimitry Andric 421fe6060f1SDimitry Andric if (Expr->getNumElements() > 0) 422fe6060f1SDimitry Andric return false; 423fe6060f1SDimitry Andric 424fe6060f1SDimitry Andric return true; 425fe6060f1SDimitry Andric } 426fe6060f1SDimitry Andric 427fe6060f1SDimitry Andric bool isEntryValueValue(const ValueIDNum &Val) const { 428fe6060f1SDimitry Andric // Must be in entry block (block number zero), and be a PHI / live-in value. 429fe6060f1SDimitry Andric if (Val.getBlock() || !Val.isPHI()) 430fe6060f1SDimitry Andric return false; 431fe6060f1SDimitry Andric 432fe6060f1SDimitry Andric // Entry values must enter in a register. 433fe6060f1SDimitry Andric if (MTracker->isSpill(Val.getLoc())) 434fe6060f1SDimitry Andric return false; 435fe6060f1SDimitry Andric 436fe6060f1SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore(); 437fe6060f1SDimitry Andric Register FP = TRI.getFrameRegister(MF); 438fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; 439fe6060f1SDimitry Andric return Reg != SP && Reg != FP; 440fe6060f1SDimitry Andric } 441fe6060f1SDimitry Andric 44204eeddc0SDimitry Andric bool recoverAsEntryValue(const DebugVariable &Var, 44304eeddc0SDimitry Andric const DbgValueProperties &Prop, 444fe6060f1SDimitry Andric const ValueIDNum &Num) { 445fe6060f1SDimitry Andric // Is this variable location a candidate to be an entry value. First, 446fe6060f1SDimitry Andric // should we be trying this at all? 447fe6060f1SDimitry Andric if (!ShouldEmitDebugEntryValues) 448fe6060f1SDimitry Andric return false; 449fe6060f1SDimitry Andric 450fe6060f1SDimitry Andric // Is the variable appropriate for entry values (i.e., is a parameter). 451fe6060f1SDimitry Andric if (!isEntryValueVariable(Var, Prop.DIExpr)) 452fe6060f1SDimitry Andric return false; 453fe6060f1SDimitry Andric 454fe6060f1SDimitry Andric // Is the value assigned to this variable still the entry value? 455fe6060f1SDimitry Andric if (!isEntryValueValue(Num)) 456fe6060f1SDimitry Andric return false; 457fe6060f1SDimitry Andric 458fe6060f1SDimitry Andric // Emit a variable location using an entry value expression. 459fe6060f1SDimitry Andric DIExpression *NewExpr = 460fe6060f1SDimitry Andric DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); 461fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; 462fe6060f1SDimitry Andric MachineOperand MO = MachineOperand::CreateReg(Reg, false); 463fe6060f1SDimitry Andric 464fe6060f1SDimitry Andric PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); 465fe6060f1SDimitry Andric return true; 466e8d8bef9SDimitry Andric } 467e8d8bef9SDimitry Andric 468e8d8bef9SDimitry Andric /// Change a variable value after encountering a DBG_VALUE inside a block. 469e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI) { 470e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 471e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 472e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 473e8d8bef9SDimitry Andric 474e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 475e8d8bef9SDimitry Andric 476e8d8bef9SDimitry Andric // Ignore non-register locations, we don't transfer those. 477e8d8bef9SDimitry Andric if (!MO.isReg() || MO.getReg() == 0) { 478e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 479e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) { 480e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 481e8d8bef9SDimitry Andric ActiveVLocs.erase(It); 482e8d8bef9SDimitry Andric } 483e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 484e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 485e8d8bef9SDimitry Andric return; 486e8d8bef9SDimitry Andric } 487e8d8bef9SDimitry Andric 488e8d8bef9SDimitry Andric Register Reg = MO.getReg(); 489e8d8bef9SDimitry Andric LocIdx NewLoc = MTracker->getRegMLoc(Reg); 490e8d8bef9SDimitry Andric redefVar(MI, Properties, NewLoc); 491e8d8bef9SDimitry Andric } 492e8d8bef9SDimitry Andric 493e8d8bef9SDimitry Andric /// Handle a change in variable location within a block. Terminate the 494e8d8bef9SDimitry Andric /// variables current location, and record the value it now refers to, so 495e8d8bef9SDimitry Andric /// that we can detect location transfers later on. 496e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, 497e8d8bef9SDimitry Andric Optional<LocIdx> OptNewLoc) { 498e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 499e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 500e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 501e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 502e8d8bef9SDimitry Andric 503e8d8bef9SDimitry Andric // Erase any previous location, 504e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 505e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) 506e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 507e8d8bef9SDimitry Andric 508e8d8bef9SDimitry Andric // If there _is_ no new location, all we had to do was erase. 509e8d8bef9SDimitry Andric if (!OptNewLoc) 510e8d8bef9SDimitry Andric return; 511e8d8bef9SDimitry Andric LocIdx NewLoc = *OptNewLoc; 512e8d8bef9SDimitry Andric 513e8d8bef9SDimitry Andric // Check whether our local copy of values-by-location in #VarLocs is out of 514e8d8bef9SDimitry Andric // date. Wipe old tracking data for the location if it's been clobbered in 515e8d8bef9SDimitry Andric // the meantime. 516349cc55cSDimitry Andric if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) { 517e8d8bef9SDimitry Andric for (auto &P : ActiveMLocs[NewLoc]) { 518e8d8bef9SDimitry Andric ActiveVLocs.erase(P); 519e8d8bef9SDimitry Andric } 520e8d8bef9SDimitry Andric ActiveMLocs[NewLoc.asU64()].clear(); 521349cc55cSDimitry Andric VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc); 522e8d8bef9SDimitry Andric } 523e8d8bef9SDimitry Andric 524e8d8bef9SDimitry Andric ActiveMLocs[NewLoc].insert(Var); 525e8d8bef9SDimitry Andric if (It == ActiveVLocs.end()) { 526e8d8bef9SDimitry Andric ActiveVLocs.insert( 527e8d8bef9SDimitry Andric std::make_pair(Var, LocAndProperties{NewLoc, Properties})); 528e8d8bef9SDimitry Andric } else { 529e8d8bef9SDimitry Andric It->second.Loc = NewLoc; 530e8d8bef9SDimitry Andric It->second.Properties = Properties; 531e8d8bef9SDimitry Andric } 532e8d8bef9SDimitry Andric } 533e8d8bef9SDimitry Andric 534fe6060f1SDimitry Andric /// Account for a location \p mloc being clobbered. Examine the variable 535fe6060f1SDimitry Andric /// locations that will be terminated: and try to recover them by using 536fe6060f1SDimitry Andric /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to 537fe6060f1SDimitry Andric /// explicitly terminate a location if it can't be recovered. 538fe6060f1SDimitry Andric void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, 539fe6060f1SDimitry Andric bool MakeUndef = true) { 540e8d8bef9SDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc); 541e8d8bef9SDimitry Andric if (ActiveMLocIt == ActiveMLocs.end()) 542e8d8bef9SDimitry Andric return; 543e8d8bef9SDimitry Andric 544fe6060f1SDimitry Andric // What was the old variable value? 545fe6060f1SDimitry Andric ValueIDNum OldValue = VarLocs[MLoc.asU64()]; 546e8d8bef9SDimitry Andric VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; 547e8d8bef9SDimitry Andric 548fe6060f1SDimitry Andric // Examine the remaining variable locations: if we can find the same value 549fe6060f1SDimitry Andric // again, we can recover the location. 550fe6060f1SDimitry Andric Optional<LocIdx> NewLoc = None; 551fe6060f1SDimitry Andric for (auto Loc : MTracker->locations()) 552fe6060f1SDimitry Andric if (Loc.Value == OldValue) 553fe6060f1SDimitry Andric NewLoc = Loc.Idx; 554fe6060f1SDimitry Andric 555fe6060f1SDimitry Andric // If there is no location, and we weren't asked to make the variable 556fe6060f1SDimitry Andric // explicitly undef, then stop here. 557fe6060f1SDimitry Andric if (!NewLoc && !MakeUndef) { 558fe6060f1SDimitry Andric // Try and recover a few more locations with entry values. 559fe6060f1SDimitry Andric for (auto &Var : ActiveMLocIt->second) { 560fe6060f1SDimitry Andric auto &Prop = ActiveVLocs.find(Var)->second.Properties; 561fe6060f1SDimitry Andric recoverAsEntryValue(Var, Prop, OldValue); 562fe6060f1SDimitry Andric } 563fe6060f1SDimitry Andric flushDbgValues(Pos, nullptr); 564fe6060f1SDimitry Andric return; 565fe6060f1SDimitry Andric } 566fe6060f1SDimitry Andric 567fe6060f1SDimitry Andric // Examine all the variables based on this location. 568fe6060f1SDimitry Andric DenseSet<DebugVariable> NewMLocs; 569e8d8bef9SDimitry Andric for (auto &Var : ActiveMLocIt->second) { 570e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 571fe6060f1SDimitry Andric // Re-state the variable location: if there's no replacement then NewLoc 572fe6060f1SDimitry Andric // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE 573fe6060f1SDimitry Andric // identifying the alternative location will be emitted. 5744824e7fdSDimitry Andric const DbgValueProperties &Properties = ActiveVLocIt->second.Properties; 575fe6060f1SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); 576fe6060f1SDimitry Andric 577fe6060f1SDimitry Andric // Update machine locations <=> variable locations maps. Defer updating 578fe6060f1SDimitry Andric // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. 579fe6060f1SDimitry Andric if (!NewLoc) { 580e8d8bef9SDimitry Andric ActiveVLocs.erase(ActiveVLocIt); 581fe6060f1SDimitry Andric } else { 582fe6060f1SDimitry Andric ActiveVLocIt->second.Loc = *NewLoc; 583fe6060f1SDimitry Andric NewMLocs.insert(Var); 584e8d8bef9SDimitry Andric } 585fe6060f1SDimitry Andric } 586fe6060f1SDimitry Andric 587fe6060f1SDimitry Andric // Commit any deferred ActiveMLoc changes. 588fe6060f1SDimitry Andric if (!NewMLocs.empty()) 589fe6060f1SDimitry Andric for (auto &Var : NewMLocs) 590fe6060f1SDimitry Andric ActiveMLocs[*NewLoc].insert(Var); 591fe6060f1SDimitry Andric 592fe6060f1SDimitry Andric // We lazily track what locations have which values; if we've found a new 593fe6060f1SDimitry Andric // location for the clobbered value, remember it. 594fe6060f1SDimitry Andric if (NewLoc) 595fe6060f1SDimitry Andric VarLocs[NewLoc->asU64()] = OldValue; 596fe6060f1SDimitry Andric 597e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 598e8d8bef9SDimitry Andric 599349cc55cSDimitry Andric // Re-find ActiveMLocIt, iterator could have been invalidated. 600349cc55cSDimitry Andric ActiveMLocIt = ActiveMLocs.find(MLoc); 601e8d8bef9SDimitry Andric ActiveMLocIt->second.clear(); 602e8d8bef9SDimitry Andric } 603e8d8bef9SDimitry Andric 604e8d8bef9SDimitry Andric /// Transfer variables based on \p Src to be based on \p Dst. This handles 605e8d8bef9SDimitry Andric /// both register copies as well as spills and restores. Creates DBG_VALUEs 606e8d8bef9SDimitry Andric /// describing the movement. 607e8d8bef9SDimitry Andric void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { 608e8d8bef9SDimitry Andric // Does Src still contain the value num we expect? If not, it's been 609e8d8bef9SDimitry Andric // clobbered in the meantime, and our variable locations are stale. 610349cc55cSDimitry Andric if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src)) 611e8d8bef9SDimitry Andric return; 612e8d8bef9SDimitry Andric 613e8d8bef9SDimitry Andric // assert(ActiveMLocs[Dst].size() == 0); 614e8d8bef9SDimitry Andric //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? 615349cc55cSDimitry Andric 616349cc55cSDimitry Andric // Move set of active variables from one location to another. 617349cc55cSDimitry Andric auto MovingVars = ActiveMLocs[Src]; 618349cc55cSDimitry Andric ActiveMLocs[Dst] = MovingVars; 619e8d8bef9SDimitry Andric VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; 620e8d8bef9SDimitry Andric 621e8d8bef9SDimitry Andric // For each variable based on Src; create a location at Dst. 622349cc55cSDimitry Andric for (auto &Var : MovingVars) { 623e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 624e8d8bef9SDimitry Andric assert(ActiveVLocIt != ActiveVLocs.end()); 625e8d8bef9SDimitry Andric ActiveVLocIt->second.Loc = Dst; 626e8d8bef9SDimitry Andric 627e8d8bef9SDimitry Andric MachineInstr *MI = 628e8d8bef9SDimitry Andric MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); 629e8d8bef9SDimitry Andric PendingDbgValues.push_back(MI); 630e8d8bef9SDimitry Andric } 631e8d8bef9SDimitry Andric ActiveMLocs[Src].clear(); 632e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 633e8d8bef9SDimitry Andric 634e8d8bef9SDimitry Andric // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data 635e8d8bef9SDimitry Andric // about the old location. 636e8d8bef9SDimitry Andric if (EmulateOldLDV) 637e8d8bef9SDimitry Andric VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; 638e8d8bef9SDimitry Andric } 639e8d8bef9SDimitry Andric 640e8d8bef9SDimitry Andric MachineInstrBuilder emitMOLoc(const MachineOperand &MO, 641e8d8bef9SDimitry Andric const DebugVariable &Var, 642e8d8bef9SDimitry Andric const DbgValueProperties &Properties) { 643e8d8bef9SDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 644e8d8bef9SDimitry Andric Var.getVariable()->getScope(), 645e8d8bef9SDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 646e8d8bef9SDimitry Andric auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 647e8d8bef9SDimitry Andric MIB.add(MO); 648e8d8bef9SDimitry Andric if (Properties.Indirect) 649e8d8bef9SDimitry Andric MIB.addImm(0); 650e8d8bef9SDimitry Andric else 651e8d8bef9SDimitry Andric MIB.addReg(0); 652e8d8bef9SDimitry Andric MIB.addMetadata(Var.getVariable()); 653e8d8bef9SDimitry Andric MIB.addMetadata(Properties.DIExpr); 654e8d8bef9SDimitry Andric return MIB; 655e8d8bef9SDimitry Andric } 656e8d8bef9SDimitry Andric }; 657e8d8bef9SDimitry Andric 658349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 659349cc55cSDimitry Andric // Implementation 660349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 661e8d8bef9SDimitry Andric 662349cc55cSDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; 663349cc55cSDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1}; 664e8d8bef9SDimitry Andric 665349cc55cSDimitry Andric #ifndef NDEBUG 666349cc55cSDimitry Andric void DbgValue::dump(const MLocTracker *MTrack) const { 667349cc55cSDimitry Andric if (Kind == Const) { 668349cc55cSDimitry Andric MO->dump(); 669349cc55cSDimitry Andric } else if (Kind == NoVal) { 670349cc55cSDimitry Andric dbgs() << "NoVal(" << BlockNo << ")"; 671349cc55cSDimitry Andric } else if (Kind == VPHI) { 672349cc55cSDimitry Andric dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")"; 673349cc55cSDimitry Andric } else { 674349cc55cSDimitry Andric assert(Kind == Def); 675349cc55cSDimitry Andric dbgs() << MTrack->IDAsString(ID); 676349cc55cSDimitry Andric } 677349cc55cSDimitry Andric if (Properties.Indirect) 678349cc55cSDimitry Andric dbgs() << " indir"; 679349cc55cSDimitry Andric if (Properties.DIExpr) 680349cc55cSDimitry Andric dbgs() << " " << *Properties.DIExpr; 681349cc55cSDimitry Andric } 682349cc55cSDimitry Andric #endif 683e8d8bef9SDimitry Andric 684349cc55cSDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 685349cc55cSDimitry Andric const TargetRegisterInfo &TRI, 686349cc55cSDimitry Andric const TargetLowering &TLI) 687349cc55cSDimitry Andric : MF(MF), TII(TII), TRI(TRI), TLI(TLI), 688349cc55cSDimitry Andric LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) { 689349cc55cSDimitry Andric NumRegs = TRI.getNumRegs(); 690349cc55cSDimitry Andric reset(); 691349cc55cSDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 692349cc55cSDimitry Andric assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure 693e8d8bef9SDimitry Andric 694349cc55cSDimitry Andric // Always track SP. This avoids the implicit clobbering caused by regmasks 695349cc55cSDimitry Andric // from affectings its values. (LiveDebugValues disbelieves calls and 696349cc55cSDimitry Andric // regmasks that claim to clobber SP). 697349cc55cSDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore(); 698349cc55cSDimitry Andric if (SP) { 699349cc55cSDimitry Andric unsigned ID = getLocID(SP); 700349cc55cSDimitry Andric (void)lookupOrTrackRegister(ID); 701e8d8bef9SDimitry Andric 702349cc55cSDimitry Andric for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI) 703349cc55cSDimitry Andric SPAliases.insert(*RAI); 704349cc55cSDimitry Andric } 705e8d8bef9SDimitry Andric 706349cc55cSDimitry Andric // Build some common stack positions -- full registers being spilt to the 707349cc55cSDimitry Andric // stack. 708349cc55cSDimitry Andric StackSlotIdxes.insert({{8, 0}, 0}); 709349cc55cSDimitry Andric StackSlotIdxes.insert({{16, 0}, 1}); 710349cc55cSDimitry Andric StackSlotIdxes.insert({{32, 0}, 2}); 711349cc55cSDimitry Andric StackSlotIdxes.insert({{64, 0}, 3}); 712349cc55cSDimitry Andric StackSlotIdxes.insert({{128, 0}, 4}); 713349cc55cSDimitry Andric StackSlotIdxes.insert({{256, 0}, 5}); 714349cc55cSDimitry Andric StackSlotIdxes.insert({{512, 0}, 6}); 715e8d8bef9SDimitry Andric 716349cc55cSDimitry Andric // Traverse all the subregister idxes, and ensure there's an index for them. 717349cc55cSDimitry Andric // Duplicates are no problem: we're interested in their position in the 718349cc55cSDimitry Andric // stack slot, we don't want to type the slot. 719349cc55cSDimitry Andric for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) { 720349cc55cSDimitry Andric unsigned Size = TRI.getSubRegIdxSize(I); 721349cc55cSDimitry Andric unsigned Offs = TRI.getSubRegIdxOffset(I); 722349cc55cSDimitry Andric unsigned Idx = StackSlotIdxes.size(); 723e8d8bef9SDimitry Andric 724349cc55cSDimitry Andric // Some subregs have -1, -2 and so forth fed into their fields, to mean 725349cc55cSDimitry Andric // special backend things. Ignore those. 726349cc55cSDimitry Andric if (Size > 60000 || Offs > 60000) 727349cc55cSDimitry Andric continue; 728e8d8bef9SDimitry Andric 729349cc55cSDimitry Andric StackSlotIdxes.insert({{Size, Offs}, Idx}); 730349cc55cSDimitry Andric } 731e8d8bef9SDimitry Andric 732349cc55cSDimitry Andric for (auto &Idx : StackSlotIdxes) 733349cc55cSDimitry Andric StackIdxesToPos[Idx.second] = Idx.first; 734e8d8bef9SDimitry Andric 735349cc55cSDimitry Andric NumSlotIdxes = StackSlotIdxes.size(); 736349cc55cSDimitry Andric } 737e8d8bef9SDimitry Andric 738349cc55cSDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) { 739349cc55cSDimitry Andric assert(ID != 0); 740349cc55cSDimitry Andric LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); 741349cc55cSDimitry Andric LocIdxToIDNum.grow(NewIdx); 742349cc55cSDimitry Andric LocIdxToLocID.grow(NewIdx); 743e8d8bef9SDimitry Andric 744349cc55cSDimitry Andric // Default: it's an mphi. 745349cc55cSDimitry Andric ValueIDNum ValNum = {CurBB, 0, NewIdx}; 746349cc55cSDimitry Andric // Was this reg ever touched by a regmask? 747349cc55cSDimitry Andric for (const auto &MaskPair : reverse(Masks)) { 748349cc55cSDimitry Andric if (MaskPair.first->clobbersPhysReg(ID)) { 749349cc55cSDimitry Andric // There was an earlier def we skipped. 750349cc55cSDimitry Andric ValNum = {CurBB, MaskPair.second, NewIdx}; 751349cc55cSDimitry Andric break; 752349cc55cSDimitry Andric } 753349cc55cSDimitry Andric } 754e8d8bef9SDimitry Andric 755349cc55cSDimitry Andric LocIdxToIDNum[NewIdx] = ValNum; 756349cc55cSDimitry Andric LocIdxToLocID[NewIdx] = ID; 757349cc55cSDimitry Andric return NewIdx; 758349cc55cSDimitry Andric } 759e8d8bef9SDimitry Andric 760349cc55cSDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB, 761349cc55cSDimitry Andric unsigned InstID) { 762349cc55cSDimitry Andric // Def any register we track have that isn't preserved. The regmask 763349cc55cSDimitry Andric // terminates the liveness of a register, meaning its value can't be 764349cc55cSDimitry Andric // relied upon -- we represent this by giving it a new value. 765349cc55cSDimitry Andric for (auto Location : locations()) { 766349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Location.Idx]; 767349cc55cSDimitry Andric // Don't clobber SP, even if the mask says it's clobbered. 768349cc55cSDimitry Andric if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID)) 769349cc55cSDimitry Andric defReg(ID, CurBB, InstID); 770349cc55cSDimitry Andric } 771349cc55cSDimitry Andric Masks.push_back(std::make_pair(MO, InstID)); 772349cc55cSDimitry Andric } 773e8d8bef9SDimitry Andric 774*d56accc7SDimitry Andric Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) { 775349cc55cSDimitry Andric SpillLocationNo SpillID(SpillLocs.idFor(L)); 776*d56accc7SDimitry Andric 777349cc55cSDimitry Andric if (SpillID.id() == 0) { 778*d56accc7SDimitry Andric // If there is no location, and we have reached the limit of how many stack 779*d56accc7SDimitry Andric // slots to track, then don't track this one. 780*d56accc7SDimitry Andric if (SpillLocs.size() >= StackWorkingSetLimit) 781*d56accc7SDimitry Andric return None; 782*d56accc7SDimitry Andric 783349cc55cSDimitry Andric // Spill location is untracked: create record for this one, and all 784349cc55cSDimitry Andric // subregister slots too. 785349cc55cSDimitry Andric SpillID = SpillLocationNo(SpillLocs.insert(L)); 786349cc55cSDimitry Andric for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) { 787349cc55cSDimitry Andric unsigned L = getSpillIDWithIdx(SpillID, StackIdx); 788349cc55cSDimitry Andric LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx 789349cc55cSDimitry Andric LocIdxToIDNum.grow(Idx); 790349cc55cSDimitry Andric LocIdxToLocID.grow(Idx); 791349cc55cSDimitry Andric LocIDToLocIdx.push_back(Idx); 792349cc55cSDimitry Andric LocIdxToLocID[Idx] = L; 793349cc55cSDimitry Andric // Initialize to PHI value; corresponds to the location's live-in value 794349cc55cSDimitry Andric // during transfer function construction. 795349cc55cSDimitry Andric LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx); 796349cc55cSDimitry Andric } 797349cc55cSDimitry Andric } 798349cc55cSDimitry Andric return SpillID; 799349cc55cSDimitry Andric } 800fe6060f1SDimitry Andric 801349cc55cSDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const { 802349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Idx]; 803349cc55cSDimitry Andric if (ID >= NumRegs) { 804349cc55cSDimitry Andric StackSlotPos Pos = locIDToSpillIdx(ID); 805349cc55cSDimitry Andric ID -= NumRegs; 806349cc55cSDimitry Andric unsigned Slot = ID / NumSlotIdxes; 807349cc55cSDimitry Andric return Twine("slot ") 808349cc55cSDimitry Andric .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first) 809349cc55cSDimitry Andric .concat(Twine(" offs ").concat(Twine(Pos.second)))))) 810349cc55cSDimitry Andric .str(); 811349cc55cSDimitry Andric } else { 812349cc55cSDimitry Andric return TRI.getRegAsmName(ID).str(); 813349cc55cSDimitry Andric } 814349cc55cSDimitry Andric } 815fe6060f1SDimitry Andric 816349cc55cSDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const { 817349cc55cSDimitry Andric std::string DefName = LocIdxToName(Num.getLoc()); 818349cc55cSDimitry Andric return Num.asString(DefName); 819349cc55cSDimitry Andric } 820fe6060f1SDimitry Andric 821349cc55cSDimitry Andric #ifndef NDEBUG 822349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() { 823349cc55cSDimitry Andric for (auto Location : locations()) { 824349cc55cSDimitry Andric std::string MLocName = LocIdxToName(Location.Value.getLoc()); 825349cc55cSDimitry Andric std::string DefName = Location.Value.asString(MLocName); 826349cc55cSDimitry Andric dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; 827349cc55cSDimitry Andric } 828349cc55cSDimitry Andric } 829e8d8bef9SDimitry Andric 830349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() { 831349cc55cSDimitry Andric for (auto Location : locations()) { 832349cc55cSDimitry Andric std::string foo = LocIdxToName(Location.Idx); 833349cc55cSDimitry Andric dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; 834349cc55cSDimitry Andric } 835349cc55cSDimitry Andric } 836349cc55cSDimitry Andric #endif 837e8d8bef9SDimitry Andric 838349cc55cSDimitry Andric MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc, 839349cc55cSDimitry Andric const DebugVariable &Var, 840349cc55cSDimitry Andric const DbgValueProperties &Properties) { 841349cc55cSDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 842349cc55cSDimitry Andric Var.getVariable()->getScope(), 843349cc55cSDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 844349cc55cSDimitry Andric auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); 845e8d8bef9SDimitry Andric 846349cc55cSDimitry Andric const DIExpression *Expr = Properties.DIExpr; 847349cc55cSDimitry Andric if (!MLoc) { 848349cc55cSDimitry Andric // No location -> DBG_VALUE $noreg 849349cc55cSDimitry Andric MIB.addReg(0); 850349cc55cSDimitry Andric MIB.addReg(0); 851349cc55cSDimitry Andric } else if (LocIdxToLocID[*MLoc] >= NumRegs) { 852349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 853349cc55cSDimitry Andric SpillLocationNo SpillID = locIDToSpill(LocID); 854349cc55cSDimitry Andric StackSlotPos StackIdx = locIDToSpillIdx(LocID); 855349cc55cSDimitry Andric unsigned short Offset = StackIdx.second; 856e8d8bef9SDimitry Andric 857349cc55cSDimitry Andric // TODO: support variables that are located in spill slots, with non-zero 858349cc55cSDimitry Andric // offsets from the start of the spill slot. It would require some more 859349cc55cSDimitry Andric // complex DIExpression calculations. This doesn't seem to be produced by 860349cc55cSDimitry Andric // LLVM right now, so don't try and support it. 861349cc55cSDimitry Andric // Accept no-subregister slots and subregisters where the offset is zero. 862349cc55cSDimitry Andric // The consumer should already have type information to work out how large 863349cc55cSDimitry Andric // the variable is. 864349cc55cSDimitry Andric if (Offset == 0) { 865349cc55cSDimitry Andric const SpillLoc &Spill = SpillLocs[SpillID.id()]; 866349cc55cSDimitry Andric Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset, 867349cc55cSDimitry Andric Spill.SpillOffset); 868349cc55cSDimitry Andric unsigned Base = Spill.SpillBase; 869349cc55cSDimitry Andric MIB.addReg(Base); 870349cc55cSDimitry Andric MIB.addImm(0); 8714824e7fdSDimitry Andric 8724824e7fdSDimitry Andric // Being on the stack makes this location indirect; if it was _already_ 8734824e7fdSDimitry Andric // indirect though, we need to add extra indirection. See this test for 8744824e7fdSDimitry Andric // a scenario where this happens: 8754824e7fdSDimitry Andric // llvm/test/DebugInfo/X86/spill-nontrivial-param.ll 8764824e7fdSDimitry Andric if (Properties.Indirect) { 8774824e7fdSDimitry Andric std::vector<uint64_t> Elts = {dwarf::DW_OP_deref}; 8784824e7fdSDimitry Andric Expr = DIExpression::append(Expr, Elts); 8794824e7fdSDimitry Andric } 880349cc55cSDimitry Andric } else { 881349cc55cSDimitry Andric // This is a stack location with a weird subregister offset: emit an undef 882349cc55cSDimitry Andric // DBG_VALUE instead. 883349cc55cSDimitry Andric MIB.addReg(0); 884349cc55cSDimitry Andric MIB.addReg(0); 885349cc55cSDimitry Andric } 886349cc55cSDimitry Andric } else { 887349cc55cSDimitry Andric // Non-empty, non-stack slot, must be a plain register. 888349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 889349cc55cSDimitry Andric MIB.addReg(LocID); 890349cc55cSDimitry Andric if (Properties.Indirect) 891349cc55cSDimitry Andric MIB.addImm(0); 892349cc55cSDimitry Andric else 893349cc55cSDimitry Andric MIB.addReg(0); 894349cc55cSDimitry Andric } 895e8d8bef9SDimitry Andric 896349cc55cSDimitry Andric MIB.addMetadata(Var.getVariable()); 897349cc55cSDimitry Andric MIB.addMetadata(Expr); 898349cc55cSDimitry Andric return MIB; 899349cc55cSDimitry Andric } 900e8d8bef9SDimitry Andric 901e8d8bef9SDimitry Andric /// Default construct and initialize the pass. 902349cc55cSDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() {} 903e8d8bef9SDimitry Andric 904349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const { 905e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 906e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 907e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 908e8d8bef9SDimitry Andric return true; 909e8d8bef9SDimitry Andric return false; 910e8d8bef9SDimitry Andric } 911e8d8bef9SDimitry Andric 912e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 913e8d8bef9SDimitry Andric // Debug Range Extension Implementation 914e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 915e8d8bef9SDimitry Andric 916e8d8bef9SDimitry Andric #ifndef NDEBUG 917e8d8bef9SDimitry Andric // Something to restore in the future. 918e8d8bef9SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..) 919e8d8bef9SDimitry Andric #endif 920e8d8bef9SDimitry Andric 921*d56accc7SDimitry Andric Optional<SpillLocationNo> 922e8d8bef9SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 923e8d8bef9SDimitry Andric assert(MI.hasOneMemOperand() && 924e8d8bef9SDimitry Andric "Spill instruction does not have exactly one memory operand?"); 925e8d8bef9SDimitry Andric auto MMOI = MI.memoperands_begin(); 926e8d8bef9SDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 927e8d8bef9SDimitry Andric assert(PVal->kind() == PseudoSourceValue::FixedStack && 928e8d8bef9SDimitry Andric "Inconsistent memory operand in spill instruction"); 929e8d8bef9SDimitry Andric int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 930e8d8bef9SDimitry Andric const MachineBasicBlock *MBB = MI.getParent(); 931e8d8bef9SDimitry Andric Register Reg; 932e8d8bef9SDimitry Andric StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 933349cc55cSDimitry Andric return MTracker->getOrTrackSpillLoc({Reg, Offset}); 934349cc55cSDimitry Andric } 935349cc55cSDimitry Andric 936*d56accc7SDimitry Andric Optional<LocIdx> 937*d56accc7SDimitry Andric InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) { 938*d56accc7SDimitry Andric Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI); 939*d56accc7SDimitry Andric if (!SpillLoc) 940*d56accc7SDimitry Andric return None; 941349cc55cSDimitry Andric 942349cc55cSDimitry Andric // Where in the stack slot is this value defined -- i.e., what size of value 943349cc55cSDimitry Andric // is this? An important question, because it could be loaded into a register 944349cc55cSDimitry Andric // from the stack at some point. Happily the memory operand will tell us 945349cc55cSDimitry Andric // the size written to the stack. 946349cc55cSDimitry Andric auto *MemOperand = *MI.memoperands_begin(); 947349cc55cSDimitry Andric unsigned SizeInBits = MemOperand->getSizeInBits(); 948349cc55cSDimitry Andric 949349cc55cSDimitry Andric // Find that position in the stack indexes we're tracking. 950349cc55cSDimitry Andric auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0}); 951349cc55cSDimitry Andric if (IdxIt == MTracker->StackSlotIdxes.end()) 952349cc55cSDimitry Andric // That index is not tracked. This is suprising, and unlikely to ever 953349cc55cSDimitry Andric // occur, but the safe action is to indicate the variable is optimised out. 954349cc55cSDimitry Andric return None; 955349cc55cSDimitry Andric 956*d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second); 957349cc55cSDimitry Andric return MTracker->getSpillMLoc(SpillID); 958e8d8bef9SDimitry Andric } 959e8d8bef9SDimitry Andric 960e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI 961e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr. 962e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { 963e8d8bef9SDimitry Andric if (!MI.isDebugValue()) 964e8d8bef9SDimitry Andric return false; 965e8d8bef9SDimitry Andric 966e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 967e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 968e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 969e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 970e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 971e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 972e8d8bef9SDimitry Andric 973e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 974e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 975e8d8bef9SDimitry Andric 976e8d8bef9SDimitry Andric // If there are no instructions in this lexical scope, do no location tracking 977e8d8bef9SDimitry Andric // at all, this variable shouldn't get a legitimate location range. 978e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 979e8d8bef9SDimitry Andric if (Scope == nullptr) 980e8d8bef9SDimitry Andric return true; // handled it; by doing nothing 981e8d8bef9SDimitry Andric 982349cc55cSDimitry Andric // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to 983349cc55cSDimitry Andric // contribute to locations in this block, but don't propagate further. 984349cc55cSDimitry Andric // Interpret it like a DBG_VALUE $noreg. 985349cc55cSDimitry Andric if (MI.isDebugValueList()) { 986349cc55cSDimitry Andric if (VTracker) 987349cc55cSDimitry Andric VTracker->defVar(MI, Properties, None); 988349cc55cSDimitry Andric if (TTracker) 989349cc55cSDimitry Andric TTracker->redefVar(MI, Properties, None); 990349cc55cSDimitry Andric return true; 991349cc55cSDimitry Andric } 992349cc55cSDimitry Andric 993e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 994e8d8bef9SDimitry Andric 995e8d8bef9SDimitry Andric // MLocTracker needs to know that this register is read, even if it's only 996e8d8bef9SDimitry Andric // read by a debug inst. 997e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg() != 0) 998e8d8bef9SDimitry Andric (void)MTracker->readReg(MO.getReg()); 999e8d8bef9SDimitry Andric 1000e8d8bef9SDimitry Andric // If we're preparing for the second analysis (variables), the machine value 1001e8d8bef9SDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value 1002e8d8bef9SDimitry Andric // it refers to to VLocTracker. 1003e8d8bef9SDimitry Andric if (VTracker) { 1004e8d8bef9SDimitry Andric if (MO.isReg()) { 1005e8d8bef9SDimitry Andric // Feed defVar the new variable location, or if this is a 1006e8d8bef9SDimitry Andric // DBG_VALUE $noreg, feed defVar None. 1007e8d8bef9SDimitry Andric if (MO.getReg()) 1008e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); 1009e8d8bef9SDimitry Andric else 1010e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, None); 1011e8d8bef9SDimitry Andric } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || 1012e8d8bef9SDimitry Andric MI.getOperand(0).isCImm()) { 1013e8d8bef9SDimitry Andric VTracker->defVar(MI, MI.getOperand(0)); 1014e8d8bef9SDimitry Andric } 1015e8d8bef9SDimitry Andric } 1016e8d8bef9SDimitry Andric 1017e8d8bef9SDimitry Andric // If performing final tracking of transfers, report this variable definition 1018e8d8bef9SDimitry Andric // to the TransferTracker too. 1019e8d8bef9SDimitry Andric if (TTracker) 1020e8d8bef9SDimitry Andric TTracker->redefVar(MI); 1021e8d8bef9SDimitry Andric return true; 1022e8d8bef9SDimitry Andric } 1023e8d8bef9SDimitry Andric 1024fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, 1025fe6060f1SDimitry Andric ValueIDNum **MLiveOuts, 1026fe6060f1SDimitry Andric ValueIDNum **MLiveIns) { 1027e8d8bef9SDimitry Andric if (!MI.isDebugRef()) 1028e8d8bef9SDimitry Andric return false; 1029e8d8bef9SDimitry Andric 1030e8d8bef9SDimitry Andric // Only handle this instruction when we are building the variable value 1031e8d8bef9SDimitry Andric // transfer function. 1032*d56accc7SDimitry Andric if (!VTracker && !TTracker) 1033e8d8bef9SDimitry Andric return false; 1034e8d8bef9SDimitry Andric 1035e8d8bef9SDimitry Andric unsigned InstNo = MI.getOperand(0).getImm(); 1036e8d8bef9SDimitry Andric unsigned OpNo = MI.getOperand(1).getImm(); 1037e8d8bef9SDimitry Andric 1038e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 1039e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 1040e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 1041e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1042e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1043e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 1044e8d8bef9SDimitry Andric 1045e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 1046e8d8bef9SDimitry Andric 1047e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1048e8d8bef9SDimitry Andric if (Scope == nullptr) 1049e8d8bef9SDimitry Andric return true; // Handled by doing nothing. This variable is never in scope. 1050e8d8bef9SDimitry Andric 1051e8d8bef9SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent(); 1052e8d8bef9SDimitry Andric 1053e8d8bef9SDimitry Andric // Various optimizations may have happened to the value during codegen, 1054e8d8bef9SDimitry Andric // recorded in the value substitution table. Apply any substitutions to 1055fe6060f1SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect 1056fe6060f1SDimitry Andric // any subregister extractions performed during optimization. 1057fe6060f1SDimitry Andric 1058fe6060f1SDimitry Andric // Create dummy substitution with Src set, for lookup. 1059fe6060f1SDimitry Andric auto SoughtSub = 1060fe6060f1SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0); 1061fe6060f1SDimitry Andric 1062fe6060f1SDimitry Andric SmallVector<unsigned, 4> SeenSubregs; 1063fe6060f1SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1064fe6060f1SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() && 1065fe6060f1SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) { 1066fe6060f1SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest; 1067fe6060f1SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest; 1068fe6060f1SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg) 1069fe6060f1SDimitry Andric SeenSubregs.push_back(Subreg); 1070fe6060f1SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1071e8d8bef9SDimitry Andric } 1072e8d8bef9SDimitry Andric 1073e8d8bef9SDimitry Andric // Default machine value number is <None> -- if no instruction defines 1074e8d8bef9SDimitry Andric // the corresponding value, it must have been optimized out. 1075e8d8bef9SDimitry Andric Optional<ValueIDNum> NewID = None; 1076e8d8bef9SDimitry Andric 1077e8d8bef9SDimitry Andric // Try to lookup the instruction number, and find the machine value number 1078fe6060f1SDimitry Andric // that it defines. It could be an instruction, or a PHI. 1079e8d8bef9SDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo); 1080fe6060f1SDimitry Andric auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), 1081fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstNo); 1082e8d8bef9SDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) { 1083e8d8bef9SDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first; 1084e8d8bef9SDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber(); 1085e8d8bef9SDimitry Andric 1086349cc55cSDimitry Andric // Pick out the designated operand. It might be a memory reference, if 1087349cc55cSDimitry Andric // a register def was folded into a stack store. 1088349cc55cSDimitry Andric if (OpNo == MachineFunction::DebugOperandMemNumber && 1089349cc55cSDimitry Andric TargetInstr.hasOneMemOperand()) { 1090349cc55cSDimitry Andric Optional<LocIdx> L = findLocationForMemOperand(TargetInstr); 1091349cc55cSDimitry Andric if (L) 1092349cc55cSDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L); 1093349cc55cSDimitry Andric } else if (OpNo != MachineFunction::DebugOperandMemNumber) { 1094e8d8bef9SDimitry Andric assert(OpNo < TargetInstr.getNumOperands()); 1095e8d8bef9SDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo); 1096e8d8bef9SDimitry Andric 1097e8d8bef9SDimitry Andric // Today, this can only be a register. 1098e8d8bef9SDimitry Andric assert(MO.isReg() && MO.isDef()); 1099e8d8bef9SDimitry Andric 1100349cc55cSDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg()); 1101e8d8bef9SDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID]; 1102e8d8bef9SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); 1103349cc55cSDimitry Andric } 1104349cc55cSDimitry Andric // else: NewID is left as None. 1105fe6060f1SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { 1106fe6060f1SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use 1107fe6060f1SDimitry Andric // the resolver helper to find out. 1108fe6060f1SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, 1109fe6060f1SDimitry Andric MI, InstNo); 1110fe6060f1SDimitry Andric } 1111fe6060f1SDimitry Andric 1112fe6060f1SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code 1113fe6060f1SDimitry Andric // like this: 1114fe6060f1SDimitry Andric // CALL64 @foo, implicit-def $rax 1115fe6060f1SDimitry Andric // %0:gr64 = COPY $rax 1116fe6060f1SDimitry Andric // %1:gr32 = COPY %0.sub_32bit 1117fe6060f1SDimitry Andric // %2:gr16 = COPY %1.sub_16bit 1118fe6060f1SDimitry Andric // %3:gr8 = COPY %2.sub_8bit 1119fe6060f1SDimitry Andric // In which case each copy would have been recorded as a substitution with 1120fe6060f1SDimitry Andric // a subregister qualifier. Apply those qualifiers now. 1121fe6060f1SDimitry Andric if (NewID && !SeenSubregs.empty()) { 1122fe6060f1SDimitry Andric unsigned Offset = 0; 1123fe6060f1SDimitry Andric unsigned Size = 0; 1124fe6060f1SDimitry Andric 1125fe6060f1SDimitry Andric // Look at each subregister that we passed through, and progressively 1126fe6060f1SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should 1127fe6060f1SDimitry Andric // only ever be the same or narrower width than what they read from; 1128fe6060f1SDimitry Andric // iterate in reverse order so that we go from wide to small. 1129fe6060f1SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) { 1130fe6060f1SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg); 1131fe6060f1SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg); 1132fe6060f1SDimitry Andric Offset += ThisOffset; 1133fe6060f1SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize); 1134fe6060f1SDimitry Andric } 1135fe6060f1SDimitry Andric 1136fe6060f1SDimitry Andric // If that worked, look for an appropriate subregister with the register 1137fe6060f1SDimitry Andric // where the define happens. Don't look at values that were defined during 1138fe6060f1SDimitry Andric // a stack write: we can't currently express register locations within 1139fe6060f1SDimitry Andric // spills. 1140fe6060f1SDimitry Andric LocIdx L = NewID->getLoc(); 1141fe6060f1SDimitry Andric if (NewID && !MTracker->isSpill(L)) { 1142fe6060f1SDimitry Andric // Find the register class for the register where this def happened. 1143fe6060f1SDimitry Andric // FIXME: no index for this? 1144fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L]; 1145fe6060f1SDimitry Andric const TargetRegisterClass *TRC = nullptr; 1146fe6060f1SDimitry Andric for (auto *TRCI : TRI->regclasses()) 1147fe6060f1SDimitry Andric if (TRCI->contains(Reg)) 1148fe6060f1SDimitry Andric TRC = TRCI; 1149fe6060f1SDimitry Andric assert(TRC && "Couldn't find target register class?"); 1150fe6060f1SDimitry Andric 1151fe6060f1SDimitry Andric // If the register we have isn't the right size or in the right place, 1152fe6060f1SDimitry Andric // Try to find a subregister inside it. 1153fe6060f1SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC); 1154fe6060f1SDimitry Andric if (Size != MainRegSize || Offset) { 1155fe6060f1SDimitry Andric // Enumerate all subregisters, searching. 1156fe6060f1SDimitry Andric Register NewReg = 0; 1157fe6060f1SDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1158fe6060f1SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1159fe6060f1SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg); 1160fe6060f1SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg); 1161fe6060f1SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) { 1162fe6060f1SDimitry Andric NewReg = *SRI; 1163fe6060f1SDimitry Andric break; 1164fe6060f1SDimitry Andric } 1165fe6060f1SDimitry Andric } 1166fe6060f1SDimitry Andric 1167fe6060f1SDimitry Andric // If we didn't find anything: there's no way to express our value. 1168fe6060f1SDimitry Andric if (!NewReg) { 1169fe6060f1SDimitry Andric NewID = None; 1170fe6060f1SDimitry Andric } else { 1171fe6060f1SDimitry Andric // Re-state the value as being defined within the subregister 1172fe6060f1SDimitry Andric // that we found. 1173fe6060f1SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg); 1174fe6060f1SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc); 1175fe6060f1SDimitry Andric } 1176fe6060f1SDimitry Andric } 1177fe6060f1SDimitry Andric } else { 1178fe6060f1SDimitry Andric // If we can't handle subregisters, unset the new value. 1179fe6060f1SDimitry Andric NewID = None; 1180fe6060f1SDimitry Andric } 1181e8d8bef9SDimitry Andric } 1182e8d8bef9SDimitry Andric 1183e8d8bef9SDimitry Andric // We, we have a value number or None. Tell the variable value tracker about 1184e8d8bef9SDimitry Andric // it. The rest of this LiveDebugValues implementation acts exactly the same 1185e8d8bef9SDimitry Andric // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that 1186e8d8bef9SDimitry Andric // aren't immediately available). 1187e8d8bef9SDimitry Andric DbgValueProperties Properties(Expr, false); 1188*d56accc7SDimitry Andric if (VTracker) 1189e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, NewID); 1190e8d8bef9SDimitry Andric 1191e8d8bef9SDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF 1192e8d8bef9SDimitry Andric // into a plain DBG_VALUE. 1193e8d8bef9SDimitry Andric if (!TTracker) 1194e8d8bef9SDimitry Andric return true; 1195e8d8bef9SDimitry Andric 1196e8d8bef9SDimitry Andric // Pick a location for the machine value number, if such a location exists. 1197e8d8bef9SDimitry Andric // (This information could be stored in TransferTracker to make it faster). 1198e8d8bef9SDimitry Andric Optional<LocIdx> FoundLoc = None; 1199e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1200e8d8bef9SDimitry Andric LocIdx CurL = Location.Idx; 1201349cc55cSDimitry Andric ValueIDNum ID = MTracker->readMLoc(CurL); 1202e8d8bef9SDimitry Andric if (NewID && ID == NewID) { 1203e8d8bef9SDimitry Andric // If this is the first location with that value, pick it. Otherwise, 1204e8d8bef9SDimitry Andric // consider whether it's a "longer term" location. 1205e8d8bef9SDimitry Andric if (!FoundLoc) { 1206e8d8bef9SDimitry Andric FoundLoc = CurL; 1207e8d8bef9SDimitry Andric continue; 1208e8d8bef9SDimitry Andric } 1209e8d8bef9SDimitry Andric 1210e8d8bef9SDimitry Andric if (MTracker->isSpill(CurL)) 1211e8d8bef9SDimitry Andric FoundLoc = CurL; // Spills are a longer term location. 1212e8d8bef9SDimitry Andric else if (!MTracker->isSpill(*FoundLoc) && 1213e8d8bef9SDimitry Andric !MTracker->isSpill(CurL) && 1214e8d8bef9SDimitry Andric !isCalleeSaved(*FoundLoc) && 1215e8d8bef9SDimitry Andric isCalleeSaved(CurL)) 1216e8d8bef9SDimitry Andric FoundLoc = CurL; // Callee saved regs are longer term than normal. 1217e8d8bef9SDimitry Andric } 1218e8d8bef9SDimitry Andric } 1219e8d8bef9SDimitry Andric 1220e8d8bef9SDimitry Andric // Tell transfer tracker that the variable value has changed. 1221e8d8bef9SDimitry Andric TTracker->redefVar(MI, Properties, FoundLoc); 1222e8d8bef9SDimitry Andric 1223e8d8bef9SDimitry Andric // If there was a value with no location; but the value is defined in a 1224e8d8bef9SDimitry Andric // later instruction in this block, this is a block-local use-before-def. 1225e8d8bef9SDimitry Andric if (!FoundLoc && NewID && NewID->getBlock() == CurBB && 1226e8d8bef9SDimitry Andric NewID->getInst() > CurInst) 1227e8d8bef9SDimitry Andric TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); 1228e8d8bef9SDimitry Andric 1229e8d8bef9SDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. 1230e8d8bef9SDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if 1231e8d8bef9SDimitry Andric // FoundLoc is None. 1232e8d8bef9SDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future). 1233e8d8bef9SDimitry Andric MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); 1234e8d8bef9SDimitry Andric TTracker->PendingDbgValues.push_back(DbgMI); 1235e8d8bef9SDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr); 1236fe6060f1SDimitry Andric return true; 1237fe6060f1SDimitry Andric } 1238fe6060f1SDimitry Andric 1239fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { 1240fe6060f1SDimitry Andric if (!MI.isDebugPHI()) 1241fe6060f1SDimitry Andric return false; 1242fe6060f1SDimitry Andric 1243fe6060f1SDimitry Andric // Analyse these only when solving the machine value location problem. 1244fe6060f1SDimitry Andric if (VTracker || TTracker) 1245fe6060f1SDimitry Andric return true; 1246fe6060f1SDimitry Andric 1247fe6060f1SDimitry Andric // First operand is the value location, either a stack slot or register. 1248fe6060f1SDimitry Andric // Second is the debug instruction number of the original PHI. 1249fe6060f1SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 1250fe6060f1SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm(); 1251fe6060f1SDimitry Andric 1252fe6060f1SDimitry Andric if (MO.isReg()) { 1253fe6060f1SDimitry Andric // The value is whatever's currently in the register. Read and record it, 1254fe6060f1SDimitry Andric // to be analysed later. 1255fe6060f1SDimitry Andric Register Reg = MO.getReg(); 1256fe6060f1SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg); 1257fe6060f1SDimitry Andric auto PHIRec = DebugPHIRecord( 1258fe6060f1SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); 1259fe6060f1SDimitry Andric DebugPHINumToValue.push_back(PHIRec); 1260349cc55cSDimitry Andric 1261349cc55cSDimitry Andric // Ensure this register is tracked. 1262349cc55cSDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1263349cc55cSDimitry Andric MTracker->lookupOrTrackRegister(*RAI); 1264fe6060f1SDimitry Andric } else { 1265fe6060f1SDimitry Andric // The value is whatever's in this stack slot. 1266fe6060f1SDimitry Andric assert(MO.isFI()); 1267fe6060f1SDimitry Andric unsigned FI = MO.getIndex(); 1268fe6060f1SDimitry Andric 1269fe6060f1SDimitry Andric // If the stack slot is dead, then this was optimized away. 1270fe6060f1SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged. 1271fe6060f1SDimitry Andric if (MFI->isDeadObjectIndex(FI)) 1272fe6060f1SDimitry Andric return true; 1273fe6060f1SDimitry Andric 1274349cc55cSDimitry Andric // Identify this spill slot, ensure it's tracked. 1275fe6060f1SDimitry Andric Register Base; 1276fe6060f1SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); 1277fe6060f1SDimitry Andric SpillLoc SL = {Base, Offs}; 1278*d56accc7SDimitry Andric Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL); 1279*d56accc7SDimitry Andric 1280*d56accc7SDimitry Andric // We might be able to find a value, but have chosen not to, to avoid 1281*d56accc7SDimitry Andric // tracking too much stack information. 1282*d56accc7SDimitry Andric if (!SpillNo) 1283*d56accc7SDimitry Andric return true; 1284fe6060f1SDimitry Andric 1285349cc55cSDimitry Andric // Problem: what value should we extract from the stack? LLVM does not 1286349cc55cSDimitry Andric // record what size the last store to the slot was, and it would become 1287349cc55cSDimitry Andric // sketchy after stack slot colouring anyway. Take a look at what values 1288349cc55cSDimitry Andric // are stored on the stack, and pick the largest one that wasn't def'd 1289349cc55cSDimitry Andric // by a spill (i.e., the value most likely to have been def'd in a register 1290349cc55cSDimitry Andric // and then spilt. 1291349cc55cSDimitry Andric std::array<unsigned, 4> CandidateSizes = {64, 32, 16, 8}; 1292349cc55cSDimitry Andric Optional<ValueIDNum> Result = None; 1293349cc55cSDimitry Andric Optional<LocIdx> SpillLoc = None; 12940eae32dcSDimitry Andric for (unsigned CS : CandidateSizes) { 1295*d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*SpillNo, {CS, 0}); 1296349cc55cSDimitry Andric SpillLoc = MTracker->getSpillMLoc(SpillID); 1297349cc55cSDimitry Andric ValueIDNum Val = MTracker->readMLoc(*SpillLoc); 1298349cc55cSDimitry Andric // If this value was defined in it's own position, then it was probably 1299349cc55cSDimitry Andric // an aliasing index of a small value that was spilt. 1300349cc55cSDimitry Andric if (Val.getLoc() != SpillLoc->asU64()) { 1301349cc55cSDimitry Andric Result = Val; 1302349cc55cSDimitry Andric break; 1303349cc55cSDimitry Andric } 1304349cc55cSDimitry Andric } 1305349cc55cSDimitry Andric 1306349cc55cSDimitry Andric // If we didn't find anything, we're probably looking at a PHI, or a memory 1307349cc55cSDimitry Andric // store folded into an instruction. FIXME: Take a guess that's it's 64 1308349cc55cSDimitry Andric // bits. This isn't ideal, but tracking the size that the spill is 1309349cc55cSDimitry Andric // "supposed" to be is more complex, and benefits a small number of 1310349cc55cSDimitry Andric // locations. 1311349cc55cSDimitry Andric if (!Result) { 1312*d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*SpillNo, {64, 0}); 1313349cc55cSDimitry Andric SpillLoc = MTracker->getSpillMLoc(SpillID); 1314349cc55cSDimitry Andric Result = MTracker->readMLoc(*SpillLoc); 1315349cc55cSDimitry Andric } 1316fe6060f1SDimitry Andric 1317fe6060f1SDimitry Andric // Record this DBG_PHI for later analysis. 1318349cc55cSDimitry Andric auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), *Result, *SpillLoc}); 1319fe6060f1SDimitry Andric DebugPHINumToValue.push_back(DbgPHI); 1320fe6060f1SDimitry Andric } 1321e8d8bef9SDimitry Andric 1322e8d8bef9SDimitry Andric return true; 1323e8d8bef9SDimitry Andric } 1324e8d8bef9SDimitry Andric 1325e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { 1326e8d8bef9SDimitry Andric // Meta Instructions do not affect the debug liveness of any register they 1327e8d8bef9SDimitry Andric // define. 1328e8d8bef9SDimitry Andric if (MI.isImplicitDef()) { 1329e8d8bef9SDimitry Andric // Except when there's an implicit def, and the location it's defining has 1330e8d8bef9SDimitry Andric // no value number. The whole point of an implicit def is to announce that 1331e8d8bef9SDimitry Andric // the register is live, without be specific about it's value. So define 1332e8d8bef9SDimitry Andric // a value if there isn't one already. 1333e8d8bef9SDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); 1334e8d8bef9SDimitry Andric // Has a legitimate value -> ignore the implicit def. 1335e8d8bef9SDimitry Andric if (Num.getLoc() != 0) 1336e8d8bef9SDimitry Andric return; 1337e8d8bef9SDimitry Andric // Otherwise, def it here. 1338e8d8bef9SDimitry Andric } else if (MI.isMetaInstruction()) 1339e8d8bef9SDimitry Andric return; 1340e8d8bef9SDimitry Andric 13414824e7fdSDimitry Andric // We always ignore SP defines on call instructions, they don't actually 13424824e7fdSDimitry Andric // change the value of the stack pointer... except for win32's _chkstk. This 13434824e7fdSDimitry Andric // is rare: filter quickly for the common case (no stack adjustments, not a 13444824e7fdSDimitry Andric // call, etc). If it is a call that modifies SP, recognise the SP register 13454824e7fdSDimitry Andric // defs. 13464824e7fdSDimitry Andric bool CallChangesSP = false; 13474824e7fdSDimitry Andric if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() && 13484824e7fdSDimitry Andric !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data())) 13494824e7fdSDimitry Andric CallChangesSP = true; 13504824e7fdSDimitry Andric 13514824e7fdSDimitry Andric // Test whether we should ignore a def of this register due to it being part 13524824e7fdSDimitry Andric // of the stack pointer. 13534824e7fdSDimitry Andric auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool { 13544824e7fdSDimitry Andric if (CallChangesSP) 13554824e7fdSDimitry Andric return false; 13564824e7fdSDimitry Andric return MI.isCall() && MTracker->SPAliases.count(R); 13574824e7fdSDimitry Andric }; 13584824e7fdSDimitry Andric 1359e8d8bef9SDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs. 1360e8d8bef9SDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this 1361e8d8bef9SDimitry Andric // prevents fallback to std::set::count() operations. 1362e8d8bef9SDimitry Andric SmallSet<uint32_t, 32> DeadRegs; 1363e8d8bef9SDimitry Andric SmallVector<const uint32_t *, 4> RegMasks; 1364e8d8bef9SDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs; 1365e8d8bef9SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1366e8d8bef9SDimitry Andric // Determine whether the operand is a register def. 1367e8d8bef9SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() && 1368e8d8bef9SDimitry Andric Register::isPhysicalRegister(MO.getReg()) && 13694824e7fdSDimitry Andric !IgnoreSPAlias(MO.getReg())) { 1370e8d8bef9SDimitry Andric // Remove ranges of all aliased registers. 1371e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1372e8d8bef9SDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs? 1373e8d8bef9SDimitry Andric DeadRegs.insert(*RAI); 1374e8d8bef9SDimitry Andric } else if (MO.isRegMask()) { 1375e8d8bef9SDimitry Andric RegMasks.push_back(MO.getRegMask()); 1376e8d8bef9SDimitry Andric RegMaskPtrs.push_back(&MO); 1377e8d8bef9SDimitry Andric } 1378e8d8bef9SDimitry Andric } 1379e8d8bef9SDimitry Andric 1380e8d8bef9SDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise. 1381e8d8bef9SDimitry Andric for (uint32_t DeadReg : DeadRegs) 1382e8d8bef9SDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst); 1383e8d8bef9SDimitry Andric 1384e8d8bef9SDimitry Andric for (auto *MO : RegMaskPtrs) 1385e8d8bef9SDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst); 1386fe6060f1SDimitry Andric 1387349cc55cSDimitry Andric // If this instruction writes to a spill slot, def that slot. 1388349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1389*d56accc7SDimitry Andric if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1390349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1391*d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1392349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1393349cc55cSDimitry Andric MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L)); 1394349cc55cSDimitry Andric } 1395349cc55cSDimitry Andric } 1396*d56accc7SDimitry Andric } 1397349cc55cSDimitry Andric 1398fe6060f1SDimitry Andric if (!TTracker) 1399fe6060f1SDimitry Andric return; 1400fe6060f1SDimitry Andric 1401fe6060f1SDimitry Andric // When committing variable values to locations: tell transfer tracker that 1402fe6060f1SDimitry Andric // we've clobbered things. It may be able to recover the variable from a 1403fe6060f1SDimitry Andric // different location. 1404fe6060f1SDimitry Andric 1405fe6060f1SDimitry Andric // Inform TTracker about any direct clobbers. 1406fe6060f1SDimitry Andric for (uint32_t DeadReg : DeadRegs) { 1407fe6060f1SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); 1408fe6060f1SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false); 1409fe6060f1SDimitry Andric } 1410fe6060f1SDimitry Andric 1411fe6060f1SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations 1412fe6060f1SDimitry Andric // that are actually being tracked. 14131fd87a68SDimitry Andric if (!RegMaskPtrs.empty()) { 1414fe6060f1SDimitry Andric for (auto L : MTracker->locations()) { 1415fe6060f1SDimitry Andric // Stack locations can't be clobbered by regmasks. 1416fe6060f1SDimitry Andric if (MTracker->isSpill(L.Idx)) 1417fe6060f1SDimitry Andric continue; 1418fe6060f1SDimitry Andric 1419fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx]; 14204824e7fdSDimitry Andric if (IgnoreSPAlias(Reg)) 14214824e7fdSDimitry Andric continue; 14224824e7fdSDimitry Andric 1423fe6060f1SDimitry Andric for (auto *MO : RegMaskPtrs) 1424fe6060f1SDimitry Andric if (MO->clobbersPhysReg(Reg)) 1425fe6060f1SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false); 1426fe6060f1SDimitry Andric } 14271fd87a68SDimitry Andric } 1428349cc55cSDimitry Andric 1429349cc55cSDimitry Andric // Tell TTracker about any folded stack store. 1430349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1431*d56accc7SDimitry Andric if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1432349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1433*d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1434349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1435349cc55cSDimitry Andric TTracker->clobberMloc(L, MI.getIterator(), true); 1436349cc55cSDimitry Andric } 1437349cc55cSDimitry Andric } 1438e8d8bef9SDimitry Andric } 1439*d56accc7SDimitry Andric } 1440e8d8bef9SDimitry Andric 1441e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { 1442349cc55cSDimitry Andric // In all circumstances, re-def all aliases. It's definitely a new value now. 1443349cc55cSDimitry Andric for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI) 1444349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1445e8d8bef9SDimitry Andric 1446349cc55cSDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); 1447e8d8bef9SDimitry Andric MTracker->setReg(DstRegNum, SrcValue); 1448e8d8bef9SDimitry Andric 1449349cc55cSDimitry Andric // Copy subregisters from one location to another. 1450e8d8bef9SDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { 1451e8d8bef9SDimitry Andric unsigned SrcSubReg = SRI.getSubReg(); 1452e8d8bef9SDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex(); 1453e8d8bef9SDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); 1454e8d8bef9SDimitry Andric if (!DstSubReg) 1455e8d8bef9SDimitry Andric continue; 1456e8d8bef9SDimitry Andric 1457e8d8bef9SDimitry Andric // Do copy. There are two matching subregisters, the source value should 1458e8d8bef9SDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked 1459e8d8bef9SDimitry Andric // yet. 1460349cc55cSDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet. Will read 1461349cc55cSDimitry Andric // mphi values if it wasn't tracked. 1462349cc55cSDimitry Andric LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg); 1463349cc55cSDimitry Andric LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg); 1464349cc55cSDimitry Andric (void)SrcL; 1465e8d8bef9SDimitry Andric (void)DstL; 1466349cc55cSDimitry Andric ValueIDNum CpyValue = MTracker->readReg(SrcSubReg); 1467e8d8bef9SDimitry Andric 1468e8d8bef9SDimitry Andric MTracker->setReg(DstSubReg, CpyValue); 1469e8d8bef9SDimitry Andric } 1470e8d8bef9SDimitry Andric } 1471e8d8bef9SDimitry Andric 1472*d56accc7SDimitry Andric Optional<SpillLocationNo> 1473*d56accc7SDimitry Andric InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, 1474e8d8bef9SDimitry Andric MachineFunction *MF) { 1475e8d8bef9SDimitry Andric // TODO: Handle multiple stores folded into one. 1476e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1477*d56accc7SDimitry Andric return None; 1478e8d8bef9SDimitry Andric 1479349cc55cSDimitry Andric // Reject any memory operand that's aliased -- we can't guarantee its value. 1480349cc55cSDimitry Andric auto MMOI = MI.memoperands_begin(); 1481349cc55cSDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 1482349cc55cSDimitry Andric if (PVal->isAliased(MFI)) 1483*d56accc7SDimitry Andric return None; 1484349cc55cSDimitry Andric 1485e8d8bef9SDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 1486*d56accc7SDimitry Andric return None; // This is not a spill instruction, since no valid size was 1487e8d8bef9SDimitry Andric // returned from either function. 1488e8d8bef9SDimitry Andric 1489*d56accc7SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1490e8d8bef9SDimitry Andric } 1491e8d8bef9SDimitry Andric 1492e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, 1493e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1494e8d8bef9SDimitry Andric if (!isSpillInstruction(MI, MF)) 1495e8d8bef9SDimitry Andric return false; 1496e8d8bef9SDimitry Andric 1497e8d8bef9SDimitry Andric int FI; 1498e8d8bef9SDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI); 1499e8d8bef9SDimitry Andric return Reg != 0; 1500e8d8bef9SDimitry Andric } 1501e8d8bef9SDimitry Andric 1502349cc55cSDimitry Andric Optional<SpillLocationNo> 1503e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, 1504e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1505e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1506e8d8bef9SDimitry Andric return None; 1507e8d8bef9SDimitry Andric 1508e8d8bef9SDimitry Andric // FIXME: Handle folded restore instructions with more than one memory 1509e8d8bef9SDimitry Andric // operand. 1510e8d8bef9SDimitry Andric if (MI.getRestoreSize(TII)) { 1511e8d8bef9SDimitry Andric Reg = MI.getOperand(0).getReg(); 1512e8d8bef9SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1513e8d8bef9SDimitry Andric } 1514e8d8bef9SDimitry Andric return None; 1515e8d8bef9SDimitry Andric } 1516e8d8bef9SDimitry Andric 1517e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { 1518e8d8bef9SDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location 1519e8d8bef9SDimitry Andric // limitations under the new model. Therefore, when comparing them, compare 1520e8d8bef9SDimitry Andric // versions that don't attempt spills or restores at all. 1521e8d8bef9SDimitry Andric if (EmulateOldLDV) 1522e8d8bef9SDimitry Andric return false; 1523e8d8bef9SDimitry Andric 1524349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1525349cc55cSDimitry Andric // that can access the stack. 1526349cc55cSDimitry Andric int DummyFI = -1; 1527349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) && 1528349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, DummyFI)) 1529349cc55cSDimitry Andric return false; 1530349cc55cSDimitry Andric 1531e8d8bef9SDimitry Andric MachineFunction *MF = MI.getMF(); 1532e8d8bef9SDimitry Andric unsigned Reg; 1533e8d8bef9SDimitry Andric 1534e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 1535e8d8bef9SDimitry Andric 1536349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1537349cc55cSDimitry Andric // that can access the stack. 1538349cc55cSDimitry Andric int FIDummy; 1539349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) && 1540349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, FIDummy)) 1541349cc55cSDimitry Andric return false; 1542349cc55cSDimitry Andric 1543e8d8bef9SDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is 1544e8d8bef9SDimitry Andric // written to, terminate that variable location. The value in memory 1545e8d8bef9SDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. 1546*d56accc7SDimitry Andric if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) { 1547349cc55cSDimitry Andric // Un-set this location and clobber, so that earlier locations don't 1548349cc55cSDimitry Andric // continue past this store. 1549349cc55cSDimitry Andric for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) { 1550*d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx); 1551349cc55cSDimitry Andric Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID); 1552349cc55cSDimitry Andric if (!MLoc) 1553349cc55cSDimitry Andric continue; 1554349cc55cSDimitry Andric 1555349cc55cSDimitry Andric // We need to over-write the stack slot with something (here, a def at 1556349cc55cSDimitry Andric // this instruction) to ensure no values are preserved in this stack slot 1557349cc55cSDimitry Andric // after the spill. It also prevents TTracker from trying to recover the 1558349cc55cSDimitry Andric // location and re-installing it in the same place. 1559349cc55cSDimitry Andric ValueIDNum Def(CurBB, CurInst, *MLoc); 1560349cc55cSDimitry Andric MTracker->setMLoc(*MLoc, Def); 1561349cc55cSDimitry Andric if (TTracker) 1562e8d8bef9SDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator()); 1563e8d8bef9SDimitry Andric } 1564e8d8bef9SDimitry Andric } 1565e8d8bef9SDimitry Andric 1566e8d8bef9SDimitry Andric // Try to recognise spill and restore instructions that may transfer a value. 1567e8d8bef9SDimitry Andric if (isLocationSpill(MI, MF, Reg)) { 1568*d56accc7SDimitry Andric // isLocationSpill returning true should guarantee we can extract a 1569*d56accc7SDimitry Andric // location. 1570*d56accc7SDimitry Andric SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI); 1571e8d8bef9SDimitry Andric 1572349cc55cSDimitry Andric auto DoTransfer = [&](Register SrcReg, unsigned SpillID) { 1573349cc55cSDimitry Andric auto ReadValue = MTracker->readReg(SrcReg); 1574349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getSpillMLoc(SpillID); 1575349cc55cSDimitry Andric MTracker->setMLoc(DstLoc, ReadValue); 1576e8d8bef9SDimitry Andric 1577349cc55cSDimitry Andric if (TTracker) { 1578349cc55cSDimitry Andric LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg); 1579349cc55cSDimitry Andric TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator()); 1580e8d8bef9SDimitry Andric } 1581349cc55cSDimitry Andric }; 1582349cc55cSDimitry Andric 1583349cc55cSDimitry Andric // Then, transfer subreg bits. 1584349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1585349cc55cSDimitry Andric // Ensure this reg is tracked, 1586349cc55cSDimitry Andric (void)MTracker->lookupOrTrackRegister(*SRI); 1587349cc55cSDimitry Andric unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI); 1588349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, SubregIdx); 1589349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1590349cc55cSDimitry Andric } 1591349cc55cSDimitry Andric 1592349cc55cSDimitry Andric // Directly lookup size of main source reg, and transfer. 1593349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1594349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); 1595349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1596349cc55cSDimitry Andric } else { 1597*d56accc7SDimitry Andric Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg); 1598*d56accc7SDimitry Andric if (!Loc) 1599349cc55cSDimitry Andric return false; 1600349cc55cSDimitry Andric 1601349cc55cSDimitry Andric // Assumption: we're reading from the base of the stack slot, not some 1602349cc55cSDimitry Andric // offset into it. It seems very unlikely LLVM would ever generate 1603349cc55cSDimitry Andric // restores where this wasn't true. This then becomes a question of what 1604349cc55cSDimitry Andric // subregisters in the destination register line up with positions in the 1605349cc55cSDimitry Andric // stack slot. 1606349cc55cSDimitry Andric 1607349cc55cSDimitry Andric // Def all registers that alias the destination. 1608349cc55cSDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1609349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1610349cc55cSDimitry Andric 1611349cc55cSDimitry Andric // Now find subregisters within the destination register, and load values 1612349cc55cSDimitry Andric // from stack slot positions. 1613349cc55cSDimitry Andric auto DoTransfer = [&](Register DestReg, unsigned SpillID) { 1614349cc55cSDimitry Andric LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID); 1615349cc55cSDimitry Andric auto ReadValue = MTracker->readMLoc(SrcIdx); 1616349cc55cSDimitry Andric MTracker->setReg(DestReg, ReadValue); 1617349cc55cSDimitry Andric 1618349cc55cSDimitry Andric if (TTracker) { 1619349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getRegMLoc(DestReg); 1620349cc55cSDimitry Andric TTracker->transferMlocs(SrcIdx, DstLoc, MI.getIterator()); 1621349cc55cSDimitry Andric } 1622349cc55cSDimitry Andric }; 1623349cc55cSDimitry Andric 1624349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1625349cc55cSDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1626*d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, Subreg); 1627349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1628349cc55cSDimitry Andric } 1629349cc55cSDimitry Andric 1630349cc55cSDimitry Andric // Directly look up this registers slot idx by size, and transfer. 1631349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1632*d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0}); 1633349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1634e8d8bef9SDimitry Andric } 1635e8d8bef9SDimitry Andric return true; 1636e8d8bef9SDimitry Andric } 1637e8d8bef9SDimitry Andric 1638e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { 1639e8d8bef9SDimitry Andric auto DestSrc = TII->isCopyInstr(MI); 1640e8d8bef9SDimitry Andric if (!DestSrc) 1641e8d8bef9SDimitry Andric return false; 1642e8d8bef9SDimitry Andric 1643e8d8bef9SDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination; 1644e8d8bef9SDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source; 1645e8d8bef9SDimitry Andric 1646e8d8bef9SDimitry Andric auto isCalleeSavedReg = [&](unsigned Reg) { 1647e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1648e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 1649e8d8bef9SDimitry Andric return true; 1650e8d8bef9SDimitry Andric return false; 1651e8d8bef9SDimitry Andric }; 1652e8d8bef9SDimitry Andric 1653e8d8bef9SDimitry Andric Register SrcReg = SrcRegOp->getReg(); 1654e8d8bef9SDimitry Andric Register DestReg = DestRegOp->getReg(); 1655e8d8bef9SDimitry Andric 1656e8d8bef9SDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues. 1657e8d8bef9SDimitry Andric if (SrcReg == DestReg) 1658e8d8bef9SDimitry Andric return true; 1659e8d8bef9SDimitry Andric 1660e8d8bef9SDimitry Andric // For emulating VarLocBasedImpl: 1661e8d8bef9SDimitry Andric // We want to recognize instructions where destination register is callee 1662e8d8bef9SDimitry Andric // saved register. If register that could be clobbered by the call is 1663e8d8bef9SDimitry Andric // included, there would be a great chance that it is going to be clobbered 1664e8d8bef9SDimitry Andric // soon. It is more likely that previous register, which is callee saved, is 1665e8d8bef9SDimitry Andric // going to stay unclobbered longer, even if it is killed. 1666e8d8bef9SDimitry Andric // 1667e8d8bef9SDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so 1668e8d8bef9SDimitry Andric // ignore this condition. 1669e8d8bef9SDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) 1670e8d8bef9SDimitry Andric return false; 1671e8d8bef9SDimitry Andric 1672e8d8bef9SDimitry Andric // InstrRefBasedImpl only followed killing copies. 1673e8d8bef9SDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill()) 1674e8d8bef9SDimitry Andric return false; 1675e8d8bef9SDimitry Andric 1676e8d8bef9SDimitry Andric // Copy MTracker info, including subregs if available. 1677e8d8bef9SDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg); 1678e8d8bef9SDimitry Andric 1679e8d8bef9SDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV 1680e8d8bef9SDimitry Andric // would have. We might make use of the additional value tracking in some 1681e8d8bef9SDimitry Andric // other way, later. 1682e8d8bef9SDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) 1683e8d8bef9SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), 1684e8d8bef9SDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator()); 1685e8d8bef9SDimitry Andric 1686e8d8bef9SDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying. 1687e8d8bef9SDimitry Andric if (EmulateOldLDV && SrcReg != DestReg) 1688e8d8bef9SDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst); 1689e8d8bef9SDimitry Andric 1690fe6060f1SDimitry Andric // Finally, the copy might have clobbered variables based on the destination 1691fe6060f1SDimitry Andric // register. Tell TTracker about it, in case a backup location exists. 1692fe6060f1SDimitry Andric if (TTracker) { 1693fe6060f1SDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { 1694fe6060f1SDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); 1695fe6060f1SDimitry Andric TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false); 1696fe6060f1SDimitry Andric } 1697fe6060f1SDimitry Andric } 1698fe6060f1SDimitry Andric 1699e8d8bef9SDimitry Andric return true; 1700e8d8bef9SDimitry Andric } 1701e8d8bef9SDimitry Andric 1702e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other 1703e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during 1704e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the 1705e8d8bef9SDimitry Andric /// known-to-overlap fragments are present". 17064824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for 1707e8d8bef9SDimitry Andric /// fragment usage. 1708e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { 17094824e7fdSDimitry Andric assert(MI.isDebugValue() || MI.isDebugRef()); 1710e8d8bef9SDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 1711e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 1712e8d8bef9SDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 1713e8d8bef9SDimitry Andric 1714e8d8bef9SDimitry Andric // If this is the first sighting of this variable, then we are guaranteed 1715e8d8bef9SDimitry Andric // there are currently no overlapping fragments either. Initialize the set 1716e8d8bef9SDimitry Andric // of seen fragments, record no overlaps for the current one, and return. 1717e8d8bef9SDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable()); 1718e8d8bef9SDimitry Andric if (SeenIt == SeenFragments.end()) { 1719e8d8bef9SDimitry Andric SmallSet<FragmentInfo, 4> OneFragment; 1720e8d8bef9SDimitry Andric OneFragment.insert(ThisFragment); 1721e8d8bef9SDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment}); 1722e8d8bef9SDimitry Andric 1723e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1724e8d8bef9SDimitry Andric return; 1725e8d8bef9SDimitry Andric } 1726e8d8bef9SDimitry Andric 1727e8d8bef9SDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap 1728e8d8bef9SDimitry Andric // map, it has already been accounted for. 1729e8d8bef9SDimitry Andric auto IsInOLapMap = 1730e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1731e8d8bef9SDimitry Andric if (!IsInOLapMap.second) 1732e8d8bef9SDimitry Andric return; 1733e8d8bef9SDimitry Andric 1734e8d8bef9SDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 1735e8d8bef9SDimitry Andric auto &AllSeenFragments = SeenIt->second; 1736e8d8bef9SDimitry Andric 1737e8d8bef9SDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this" 1738e8d8bef9SDimitry Andric // fragment being a previously unseen fragment. Record any pair of 1739e8d8bef9SDimitry Andric // overlapping fragments. 1740e8d8bef9SDimitry Andric for (auto &ASeenFragment : AllSeenFragments) { 1741e8d8bef9SDimitry Andric // Does this previously seen fragment overlap? 1742e8d8bef9SDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 1743e8d8bef9SDimitry Andric // Yes: Mark the current fragment as being overlapped. 1744e8d8bef9SDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment); 1745e8d8bef9SDimitry Andric // Mark the previously seen fragment as being overlapped by the current 1746e8d8bef9SDimitry Andric // one. 1747e8d8bef9SDimitry Andric auto ASeenFragmentsOverlaps = 1748e8d8bef9SDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); 1749e8d8bef9SDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() && 1750e8d8bef9SDimitry Andric "Previously seen var fragment has no vector of overlaps"); 1751e8d8bef9SDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment); 1752e8d8bef9SDimitry Andric } 1753e8d8bef9SDimitry Andric } 1754e8d8bef9SDimitry Andric 1755e8d8bef9SDimitry Andric AllSeenFragments.insert(ThisFragment); 1756e8d8bef9SDimitry Andric } 1757e8d8bef9SDimitry Andric 1758fe6060f1SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, ValueIDNum **MLiveOuts, 1759fe6060f1SDimitry Andric ValueIDNum **MLiveIns) { 1760e8d8bef9SDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's 1761e8d8bef9SDimitry Andric // none of these should we interpret it's register defs as new value 1762e8d8bef9SDimitry Andric // definitions. 1763e8d8bef9SDimitry Andric if (transferDebugValue(MI)) 1764e8d8bef9SDimitry Andric return; 1765fe6060f1SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) 1766fe6060f1SDimitry Andric return; 1767fe6060f1SDimitry Andric if (transferDebugPHI(MI)) 1768e8d8bef9SDimitry Andric return; 1769e8d8bef9SDimitry Andric if (transferRegisterCopy(MI)) 1770e8d8bef9SDimitry Andric return; 1771e8d8bef9SDimitry Andric if (transferSpillOrRestoreInst(MI)) 1772e8d8bef9SDimitry Andric return; 1773e8d8bef9SDimitry Andric transferRegisterDef(MI); 1774e8d8bef9SDimitry Andric } 1775e8d8bef9SDimitry Andric 1776e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction( 1777e8d8bef9SDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, 1778e8d8bef9SDimitry Andric unsigned MaxNumBlocks) { 1779e8d8bef9SDimitry Andric // Because we try to optimize around register mask operands by ignoring regs 1780e8d8bef9SDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask 1781e8d8bef9SDimitry Andric // operands that are seen earlier than the first use of a register, still need 1782e8d8bef9SDimitry Andric // to clobber that register in the transfer function. But this information 1783e8d8bef9SDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block, 1784e8d8bef9SDimitry Andric // and accumulated the clobbered but untracked registers in each block into 1785e8d8bef9SDimitry Andric // the following bitvector. Later, if new values are tracked, we can add 1786e8d8bef9SDimitry Andric // appropriate clobbers. 1787e8d8bef9SDimitry Andric SmallVector<BitVector, 32> BlockMasks; 1788e8d8bef9SDimitry Andric BlockMasks.resize(MaxNumBlocks); 1789e8d8bef9SDimitry Andric 1790e8d8bef9SDimitry Andric // Reserve one bit per register for the masks described above. 1791e8d8bef9SDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); 1792e8d8bef9SDimitry Andric for (auto &BV : BlockMasks) 1793e8d8bef9SDimitry Andric BV.resize(TRI->getNumRegs(), true); 1794e8d8bef9SDimitry Andric 1795e8d8bef9SDimitry Andric // Step through all instructions and inhale the transfer function. 1796e8d8bef9SDimitry Andric for (auto &MBB : MF) { 1797e8d8bef9SDimitry Andric // Object fields that are read by trackers to know where we are in the 1798e8d8bef9SDimitry Andric // function. 1799e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 1800e8d8bef9SDimitry Andric CurInst = 1; 1801e8d8bef9SDimitry Andric 1802e8d8bef9SDimitry Andric // Set all machine locations to a PHI value. For transfer function 1803e8d8bef9SDimitry Andric // production only, this signifies the live-in value to the block. 1804e8d8bef9SDimitry Andric MTracker->reset(); 1805e8d8bef9SDimitry Andric MTracker->setMPhis(CurBB); 1806e8d8bef9SDimitry Andric 1807e8d8bef9SDimitry Andric // Step through each instruction in this block. 1808e8d8bef9SDimitry Andric for (auto &MI : MBB) { 1809e8d8bef9SDimitry Andric process(MI); 1810e8d8bef9SDimitry Andric // Also accumulate fragment map. 18114824e7fdSDimitry Andric if (MI.isDebugValue() || MI.isDebugRef()) 1812e8d8bef9SDimitry Andric accumulateFragmentMap(MI); 1813e8d8bef9SDimitry Andric 1814e8d8bef9SDimitry Andric // Create a map from the instruction number (if present) to the 1815e8d8bef9SDimitry Andric // MachineInstr and its position. 1816e8d8bef9SDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 1817e8d8bef9SDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst); 1818e8d8bef9SDimitry Andric auto InsertResult = 1819e8d8bef9SDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 1820e8d8bef9SDimitry Andric 1821e8d8bef9SDimitry Andric // There should never be duplicate instruction numbers. 1822e8d8bef9SDimitry Andric assert(InsertResult.second); 1823e8d8bef9SDimitry Andric (void)InsertResult; 1824e8d8bef9SDimitry Andric } 1825e8d8bef9SDimitry Andric 1826e8d8bef9SDimitry Andric ++CurInst; 1827e8d8bef9SDimitry Andric } 1828e8d8bef9SDimitry Andric 1829e8d8bef9SDimitry Andric // Produce the transfer function, a map of machine location to new value. If 1830e8d8bef9SDimitry Andric // any machine location has the live-in phi value from the start of the 1831e8d8bef9SDimitry Andric // block, it's live-through and doesn't need recording in the transfer 1832e8d8bef9SDimitry Andric // function. 1833e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1834e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1835e8d8bef9SDimitry Andric ValueIDNum &P = Location.Value; 1836e8d8bef9SDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64()) 1837e8d8bef9SDimitry Andric continue; 1838e8d8bef9SDimitry Andric 1839e8d8bef9SDimitry Andric // Insert-or-update. 1840e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[CurBB]; 1841e8d8bef9SDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 1842e8d8bef9SDimitry Andric if (!Result.second) 1843e8d8bef9SDimitry Andric Result.first->second = P; 1844e8d8bef9SDimitry Andric } 1845e8d8bef9SDimitry Andric 1846e8d8bef9SDimitry Andric // Accumulate any bitmask operands into the clobberred reg mask for this 1847e8d8bef9SDimitry Andric // block. 1848e8d8bef9SDimitry Andric for (auto &P : MTracker->Masks) { 1849e8d8bef9SDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 1850e8d8bef9SDimitry Andric } 1851e8d8bef9SDimitry Andric } 1852e8d8bef9SDimitry Andric 1853e8d8bef9SDimitry Andric // Compute a bitvector of all the registers that are tracked in this block. 1854e8d8bef9SDimitry Andric BitVector UsedRegs(TRI->getNumRegs()); 1855e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1856e8d8bef9SDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 1857349cc55cSDimitry Andric // Ignore stack slots, and aliases of the stack pointer. 1858349cc55cSDimitry Andric if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) 1859e8d8bef9SDimitry Andric continue; 1860e8d8bef9SDimitry Andric UsedRegs.set(ID); 1861e8d8bef9SDimitry Andric } 1862e8d8bef9SDimitry Andric 1863e8d8bef9SDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not 1864e8d8bef9SDimitry Andric // live-through in the transfer function. It needs to be clobbered at the 1865e8d8bef9SDimitry Andric // very least. 1866e8d8bef9SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 1867e8d8bef9SDimitry Andric BitVector &BV = BlockMasks[I]; 1868e8d8bef9SDimitry Andric BV.flip(); 1869e8d8bef9SDimitry Andric BV &= UsedRegs; 1870e8d8bef9SDimitry Andric // This produces all the bits that we clobber, but also use. Check that 1871e8d8bef9SDimitry Andric // they're all clobbered or at least set in the designated transfer 1872e8d8bef9SDimitry Andric // elem. 1873e8d8bef9SDimitry Andric for (unsigned Bit : BV.set_bits()) { 1874349cc55cSDimitry Andric unsigned ID = MTracker->getLocID(Bit); 1875e8d8bef9SDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 1876e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[I]; 1877e8d8bef9SDimitry Andric 1878e8d8bef9SDimitry Andric // Install a value representing the fact that this location is effectively 1879e8d8bef9SDimitry Andric // written to in this block. As there's no reserved value, instead use 1880e8d8bef9SDimitry Andric // a value number that is never generated. Pick the value number for the 1881e8d8bef9SDimitry Andric // first instruction in the block, def'ing this location, which we know 1882e8d8bef9SDimitry Andric // this block never used anyway. 1883e8d8bef9SDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 1884e8d8bef9SDimitry Andric auto Result = 1885e8d8bef9SDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 1886e8d8bef9SDimitry Andric if (!Result.second) { 1887e8d8bef9SDimitry Andric ValueIDNum &ValueID = Result.first->second; 1888e8d8bef9SDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI()) 1889e8d8bef9SDimitry Andric // It was left as live-through. Set it to clobbered. 1890e8d8bef9SDimitry Andric ValueID = NotGeneratedNum; 1891e8d8bef9SDimitry Andric } 1892e8d8bef9SDimitry Andric } 1893e8d8bef9SDimitry Andric } 1894e8d8bef9SDimitry Andric } 1895e8d8bef9SDimitry Andric 1896349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin( 1897349cc55cSDimitry Andric MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1898e8d8bef9SDimitry Andric ValueIDNum **OutLocs, ValueIDNum *InLocs) { 1899e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1900e8d8bef9SDimitry Andric bool Changed = false; 1901e8d8bef9SDimitry Andric 1902349cc55cSDimitry Andric // Handle value-propagation when control flow merges on entry to a block. For 1903349cc55cSDimitry Andric // any location without a PHI already placed, the location has the same value 1904349cc55cSDimitry Andric // as its predecessors. If a PHI is placed, test to see whether it's now a 1905349cc55cSDimitry Andric // redundant PHI that we can eliminate. 1906349cc55cSDimitry Andric 1907e8d8bef9SDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders; 1908349cc55cSDimitry Andric for (auto Pred : MBB.predecessors()) 1909e8d8bef9SDimitry Andric BlockOrders.push_back(Pred); 1910e8d8bef9SDimitry Andric 1911e8d8bef9SDimitry Andric // Visit predecessors in RPOT order. 1912e8d8bef9SDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1913e8d8bef9SDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 1914e8d8bef9SDimitry Andric }; 1915e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 1916e8d8bef9SDimitry Andric 1917e8d8bef9SDimitry Andric // Skip entry block. 1918e8d8bef9SDimitry Andric if (BlockOrders.size() == 0) 1919349cc55cSDimitry Andric return false; 1920e8d8bef9SDimitry Andric 1921349cc55cSDimitry Andric // Step through all machine locations, look at each predecessor and test 1922349cc55cSDimitry Andric // whether we can eliminate redundant PHIs. 1923e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1924e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1925349cc55cSDimitry Andric 1926e8d8bef9SDimitry Andric // Pick out the first predecessors live-out value for this location. It's 1927349cc55cSDimitry Andric // guaranteed to not be a backedge, as we order by RPO. 1928349cc55cSDimitry Andric ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 1929e8d8bef9SDimitry Andric 1930349cc55cSDimitry Andric // If we've already eliminated a PHI here, do no further checking, just 1931349cc55cSDimitry Andric // propagate the first live-in value into this block. 1932349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { 1933349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != FirstVal) { 1934349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 1935349cc55cSDimitry Andric Changed |= true; 1936349cc55cSDimitry Andric } 1937349cc55cSDimitry Andric continue; 1938349cc55cSDimitry Andric } 1939349cc55cSDimitry Andric 1940349cc55cSDimitry Andric // We're now examining a PHI to see whether it's un-necessary. Loop around 1941349cc55cSDimitry Andric // the other live-in values and test whether they're all the same. 1942e8d8bef9SDimitry Andric bool Disagree = false; 1943e8d8bef9SDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 1944349cc55cSDimitry Andric const MachineBasicBlock *PredMBB = BlockOrders[I]; 1945349cc55cSDimitry Andric const ValueIDNum &PredLiveOut = 1946349cc55cSDimitry Andric OutLocs[PredMBB->getNumber()][Idx.asU64()]; 1947349cc55cSDimitry Andric 1948349cc55cSDimitry Andric // Incoming values agree, continue trying to eliminate this PHI. 1949349cc55cSDimitry Andric if (FirstVal == PredLiveOut) 1950349cc55cSDimitry Andric continue; 1951349cc55cSDimitry Andric 1952349cc55cSDimitry Andric // We can also accept a PHI value that feeds back into itself. 1953349cc55cSDimitry Andric if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) 1954349cc55cSDimitry Andric continue; 1955349cc55cSDimitry Andric 1956e8d8bef9SDimitry Andric // Live-out of a predecessor disagrees with the first predecessor. 1957e8d8bef9SDimitry Andric Disagree = true; 1958e8d8bef9SDimitry Andric } 1959e8d8bef9SDimitry Andric 1960349cc55cSDimitry Andric // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. 1961349cc55cSDimitry Andric if (!Disagree) { 1962349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 1963e8d8bef9SDimitry Andric Changed |= true; 1964e8d8bef9SDimitry Andric } 1965e8d8bef9SDimitry Andric } 1966e8d8bef9SDimitry Andric 1967e8d8bef9SDimitry Andric // TODO: Reimplement NumInserted and NumRemoved. 1968349cc55cSDimitry Andric return Changed; 1969e8d8bef9SDimitry Andric } 1970e8d8bef9SDimitry Andric 1971349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference( 1972349cc55cSDimitry Andric SmallVectorImpl<unsigned> &Slots) { 1973349cc55cSDimitry Andric // We could spend a bit of time finding the exact, minimal, set of stack 1974349cc55cSDimitry Andric // indexes that interfere with each other, much like reg units. Or, we can 1975349cc55cSDimitry Andric // rely on the fact that: 1976349cc55cSDimitry Andric // * The smallest / lowest index will interfere with everything at zero 1977349cc55cSDimitry Andric // offset, which will be the largest set of registers, 1978349cc55cSDimitry Andric // * Most indexes with non-zero offset will end up being interference units 1979349cc55cSDimitry Andric // anyway. 1980349cc55cSDimitry Andric // So just pick those out and return them. 1981349cc55cSDimitry Andric 1982349cc55cSDimitry Andric // We can rely on a single-byte stack index existing already, because we 1983349cc55cSDimitry Andric // initialize them in MLocTracker. 1984349cc55cSDimitry Andric auto It = MTracker->StackSlotIdxes.find({8, 0}); 1985349cc55cSDimitry Andric assert(It != MTracker->StackSlotIdxes.end()); 1986349cc55cSDimitry Andric Slots.push_back(It->second); 1987349cc55cSDimitry Andric 1988349cc55cSDimitry Andric // Find anything that has a non-zero offset and add that too. 1989349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 1990349cc55cSDimitry Andric // Is offset zero? If so, ignore. 1991349cc55cSDimitry Andric if (!Pair.first.second) 1992349cc55cSDimitry Andric continue; 1993349cc55cSDimitry Andric Slots.push_back(Pair.second); 1994349cc55cSDimitry Andric } 1995349cc55cSDimitry Andric } 1996349cc55cSDimitry Andric 1997349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs( 1998349cc55cSDimitry Andric MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 1999349cc55cSDimitry Andric ValueIDNum **MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2000349cc55cSDimitry Andric SmallVector<unsigned, 4> StackUnits; 2001349cc55cSDimitry Andric findStackIndexInterference(StackUnits); 2002349cc55cSDimitry Andric 2003349cc55cSDimitry Andric // To avoid repeatedly running the PHI placement algorithm, leverage the 2004349cc55cSDimitry Andric // fact that a def of register MUST also def its register units. Find the 2005349cc55cSDimitry Andric // units for registers, place PHIs for them, and then replicate them for 2006349cc55cSDimitry Andric // aliasing registers. Some inputs that are never def'd (DBG_PHIs of 2007349cc55cSDimitry Andric // arguments) don't lead to register units being tracked, just place PHIs for 2008349cc55cSDimitry Andric // those registers directly. Stack slots have their own form of "unit", 2009349cc55cSDimitry Andric // store them to one side. 2010349cc55cSDimitry Andric SmallSet<Register, 32> RegUnitsToPHIUp; 2011349cc55cSDimitry Andric SmallSet<LocIdx, 32> NormalLocsToPHI; 2012349cc55cSDimitry Andric SmallSet<SpillLocationNo, 32> StackSlots; 2013349cc55cSDimitry Andric for (auto Location : MTracker->locations()) { 2014349cc55cSDimitry Andric LocIdx L = Location.Idx; 2015349cc55cSDimitry Andric if (MTracker->isSpill(L)) { 2016349cc55cSDimitry Andric StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); 2017349cc55cSDimitry Andric continue; 2018349cc55cSDimitry Andric } 2019349cc55cSDimitry Andric 2020349cc55cSDimitry Andric Register R = MTracker->LocIdxToLocID[L]; 2021349cc55cSDimitry Andric SmallSet<Register, 8> FoundRegUnits; 2022349cc55cSDimitry Andric bool AnyIllegal = false; 2023349cc55cSDimitry Andric for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { 2024349cc55cSDimitry Andric for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ 2025349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*URoot)) { 2026349cc55cSDimitry Andric // Not all roots were loaded into the tracking map: this register 2027349cc55cSDimitry Andric // isn't actually def'd anywhere, we only read from it. Generate PHIs 2028349cc55cSDimitry Andric // for this reg, but don't iterate units. 2029349cc55cSDimitry Andric AnyIllegal = true; 2030349cc55cSDimitry Andric } else { 2031349cc55cSDimitry Andric FoundRegUnits.insert(*URoot); 2032349cc55cSDimitry Andric } 2033349cc55cSDimitry Andric } 2034349cc55cSDimitry Andric } 2035349cc55cSDimitry Andric 2036349cc55cSDimitry Andric if (AnyIllegal) { 2037349cc55cSDimitry Andric NormalLocsToPHI.insert(L); 2038349cc55cSDimitry Andric continue; 2039349cc55cSDimitry Andric } 2040349cc55cSDimitry Andric 2041349cc55cSDimitry Andric RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); 2042349cc55cSDimitry Andric } 2043349cc55cSDimitry Andric 2044349cc55cSDimitry Andric // Lambda to fetch PHIs for a given location, and write into the PHIBlocks 2045349cc55cSDimitry Andric // collection. 2046349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2047349cc55cSDimitry Andric auto CollectPHIsForLoc = [&](LocIdx L) { 2048349cc55cSDimitry Andric // Collect the set of defs. 2049349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2050349cc55cSDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 2051349cc55cSDimitry Andric MachineBasicBlock *MBB = OrderToBB[I]; 2052349cc55cSDimitry Andric const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; 2053349cc55cSDimitry Andric if (TransferFunc.find(L) != TransferFunc.end()) 2054349cc55cSDimitry Andric DefBlocks.insert(MBB); 2055349cc55cSDimitry Andric } 2056349cc55cSDimitry Andric 2057349cc55cSDimitry Andric // The entry block defs the location too: it's the live-in / argument value. 2058349cc55cSDimitry Andric // Only insert if there are other defs though; everything is trivially live 2059349cc55cSDimitry Andric // through otherwise. 2060349cc55cSDimitry Andric if (!DefBlocks.empty()) 2061349cc55cSDimitry Andric DefBlocks.insert(&*MF.begin()); 2062349cc55cSDimitry Andric 2063349cc55cSDimitry Andric // Ask the SSA construction algorithm where we should put PHIs. Clear 2064349cc55cSDimitry Andric // anything that might have been hanging around from earlier. 2065349cc55cSDimitry Andric PHIBlocks.clear(); 2066349cc55cSDimitry Andric BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); 2067349cc55cSDimitry Andric }; 2068349cc55cSDimitry Andric 2069349cc55cSDimitry Andric auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { 2070349cc55cSDimitry Andric for (const MachineBasicBlock *MBB : PHIBlocks) 2071349cc55cSDimitry Andric MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); 2072349cc55cSDimitry Andric }; 2073349cc55cSDimitry Andric 2074349cc55cSDimitry Andric // For locations with no reg units, just place PHIs. 2075349cc55cSDimitry Andric for (LocIdx L : NormalLocsToPHI) { 2076349cc55cSDimitry Andric CollectPHIsForLoc(L); 2077349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2078349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2079349cc55cSDimitry Andric } 2080349cc55cSDimitry Andric 2081349cc55cSDimitry Andric // For stack slots, calculate PHIs for the equivalent of the units, then 2082349cc55cSDimitry Andric // install for each index. 2083349cc55cSDimitry Andric for (SpillLocationNo Slot : StackSlots) { 2084349cc55cSDimitry Andric for (unsigned Idx : StackUnits) { 2085349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); 2086349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 2087349cc55cSDimitry Andric CollectPHIsForLoc(L); 2088349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2089349cc55cSDimitry Andric 2090349cc55cSDimitry Andric // Find anything that aliases this stack index, install PHIs for it too. 2091349cc55cSDimitry Andric unsigned Size, Offset; 2092349cc55cSDimitry Andric std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; 2093349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 2094349cc55cSDimitry Andric unsigned ThisSize, ThisOffset; 2095349cc55cSDimitry Andric std::tie(ThisSize, ThisOffset) = Pair.first; 2096349cc55cSDimitry Andric if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) 2097349cc55cSDimitry Andric continue; 2098349cc55cSDimitry Andric 2099349cc55cSDimitry Andric unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); 2100349cc55cSDimitry Andric LocIdx ThisL = MTracker->getSpillMLoc(ThisID); 2101349cc55cSDimitry Andric InstallPHIsAtLoc(ThisL); 2102349cc55cSDimitry Andric } 2103349cc55cSDimitry Andric } 2104349cc55cSDimitry Andric } 2105349cc55cSDimitry Andric 2106349cc55cSDimitry Andric // For reg units, place PHIs, and then place them for any aliasing registers. 2107349cc55cSDimitry Andric for (Register R : RegUnitsToPHIUp) { 2108349cc55cSDimitry Andric LocIdx L = MTracker->lookupOrTrackRegister(R); 2109349cc55cSDimitry Andric CollectPHIsForLoc(L); 2110349cc55cSDimitry Andric 2111349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2112349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2113349cc55cSDimitry Andric 2114349cc55cSDimitry Andric // Now find aliases and install PHIs for those. 2115349cc55cSDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { 2116349cc55cSDimitry Andric // Super-registers that are "above" the largest register read/written by 2117349cc55cSDimitry Andric // the function will alias, but will not be tracked. 2118349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*RAI)) 2119349cc55cSDimitry Andric continue; 2120349cc55cSDimitry Andric 2121349cc55cSDimitry Andric LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); 2122349cc55cSDimitry Andric InstallPHIsAtLoc(AliasLoc); 2123349cc55cSDimitry Andric } 2124349cc55cSDimitry Andric } 2125349cc55cSDimitry Andric } 2126349cc55cSDimitry Andric 2127349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap( 2128349cc55cSDimitry Andric MachineFunction &MF, ValueIDNum **MInLocs, ValueIDNum **MOutLocs, 2129e8d8bef9SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2130e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2131e8d8bef9SDimitry Andric std::greater<unsigned int>> 2132e8d8bef9SDimitry Andric Worklist, Pending; 2133e8d8bef9SDimitry Andric 2134e8d8bef9SDimitry Andric // We track what is on the current and pending worklist to avoid inserting 2135e8d8bef9SDimitry Andric // the same thing twice. We could avoid this with a custom priority queue, 2136e8d8bef9SDimitry Andric // but this is probably not worth it. 2137e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2138e8d8bef9SDimitry Andric 2139349cc55cSDimitry Andric // Initialize worklist with every block to be visited. Also produce list of 2140349cc55cSDimitry Andric // all blocks. 2141349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; 2142e8d8bef9SDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2143e8d8bef9SDimitry Andric Worklist.push(I); 2144e8d8bef9SDimitry Andric OnWorklist.insert(OrderToBB[I]); 2145349cc55cSDimitry Andric AllBlocks.insert(OrderToBB[I]); 2146e8d8bef9SDimitry Andric } 2147e8d8bef9SDimitry Andric 2148349cc55cSDimitry Andric // Initialize entry block to PHIs. These represent arguments. 2149349cc55cSDimitry Andric for (auto Location : MTracker->locations()) 2150349cc55cSDimitry Andric MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); 2151349cc55cSDimitry Andric 2152e8d8bef9SDimitry Andric MTracker->reset(); 2153e8d8bef9SDimitry Andric 2154349cc55cSDimitry Andric // Start by placing PHIs, using the usual SSA constructor algorithm. Consider 2155349cc55cSDimitry Andric // any machine-location that isn't live-through a block to be def'd in that 2156349cc55cSDimitry Andric // block. 2157349cc55cSDimitry Andric placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); 2158e8d8bef9SDimitry Andric 2159349cc55cSDimitry Andric // Propagate values to eliminate redundant PHIs. At the same time, this 2160349cc55cSDimitry Andric // produces the table of Block x Location => Value for the entry to each 2161349cc55cSDimitry Andric // block. 2162349cc55cSDimitry Andric // The kind of PHIs we can eliminate are, for example, where one path in a 2163349cc55cSDimitry Andric // conditional spills and restores a register, and the register still has 2164349cc55cSDimitry Andric // the same value once control flow joins, unbeknowns to the PHI placement 2165349cc55cSDimitry Andric // code. Propagating values allows us to identify such un-necessary PHIs and 2166349cc55cSDimitry Andric // remove them. 2167e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2168e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2169e8d8bef9SDimitry Andric // Vector for storing the evaluated block transfer function. 2170e8d8bef9SDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2171e8d8bef9SDimitry Andric 2172e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2173e8d8bef9SDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2174e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2175e8d8bef9SDimitry Andric Worklist.pop(); 2176e8d8bef9SDimitry Andric 2177e8d8bef9SDimitry Andric // Join the values in all predecessor blocks. 2178349cc55cSDimitry Andric bool InLocsChanged; 2179349cc55cSDimitry Andric InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2180e8d8bef9SDimitry Andric InLocsChanged |= Visited.insert(MBB).second; 2181e8d8bef9SDimitry Andric 2182e8d8bef9SDimitry Andric // Don't examine transfer function if we've visited this loc at least 2183e8d8bef9SDimitry Andric // once, and inlocs haven't changed. 2184e8d8bef9SDimitry Andric if (!InLocsChanged) 2185e8d8bef9SDimitry Andric continue; 2186e8d8bef9SDimitry Andric 2187e8d8bef9SDimitry Andric // Load the current set of live-ins into MLocTracker. 2188e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2189e8d8bef9SDimitry Andric 2190e8d8bef9SDimitry Andric // Each element of the transfer function can be a new def, or a read of 2191e8d8bef9SDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap". 2192e8d8bef9SDimitry Andric ToRemap.clear(); 2193e8d8bef9SDimitry Andric for (auto &P : MLocTransfer[CurBB]) { 2194e8d8bef9SDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2195e8d8bef9SDimitry Andric // This is a movement of whatever was live in. Read it. 2196349cc55cSDimitry Andric ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); 2197e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID)); 2198e8d8bef9SDimitry Andric } else { 2199e8d8bef9SDimitry Andric // It's a def. Just set it. 2200e8d8bef9SDimitry Andric assert(P.second.getBlock() == CurBB); 2201e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second)); 2202e8d8bef9SDimitry Andric } 2203e8d8bef9SDimitry Andric } 2204e8d8bef9SDimitry Andric 2205e8d8bef9SDimitry Andric // Commit the transfer function changes into mloc tracker, which 2206e8d8bef9SDimitry Andric // transforms the contents of the MLocTracker into the live-outs. 2207e8d8bef9SDimitry Andric for (auto &P : ToRemap) 2208e8d8bef9SDimitry Andric MTracker->setMLoc(P.first, P.second); 2209e8d8bef9SDimitry Andric 2210e8d8bef9SDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking 2211e8d8bef9SDimitry Andric // whether changes have occurred. These changes can have come from both 2212e8d8bef9SDimitry Andric // the transfer function, and mlocJoin. 2213e8d8bef9SDimitry Andric bool OLChanged = false; 2214e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 2215e8d8bef9SDimitry Andric OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2216e8d8bef9SDimitry Andric MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2217e8d8bef9SDimitry Andric } 2218e8d8bef9SDimitry Andric 2219e8d8bef9SDimitry Andric MTracker->reset(); 2220e8d8bef9SDimitry Andric 2221e8d8bef9SDimitry Andric // No need to examine successors again if out-locs didn't change. 2222e8d8bef9SDimitry Andric if (!OLChanged) 2223e8d8bef9SDimitry Andric continue; 2224e8d8bef9SDimitry Andric 2225e8d8bef9SDimitry Andric // All successors should be visited: put any back-edges on the pending 2226349cc55cSDimitry Andric // list for the next pass-through, and any other successors to be 2227349cc55cSDimitry Andric // visited this pass, if they're not going to be already. 2228e8d8bef9SDimitry Andric for (auto s : MBB->successors()) { 2229e8d8bef9SDimitry Andric // Does branching to this successor represent a back-edge? 2230e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2231e8d8bef9SDimitry Andric // No: visit it during this dataflow iteration. 2232e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2233e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2234e8d8bef9SDimitry Andric } else { 2235e8d8bef9SDimitry Andric // Yes: visit it on the next iteration. 2236e8d8bef9SDimitry Andric if (OnPending.insert(s).second) 2237e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2238e8d8bef9SDimitry Andric } 2239e8d8bef9SDimitry Andric } 2240e8d8bef9SDimitry Andric } 2241e8d8bef9SDimitry Andric 2242e8d8bef9SDimitry Andric Worklist.swap(Pending); 2243e8d8bef9SDimitry Andric std::swap(OnPending, OnWorklist); 2244e8d8bef9SDimitry Andric OnPending.clear(); 2245e8d8bef9SDimitry Andric // At this point, pending must be empty, since it was just the empty 2246e8d8bef9SDimitry Andric // worklist 2247e8d8bef9SDimitry Andric assert(Pending.empty() && "Pending should be empty"); 2248e8d8bef9SDimitry Andric } 2249e8d8bef9SDimitry Andric 2250349cc55cSDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've eliminated all 2251349cc55cSDimitry Andric // redundant PHIs. 2252e8d8bef9SDimitry Andric } 2253e8d8bef9SDimitry Andric 2254349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement( 2255349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2256349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 2257349cc55cSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { 2258349cc55cSDimitry Andric // Apply IDF calculator to the designated set of location defs, storing 2259349cc55cSDimitry Andric // required PHIs into PHIBlocks. Uses the dominator tree stored in the 2260349cc55cSDimitry Andric // InstrRefBasedLDV object. 22611fd87a68SDimitry Andric IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase()); 2262349cc55cSDimitry Andric 2263349cc55cSDimitry Andric IDF.setLiveInBlocks(AllBlocks); 2264349cc55cSDimitry Andric IDF.setDefiningBlocks(DefBlocks); 2265349cc55cSDimitry Andric IDF.calculate(PHIBlocks); 2266e8d8bef9SDimitry Andric } 2267e8d8bef9SDimitry Andric 2268349cc55cSDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( 2269349cc55cSDimitry Andric const MachineBasicBlock &MBB, const DebugVariable &Var, 2270349cc55cSDimitry Andric const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 2271349cc55cSDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { 2272e8d8bef9SDimitry Andric // Collect a set of locations from predecessor where its live-out value can 2273e8d8bef9SDimitry Andric // be found. 2274e8d8bef9SDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2275349cc55cSDimitry Andric SmallVector<const DbgValueProperties *, 4> Properties; 2276e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2277349cc55cSDimitry Andric 2278349cc55cSDimitry Andric // No predecessors means no PHIs. 2279349cc55cSDimitry Andric if (BlockOrders.empty()) 2280349cc55cSDimitry Andric return None; 2281e8d8bef9SDimitry Andric 2282e8d8bef9SDimitry Andric for (auto p : BlockOrders) { 2283e8d8bef9SDimitry Andric unsigned ThisBBNum = p->getNumber(); 2284349cc55cSDimitry Andric auto OutValIt = LiveOuts.find(p); 2285349cc55cSDimitry Andric if (OutValIt == LiveOuts.end()) 2286349cc55cSDimitry Andric // If we have a predecessor not in scope, we'll never find a PHI position. 2287349cc55cSDimitry Andric return None; 2288349cc55cSDimitry Andric const DbgValue &OutVal = *OutValIt->second; 2289e8d8bef9SDimitry Andric 2290e8d8bef9SDimitry Andric if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2291e8d8bef9SDimitry Andric // Consts and no-values cannot have locations we can join on. 2292349cc55cSDimitry Andric return None; 2293e8d8bef9SDimitry Andric 2294349cc55cSDimitry Andric Properties.push_back(&OutVal.Properties); 2295349cc55cSDimitry Andric 2296349cc55cSDimitry Andric // Create new empty vector of locations. 2297349cc55cSDimitry Andric Locs.resize(Locs.size() + 1); 2298349cc55cSDimitry Andric 2299349cc55cSDimitry Andric // If the live-in value is a def, find the locations where that value is 2300349cc55cSDimitry Andric // present. Do the same for VPHIs where we know the VPHI value. 2301349cc55cSDimitry Andric if (OutVal.Kind == DbgValue::Def || 2302349cc55cSDimitry Andric (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && 2303349cc55cSDimitry Andric OutVal.ID != ValueIDNum::EmptyValue)) { 2304e8d8bef9SDimitry Andric ValueIDNum ValToLookFor = OutVal.ID; 2305e8d8bef9SDimitry Andric // Search the live-outs of the predecessor for the specified value. 2306e8d8bef9SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2307e8d8bef9SDimitry Andric if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2308e8d8bef9SDimitry Andric Locs.back().push_back(LocIdx(I)); 2309e8d8bef9SDimitry Andric } 2310349cc55cSDimitry Andric } else { 2311349cc55cSDimitry Andric assert(OutVal.Kind == DbgValue::VPHI); 2312349cc55cSDimitry Andric // For VPHIs where we don't know the location, we definitely can't find 2313349cc55cSDimitry Andric // a join loc. 2314349cc55cSDimitry Andric if (OutVal.BlockNo != MBB.getNumber()) 2315349cc55cSDimitry Andric return None; 2316349cc55cSDimitry Andric 2317349cc55cSDimitry Andric // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. 2318349cc55cSDimitry Andric // a value that's live-through the whole loop. (It has to be a backedge, 2319349cc55cSDimitry Andric // because a block can't dominate itself). We can accept as a PHI location 2320349cc55cSDimitry Andric // any location where the other predecessors agree, _and_ the machine 2321349cc55cSDimitry Andric // locations feed back into themselves. Therefore, add all self-looping 2322349cc55cSDimitry Andric // machine-value PHI locations. 2323349cc55cSDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2324349cc55cSDimitry Andric ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); 2325349cc55cSDimitry Andric if (MOutLocs[ThisBBNum][I] == MPHI) 2326349cc55cSDimitry Andric Locs.back().push_back(LocIdx(I)); 2327349cc55cSDimitry Andric } 2328349cc55cSDimitry Andric } 2329e8d8bef9SDimitry Andric } 2330e8d8bef9SDimitry Andric 2331349cc55cSDimitry Andric // We should have found locations for all predecessors, or returned. 2332349cc55cSDimitry Andric assert(Locs.size() == BlockOrders.size()); 2333e8d8bef9SDimitry Andric 2334349cc55cSDimitry Andric // Check that all properties are the same. We can't pick a location if they're 2335349cc55cSDimitry Andric // not. 2336349cc55cSDimitry Andric const DbgValueProperties *Properties0 = Properties[0]; 2337349cc55cSDimitry Andric for (auto *Prop : Properties) 2338349cc55cSDimitry Andric if (*Prop != *Properties0) 2339349cc55cSDimitry Andric return None; 2340349cc55cSDimitry Andric 2341e8d8bef9SDimitry Andric // Starting with the first set of locations, take the intersection with 2342e8d8bef9SDimitry Andric // subsequent sets. 2343349cc55cSDimitry Andric SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; 2344349cc55cSDimitry Andric for (unsigned int I = 1; I < Locs.size(); ++I) { 2345349cc55cSDimitry Andric auto &LocVec = Locs[I]; 2346349cc55cSDimitry Andric SmallVector<LocIdx, 4> NewCandidates; 2347349cc55cSDimitry Andric std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), 2348349cc55cSDimitry Andric LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); 2349349cc55cSDimitry Andric CandidateLocs = NewCandidates; 2350e8d8bef9SDimitry Andric } 2351349cc55cSDimitry Andric if (CandidateLocs.empty()) 2352e8d8bef9SDimitry Andric return None; 2353e8d8bef9SDimitry Andric 2354e8d8bef9SDimitry Andric // We now have a set of LocIdxes that contain the right output value in 2355e8d8bef9SDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc, 2356e8d8bef9SDimitry Andric // that'll be it. 2357349cc55cSDimitry Andric LocIdx L = *CandidateLocs.begin(); 2358e8d8bef9SDimitry Andric 2359e8d8bef9SDimitry Andric // Return a PHI-value-number for the found location. 2360e8d8bef9SDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2361349cc55cSDimitry Andric return PHIVal; 2362e8d8bef9SDimitry Andric } 2363e8d8bef9SDimitry Andric 2364349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin( 2365349cc55cSDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 2366e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2367349cc55cSDimitry Andric DbgValue &LiveIn) { 2368e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2369e8d8bef9SDimitry Andric bool Changed = false; 2370e8d8bef9SDimitry Andric 2371e8d8bef9SDimitry Andric // Order predecessors by RPOT order, for exploring them in that order. 2372fe6060f1SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2373e8d8bef9SDimitry Andric 2374e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2375e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2376e8d8bef9SDimitry Andric }; 2377e8d8bef9SDimitry Andric 2378e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2379e8d8bef9SDimitry Andric 2380e8d8bef9SDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB]; 2381e8d8bef9SDimitry Andric 2382349cc55cSDimitry Andric // Collect all the incoming DbgValues for this variable, from predecessor 2383349cc55cSDimitry Andric // live-out values. 2384e8d8bef9SDimitry Andric SmallVector<InValueT, 8> Values; 2385e8d8bef9SDimitry Andric bool Bail = false; 2386349cc55cSDimitry Andric int BackEdgesStart = 0; 2387e8d8bef9SDimitry Andric for (auto p : BlockOrders) { 2388e8d8bef9SDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be 2389e8d8bef9SDimitry Andric // able to join any locations. 2390e8d8bef9SDimitry Andric if (!BlocksToExplore.contains(p)) { 2391e8d8bef9SDimitry Andric Bail = true; 2392e8d8bef9SDimitry Andric break; 2393e8d8bef9SDimitry Andric } 2394e8d8bef9SDimitry Andric 2395349cc55cSDimitry Andric // All Live-outs will have been initialized. 2396349cc55cSDimitry Andric DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; 2397e8d8bef9SDimitry Andric 2398e8d8bef9SDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on 2399e8d8bef9SDimitry Andric // BlockOrders being sorted by RPO. 2400e8d8bef9SDimitry Andric unsigned ThisBBRPONum = BBToOrder[p]; 2401e8d8bef9SDimitry Andric if (ThisBBRPONum < CurBlockRPONum) 2402e8d8bef9SDimitry Andric ++BackEdgesStart; 2403e8d8bef9SDimitry Andric 2404349cc55cSDimitry Andric Values.push_back(std::make_pair(p, &OutLoc)); 2405e8d8bef9SDimitry Andric } 2406e8d8bef9SDimitry Andric 2407e8d8bef9SDimitry Andric // If there were no values, or one of the predecessors couldn't have a 2408e8d8bef9SDimitry Andric // value, then give up immediately. It's not safe to produce a live-in 2409349cc55cSDimitry Andric // value. Leave as whatever it was before. 2410e8d8bef9SDimitry Andric if (Bail || Values.size() == 0) 2411349cc55cSDimitry Andric return false; 2412e8d8bef9SDimitry Andric 2413e8d8bef9SDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor. 2414e8d8bef9SDimitry Andric // Pick the variable value from the first of these, to compare against 2415e8d8bef9SDimitry Andric // all others. 2416e8d8bef9SDimitry Andric const DbgValue &FirstVal = *Values[0].second; 2417e8d8bef9SDimitry Andric 2418349cc55cSDimitry Andric // If the old live-in value is not a PHI then either a) no PHI is needed 2419349cc55cSDimitry Andric // here, or b) we eliminated the PHI that was here. If so, we can just 2420349cc55cSDimitry Andric // propagate in the first parent's incoming value. 2421349cc55cSDimitry Andric if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { 2422349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2423349cc55cSDimitry Andric if (Changed) 2424349cc55cSDimitry Andric LiveIn = FirstVal; 2425349cc55cSDimitry Andric return Changed; 2426349cc55cSDimitry Andric } 2427349cc55cSDimitry Andric 2428349cc55cSDimitry Andric // Scan for variable values that can never be resolved: if they have 2429349cc55cSDimitry Andric // different DIExpressions, different indirectness, or are mixed constants / 2430e8d8bef9SDimitry Andric // non-constants. 2431e8d8bef9SDimitry Andric for (auto &V : Values) { 2432e8d8bef9SDimitry Andric if (V.second->Properties != FirstVal.Properties) 2433349cc55cSDimitry Andric return false; 2434349cc55cSDimitry Andric if (V.second->Kind == DbgValue::NoVal) 2435349cc55cSDimitry Andric return false; 2436e8d8bef9SDimitry Andric if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 2437349cc55cSDimitry Andric return false; 2438e8d8bef9SDimitry Andric } 2439e8d8bef9SDimitry Andric 2440349cc55cSDimitry Andric // Try to eliminate this PHI. Do the incoming values all agree? 2441e8d8bef9SDimitry Andric bool Disagree = false; 2442e8d8bef9SDimitry Andric for (auto &V : Values) { 2443e8d8bef9SDimitry Andric if (*V.second == FirstVal) 2444e8d8bef9SDimitry Andric continue; // No disagreement. 2445e8d8bef9SDimitry Andric 2446349cc55cSDimitry Andric // Eliminate if a backedge feeds a VPHI back into itself. 2447349cc55cSDimitry Andric if (V.second->Kind == DbgValue::VPHI && 2448349cc55cSDimitry Andric V.second->BlockNo == MBB.getNumber() && 2449349cc55cSDimitry Andric // Is this a backedge? 2450349cc55cSDimitry Andric std::distance(Values.begin(), &V) >= BackEdgesStart) 2451349cc55cSDimitry Andric continue; 2452349cc55cSDimitry Andric 2453e8d8bef9SDimitry Andric Disagree = true; 2454e8d8bef9SDimitry Andric } 2455e8d8bef9SDimitry Andric 2456349cc55cSDimitry Andric // No disagreement -> live-through value. 2457349cc55cSDimitry Andric if (!Disagree) { 2458349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2459e8d8bef9SDimitry Andric if (Changed) 2460349cc55cSDimitry Andric LiveIn = FirstVal; 2461349cc55cSDimitry Andric return Changed; 2462349cc55cSDimitry Andric } else { 2463349cc55cSDimitry Andric // Otherwise use a VPHI. 2464349cc55cSDimitry Andric DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); 2465349cc55cSDimitry Andric Changed = LiveIn != VPHI; 2466349cc55cSDimitry Andric if (Changed) 2467349cc55cSDimitry Andric LiveIn = VPHI; 2468349cc55cSDimitry Andric return Changed; 2469349cc55cSDimitry Andric } 2470e8d8bef9SDimitry Andric } 2471e8d8bef9SDimitry Andric 24721fd87a68SDimitry Andric void InstrRefBasedLDV::getBlocksForScope( 24731fd87a68SDimitry Andric const DILocation *DILoc, 24741fd87a68SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore, 24751fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) { 24761fd87a68SDimitry Andric // Get the set of "normal" in-lexical-scope blocks. 24771fd87a68SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 24781fd87a68SDimitry Andric 24791fd87a68SDimitry Andric // VarLoc LiveDebugValues tracks variable locations that are defined in 24801fd87a68SDimitry Andric // blocks not in scope. This is something we could legitimately ignore, but 24811fd87a68SDimitry Andric // lets allow it for now for the sake of coverage. 24821fd87a68SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 24831fd87a68SDimitry Andric 24841fd87a68SDimitry Andric // Storage for artificial blocks we intend to add to BlocksToExplore. 24851fd87a68SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd; 24861fd87a68SDimitry Andric 24871fd87a68SDimitry Andric // To avoid needlessly dropping large volumes of variable locations, propagate 24881fd87a68SDimitry Andric // variables through aritifical blocks, i.e. those that don't have any 24891fd87a68SDimitry Andric // instructions in scope at all. To accurately replicate VarLoc 24901fd87a68SDimitry Andric // LiveDebugValues, this means exploring all artificial successors too. 24911fd87a68SDimitry Andric // Perform a depth-first-search to enumerate those blocks. 24921fd87a68SDimitry Andric for (auto *MBB : BlocksToExplore) { 24931fd87a68SDimitry Andric // Depth-first-search state: each node is a block and which successor 24941fd87a68SDimitry Andric // we're currently exploring. 24951fd87a68SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, 24961fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator>, 24971fd87a68SDimitry Andric 8> 24981fd87a68SDimitry Andric DFS; 24991fd87a68SDimitry Andric 25001fd87a68SDimitry Andric // Find any artificial successors not already tracked. 25011fd87a68SDimitry Andric for (auto *succ : MBB->successors()) { 25021fd87a68SDimitry Andric if (BlocksToExplore.count(succ)) 25031fd87a68SDimitry Andric continue; 25041fd87a68SDimitry Andric if (!ArtificialBlocks.count(succ)) 25051fd87a68SDimitry Andric continue; 25061fd87a68SDimitry Andric ToAdd.insert(succ); 25071fd87a68SDimitry Andric DFS.push_back({succ, succ->succ_begin()}); 25081fd87a68SDimitry Andric } 25091fd87a68SDimitry Andric 25101fd87a68SDimitry Andric // Search all those blocks, depth first. 25111fd87a68SDimitry Andric while (!DFS.empty()) { 25121fd87a68SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first; 25131fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 25141fd87a68SDimitry Andric // Walk back if we've explored this blocks successors to the end. 25151fd87a68SDimitry Andric if (CurSucc == CurBB->succ_end()) { 25161fd87a68SDimitry Andric DFS.pop_back(); 25171fd87a68SDimitry Andric continue; 25181fd87a68SDimitry Andric } 25191fd87a68SDimitry Andric 25201fd87a68SDimitry Andric // If the current successor is artificial and unexplored, descend into 25211fd87a68SDimitry Andric // it. 25221fd87a68SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 25231fd87a68SDimitry Andric ToAdd.insert(*CurSucc); 25241fd87a68SDimitry Andric DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()}); 25251fd87a68SDimitry Andric continue; 25261fd87a68SDimitry Andric } 25271fd87a68SDimitry Andric 25281fd87a68SDimitry Andric ++CurSucc; 25291fd87a68SDimitry Andric } 25301fd87a68SDimitry Andric }; 25311fd87a68SDimitry Andric 25321fd87a68SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 25331fd87a68SDimitry Andric } 25341fd87a68SDimitry Andric 25351fd87a68SDimitry Andric void InstrRefBasedLDV::buildVLocValueMap( 25361fd87a68SDimitry Andric const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 2537e8d8bef9SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 2538e8d8bef9SDimitry Andric ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 2539e8d8bef9SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) { 2540349cc55cSDimitry Andric // This method is much like buildMLocValueMap: but focuses on a single 2541e8d8bef9SDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are 2542e8d8bef9SDimitry Andric // to have their value assignments solved, then run our dataflow algorithm 2543e8d8bef9SDimitry Andric // until a fixedpoint is reached. 2544e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2545e8d8bef9SDimitry Andric std::greater<unsigned int>> 2546e8d8bef9SDimitry Andric Worklist, Pending; 2547e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 2548e8d8bef9SDimitry Andric 2549e8d8bef9SDimitry Andric // The set of blocks we'll be examining. 2550e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2551e8d8bef9SDimitry Andric 2552e8d8bef9SDimitry Andric // The order in which to examine them (RPO). 2553e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders; 2554e8d8bef9SDimitry Andric 2555e8d8bef9SDimitry Andric // RPO ordering function. 2556e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2557e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2558e8d8bef9SDimitry Andric }; 2559e8d8bef9SDimitry Andric 25601fd87a68SDimitry Andric getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks); 2561e8d8bef9SDimitry Andric 2562e8d8bef9SDimitry Andric // Single block scope: not interesting! No propagation at all. Note that 2563e8d8bef9SDimitry Andric // this could probably go above ArtificialBlocks without damage, but 2564e8d8bef9SDimitry Andric // that then produces output differences from original-live-debug-values, 2565e8d8bef9SDimitry Andric // which propagates from a single block into many artificial ones. 2566e8d8bef9SDimitry Andric if (BlocksToExplore.size() == 1) 2567e8d8bef9SDimitry Andric return; 2568e8d8bef9SDimitry Andric 2569349cc55cSDimitry Andric // Convert a const set to a non-const set. LexicalScopes 2570349cc55cSDimitry Andric // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. 2571349cc55cSDimitry Andric // (Neither of them mutate anything). 2572349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; 2573349cc55cSDimitry Andric for (const auto *MBB : BlocksToExplore) 2574349cc55cSDimitry Andric MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); 2575349cc55cSDimitry Andric 2576e8d8bef9SDimitry Andric // Picks out relevants blocks RPO order and sort them. 2577e8d8bef9SDimitry Andric for (auto *MBB : BlocksToExplore) 2578e8d8bef9SDimitry Andric BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 2579e8d8bef9SDimitry Andric 2580e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2581e8d8bef9SDimitry Andric unsigned NumBlocks = BlockOrders.size(); 2582e8d8bef9SDimitry Andric 2583e8d8bef9SDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large. 2584349cc55cSDimitry Andric SmallVector<DbgValue, 32> LiveIns, LiveOuts; 2585349cc55cSDimitry Andric LiveIns.reserve(NumBlocks); 2586349cc55cSDimitry Andric LiveOuts.reserve(NumBlocks); 2587349cc55cSDimitry Andric 2588349cc55cSDimitry Andric // Initialize all values to start as NoVals. This signifies "it's live 2589349cc55cSDimitry Andric // through, but we don't know what it is". 2590349cc55cSDimitry Andric DbgValueProperties EmptyProperties(EmptyExpr, false); 2591349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2592349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2593349cc55cSDimitry Andric LiveIns.push_back(EmptyDbgValue); 2594349cc55cSDimitry Andric LiveOuts.push_back(EmptyDbgValue); 2595349cc55cSDimitry Andric } 2596e8d8bef9SDimitry Andric 2597e8d8bef9SDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 2598e8d8bef9SDimitry Andric // vlocJoin. 2599e8d8bef9SDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx; 2600e8d8bef9SDimitry Andric LiveOutIdx.reserve(NumBlocks); 2601e8d8bef9SDimitry Andric LiveInIdx.reserve(NumBlocks); 2602e8d8bef9SDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) { 2603e8d8bef9SDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 2604e8d8bef9SDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 2605e8d8bef9SDimitry Andric } 2606e8d8bef9SDimitry Andric 2607349cc55cSDimitry Andric // Loop over each variable and place PHIs for it, then propagate values 2608349cc55cSDimitry Andric // between blocks. This keeps the locality of working on one lexical scope at 2609349cc55cSDimitry Andric // at time, but avoids re-processing variable values because some other 2610349cc55cSDimitry Andric // variable has been assigned. 2611349cc55cSDimitry Andric for (auto &Var : VarsWeCareAbout) { 2612349cc55cSDimitry Andric // Re-initialize live-ins and live-outs, to clear the remains of previous 2613349cc55cSDimitry Andric // variables live-ins / live-outs. 2614349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2615349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2616349cc55cSDimitry Andric LiveIns[I] = EmptyDbgValue; 2617349cc55cSDimitry Andric LiveOuts[I] = EmptyDbgValue; 2618349cc55cSDimitry Andric } 2619349cc55cSDimitry Andric 2620349cc55cSDimitry Andric // Place PHIs for variable values, using the LLVM IDF calculator. 2621349cc55cSDimitry Andric // Collect the set of blocks where variables are def'd. 2622349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2623349cc55cSDimitry Andric for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { 2624349cc55cSDimitry Andric auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; 2625349cc55cSDimitry Andric if (TransferFunc.find(Var) != TransferFunc.end()) 2626349cc55cSDimitry Andric DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); 2627349cc55cSDimitry Andric } 2628349cc55cSDimitry Andric 2629349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2630349cc55cSDimitry Andric 26311fd87a68SDimitry Andric // Request the set of PHIs we should insert for this variable. If there's 26321fd87a68SDimitry Andric // only one value definition, things are very simple. 26331fd87a68SDimitry Andric if (DefBlocks.size() == 1) { 26341fd87a68SDimitry Andric placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(), 26351fd87a68SDimitry Andric AllTheVLocs, Var, Output); 26361fd87a68SDimitry Andric continue; 26371fd87a68SDimitry Andric } 26381fd87a68SDimitry Andric 26391fd87a68SDimitry Andric // Otherwise: we need to place PHIs through SSA and propagate values. 2640349cc55cSDimitry Andric BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); 2641349cc55cSDimitry Andric 2642349cc55cSDimitry Andric // Insert PHIs into the per-block live-in tables for this variable. 2643349cc55cSDimitry Andric for (MachineBasicBlock *PHIMBB : PHIBlocks) { 2644349cc55cSDimitry Andric unsigned BlockNo = PHIMBB->getNumber(); 2645349cc55cSDimitry Andric DbgValue *LiveIn = LiveInIdx[PHIMBB]; 2646349cc55cSDimitry Andric *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); 2647349cc55cSDimitry Andric } 2648349cc55cSDimitry Andric 2649e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2650e8d8bef9SDimitry Andric Worklist.push(BBToOrder[MBB]); 2651e8d8bef9SDimitry Andric OnWorklist.insert(MBB); 2652e8d8bef9SDimitry Andric } 2653e8d8bef9SDimitry Andric 2654349cc55cSDimitry Andric // Iterate over all the blocks we selected, propagating the variables value. 2655349cc55cSDimitry Andric // This loop does two things: 2656349cc55cSDimitry Andric // * Eliminates un-necessary VPHIs in vlocJoin, 2657349cc55cSDimitry Andric // * Evaluates the blocks transfer function (i.e. variable assignments) and 2658349cc55cSDimitry Andric // stores the result to the blocks live-outs. 2659349cc55cSDimitry Andric // Always evaluate the transfer function on the first iteration, and when 2660349cc55cSDimitry Andric // the live-ins change thereafter. 2661e8d8bef9SDimitry Andric bool FirstTrip = true; 2662e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2663e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2664e8d8bef9SDimitry Andric auto *MBB = OrderToBB[Worklist.top()]; 2665e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2666e8d8bef9SDimitry Andric Worklist.pop(); 2667e8d8bef9SDimitry Andric 2668349cc55cSDimitry Andric auto LiveInsIt = LiveInIdx.find(MBB); 2669349cc55cSDimitry Andric assert(LiveInsIt != LiveInIdx.end()); 2670349cc55cSDimitry Andric DbgValue *LiveIn = LiveInsIt->second; 2671e8d8bef9SDimitry Andric 2672e8d8bef9SDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output 2673e8d8bef9SDimitry Andric // into JoinedInLocs. 2674349cc55cSDimitry Andric bool InLocsChanged = 26754824e7fdSDimitry Andric vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); 2676e8d8bef9SDimitry Andric 2677349cc55cSDimitry Andric SmallVector<const MachineBasicBlock *, 8> Preds; 2678349cc55cSDimitry Andric for (const auto *Pred : MBB->predecessors()) 2679349cc55cSDimitry Andric Preds.push_back(Pred); 2680e8d8bef9SDimitry Andric 2681349cc55cSDimitry Andric // If this block's live-in value is a VPHI, try to pick a machine-value 2682349cc55cSDimitry Andric // for it. This makes the machine-value available and propagated 2683349cc55cSDimitry Andric // through all blocks by the time value propagation finishes. We can't 2684349cc55cSDimitry Andric // do this any earlier as it needs to read the block live-outs. 2685349cc55cSDimitry Andric if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { 2686349cc55cSDimitry Andric // There's a small possibility that on a preceeding path, a VPHI is 2687349cc55cSDimitry Andric // eliminated and transitions from VPHI-with-location to 2688349cc55cSDimitry Andric // live-through-value. As a result, the selected location of any VPHI 2689349cc55cSDimitry Andric // might change, so we need to re-compute it on each iteration. 2690349cc55cSDimitry Andric Optional<ValueIDNum> ValueNum = 2691349cc55cSDimitry Andric pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); 2692e8d8bef9SDimitry Andric 2693349cc55cSDimitry Andric if (ValueNum) { 2694349cc55cSDimitry Andric InLocsChanged |= LiveIn->ID != *ValueNum; 2695349cc55cSDimitry Andric LiveIn->ID = *ValueNum; 2696349cc55cSDimitry Andric } 2697349cc55cSDimitry Andric } 2698e8d8bef9SDimitry Andric 2699349cc55cSDimitry Andric if (!InLocsChanged && !FirstTrip) 2700e8d8bef9SDimitry Andric continue; 2701e8d8bef9SDimitry Andric 2702349cc55cSDimitry Andric DbgValue *LiveOut = LiveOutIdx[MBB]; 2703349cc55cSDimitry Andric bool OLChanged = false; 2704349cc55cSDimitry Andric 2705e8d8bef9SDimitry Andric // Do transfer function. 2706e8d8bef9SDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()]; 2707349cc55cSDimitry Andric auto TransferIt = VTracker.Vars.find(Var); 2708349cc55cSDimitry Andric if (TransferIt != VTracker.Vars.end()) { 2709e8d8bef9SDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg). 2710349cc55cSDimitry Andric if (TransferIt->second.Kind == DbgValue::Undef) { 2711349cc55cSDimitry Andric DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); 2712349cc55cSDimitry Andric if (*LiveOut != NewVal) { 2713349cc55cSDimitry Andric *LiveOut = NewVal; 2714349cc55cSDimitry Andric OLChanged = true; 2715349cc55cSDimitry Andric } 2716e8d8bef9SDimitry Andric } else { 2717e8d8bef9SDimitry Andric // Insert new variable value; or overwrite. 2718349cc55cSDimitry Andric if (*LiveOut != TransferIt->second) { 2719349cc55cSDimitry Andric *LiveOut = TransferIt->second; 2720349cc55cSDimitry Andric OLChanged = true; 2721e8d8bef9SDimitry Andric } 2722e8d8bef9SDimitry Andric } 2723349cc55cSDimitry Andric } else { 2724349cc55cSDimitry Andric // Just copy live-ins to live-outs, for anything not transferred. 2725349cc55cSDimitry Andric if (*LiveOut != *LiveIn) { 2726349cc55cSDimitry Andric *LiveOut = *LiveIn; 2727349cc55cSDimitry Andric OLChanged = true; 2728349cc55cSDimitry Andric } 2729e8d8bef9SDimitry Andric } 2730e8d8bef9SDimitry Andric 2731349cc55cSDimitry Andric // If no live-out value changed, there's no need to explore further. 2732e8d8bef9SDimitry Andric if (!OLChanged) 2733e8d8bef9SDimitry Andric continue; 2734e8d8bef9SDimitry Andric 2735e8d8bef9SDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge 2736e8d8bef9SDimitry Andric // successors during this dataflow iteration; book backedge successors 2737e8d8bef9SDimitry Andric // to be visited next time around. 2738e8d8bef9SDimitry Andric for (auto s : MBB->successors()) { 2739e8d8bef9SDimitry Andric // Ignore out of scope / not-to-be-explored successors. 2740e8d8bef9SDimitry Andric if (LiveInIdx.find(s) == LiveInIdx.end()) 2741e8d8bef9SDimitry Andric continue; 2742e8d8bef9SDimitry Andric 2743e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2744e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2745e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2746e8d8bef9SDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 2747e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2748e8d8bef9SDimitry Andric } 2749e8d8bef9SDimitry Andric } 2750e8d8bef9SDimitry Andric } 2751e8d8bef9SDimitry Andric Worklist.swap(Pending); 2752e8d8bef9SDimitry Andric std::swap(OnWorklist, OnPending); 2753e8d8bef9SDimitry Andric OnPending.clear(); 2754e8d8bef9SDimitry Andric assert(Pending.empty()); 2755e8d8bef9SDimitry Andric FirstTrip = false; 2756e8d8bef9SDimitry Andric } 2757e8d8bef9SDimitry Andric 2758349cc55cSDimitry Andric // Save live-ins to output vector. Ignore any that are still marked as being 2759349cc55cSDimitry Andric // VPHIs with no location -- those are variables that we know the value of, 2760349cc55cSDimitry Andric // but are not actually available in the register file. 2761e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2762349cc55cSDimitry Andric DbgValue *BlockLiveIn = LiveInIdx[MBB]; 2763349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::NoVal) 2764e8d8bef9SDimitry Andric continue; 2765349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI && 2766349cc55cSDimitry Andric BlockLiveIn->ID == ValueIDNum::EmptyValue) 2767349cc55cSDimitry Andric continue; 2768349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI) 2769349cc55cSDimitry Andric BlockLiveIn->Kind = DbgValue::Def; 27704824e7fdSDimitry Andric assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == 27714824e7fdSDimitry Andric Var.getFragment() && "Fragment info missing during value prop"); 2772349cc55cSDimitry Andric Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); 2773e8d8bef9SDimitry Andric } 2774349cc55cSDimitry Andric } // Per-variable loop. 2775e8d8bef9SDimitry Andric 2776e8d8bef9SDimitry Andric BlockOrders.clear(); 2777e8d8bef9SDimitry Andric BlocksToExplore.clear(); 2778e8d8bef9SDimitry Andric } 2779e8d8bef9SDimitry Andric 27801fd87a68SDimitry Andric void InstrRefBasedLDV::placePHIsForSingleVarDefinition( 27811fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks, 27821fd87a68SDimitry Andric MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs, 27831fd87a68SDimitry Andric const DebugVariable &Var, LiveInsT &Output) { 27841fd87a68SDimitry Andric // If there is a single definition of the variable, then working out it's 27851fd87a68SDimitry Andric // value everywhere is very simple: it's every block dominated by the 27861fd87a68SDimitry Andric // definition. At the dominance frontier, the usual algorithm would: 27871fd87a68SDimitry Andric // * Place PHIs, 27881fd87a68SDimitry Andric // * Propagate values into them, 27891fd87a68SDimitry Andric // * Find there's no incoming variable value from the other incoming branches 27901fd87a68SDimitry Andric // of the dominance frontier, 27911fd87a68SDimitry Andric // * Specify there's no variable value in blocks past the frontier. 27921fd87a68SDimitry Andric // This is a common case, hence it's worth special-casing it. 27931fd87a68SDimitry Andric 27941fd87a68SDimitry Andric // Pick out the variables value from the block transfer function. 27951fd87a68SDimitry Andric VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()]; 27961fd87a68SDimitry Andric auto ValueIt = VLocs.Vars.find(Var); 27971fd87a68SDimitry Andric const DbgValue &Value = ValueIt->second; 27981fd87a68SDimitry Andric 2799*d56accc7SDimitry Andric // If it's an explicit assignment of "undef", that means there is no location 2800*d56accc7SDimitry Andric // anyway, anywhere. 2801*d56accc7SDimitry Andric if (Value.Kind == DbgValue::Undef) 2802*d56accc7SDimitry Andric return; 2803*d56accc7SDimitry Andric 28041fd87a68SDimitry Andric // Assign the variable value to entry to each dominated block that's in scope. 28051fd87a68SDimitry Andric // Skip the definition block -- it's assigned the variable value in the middle 28061fd87a68SDimitry Andric // of the block somewhere. 28071fd87a68SDimitry Andric for (auto *ScopeBlock : InScopeBlocks) { 28081fd87a68SDimitry Andric if (!DomTree->properlyDominates(AssignMBB, ScopeBlock)) 28091fd87a68SDimitry Andric continue; 28101fd87a68SDimitry Andric 28111fd87a68SDimitry Andric Output[ScopeBlock->getNumber()].push_back({Var, Value}); 28121fd87a68SDimitry Andric } 28131fd87a68SDimitry Andric 28141fd87a68SDimitry Andric // All blocks that aren't dominated have no live-in value, thus no variable 28151fd87a68SDimitry Andric // value will be given to them. 28161fd87a68SDimitry Andric } 28171fd87a68SDimitry Andric 2818e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2819e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer( 2820e8d8bef9SDimitry Andric const MLocTransferMap &mloc_transfer) const { 2821e8d8bef9SDimitry Andric for (auto &P : mloc_transfer) { 2822e8d8bef9SDimitry Andric std::string foo = MTracker->LocIdxToName(P.first); 2823e8d8bef9SDimitry Andric std::string bar = MTracker->IDAsString(P.second); 2824e8d8bef9SDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n"; 2825e8d8bef9SDimitry Andric } 2826e8d8bef9SDimitry Andric } 2827e8d8bef9SDimitry Andric #endif 2828e8d8bef9SDimitry Andric 2829e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 2830e8d8bef9SDimitry Andric // Build some useful data structures. 2831349cc55cSDimitry Andric 2832349cc55cSDimitry Andric LLVMContext &Context = MF.getFunction().getContext(); 2833349cc55cSDimitry Andric EmptyExpr = DIExpression::get(Context, {}); 2834349cc55cSDimitry Andric 2835e8d8bef9SDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 2836e8d8bef9SDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc()) 2837e8d8bef9SDimitry Andric return DL.getLine() != 0; 2838e8d8bef9SDimitry Andric return false; 2839e8d8bef9SDimitry Andric }; 2840e8d8bef9SDimitry Andric // Collect a set of all the artificial blocks. 2841e8d8bef9SDimitry Andric for (auto &MBB : MF) 2842e8d8bef9SDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation)) 2843e8d8bef9SDimitry Andric ArtificialBlocks.insert(&MBB); 2844e8d8bef9SDimitry Andric 2845e8d8bef9SDimitry Andric // Compute mappings of block <=> RPO order. 2846e8d8bef9SDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 2847e8d8bef9SDimitry Andric unsigned int RPONumber = 0; 2848fe6060f1SDimitry Andric for (MachineBasicBlock *MBB : RPOT) { 2849fe6060f1SDimitry Andric OrderToBB[RPONumber] = MBB; 2850fe6060f1SDimitry Andric BBToOrder[MBB] = RPONumber; 2851fe6060f1SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber; 2852e8d8bef9SDimitry Andric ++RPONumber; 2853e8d8bef9SDimitry Andric } 2854fe6060f1SDimitry Andric 2855fe6060f1SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup. 2856fe6060f1SDimitry Andric llvm::sort(MF.DebugValueSubstitutions); 2857fe6060f1SDimitry Andric 2858fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS 2859fe6060f1SDimitry Andric // As an expensive check, test whether there are any duplicate substitution 2860fe6060f1SDimitry Andric // sources in the collection. 2861fe6060f1SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) { 2862fe6060f1SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin(); 2863fe6060f1SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { 2864fe6060f1SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location " 2865fe6060f1SDimitry Andric "substitution seen"); 2866fe6060f1SDimitry Andric } 2867fe6060f1SDimitry Andric } 2868fe6060f1SDimitry Andric #endif 2869e8d8bef9SDimitry Andric } 2870e8d8bef9SDimitry Andric 2871*d56accc7SDimitry Andric // Produce an "ejection map" for blocks, i.e., what's the highest-numbered 2872*d56accc7SDimitry Andric // lexical scope it's used in. When exploring in DFS order and we pass that 2873*d56accc7SDimitry Andric // scope, the block can be processed and any tracking information freed. 2874*d56accc7SDimitry Andric void InstrRefBasedLDV::makeDepthFirstEjectionMap( 2875*d56accc7SDimitry Andric SmallVectorImpl<unsigned> &EjectionMap, 2876*d56accc7SDimitry Andric const ScopeToDILocT &ScopeToDILocation, 2877*d56accc7SDimitry Andric ScopeToAssignBlocksT &ScopeToAssignBlocks) { 2878*d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2879*d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2880*d56accc7SDimitry Andric auto *TopScope = LS.getCurrentFunctionScope(); 2881*d56accc7SDimitry Andric 2882*d56accc7SDimitry Andric // Unlike lexical scope explorers, we explore in reverse order, to find the 2883*d56accc7SDimitry Andric // "last" lexical scope used for each block early. 2884*d56accc7SDimitry Andric WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1}); 2885*d56accc7SDimitry Andric 2886*d56accc7SDimitry Andric while (!WorkStack.empty()) { 2887*d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back(); 2888*d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first; 2889*d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second--; 2890*d56accc7SDimitry Andric 2891*d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 2892*d56accc7SDimitry Andric if (ChildNum >= 0) { 2893*d56accc7SDimitry Andric // If ChildNum is positive, there are remaining children to explore. 2894*d56accc7SDimitry Andric // Push the child and its children-count onto the stack. 2895*d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum]; 2896*d56accc7SDimitry Andric WorkStack.push_back( 2897*d56accc7SDimitry Andric std::make_pair(ChildScope, ChildScope->getChildren().size() - 1)); 2898*d56accc7SDimitry Andric } else { 2899*d56accc7SDimitry Andric WorkStack.pop_back(); 2900*d56accc7SDimitry Andric 2901*d56accc7SDimitry Andric // We've explored all children and any later blocks: examine all blocks 2902*d56accc7SDimitry Andric // in our scope. If they haven't yet had an ejection number set, then 2903*d56accc7SDimitry Andric // this scope will be the last to use that block. 2904*d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS); 2905*d56accc7SDimitry Andric if (DILocationIt != ScopeToDILocation.end()) { 2906*d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore, 2907*d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second); 2908*d56accc7SDimitry Andric for (auto *MBB : BlocksToExplore) { 2909*d56accc7SDimitry Andric unsigned BBNum = MBB->getNumber(); 2910*d56accc7SDimitry Andric if (EjectionMap[BBNum] == 0) 2911*d56accc7SDimitry Andric EjectionMap[BBNum] = WS->getDFSOut(); 2912*d56accc7SDimitry Andric } 2913*d56accc7SDimitry Andric 2914*d56accc7SDimitry Andric BlocksToExplore.clear(); 2915*d56accc7SDimitry Andric } 2916*d56accc7SDimitry Andric } 2917*d56accc7SDimitry Andric } 2918*d56accc7SDimitry Andric } 2919*d56accc7SDimitry Andric 2920*d56accc7SDimitry Andric bool InstrRefBasedLDV::depthFirstVLocAndEmit( 2921*d56accc7SDimitry Andric unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation, 2922*d56accc7SDimitry Andric const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks, 2923*d56accc7SDimitry Andric LiveInsT &Output, ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 2924*d56accc7SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF, 2925*d56accc7SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 2926*d56accc7SDimitry Andric const TargetPassConfig &TPC) { 2927*d56accc7SDimitry Andric TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 2928*d56accc7SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2929*d56accc7SDimitry Andric VTracker = nullptr; 2930*d56accc7SDimitry Andric 2931*d56accc7SDimitry Andric // No scopes? No variable locations. 2932*d56accc7SDimitry Andric if (!LS.getCurrentFunctionScope()) { 2933*d56accc7SDimitry Andric // FIXME: this is a sticking plaster to prevent a memory leak, these 2934*d56accc7SDimitry Andric // pointers will be automagically freed by being unique pointers, shortly. 2935*d56accc7SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 2936*d56accc7SDimitry Andric delete[] MInLocs[I]; 2937*d56accc7SDimitry Andric delete[] MOutLocs[I]; 2938*d56accc7SDimitry Andric } 2939*d56accc7SDimitry Andric return false; 2940*d56accc7SDimitry Andric } 2941*d56accc7SDimitry Andric 2942*d56accc7SDimitry Andric // Build map from block number to the last scope that uses the block. 2943*d56accc7SDimitry Andric SmallVector<unsigned, 16> EjectionMap; 2944*d56accc7SDimitry Andric EjectionMap.resize(MaxNumBlocks, 0); 2945*d56accc7SDimitry Andric makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation, 2946*d56accc7SDimitry Andric ScopeToAssignBlocks); 2947*d56accc7SDimitry Andric 2948*d56accc7SDimitry Andric // Helper lambda for ejecting a block -- if nothing is going to use the block, 2949*d56accc7SDimitry Andric // we can translate the variable location information into DBG_VALUEs and then 2950*d56accc7SDimitry Andric // free all of InstrRefBasedLDV's data structures. 2951*d56accc7SDimitry Andric auto EjectBlock = [&](MachineBasicBlock &MBB) -> void { 2952*d56accc7SDimitry Andric unsigned BBNum = MBB.getNumber(); 2953*d56accc7SDimitry Andric AllTheVLocs[BBNum].clear(); 2954*d56accc7SDimitry Andric 2955*d56accc7SDimitry Andric // Prime the transfer-tracker, and then step through all the block 2956*d56accc7SDimitry Andric // instructions, installing transfers. 2957*d56accc7SDimitry Andric MTracker->reset(); 2958*d56accc7SDimitry Andric MTracker->loadFromArray(MInLocs[BBNum], BBNum); 2959*d56accc7SDimitry Andric TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs); 2960*d56accc7SDimitry Andric 2961*d56accc7SDimitry Andric CurBB = BBNum; 2962*d56accc7SDimitry Andric CurInst = 1; 2963*d56accc7SDimitry Andric for (auto &MI : MBB) { 2964*d56accc7SDimitry Andric process(MI, MOutLocs, MInLocs); 2965*d56accc7SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 2966*d56accc7SDimitry Andric ++CurInst; 2967*d56accc7SDimitry Andric } 2968*d56accc7SDimitry Andric 2969*d56accc7SDimitry Andric // Free machine-location tables for this block. 2970*d56accc7SDimitry Andric delete[] MInLocs[BBNum]; 2971*d56accc7SDimitry Andric delete[] MOutLocs[BBNum]; 2972*d56accc7SDimitry Andric // Make ourselves brittle to use-after-free errors. 2973*d56accc7SDimitry Andric MInLocs[BBNum] = nullptr; 2974*d56accc7SDimitry Andric MOutLocs[BBNum] = nullptr; 2975*d56accc7SDimitry Andric // We don't need live-in variable values for this block either. 2976*d56accc7SDimitry Andric Output[BBNum].clear(); 2977*d56accc7SDimitry Andric AllTheVLocs[BBNum].clear(); 2978*d56accc7SDimitry Andric }; 2979*d56accc7SDimitry Andric 2980*d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2981*d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2982*d56accc7SDimitry Andric WorkStack.push_back({LS.getCurrentFunctionScope(), 0}); 2983*d56accc7SDimitry Andric unsigned HighestDFSIn = 0; 2984*d56accc7SDimitry Andric 2985*d56accc7SDimitry Andric // Proceed to explore in depth first order. 2986*d56accc7SDimitry Andric while (!WorkStack.empty()) { 2987*d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back(); 2988*d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first; 2989*d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second++; 2990*d56accc7SDimitry Andric 2991*d56accc7SDimitry Andric // We obesrve scopes with children twice here, once descending in, once 2992*d56accc7SDimitry Andric // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure 2993*d56accc7SDimitry Andric // we don't process a scope twice. Additionally, ignore scopes that don't 2994*d56accc7SDimitry Andric // have a DILocation -- by proxy, this means we never tracked any variable 2995*d56accc7SDimitry Andric // assignments in that scope. 2996*d56accc7SDimitry Andric auto DILocIt = ScopeToDILocation.find(WS); 2997*d56accc7SDimitry Andric if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) { 2998*d56accc7SDimitry Andric const DILocation *DILoc = DILocIt->second; 2999*d56accc7SDimitry Andric auto &VarsWeCareAbout = ScopeToVars.find(WS)->second; 3000*d56accc7SDimitry Andric auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second; 3001*d56accc7SDimitry Andric 3002*d56accc7SDimitry Andric buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs, 3003*d56accc7SDimitry Andric MInLocs, AllTheVLocs); 3004*d56accc7SDimitry Andric } 3005*d56accc7SDimitry Andric 3006*d56accc7SDimitry Andric HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn()); 3007*d56accc7SDimitry Andric 3008*d56accc7SDimitry Andric // Descend into any scope nests. 3009*d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 3010*d56accc7SDimitry Andric if (ChildNum < (ssize_t)Children.size()) { 3011*d56accc7SDimitry Andric // There are children to explore -- push onto stack and continue. 3012*d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum]; 3013*d56accc7SDimitry Andric WorkStack.push_back(std::make_pair(ChildScope, 0)); 3014*d56accc7SDimitry Andric } else { 3015*d56accc7SDimitry Andric WorkStack.pop_back(); 3016*d56accc7SDimitry Andric 3017*d56accc7SDimitry Andric // We've explored a leaf, or have explored all the children of a scope. 3018*d56accc7SDimitry Andric // Try to eject any blocks where this is the last scope it's relevant to. 3019*d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS); 3020*d56accc7SDimitry Andric if (DILocationIt == ScopeToDILocation.end()) 3021*d56accc7SDimitry Andric continue; 3022*d56accc7SDimitry Andric 3023*d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore, 3024*d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second); 3025*d56accc7SDimitry Andric for (auto *MBB : BlocksToExplore) 3026*d56accc7SDimitry Andric if (WS->getDFSOut() == EjectionMap[MBB->getNumber()]) 3027*d56accc7SDimitry Andric EjectBlock(const_cast<MachineBasicBlock &>(*MBB)); 3028*d56accc7SDimitry Andric 3029*d56accc7SDimitry Andric BlocksToExplore.clear(); 3030*d56accc7SDimitry Andric } 3031*d56accc7SDimitry Andric } 3032*d56accc7SDimitry Andric 3033*d56accc7SDimitry Andric // Some artificial blocks may not have been ejected, meaning they're not 3034*d56accc7SDimitry Andric // connected to an actual legitimate scope. This can technically happen 3035*d56accc7SDimitry Andric // with things like the entry block. In theory, we shouldn't need to do 3036*d56accc7SDimitry Andric // anything for such out-of-scope blocks, but for the sake of being similar 3037*d56accc7SDimitry Andric // to VarLocBasedLDV, eject these too. 3038*d56accc7SDimitry Andric for (auto *MBB : ArtificialBlocks) 3039*d56accc7SDimitry Andric if (MOutLocs[MBB->getNumber()]) 3040*d56accc7SDimitry Andric EjectBlock(*MBB); 3041*d56accc7SDimitry Andric 3042*d56accc7SDimitry Andric // Finally, there might have been gaps in the block numbering, from dead 3043*d56accc7SDimitry Andric // blocks being deleted or folded. In those scenarios, we might allocate a 3044*d56accc7SDimitry Andric // block-table that's never ejected, meaning we have to free it at the end. 3045*d56accc7SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 3046*d56accc7SDimitry Andric if (MInLocs[I]) { 3047*d56accc7SDimitry Andric delete[] MInLocs[I]; 3048*d56accc7SDimitry Andric delete[] MOutLocs[I]; 3049*d56accc7SDimitry Andric } 3050*d56accc7SDimitry Andric } 3051*d56accc7SDimitry Andric 3052*d56accc7SDimitry Andric return emitTransfers(AllVarsNumbering); 3053*d56accc7SDimitry Andric } 3054*d56accc7SDimitry Andric 30551fd87a68SDimitry Andric bool InstrRefBasedLDV::emitTransfers( 30561fd87a68SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering) { 30571fd87a68SDimitry Andric // Go through all the transfers recorded in the TransferTracker -- this is 30581fd87a68SDimitry Andric // both the live-ins to a block, and any movements of values that happen 30591fd87a68SDimitry Andric // in the middle. 30601fd87a68SDimitry Andric for (const auto &P : TTracker->Transfers) { 30611fd87a68SDimitry Andric // We have to insert DBG_VALUEs in a consistent order, otherwise they 30621fd87a68SDimitry Andric // appear in DWARF in different orders. Use the order that they appear 30631fd87a68SDimitry Andric // when walking through each block / each instruction, stored in 30641fd87a68SDimitry Andric // AllVarsNumbering. 30651fd87a68SDimitry Andric SmallVector<std::pair<unsigned, MachineInstr *>> Insts; 30661fd87a68SDimitry Andric for (MachineInstr *MI : P.Insts) { 30671fd87a68SDimitry Andric DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(), 30681fd87a68SDimitry Andric MI->getDebugLoc()->getInlinedAt()); 30691fd87a68SDimitry Andric Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI); 30701fd87a68SDimitry Andric } 30711fd87a68SDimitry Andric llvm::sort(Insts, 30721fd87a68SDimitry Andric [](const auto &A, const auto &B) { return A.first < B.first; }); 30731fd87a68SDimitry Andric 30741fd87a68SDimitry Andric // Insert either before or after the designated point... 30751fd87a68SDimitry Andric if (P.MBB) { 30761fd87a68SDimitry Andric MachineBasicBlock &MBB = *P.MBB; 30771fd87a68SDimitry Andric for (const auto &Pair : Insts) 30781fd87a68SDimitry Andric MBB.insert(P.Pos, Pair.second); 30791fd87a68SDimitry Andric } else { 30801fd87a68SDimitry Andric // Terminators, like tail calls, can clobber things. Don't try and place 30811fd87a68SDimitry Andric // transfers after them. 30821fd87a68SDimitry Andric if (P.Pos->isTerminator()) 30831fd87a68SDimitry Andric continue; 30841fd87a68SDimitry Andric 30851fd87a68SDimitry Andric MachineBasicBlock &MBB = *P.Pos->getParent(); 30861fd87a68SDimitry Andric for (const auto &Pair : Insts) 30871fd87a68SDimitry Andric MBB.insertAfterBundle(P.Pos, Pair.second); 30881fd87a68SDimitry Andric } 30891fd87a68SDimitry Andric } 30901fd87a68SDimitry Andric 30911fd87a68SDimitry Andric return TTracker->Transfers.size() != 0; 30921fd87a68SDimitry Andric } 30931fd87a68SDimitry Andric 3094e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and 3095e8d8bef9SDimitry Andric /// extend ranges across basic blocks. 3096e8d8bef9SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 3097349cc55cSDimitry Andric MachineDominatorTree *DomTree, 3098349cc55cSDimitry Andric TargetPassConfig *TPC, 3099349cc55cSDimitry Andric unsigned InputBBLimit, 3100349cc55cSDimitry Andric unsigned InputDbgValLimit) { 3101e8d8bef9SDimitry Andric // No subprogram means this function contains no debuginfo. 3102e8d8bef9SDimitry Andric if (!MF.getFunction().getSubprogram()) 3103e8d8bef9SDimitry Andric return false; 3104e8d8bef9SDimitry Andric 3105e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 3106e8d8bef9SDimitry Andric this->TPC = TPC; 3107e8d8bef9SDimitry Andric 3108349cc55cSDimitry Andric this->DomTree = DomTree; 3109e8d8bef9SDimitry Andric TRI = MF.getSubtarget().getRegisterInfo(); 3110349cc55cSDimitry Andric MRI = &MF.getRegInfo(); 3111e8d8bef9SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 3112e8d8bef9SDimitry Andric TFI = MF.getSubtarget().getFrameLowering(); 3113e8d8bef9SDimitry Andric TFI->getCalleeSaves(MF, CalleeSavedRegs); 3114fe6060f1SDimitry Andric MFI = &MF.getFrameInfo(); 3115e8d8bef9SDimitry Andric LS.initialize(MF); 3116e8d8bef9SDimitry Andric 31174824e7fdSDimitry Andric const auto &STI = MF.getSubtarget(); 31184824e7fdSDimitry Andric AdjustsStackInCalls = MFI->adjustsStack() && 31194824e7fdSDimitry Andric STI.getFrameLowering()->stackProbeFunctionModifiesSP(); 31204824e7fdSDimitry Andric if (AdjustsStackInCalls) 31214824e7fdSDimitry Andric StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); 31224824e7fdSDimitry Andric 3123e8d8bef9SDimitry Andric MTracker = 3124e8d8bef9SDimitry Andric new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 3125e8d8bef9SDimitry Andric VTracker = nullptr; 3126e8d8bef9SDimitry Andric TTracker = nullptr; 3127e8d8bef9SDimitry Andric 3128e8d8bef9SDimitry Andric SmallVector<MLocTransferMap, 32> MLocTransfer; 3129e8d8bef9SDimitry Andric SmallVector<VLocTracker, 8> vlocs; 3130e8d8bef9SDimitry Andric LiveInsT SavedLiveIns; 3131e8d8bef9SDimitry Andric 3132e8d8bef9SDimitry Andric int MaxNumBlocks = -1; 3133e8d8bef9SDimitry Andric for (auto &MBB : MF) 3134e8d8bef9SDimitry Andric MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 3135e8d8bef9SDimitry Andric assert(MaxNumBlocks >= 0); 3136e8d8bef9SDimitry Andric ++MaxNumBlocks; 3137e8d8bef9SDimitry Andric 3138e8d8bef9SDimitry Andric MLocTransfer.resize(MaxNumBlocks); 31394824e7fdSDimitry Andric vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); 3140e8d8bef9SDimitry Andric SavedLiveIns.resize(MaxNumBlocks); 3141e8d8bef9SDimitry Andric 3142e8d8bef9SDimitry Andric initialSetup(MF); 3143e8d8bef9SDimitry Andric 3144e8d8bef9SDimitry Andric produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 3145e8d8bef9SDimitry Andric 3146e8d8bef9SDimitry Andric // Allocate and initialize two array-of-arrays for the live-in and live-out 3147e8d8bef9SDimitry Andric // machine values. The outer dimension is the block number; while the inner 3148e8d8bef9SDimitry Andric // dimension is a LocIdx from MLocTracker. 3149e8d8bef9SDimitry Andric ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks]; 3150e8d8bef9SDimitry Andric ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks]; 3151e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 3152e8d8bef9SDimitry Andric for (int i = 0; i < MaxNumBlocks; ++i) { 3153349cc55cSDimitry Andric // These all auto-initialize to ValueIDNum::EmptyValue 3154e8d8bef9SDimitry Andric MOutLocs[i] = new ValueIDNum[NumLocs]; 3155e8d8bef9SDimitry Andric MInLocs[i] = new ValueIDNum[NumLocs]; 3156e8d8bef9SDimitry Andric } 3157e8d8bef9SDimitry Andric 3158e8d8bef9SDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function, 3159e8d8bef9SDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use 3160e8d8bef9SDimitry Andric // both live-ins and live-outs for decision making in the variable value 3161e8d8bef9SDimitry Andric // dataflow problem. 3162349cc55cSDimitry Andric buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); 3163e8d8bef9SDimitry Andric 3164fe6060f1SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into 3165fe6060f1SDimitry Andric // either live-through machine values, or PHIs. 3166fe6060f1SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) { 3167fe6060f1SDimitry Andric // Identify unresolved block-live-ins. 3168fe6060f1SDimitry Andric ValueIDNum &Num = DBG_PHI.ValueRead; 3169fe6060f1SDimitry Andric if (!Num.isPHI()) 3170fe6060f1SDimitry Andric continue; 3171fe6060f1SDimitry Andric 3172fe6060f1SDimitry Andric unsigned BlockNo = Num.getBlock(); 3173fe6060f1SDimitry Andric LocIdx LocNo = Num.getLoc(); 3174fe6060f1SDimitry Andric Num = MInLocs[BlockNo][LocNo.asU64()]; 3175fe6060f1SDimitry Andric } 3176fe6060f1SDimitry Andric // Later, we'll be looking up ranges of instruction numbers. 3177fe6060f1SDimitry Andric llvm::sort(DebugPHINumToValue); 3178fe6060f1SDimitry Andric 3179e8d8bef9SDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE 3180e8d8bef9SDimitry Andric // instructions and recording what machine value their operands refer to. 3181e8d8bef9SDimitry Andric for (auto &OrderPair : OrderToBB) { 3182e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *OrderPair.second; 3183e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 3184e8d8bef9SDimitry Andric VTracker = &vlocs[CurBB]; 3185e8d8bef9SDimitry Andric VTracker->MBB = &MBB; 3186e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 3187e8d8bef9SDimitry Andric CurInst = 1; 3188e8d8bef9SDimitry Andric for (auto &MI : MBB) { 3189fe6060f1SDimitry Andric process(MI, MOutLocs, MInLocs); 3190e8d8bef9SDimitry Andric ++CurInst; 3191e8d8bef9SDimitry Andric } 3192e8d8bef9SDimitry Andric MTracker->reset(); 3193e8d8bef9SDimitry Andric } 3194e8d8bef9SDimitry Andric 3195e8d8bef9SDimitry Andric // Number all variables in the order that they appear, to be used as a stable 3196e8d8bef9SDimitry Andric // insertion order later. 3197e8d8bef9SDimitry Andric DenseMap<DebugVariable, unsigned> AllVarsNumbering; 3198e8d8bef9SDimitry Andric 3199e8d8bef9SDimitry Andric // Map from one LexicalScope to all the variables in that scope. 32001fd87a68SDimitry Andric ScopeToVarsT ScopeToVars; 3201e8d8bef9SDimitry Andric 32021fd87a68SDimitry Andric // Map from One lexical scope to all blocks where assignments happen for 32031fd87a68SDimitry Andric // that scope. 32041fd87a68SDimitry Andric ScopeToAssignBlocksT ScopeToAssignBlocks; 3205e8d8bef9SDimitry Andric 32061fd87a68SDimitry Andric // Store map of DILocations that describes scopes. 32071fd87a68SDimitry Andric ScopeToDILocT ScopeToDILocation; 3208e8d8bef9SDimitry Andric 3209e8d8bef9SDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3210e8d8bef9SDimitry Andric // the order is unimportant, it just has to be stable. 3211349cc55cSDimitry Andric unsigned VarAssignCount = 0; 3212e8d8bef9SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3213e8d8bef9SDimitry Andric auto *MBB = OrderToBB[I]; 3214e8d8bef9SDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()]; 3215e8d8bef9SDimitry Andric // Collect each variable with a DBG_VALUE in this block. 3216e8d8bef9SDimitry Andric for (auto &idx : VTracker->Vars) { 3217e8d8bef9SDimitry Andric const auto &Var = idx.first; 3218e8d8bef9SDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3219e8d8bef9SDimitry Andric assert(ScopeLoc != nullptr); 3220e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc); 3221e8d8bef9SDimitry Andric 3222e8d8bef9SDimitry Andric // No insts in scope -> shouldn't have been recorded. 3223e8d8bef9SDimitry Andric assert(Scope != nullptr); 3224e8d8bef9SDimitry Andric 3225e8d8bef9SDimitry Andric AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3226e8d8bef9SDimitry Andric ScopeToVars[Scope].insert(Var); 32271fd87a68SDimitry Andric ScopeToAssignBlocks[Scope].insert(VTracker->MBB); 3228e8d8bef9SDimitry Andric ScopeToDILocation[Scope] = ScopeLoc; 3229349cc55cSDimitry Andric ++VarAssignCount; 3230e8d8bef9SDimitry Andric } 3231e8d8bef9SDimitry Andric } 3232e8d8bef9SDimitry Andric 3233349cc55cSDimitry Andric bool Changed = false; 3234349cc55cSDimitry Andric 3235349cc55cSDimitry Andric // If we have an extremely large number of variable assignments and blocks, 3236349cc55cSDimitry Andric // bail out at this point. We've burnt some time doing analysis already, 3237349cc55cSDimitry Andric // however we should cut our losses. 3238349cc55cSDimitry Andric if ((unsigned)MaxNumBlocks > InputBBLimit && 3239349cc55cSDimitry Andric VarAssignCount > InputDbgValLimit) { 3240349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() 3241349cc55cSDimitry Andric << " has " << MaxNumBlocks << " basic blocks and " 3242349cc55cSDimitry Andric << VarAssignCount 3243349cc55cSDimitry Andric << " variable assignments, exceeding limits.\n"); 3244e8d8bef9SDimitry Andric 3245*d56accc7SDimitry Andric // Perform memory cleanup that emitLocations would do otherwise. 3246e8d8bef9SDimitry Andric for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) { 3247e8d8bef9SDimitry Andric delete[] MOutLocs[Idx]; 3248e8d8bef9SDimitry Andric delete[] MInLocs[Idx]; 3249e8d8bef9SDimitry Andric } 3250*d56accc7SDimitry Andric } else { 3251*d56accc7SDimitry Andric // Optionally, solve the variable value problem and emit to blocks by using 3252*d56accc7SDimitry Andric // a lexical-scope-depth search. It should be functionally identical to 3253*d56accc7SDimitry Andric // the "else" block of this condition. 3254*d56accc7SDimitry Andric Changed = depthFirstVLocAndEmit( 3255*d56accc7SDimitry Andric MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks, 3256*d56accc7SDimitry Andric SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC); 3257*d56accc7SDimitry Andric } 3258*d56accc7SDimitry Andric 3259*d56accc7SDimitry Andric // Elements of these arrays will be deleted by emitLocations. 3260e8d8bef9SDimitry Andric delete[] MOutLocs; 3261e8d8bef9SDimitry Andric delete[] MInLocs; 3262e8d8bef9SDimitry Andric 3263e8d8bef9SDimitry Andric delete MTracker; 3264e8d8bef9SDimitry Andric delete TTracker; 3265e8d8bef9SDimitry Andric MTracker = nullptr; 3266e8d8bef9SDimitry Andric VTracker = nullptr; 3267e8d8bef9SDimitry Andric TTracker = nullptr; 3268e8d8bef9SDimitry Andric 3269e8d8bef9SDimitry Andric ArtificialBlocks.clear(); 3270e8d8bef9SDimitry Andric OrderToBB.clear(); 3271e8d8bef9SDimitry Andric BBToOrder.clear(); 3272e8d8bef9SDimitry Andric BBNumToRPO.clear(); 3273e8d8bef9SDimitry Andric DebugInstrNumToInstr.clear(); 3274fe6060f1SDimitry Andric DebugPHINumToValue.clear(); 32754824e7fdSDimitry Andric OverlapFragments.clear(); 32764824e7fdSDimitry Andric SeenFragments.clear(); 3277*d56accc7SDimitry Andric SeenDbgPHIs.clear(); 3278e8d8bef9SDimitry Andric 3279e8d8bef9SDimitry Andric return Changed; 3280e8d8bef9SDimitry Andric } 3281e8d8bef9SDimitry Andric 3282e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3283e8d8bef9SDimitry Andric return new InstrRefBasedLDV(); 3284e8d8bef9SDimitry Andric } 3285fe6060f1SDimitry Andric 3286fe6060f1SDimitry Andric namespace { 3287fe6060f1SDimitry Andric class LDVSSABlock; 3288fe6060f1SDimitry Andric class LDVSSAUpdater; 3289fe6060f1SDimitry Andric 3290fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We 3291fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater 3292fe6060f1SDimitry Andric // expects to zero-initialize the type. 3293fe6060f1SDimitry Andric typedef uint64_t BlockValueNum; 3294fe6060f1SDimitry Andric 3295fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block 3296fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming 3297fe6060f1SDimitry Andric /// values from parent blocks. 3298fe6060f1SDimitry Andric class LDVSSAPhi { 3299fe6060f1SDimitry Andric public: 3300fe6060f1SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3301fe6060f1SDimitry Andric LDVSSABlock *ParentBlock; 3302fe6060f1SDimitry Andric BlockValueNum PHIValNum; 3303fe6060f1SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3304fe6060f1SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3305fe6060f1SDimitry Andric 3306fe6060f1SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; } 3307fe6060f1SDimitry Andric }; 3308fe6060f1SDimitry Andric 3309fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a 3310fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock. 3311fe6060f1SDimitry Andric class LDVSSABlockIterator { 3312fe6060f1SDimitry Andric public: 3313fe6060f1SDimitry Andric MachineBasicBlock::pred_iterator PredIt; 3314fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3315fe6060f1SDimitry Andric 3316fe6060f1SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3317fe6060f1SDimitry Andric LDVSSAUpdater &Updater) 3318fe6060f1SDimitry Andric : PredIt(PredIt), Updater(Updater) {} 3319fe6060f1SDimitry Andric 3320fe6060f1SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3321fe6060f1SDimitry Andric return OtherIt.PredIt != PredIt; 3322fe6060f1SDimitry Andric } 3323fe6060f1SDimitry Andric 3324fe6060f1SDimitry Andric LDVSSABlockIterator &operator++() { 3325fe6060f1SDimitry Andric ++PredIt; 3326fe6060f1SDimitry Andric return *this; 3327fe6060f1SDimitry Andric } 3328fe6060f1SDimitry Andric 3329fe6060f1SDimitry Andric LDVSSABlock *operator*(); 3330fe6060f1SDimitry Andric }; 3331fe6060f1SDimitry Andric 3332fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because 3333fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary 3334fe6060f1SDimitry Andric /// in this block. 3335fe6060f1SDimitry Andric class LDVSSABlock { 3336fe6060f1SDimitry Andric public: 3337fe6060f1SDimitry Andric MachineBasicBlock &BB; 3338fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3339fe6060f1SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>; 3340fe6060f1SDimitry Andric /// List of PHIs in this block. There should only ever be one. 3341fe6060f1SDimitry Andric PHIListT PHIList; 3342fe6060f1SDimitry Andric 3343fe6060f1SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3344fe6060f1SDimitry Andric : BB(BB), Updater(Updater) {} 3345fe6060f1SDimitry Andric 3346fe6060f1SDimitry Andric LDVSSABlockIterator succ_begin() { 3347fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater); 3348fe6060f1SDimitry Andric } 3349fe6060f1SDimitry Andric 3350fe6060f1SDimitry Andric LDVSSABlockIterator succ_end() { 3351fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater); 3352fe6060f1SDimitry Andric } 3353fe6060f1SDimitry Andric 3354fe6060f1SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record. 3355fe6060f1SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) { 3356fe6060f1SDimitry Andric PHIList.emplace_back(Value, this); 3357fe6060f1SDimitry Andric return &PHIList.back(); 3358fe6060f1SDimitry Andric } 3359fe6060f1SDimitry Andric 3360fe6060f1SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block. 3361fe6060f1SDimitry Andric PHIListT &phis() { return PHIList; } 3362fe6060f1SDimitry Andric }; 3363fe6060f1SDimitry Andric 3364fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3365fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3366fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>. 3367fe6060f1SDimitry Andric class LDVSSAUpdater { 3368fe6060f1SDimitry Andric public: 3369fe6060f1SDimitry Andric /// Map of value numbers to PHI records. 3370fe6060f1SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3371fe6060f1SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not 3372fe6060f1SDimitry Andric /// dominated by any Def. 3373fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3374fe6060f1SDimitry Andric /// Map of machine blocks to our own records of them. 3375fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3376fe6060f1SDimitry Andric /// Machine location where any PHI must occur. 3377fe6060f1SDimitry Andric LocIdx Loc; 3378fe6060f1SDimitry Andric /// Table of live-in machine value numbers for blocks / locations. 3379fe6060f1SDimitry Andric ValueIDNum **MLiveIns; 3380fe6060f1SDimitry Andric 3381fe6060f1SDimitry Andric LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {} 3382fe6060f1SDimitry Andric 3383fe6060f1SDimitry Andric void reset() { 3384fe6060f1SDimitry Andric for (auto &Block : BlockMap) 3385fe6060f1SDimitry Andric delete Block.second; 3386fe6060f1SDimitry Andric 3387fe6060f1SDimitry Andric PHIs.clear(); 3388fe6060f1SDimitry Andric UndefMap.clear(); 3389fe6060f1SDimitry Andric BlockMap.clear(); 3390fe6060f1SDimitry Andric } 3391fe6060f1SDimitry Andric 3392fe6060f1SDimitry Andric ~LDVSSAUpdater() { reset(); } 3393fe6060f1SDimitry Andric 3394fe6060f1SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the 3395fe6060f1SDimitry Andric /// LDVSSAUpdater block map. 3396fe6060f1SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3397fe6060f1SDimitry Andric auto it = BlockMap.find(BB); 3398fe6060f1SDimitry Andric if (it == BlockMap.end()) { 3399fe6060f1SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this); 3400fe6060f1SDimitry Andric it = BlockMap.find(BB); 3401fe6060f1SDimitry Andric } 3402fe6060f1SDimitry Andric return it->second; 3403fe6060f1SDimitry Andric } 3404fe6060f1SDimitry Andric 3405fe6060f1SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at 3406fe6060f1SDimitry Andric /// the PHI location on entry. 3407fe6060f1SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) { 3408fe6060f1SDimitry Andric return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3409fe6060f1SDimitry Andric } 3410fe6060f1SDimitry Andric }; 3411fe6060f1SDimitry Andric 3412fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() { 3413fe6060f1SDimitry Andric return Updater.getSSALDVBlock(*PredIt); 3414fe6060f1SDimitry Andric } 3415fe6060f1SDimitry Andric 3416fe6060f1SDimitry Andric #ifndef NDEBUG 3417fe6060f1SDimitry Andric 3418fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3419fe6060f1SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum; 3420fe6060f1SDimitry Andric return out; 3421fe6060f1SDimitry Andric } 3422fe6060f1SDimitry Andric 3423fe6060f1SDimitry Andric #endif 3424fe6060f1SDimitry Andric 3425fe6060f1SDimitry Andric } // namespace 3426fe6060f1SDimitry Andric 3427fe6060f1SDimitry Andric namespace llvm { 3428fe6060f1SDimitry Andric 3429fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value 3430fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the 3431fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define. 3432fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them. 3433fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3434fe6060f1SDimitry Andric public: 3435fe6060f1SDimitry Andric using BlkT = LDVSSABlock; 3436fe6060f1SDimitry Andric using ValT = BlockValueNum; 3437fe6060f1SDimitry Andric using PhiT = LDVSSAPhi; 3438fe6060f1SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator; 3439fe6060f1SDimitry Andric 3440fe6060f1SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class. 3441fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3442fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3443fe6060f1SDimitry Andric 3444fe6060f1SDimitry Andric /// Iterator for PHI operands. 3445fe6060f1SDimitry Andric class PHI_iterator { 3446fe6060f1SDimitry Andric private: 3447fe6060f1SDimitry Andric LDVSSAPhi *PHI; 3448fe6060f1SDimitry Andric unsigned Idx; 3449fe6060f1SDimitry Andric 3450fe6060f1SDimitry Andric public: 3451fe6060f1SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3452fe6060f1SDimitry Andric : PHI(P), Idx(0) {} 3453fe6060f1SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3454fe6060f1SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {} 3455fe6060f1SDimitry Andric 3456fe6060f1SDimitry Andric PHI_iterator &operator++() { 3457fe6060f1SDimitry Andric Idx++; 3458fe6060f1SDimitry Andric return *this; 3459fe6060f1SDimitry Andric } 3460fe6060f1SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3461fe6060f1SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3462fe6060f1SDimitry Andric 3463fe6060f1SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3464fe6060f1SDimitry Andric 3465fe6060f1SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3466fe6060f1SDimitry Andric }; 3467fe6060f1SDimitry Andric 3468fe6060f1SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3469fe6060f1SDimitry Andric 3470fe6060f1SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) { 3471fe6060f1SDimitry Andric return PHI_iterator(PHI, true); 3472fe6060f1SDimitry Andric } 3473fe6060f1SDimitry Andric 3474fe6060f1SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3475fe6060f1SDimitry Andric /// vector. 3476fe6060f1SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB, 3477fe6060f1SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) { 3478349cc55cSDimitry Andric for (MachineBasicBlock *Pred : BB->BB.predecessors()) 3479349cc55cSDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); 3480fe6060f1SDimitry Andric } 3481fe6060f1SDimitry Andric 3482fe6060f1SDimitry Andric /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3483fe6060f1SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having 3484fe6060f1SDimitry Andric /// any DBG_PHI predecessors. 3485fe6060f1SDimitry Andric static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3486fe6060f1SDimitry Andric // Create a value number for this block -- it needs to be unique and in the 3487fe6060f1SDimitry Andric // "undef" collection, so that we know it's not real. Use a number 3488fe6060f1SDimitry Andric // representing a PHI into this block. 3489fe6060f1SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3490fe6060f1SDimitry Andric Updater->UndefMap[&BB->BB] = Num; 3491fe6060f1SDimitry Andric return Num; 3492fe6060f1SDimitry Andric } 3493fe6060f1SDimitry Andric 3494fe6060f1SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3495fe6060f1SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The 3496fe6060f1SDimitry Andric /// value number of this PHI is whatever the machine value number problem 3497fe6060f1SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater 3498fe6060f1SDimitry Andric /// tries to create a PHI where the incoming values are identical. 3499fe6060f1SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3500fe6060f1SDimitry Andric LDVSSAUpdater *Updater) { 3501fe6060f1SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB); 3502fe6060f1SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3503fe6060f1SDimitry Andric Updater->PHIs[PHIValNum] = PHI; 3504fe6060f1SDimitry Andric return PHIValNum; 3505fe6060f1SDimitry Andric } 3506fe6060f1SDimitry Andric 3507fe6060f1SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for 3508fe6060f1SDimitry Andric /// the specified predecessor block. 3509fe6060f1SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3510fe6060f1SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3511fe6060f1SDimitry Andric } 3512fe6060f1SDimitry Andric 3513fe6060f1SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value 3514fe6060f1SDimitry Andric /// is a PHI instruction. 3515fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3516fe6060f1SDimitry Andric auto PHIIt = Updater->PHIs.find(Val); 3517fe6060f1SDimitry Andric if (PHIIt == Updater->PHIs.end()) 3518fe6060f1SDimitry Andric return nullptr; 3519fe6060f1SDimitry Andric return PHIIt->second; 3520fe6060f1SDimitry Andric } 3521fe6060f1SDimitry Andric 3522fe6060f1SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3523fe6060f1SDimitry Andric /// operands, i.e., it was just added. 3524fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3525fe6060f1SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3526fe6060f1SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0) 3527fe6060f1SDimitry Andric return PHI; 3528fe6060f1SDimitry Andric return nullptr; 3529fe6060f1SDimitry Andric } 3530fe6060f1SDimitry Andric 3531fe6060f1SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value 3532fe6060f1SDimitry Andric /// that it defines. 3533fe6060f1SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3534fe6060f1SDimitry Andric }; 3535fe6060f1SDimitry Andric 3536fe6060f1SDimitry Andric } // end namespace llvm 3537fe6060f1SDimitry Andric 3538fe6060f1SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF, 3539fe6060f1SDimitry Andric ValueIDNum **MLiveOuts, 3540fe6060f1SDimitry Andric ValueIDNum **MLiveIns, 3541fe6060f1SDimitry Andric MachineInstr &Here, 3542fe6060f1SDimitry Andric uint64_t InstrNum) { 3543*d56accc7SDimitry Andric // This function will be called twice per DBG_INSTR_REF, and might end up 3544*d56accc7SDimitry Andric // computing lots of SSA information: memoize it. 3545*d56accc7SDimitry Andric auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here); 3546*d56accc7SDimitry Andric if (SeenDbgPHIIt != SeenDbgPHIs.end()) 3547*d56accc7SDimitry Andric return SeenDbgPHIIt->second; 3548*d56accc7SDimitry Andric 3549*d56accc7SDimitry Andric Optional<ValueIDNum> Result = 3550*d56accc7SDimitry Andric resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum); 3551*d56accc7SDimitry Andric SeenDbgPHIs.insert({&Here, Result}); 3552*d56accc7SDimitry Andric return Result; 3553*d56accc7SDimitry Andric } 3554*d56accc7SDimitry Andric 3555*d56accc7SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl( 3556*d56accc7SDimitry Andric MachineFunction &MF, ValueIDNum **MLiveOuts, ValueIDNum **MLiveIns, 3557*d56accc7SDimitry Andric MachineInstr &Here, uint64_t InstrNum) { 3558fe6060f1SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there 3559fe6060f1SDimitry Andric // are none, then we cannot compute a value number. 3560fe6060f1SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3561fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstrNum); 3562fe6060f1SDimitry Andric auto LowerIt = RangePair.first; 3563fe6060f1SDimitry Andric auto UpperIt = RangePair.second; 3564fe6060f1SDimitry Andric 3565fe6060f1SDimitry Andric // No DBG_PHI means there can be no location. 3566fe6060f1SDimitry Andric if (LowerIt == UpperIt) 3567fe6060f1SDimitry Andric return None; 3568fe6060f1SDimitry Andric 3569fe6060f1SDimitry Andric // If there's only one DBG_PHI, then that is our value number. 3570fe6060f1SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1) 3571fe6060f1SDimitry Andric return LowerIt->ValueRead; 3572fe6060f1SDimitry Andric 3573fe6060f1SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt); 3574fe6060f1SDimitry Andric 3575fe6060f1SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's 3576fe6060f1SDimitry Andric // technically possible for us to merge values in different registers in each 3577fe6060f1SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register 3578fe6060f1SDimitry Andric // allocation. 3579fe6060f1SDimitry Andric LocIdx Loc = LowerIt->ReadLoc; 3580fe6060f1SDimitry Andric 3581fe6060f1SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each 3582fe6060f1SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each 3583fe6060f1SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3584fe6060f1SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3585fe6060f1SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along 3586fe6060f1SDimitry Andric // the way. 3587fe6060f1SDimitry Andric // Adapted LLVM SSA Updater: 3588fe6060f1SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns); 3589fe6060f1SDimitry Andric // Map of which Def or PHI is the current value in each block. 3590fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3591fe6060f1SDimitry Andric // Set of PHIs that we have created along the way. 3592fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3593fe6060f1SDimitry Andric 3594fe6060f1SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3595fe6060f1SDimitry Andric // for the SSAUpdater. 3596fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3597fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3598fe6060f1SDimitry Andric const ValueIDNum &Num = DBG_PHI.ValueRead; 3599fe6060f1SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3600fe6060f1SDimitry Andric } 3601fe6060f1SDimitry Andric 3602fe6060f1SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3603fe6060f1SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock); 3604fe6060f1SDimitry Andric if (AvailIt != AvailableValues.end()) { 3605fe6060f1SDimitry Andric // Actually, we already know what the value is -- the Use is in the same 3606fe6060f1SDimitry Andric // block as the Def. 3607fe6060f1SDimitry Andric return ValueIDNum::fromU64(AvailIt->second); 3608fe6060f1SDimitry Andric } 3609fe6060f1SDimitry Andric 3610fe6060f1SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number 3611fe6060f1SDimitry Andric // that we are to use, and the PHIs that must happen along the way. 3612fe6060f1SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3613fe6060f1SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3614fe6060f1SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3615fe6060f1SDimitry Andric 3616fe6060f1SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used 3617fe6060f1SDimitry Andric // at this Use. There are a number of things we have to check about it though: 3618fe6060f1SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3619fe6060f1SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort. 3620fe6060f1SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3621fe6060f1SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the 3622fe6060f1SDimitry Andric // expected values. 3623fe6060f1SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the 3624fe6060f1SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number? 3625fe6060f1SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3626fe6060f1SDimitry Andric // the ValidatedValues collection below to sort this out. 3627fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3628fe6060f1SDimitry Andric 3629fe6060f1SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues. 3630fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3631fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3632fe6060f1SDimitry Andric const ValueIDNum &Num = DBG_PHI.ValueRead; 3633fe6060f1SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num)); 3634fe6060f1SDimitry Andric } 3635fe6060f1SDimitry Andric 3636fe6060f1SDimitry Andric // Sort PHIs to validate into RPO-order. 3637fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3638fe6060f1SDimitry Andric for (auto &PHI : CreatedPHIs) 3639fe6060f1SDimitry Andric SortedPHIs.push_back(PHI); 3640fe6060f1SDimitry Andric 3641fe6060f1SDimitry Andric std::sort( 3642fe6060f1SDimitry Andric SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3643fe6060f1SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3644fe6060f1SDimitry Andric }); 3645fe6060f1SDimitry Andric 3646fe6060f1SDimitry Andric for (auto &PHI : SortedPHIs) { 3647fe6060f1SDimitry Andric ValueIDNum ThisBlockValueNum = 3648fe6060f1SDimitry Andric MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3649fe6060f1SDimitry Andric 3650fe6060f1SDimitry Andric // Are all these things actually defined? 3651fe6060f1SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) { 3652fe6060f1SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point. 3653fe6060f1SDimitry Andric if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3654fe6060f1SDimitry Andric return None; 3655fe6060f1SDimitry Andric 3656fe6060f1SDimitry Andric ValueIDNum ValueToCheck; 3657fe6060f1SDimitry Andric ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 3658fe6060f1SDimitry Andric 3659fe6060f1SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first); 3660fe6060f1SDimitry Andric if (VVal == ValidatedValues.end()) { 3661fe6060f1SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication 3662fe6060f1SDimitry Andric // happens so late that DBG_PHI instructions should not be able to 3663fe6060f1SDimitry Andric // migrate into loops -- meaning we can only be live-through this 3664fe6060f1SDimitry Andric // loop. 3665fe6060f1SDimitry Andric ValueToCheck = ThisBlockValueNum; 3666fe6060f1SDimitry Andric } else { 3667fe6060f1SDimitry Andric // Does the block have as a live-out, in the location we're examining, 3668fe6060f1SDimitry Andric // the value that we expect? If not, it's been moved or clobbered. 3669fe6060f1SDimitry Andric ValueToCheck = VVal->second; 3670fe6060f1SDimitry Andric } 3671fe6060f1SDimitry Andric 3672fe6060f1SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 3673fe6060f1SDimitry Andric return None; 3674fe6060f1SDimitry Andric } 3675fe6060f1SDimitry Andric 3676fe6060f1SDimitry Andric // Record this value as validated. 3677fe6060f1SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 3678fe6060f1SDimitry Andric } 3679fe6060f1SDimitry Andric 3680fe6060f1SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value 3681fe6060f1SDimitry Andric // number was. 3682fe6060f1SDimitry Andric return Result; 3683fe6060f1SDimitry Andric } 3684