10b57cec5SDimitry Andric //===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This implements the SelectionDAGISel class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAGISel.h"
140b57cec5SDimitry Andric #include "ScheduleDAGSDNodes.h"
150b57cec5SDimitry Andric #include "SelectionDAGBuilder.h"
160b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
25bdd1243dSDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
28480093f4SDimitry Andric #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
30480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
310b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
3306c3fb27SDimitry Andric #include "llvm/Analysis/UniformityAnalysis.h"
34bdd1243dSDimitry Andric #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
35349cc55cSDimitry Andric #include "llvm/CodeGen/CodeGenCommonISel.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/FastISel.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/ISDOpcodes.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
490b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePassRegistry.h"
500b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
510b57cec5SDimitry Andric #include "llvm/CodeGen/SchedulerRegistry.h"
520b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
530b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
54753f127fSDimitry Andric #include "llvm/CodeGen/StackMaps.h"
550b57cec5SDimitry Andric #include "llvm/CodeGen/StackProtector.h"
560b57cec5SDimitry Andric #include "llvm/CodeGen/SwiftErrorValueTracking.h"
570b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
600b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
610b57cec5SDimitry Andric #include "llvm/CodeGen/ValueTypes.h"
6206c3fb27SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
630fca6ea1SDimitry Andric #include "llvm/CodeGenTypes/MachineValueType.h"
640b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
650b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
660b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
67bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
680b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
690b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
700b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
7106c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
720b57cec5SDimitry Andric #include "llvm/IR/Function.h"
730b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
740b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
750b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
760b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
770b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
780b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
79480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
800b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
810fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
825f757f3fSDimitry Andric #include "llvm/IR/PrintPasses.h"
83e8d8bef9SDimitry Andric #include "llvm/IR/Statepoint.h"
840b57cec5SDimitry Andric #include "llvm/IR/Type.h"
850b57cec5SDimitry Andric #include "llvm/IR/User.h"
860b57cec5SDimitry Andric #include "llvm/IR/Value.h"
87480093f4SDimitry Andric #include "llvm/InitializePasses.h"
880b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
890b57cec5SDimitry Andric #include "llvm/Pass.h"
900b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
910b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
920b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
930b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
940b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
950b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
960b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
970b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
980b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
990b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1000b57cec5SDimitry Andric #include "llvm/Target/TargetIntrinsicInfo.h"
1010b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
1020b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
1030b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
1040b57cec5SDimitry Andric #include <algorithm>
1050b57cec5SDimitry Andric #include <cassert>
1060b57cec5SDimitry Andric #include <cstdint>
1070b57cec5SDimitry Andric #include <iterator>
1080b57cec5SDimitry Andric #include <limits>
1090b57cec5SDimitry Andric #include <memory>
110bdd1243dSDimitry Andric #include <optional>
1110b57cec5SDimitry Andric #include <string>
1120b57cec5SDimitry Andric #include <utility>
1130b57cec5SDimitry Andric #include <vector>
1140b57cec5SDimitry Andric
1150b57cec5SDimitry Andric using namespace llvm;
1160b57cec5SDimitry Andric
1170b57cec5SDimitry Andric #define DEBUG_TYPE "isel"
1185f757f3fSDimitry Andric #define ISEL_DUMP_DEBUG_TYPE DEBUG_TYPE "-dump"
1190b57cec5SDimitry Andric
1200b57cec5SDimitry Andric STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
1210b57cec5SDimitry Andric STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
1220b57cec5SDimitry Andric STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
1230b57cec5SDimitry Andric STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
1240b57cec5SDimitry Andric STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
1250b57cec5SDimitry Andric STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
1260b57cec5SDimitry Andric STATISTIC(NumFastIselFailLowerArguments,
1270b57cec5SDimitry Andric "Number of entry blocks where fast isel failed to lower arguments");
1280b57cec5SDimitry Andric
1290b57cec5SDimitry Andric static cl::opt<int> EnableFastISelAbort(
1300b57cec5SDimitry Andric "fast-isel-abort", cl::Hidden,
1310b57cec5SDimitry Andric cl::desc("Enable abort calls when \"fast\" instruction selection "
1320b57cec5SDimitry Andric "fails to lower an instruction: 0 disable the abort, 1 will "
1330b57cec5SDimitry Andric "abort but for args, calls and terminators, 2 will also "
1340b57cec5SDimitry Andric "abort for argument lowering, and 3 will never fallback "
1350b57cec5SDimitry Andric "to SelectionDAG."));
1360b57cec5SDimitry Andric
1370b57cec5SDimitry Andric static cl::opt<bool> EnableFastISelFallbackReport(
1380b57cec5SDimitry Andric "fast-isel-report-on-fallback", cl::Hidden,
1390b57cec5SDimitry Andric cl::desc("Emit a diagnostic when \"fast\" instruction selection "
1400b57cec5SDimitry Andric "falls back to SelectionDAG."));
1410b57cec5SDimitry Andric
1420b57cec5SDimitry Andric static cl::opt<bool>
1430b57cec5SDimitry Andric UseMBPI("use-mbpi",
1440b57cec5SDimitry Andric cl::desc("use Machine Branch Probability Info"),
1450b57cec5SDimitry Andric cl::init(true), cl::Hidden);
1460b57cec5SDimitry Andric
1470b57cec5SDimitry Andric #ifndef NDEBUG
1480b57cec5SDimitry Andric static cl::opt<std::string>
1490b57cec5SDimitry Andric FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
1500b57cec5SDimitry Andric cl::desc("Only display the basic block whose name "
1510b57cec5SDimitry Andric "matches this for all view-*-dags options"));
1520b57cec5SDimitry Andric static cl::opt<bool>
1530b57cec5SDimitry Andric ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
1540b57cec5SDimitry Andric cl::desc("Pop up a window to show dags before the first "
1550b57cec5SDimitry Andric "dag combine pass"));
1560b57cec5SDimitry Andric static cl::opt<bool>
1570b57cec5SDimitry Andric ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
1580b57cec5SDimitry Andric cl::desc("Pop up a window to show dags before legalize types"));
1590b57cec5SDimitry Andric static cl::opt<bool>
160480093f4SDimitry Andric ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
161480093f4SDimitry Andric cl::desc("Pop up a window to show dags before the post "
162480093f4SDimitry Andric "legalize types dag combine pass"));
163480093f4SDimitry Andric static cl::opt<bool>
1640b57cec5SDimitry Andric ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
1650b57cec5SDimitry Andric cl::desc("Pop up a window to show dags before legalize"));
1660b57cec5SDimitry Andric static cl::opt<bool>
1670b57cec5SDimitry Andric ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
1680b57cec5SDimitry Andric cl::desc("Pop up a window to show dags before the second "
1690b57cec5SDimitry Andric "dag combine pass"));
1700b57cec5SDimitry Andric static cl::opt<bool>
1710b57cec5SDimitry Andric ViewISelDAGs("view-isel-dags", cl::Hidden,
1720b57cec5SDimitry Andric cl::desc("Pop up a window to show isel dags as they are selected"));
1730b57cec5SDimitry Andric static cl::opt<bool>
1740b57cec5SDimitry Andric ViewSchedDAGs("view-sched-dags", cl::Hidden,
1750b57cec5SDimitry Andric cl::desc("Pop up a window to show sched dags as they are processed"));
1760b57cec5SDimitry Andric static cl::opt<bool>
1770b57cec5SDimitry Andric ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
1780b57cec5SDimitry Andric cl::desc("Pop up a window to show SUnit dags after they are processed"));
1790b57cec5SDimitry Andric #else
180480093f4SDimitry Andric static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
181480093f4SDimitry Andric ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
182480093f4SDimitry Andric ViewDAGCombine2 = false, ViewISelDAGs = false,
183480093f4SDimitry Andric ViewSchedDAGs = false, ViewSUnitDAGs = false;
1840b57cec5SDimitry Andric #endif
1850b57cec5SDimitry Andric
1865f757f3fSDimitry Andric #ifndef NDEBUG
1875f757f3fSDimitry Andric #define ISEL_DUMP(X) \
1885f757f3fSDimitry Andric do { \
1895f757f3fSDimitry Andric if (llvm::DebugFlag && \
1905f757f3fSDimitry Andric (isCurrentDebugType(DEBUG_TYPE) || \
1915f757f3fSDimitry Andric (isCurrentDebugType(ISEL_DUMP_DEBUG_TYPE) && MatchFilterFuncName))) { \
1925f757f3fSDimitry Andric X; \
1935f757f3fSDimitry Andric } \
1945f757f3fSDimitry Andric } while (false)
1955f757f3fSDimitry Andric #else
1965f757f3fSDimitry Andric #define ISEL_DUMP(X) do { } while (false)
1975f757f3fSDimitry Andric #endif
1985f757f3fSDimitry Andric
1990b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
2000b57cec5SDimitry Andric ///
2010b57cec5SDimitry Andric /// RegisterScheduler class - Track the registration of instruction schedulers.
2020b57cec5SDimitry Andric ///
2030b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
2040b57cec5SDimitry Andric MachinePassRegistry<RegisterScheduler::FunctionPassCtor>
2050b57cec5SDimitry Andric RegisterScheduler::Registry;
2060b57cec5SDimitry Andric
2070b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
2080b57cec5SDimitry Andric ///
2090b57cec5SDimitry Andric /// ISHeuristic command line option for instruction schedulers.
2100b57cec5SDimitry Andric ///
2110b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
2120b57cec5SDimitry Andric static cl::opt<RegisterScheduler::FunctionPassCtor, false,
2130b57cec5SDimitry Andric RegisterPassParser<RegisterScheduler>>
2140b57cec5SDimitry Andric ISHeuristic("pre-RA-sched",
2150b57cec5SDimitry Andric cl::init(&createDefaultScheduler), cl::Hidden,
2160b57cec5SDimitry Andric cl::desc("Instruction schedulers available (before register"
2170b57cec5SDimitry Andric " allocation):"));
2180b57cec5SDimitry Andric
2190b57cec5SDimitry Andric static RegisterScheduler
2200b57cec5SDimitry Andric defaultListDAGScheduler("default", "Best scheduler for the target",
2210b57cec5SDimitry Andric createDefaultScheduler);
2220b57cec5SDimitry Andric
dontUseFastISelFor(const Function & Fn)2235f757f3fSDimitry Andric static bool dontUseFastISelFor(const Function &Fn) {
2245f757f3fSDimitry Andric // Don't enable FastISel for functions with swiftasync Arguments.
2255f757f3fSDimitry Andric // Debug info on those is reliant on good Argument lowering, and FastISel is
2265f757f3fSDimitry Andric // not capable of lowering the entire function. Mixing the two selectors tend
2275f757f3fSDimitry Andric // to result in poor lowering of Arguments.
2285f757f3fSDimitry Andric return any_of(Fn.args(), [](const Argument &Arg) {
2295f757f3fSDimitry Andric return Arg.hasAttribute(Attribute::AttrKind::SwiftAsync);
2305f757f3fSDimitry Andric });
2315f757f3fSDimitry Andric }
2325f757f3fSDimitry Andric
2330b57cec5SDimitry Andric namespace llvm {
2340b57cec5SDimitry Andric
2350b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
2360b57cec5SDimitry Andric /// This class is used by SelectionDAGISel to temporarily override
2370b57cec5SDimitry Andric /// the optimization level on a per-function basis.
2380b57cec5SDimitry Andric class OptLevelChanger {
2390b57cec5SDimitry Andric SelectionDAGISel &IS;
2405f757f3fSDimitry Andric CodeGenOptLevel SavedOptLevel;
2410b57cec5SDimitry Andric bool SavedFastISel;
2420b57cec5SDimitry Andric
2430b57cec5SDimitry Andric public:
OptLevelChanger(SelectionDAGISel & ISel,CodeGenOptLevel NewOptLevel)2445f757f3fSDimitry Andric OptLevelChanger(SelectionDAGISel &ISel, CodeGenOptLevel NewOptLevel)
2455f757f3fSDimitry Andric : IS(ISel) {
2460b57cec5SDimitry Andric SavedOptLevel = IS.OptLevel;
2475ffd83dbSDimitry Andric SavedFastISel = IS.TM.Options.EnableFastISel;
2485f757f3fSDimitry Andric if (NewOptLevel != SavedOptLevel) {
2490b57cec5SDimitry Andric IS.OptLevel = NewOptLevel;
2500b57cec5SDimitry Andric IS.TM.setOptLevel(NewOptLevel);
2510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
2520b57cec5SDimitry Andric << IS.MF->getFunction().getName() << "\n");
2535f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(SavedOptLevel)
2545f757f3fSDimitry Andric << " ; After: -O" << static_cast<int>(NewOptLevel)
2555f757f3fSDimitry Andric << "\n");
2565f757f3fSDimitry Andric if (NewOptLevel == CodeGenOptLevel::None)
2570b57cec5SDimitry Andric IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
2585f757f3fSDimitry Andric }
2595f757f3fSDimitry Andric if (dontUseFastISelFor(IS.MF->getFunction()))
2605f757f3fSDimitry Andric IS.TM.setFastISel(false);
2610b57cec5SDimitry Andric LLVM_DEBUG(
2620b57cec5SDimitry Andric dbgs() << "\tFastISel is "
2630b57cec5SDimitry Andric << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
2640b57cec5SDimitry Andric << "\n");
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric
~OptLevelChanger()2670b57cec5SDimitry Andric ~OptLevelChanger() {
2680b57cec5SDimitry Andric if (IS.OptLevel == SavedOptLevel)
2690b57cec5SDimitry Andric return;
2700b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
2710b57cec5SDimitry Andric << IS.MF->getFunction().getName() << "\n");
2725f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(IS.OptLevel)
2735f757f3fSDimitry Andric << " ; After: -O" << static_cast<int>(SavedOptLevel) << "\n");
2740b57cec5SDimitry Andric IS.OptLevel = SavedOptLevel;
2750b57cec5SDimitry Andric IS.TM.setOptLevel(SavedOptLevel);
2760b57cec5SDimitry Andric IS.TM.setFastISel(SavedFastISel);
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric };
2790b57cec5SDimitry Andric
2800b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
2810b57cec5SDimitry Andric /// createDefaultScheduler - This creates an instruction scheduler appropriate
2820b57cec5SDimitry Andric /// for the target.
createDefaultScheduler(SelectionDAGISel * IS,CodeGenOptLevel OptLevel)2830b57cec5SDimitry Andric ScheduleDAGSDNodes *createDefaultScheduler(SelectionDAGISel *IS,
2845f757f3fSDimitry Andric CodeGenOptLevel OptLevel) {
2850b57cec5SDimitry Andric const TargetLowering *TLI = IS->TLI;
2860b57cec5SDimitry Andric const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric // Try first to see if the Target has its own way of selecting a scheduler
2890b57cec5SDimitry Andric if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
2900b57cec5SDimitry Andric return SchedulerCtor(IS, OptLevel);
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric
2935f757f3fSDimitry Andric if (OptLevel == CodeGenOptLevel::None ||
2940b57cec5SDimitry Andric (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
2950b57cec5SDimitry Andric TLI->getSchedulingPreference() == Sched::Source)
2960b57cec5SDimitry Andric return createSourceListDAGScheduler(IS, OptLevel);
2970b57cec5SDimitry Andric if (TLI->getSchedulingPreference() == Sched::RegPressure)
2980b57cec5SDimitry Andric return createBURRListDAGScheduler(IS, OptLevel);
2990b57cec5SDimitry Andric if (TLI->getSchedulingPreference() == Sched::Hybrid)
3000b57cec5SDimitry Andric return createHybridListDAGScheduler(IS, OptLevel);
3010b57cec5SDimitry Andric if (TLI->getSchedulingPreference() == Sched::VLIW)
3020b57cec5SDimitry Andric return createVLIWDAGScheduler(IS, OptLevel);
303fe6060f1SDimitry Andric if (TLI->getSchedulingPreference() == Sched::Fast)
304fe6060f1SDimitry Andric return createFastDAGScheduler(IS, OptLevel);
305fe6060f1SDimitry Andric if (TLI->getSchedulingPreference() == Sched::Linearize)
306fe6060f1SDimitry Andric return createDAGLinearizer(IS, OptLevel);
3070b57cec5SDimitry Andric assert(TLI->getSchedulingPreference() == Sched::ILP &&
3080b57cec5SDimitry Andric "Unknown sched type!");
3090b57cec5SDimitry Andric return createILPListDAGScheduler(IS, OptLevel);
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric
3120b57cec5SDimitry Andric } // end namespace llvm
3130b57cec5SDimitry Andric
3140b57cec5SDimitry Andric MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const3150b57cec5SDimitry Andric TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
3160b57cec5SDimitry Andric MachineBasicBlock *MBB) const {
3170b57cec5SDimitry Andric #ifndef NDEBUG
3180b57cec5SDimitry Andric dbgs() << "If a target marks an instruction with "
3190b57cec5SDimitry Andric "'usesCustomInserter', it must implement "
3200eae32dcSDimitry Andric "TargetLowering::EmitInstrWithCustomInserter!\n";
3210b57cec5SDimitry Andric #endif
3220b57cec5SDimitry Andric llvm_unreachable(nullptr);
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric
AdjustInstrPostInstrSelection(MachineInstr & MI,SDNode * Node) const3250b57cec5SDimitry Andric void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
3260b57cec5SDimitry Andric SDNode *Node) const {
3270b57cec5SDimitry Andric assert(!MI.hasPostISelHook() &&
3280b57cec5SDimitry Andric "If a target marks an instruction with 'hasPostISelHook', "
3290b57cec5SDimitry Andric "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric
3320b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3330b57cec5SDimitry Andric // SelectionDAGISel code
3340b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3350b57cec5SDimitry Andric
SelectionDAGISelLegacy(char & ID,std::unique_ptr<SelectionDAGISel> S)3360fca6ea1SDimitry Andric SelectionDAGISelLegacy::SelectionDAGISelLegacy(
3370fca6ea1SDimitry Andric char &ID, std::unique_ptr<SelectionDAGISel> S)
3380fca6ea1SDimitry Andric : MachineFunctionPass(ID), Selector(std::move(S)) {
3390fca6ea1SDimitry Andric initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
3400fca6ea1SDimitry Andric initializeBranchProbabilityInfoWrapperPassPass(
3410fca6ea1SDimitry Andric *PassRegistry::getPassRegistry());
3420fca6ea1SDimitry Andric initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
3430fca6ea1SDimitry Andric initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
3440fca6ea1SDimitry Andric }
3450fca6ea1SDimitry Andric
runOnMachineFunction(MachineFunction & MF)3460fca6ea1SDimitry Andric bool SelectionDAGISelLegacy::runOnMachineFunction(MachineFunction &MF) {
3470fca6ea1SDimitry Andric // If we already selected that function, we do not need to run SDISel.
3480fca6ea1SDimitry Andric if (MF.getProperties().hasProperty(
3490fca6ea1SDimitry Andric MachineFunctionProperties::Property::Selected))
3500fca6ea1SDimitry Andric return false;
3510fca6ea1SDimitry Andric
3520fca6ea1SDimitry Andric // Do some sanity-checking on the command-line options.
3530fca6ea1SDimitry Andric if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
3540fca6ea1SDimitry Andric report_fatal_error("-fast-isel-abort > 0 requires -fast-isel");
3550fca6ea1SDimitry Andric
3560fca6ea1SDimitry Andric // Decide what flavour of variable location debug-info will be used, before
3570fca6ea1SDimitry Andric // we change the optimisation level.
3580fca6ea1SDimitry Andric MF.setUseDebugInstrRef(MF.shouldUseDebugInstrRef());
3590fca6ea1SDimitry Andric
3600fca6ea1SDimitry Andric // Reset the target options before resetting the optimization
3610fca6ea1SDimitry Andric // level below.
3620fca6ea1SDimitry Andric // FIXME: This is a horrible hack and should be processed via
3630fca6ea1SDimitry Andric // codegen looking at the optimization level explicitly when
3640fca6ea1SDimitry Andric // it wants to look at it.
3650fca6ea1SDimitry Andric Selector->TM.resetTargetOptions(MF.getFunction());
3660fca6ea1SDimitry Andric // Reset OptLevel to None for optnone functions.
3670fca6ea1SDimitry Andric CodeGenOptLevel NewOptLevel = skipFunction(MF.getFunction())
3680fca6ea1SDimitry Andric ? CodeGenOptLevel::None
3690fca6ea1SDimitry Andric : Selector->OptLevel;
3700fca6ea1SDimitry Andric
3710fca6ea1SDimitry Andric Selector->MF = &MF;
3720fca6ea1SDimitry Andric OptLevelChanger OLC(*Selector, NewOptLevel);
3730fca6ea1SDimitry Andric Selector->initializeAnalysisResults(*this);
3740fca6ea1SDimitry Andric return Selector->runOnMachineFunction(MF);
3750fca6ea1SDimitry Andric }
3760fca6ea1SDimitry Andric
SelectionDAGISel(TargetMachine & tm,CodeGenOptLevel OL)3770fca6ea1SDimitry Andric SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOptLevel OL)
3780fca6ea1SDimitry Andric : TM(tm), FuncInfo(new FunctionLoweringInfo()),
3790b57cec5SDimitry Andric SwiftError(new SwiftErrorValueTracking()),
3800b57cec5SDimitry Andric CurDAG(new SelectionDAG(tm, OL)),
381480093f4SDimitry Andric SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
382480093f4SDimitry Andric OL)),
3831fd87a68SDimitry Andric OptLevel(OL) {
3840b57cec5SDimitry Andric initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
3850b57cec5SDimitry Andric initializeBranchProbabilityInfoWrapperPassPass(
3860b57cec5SDimitry Andric *PassRegistry::getPassRegistry());
3870b57cec5SDimitry Andric initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
388480093f4SDimitry Andric initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric
~SelectionDAGISel()3910b57cec5SDimitry Andric SelectionDAGISel::~SelectionDAGISel() {
3920b57cec5SDimitry Andric delete CurDAG;
3930b57cec5SDimitry Andric delete SwiftError;
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const3960fca6ea1SDimitry Andric void SelectionDAGISelLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
3970fca6ea1SDimitry Andric CodeGenOptLevel OptLevel = Selector->OptLevel;
3985f757f3fSDimitry Andric if (OptLevel != CodeGenOptLevel::None)
3990b57cec5SDimitry Andric AU.addRequired<AAResultsWrapperPass>();
4000b57cec5SDimitry Andric AU.addRequired<GCModuleInfo>();
4010b57cec5SDimitry Andric AU.addRequired<StackProtector>();
4020b57cec5SDimitry Andric AU.addPreserved<GCModuleInfo>();
4030b57cec5SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>();
4040fca6ea1SDimitry Andric #ifndef NDEBUG
4050b57cec5SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>();
4060fca6ea1SDimitry Andric #endif
407bdd1243dSDimitry Andric AU.addRequired<AssumptionCacheTracker>();
4085f757f3fSDimitry Andric if (UseMBPI && OptLevel != CodeGenOptLevel::None)
4090b57cec5SDimitry Andric AU.addRequired<BranchProbabilityInfoWrapperPass>();
410480093f4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>();
411bdd1243dSDimitry Andric // AssignmentTrackingAnalysis only runs if assignment tracking is enabled for
412bdd1243dSDimitry Andric // the module.
413bdd1243dSDimitry Andric AU.addRequired<AssignmentTrackingAnalysis>();
414bdd1243dSDimitry Andric AU.addPreserved<AssignmentTrackingAnalysis>();
4155f757f3fSDimitry Andric if (OptLevel != CodeGenOptLevel::None)
416480093f4SDimitry Andric LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
4170b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric
computeUsesMSVCFloatingPoint(const Triple & TT,const Function & F,MachineModuleInfo & MMI)4200b57cec5SDimitry Andric static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
4210b57cec5SDimitry Andric MachineModuleInfo &MMI) {
4220b57cec5SDimitry Andric // Only needed for MSVC
4230b57cec5SDimitry Andric if (!TT.isWindowsMSVCEnvironment())
4240b57cec5SDimitry Andric return;
4250b57cec5SDimitry Andric
4260b57cec5SDimitry Andric // If it's already set, nothing to do.
4270b57cec5SDimitry Andric if (MMI.usesMSVCFloatingPoint())
4280b57cec5SDimitry Andric return;
4290b57cec5SDimitry Andric
4300b57cec5SDimitry Andric for (const Instruction &I : instructions(F)) {
4310b57cec5SDimitry Andric if (I.getType()->isFPOrFPVectorTy()) {
4320b57cec5SDimitry Andric MMI.setUsesMSVCFloatingPoint(true);
4330b57cec5SDimitry Andric return;
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric for (const auto &Op : I.operands()) {
4360b57cec5SDimitry Andric if (Op->getType()->isFPOrFPVectorTy()) {
4370b57cec5SDimitry Andric MMI.setUsesMSVCFloatingPoint(true);
4380b57cec5SDimitry Andric return;
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric }
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric
4440fca6ea1SDimitry Andric PreservedAnalyses
run(MachineFunction & MF,MachineFunctionAnalysisManager & MFAM)4450fca6ea1SDimitry Andric SelectionDAGISelPass::run(MachineFunction &MF,
4460fca6ea1SDimitry Andric MachineFunctionAnalysisManager &MFAM) {
4470b57cec5SDimitry Andric // If we already selected that function, we do not need to run SDISel.
4480fca6ea1SDimitry Andric if (MF.getProperties().hasProperty(
4490b57cec5SDimitry Andric MachineFunctionProperties::Property::Selected))
4500fca6ea1SDimitry Andric return PreservedAnalyses::all();
4510fca6ea1SDimitry Andric
4520b57cec5SDimitry Andric // Do some sanity-checking on the command-line options.
4530fca6ea1SDimitry Andric if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
4540fca6ea1SDimitry Andric report_fatal_error("-fast-isel-abort > 0 requires -fast-isel");
4555f757f3fSDimitry Andric
4563a9a9c0cSDimitry Andric // Decide what flavour of variable location debug-info will be used, before
4573a9a9c0cSDimitry Andric // we change the optimisation level.
4580fca6ea1SDimitry Andric MF.setUseDebugInstrRef(MF.shouldUseDebugInstrRef());
4593a9a9c0cSDimitry Andric
4600b57cec5SDimitry Andric // Reset the target options before resetting the optimization
4610b57cec5SDimitry Andric // level below.
4620b57cec5SDimitry Andric // FIXME: This is a horrible hack and should be processed via
4630b57cec5SDimitry Andric // codegen looking at the optimization level explicitly when
4640b57cec5SDimitry Andric // it wants to look at it.
4650fca6ea1SDimitry Andric Selector->TM.resetTargetOptions(MF.getFunction());
4660b57cec5SDimitry Andric // Reset OptLevel to None for optnone functions.
4670fca6ea1SDimitry Andric // TODO: Add a function analysis to handle this.
4680fca6ea1SDimitry Andric Selector->MF = &MF;
4690fca6ea1SDimitry Andric // Reset OptLevel to None for optnone functions.
4700fca6ea1SDimitry Andric CodeGenOptLevel NewOptLevel = MF.getFunction().hasOptNone()
4710fca6ea1SDimitry Andric ? CodeGenOptLevel::None
4720fca6ea1SDimitry Andric : Selector->OptLevel;
4730fca6ea1SDimitry Andric
4740fca6ea1SDimitry Andric OptLevelChanger OLC(*Selector, NewOptLevel);
4750fca6ea1SDimitry Andric Selector->initializeAnalysisResults(MFAM);
4760fca6ea1SDimitry Andric Selector->runOnMachineFunction(MF);
4770fca6ea1SDimitry Andric
4780fca6ea1SDimitry Andric return getMachineFunctionPassPreservedAnalyses();
4790fca6ea1SDimitry Andric }
4800fca6ea1SDimitry Andric
initializeAnalysisResults(MachineFunctionAnalysisManager & MFAM)4810fca6ea1SDimitry Andric void SelectionDAGISel::initializeAnalysisResults(
4820fca6ea1SDimitry Andric MachineFunctionAnalysisManager &MFAM) {
4830fca6ea1SDimitry Andric auto &FAM = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(*MF)
4840fca6ea1SDimitry Andric .getManager();
4850fca6ea1SDimitry Andric auto &MAMP = MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(*MF);
4860fca6ea1SDimitry Andric Function &Fn = MF->getFunction();
4870fca6ea1SDimitry Andric #ifndef NDEBUG
4880fca6ea1SDimitry Andric FuncName = Fn.getName();
4890fca6ea1SDimitry Andric MatchFilterFuncName = isFunctionInPrintList(FuncName);
4900fca6ea1SDimitry Andric #else
4910fca6ea1SDimitry Andric (void)MatchFilterFuncName;
4920fca6ea1SDimitry Andric #endif
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric TII = MF->getSubtarget().getInstrInfo();
4950b57cec5SDimitry Andric TLI = MF->getSubtarget().getTargetLowering();
4960b57cec5SDimitry Andric RegInfo = &MF->getRegInfo();
4970fca6ea1SDimitry Andric LibInfo = &FAM.getResult<TargetLibraryAnalysis>(Fn);
4980fca6ea1SDimitry Andric GFI = Fn.hasGC() ? &FAM.getResult<GCFunctionAnalysis>(Fn) : nullptr;
4998bcb0991SDimitry Andric ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
5000fca6ea1SDimitry Andric AC = &FAM.getResult<AssumptionAnalysis>(Fn);
5010fca6ea1SDimitry Andric auto *PSI = MAMP.getCachedResult<ProfileSummaryAnalysis>(*Fn.getParent());
5025ffd83dbSDimitry Andric BlockFrequencyInfo *BFI = nullptr;
5030fca6ea1SDimitry Andric FAM.getResult<BlockFrequencyAnalysis>(Fn);
5045f757f3fSDimitry Andric if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
5050fca6ea1SDimitry Andric BFI = &FAM.getResult<BlockFrequencyAnalysis>(Fn);
5060b57cec5SDimitry Andric
507bdd1243dSDimitry Andric FunctionVarLocs const *FnVarLocs = nullptr;
508bdd1243dSDimitry Andric if (isAssignmentTrackingEnabled(*Fn.getParent()))
5090fca6ea1SDimitry Andric FnVarLocs = &FAM.getResult<DebugAssignmentTrackingAnalysis>(Fn);
510bdd1243dSDimitry Andric
5110fca6ea1SDimitry Andric auto *UA = FAM.getCachedResult<UniformityInfoAnalysis>(Fn);
5120fca6ea1SDimitry Andric CurDAG->init(*MF, *ORE, MFAM, LibInfo, UA, PSI, BFI, FnVarLocs);
5130b57cec5SDimitry Andric
5140b57cec5SDimitry Andric // Now get the optional analyzes if we want to.
5150b57cec5SDimitry Andric // This is based on the possibly changed OptLevel (after optnone is taken
5160b57cec5SDimitry Andric // into account). That's unfortunate but OK because it just means we won't
5170b57cec5SDimitry Andric // ask for passes that have been required anyway.
5180b57cec5SDimitry Andric
5195f757f3fSDimitry Andric if (UseMBPI && OptLevel != CodeGenOptLevel::None)
5200fca6ea1SDimitry Andric FuncInfo->BPI = &FAM.getResult<BranchProbabilityAnalysis>(Fn);
5210b57cec5SDimitry Andric else
5220b57cec5SDimitry Andric FuncInfo->BPI = nullptr;
5230b57cec5SDimitry Andric
5245f757f3fSDimitry Andric if (OptLevel != CodeGenOptLevel::None)
5250fca6ea1SDimitry Andric AA = &FAM.getResult<AAManager>(Fn);
5260b57cec5SDimitry Andric else
5270b57cec5SDimitry Andric AA = nullptr;
5280b57cec5SDimitry Andric
5290fca6ea1SDimitry Andric SP = &FAM.getResult<SSPLayoutAnalysis>(Fn);
5300fca6ea1SDimitry Andric
5310fca6ea1SDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
5320fca6ea1SDimitry Andric TTI = &FAM.getResult<TargetIRAnalysis>(Fn);
5330fca6ea1SDimitry Andric #endif
5340fca6ea1SDimitry Andric }
5350fca6ea1SDimitry Andric
initializeAnalysisResults(MachineFunctionPass & MFP)5360fca6ea1SDimitry Andric void SelectionDAGISel::initializeAnalysisResults(MachineFunctionPass &MFP) {
5370fca6ea1SDimitry Andric Function &Fn = MF->getFunction();
5380fca6ea1SDimitry Andric #ifndef NDEBUG
5390fca6ea1SDimitry Andric FuncName = Fn.getName();
5400fca6ea1SDimitry Andric MatchFilterFuncName = isFunctionInPrintList(FuncName);
5410fca6ea1SDimitry Andric #else
5420fca6ea1SDimitry Andric (void)MatchFilterFuncName;
5430fca6ea1SDimitry Andric #endif
5440fca6ea1SDimitry Andric
5450fca6ea1SDimitry Andric TII = MF->getSubtarget().getInstrInfo();
5460fca6ea1SDimitry Andric TLI = MF->getSubtarget().getTargetLowering();
5470fca6ea1SDimitry Andric RegInfo = &MF->getRegInfo();
5480fca6ea1SDimitry Andric LibInfo = &MFP.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn);
5490fca6ea1SDimitry Andric GFI = Fn.hasGC() ? &MFP.getAnalysis<GCModuleInfo>().getFunctionInfo(Fn)
5500fca6ea1SDimitry Andric : nullptr;
5510fca6ea1SDimitry Andric ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
5520fca6ea1SDimitry Andric AC = &MFP.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(Fn);
5530fca6ea1SDimitry Andric auto *PSI = &MFP.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
5540fca6ea1SDimitry Andric BlockFrequencyInfo *BFI = nullptr;
5550fca6ea1SDimitry Andric if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
5560fca6ea1SDimitry Andric BFI = &MFP.getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
5570fca6ea1SDimitry Andric
5580fca6ea1SDimitry Andric FunctionVarLocs const *FnVarLocs = nullptr;
5590fca6ea1SDimitry Andric if (isAssignmentTrackingEnabled(*Fn.getParent()))
5600fca6ea1SDimitry Andric FnVarLocs = MFP.getAnalysis<AssignmentTrackingAnalysis>().getResults();
5610fca6ea1SDimitry Andric
5620fca6ea1SDimitry Andric UniformityInfo *UA = nullptr;
5630fca6ea1SDimitry Andric if (auto *UAPass = MFP.getAnalysisIfAvailable<UniformityInfoWrapperPass>())
5640fca6ea1SDimitry Andric UA = &UAPass->getUniformityInfo();
5650fca6ea1SDimitry Andric CurDAG->init(*MF, *ORE, &MFP, LibInfo, UA, PSI, BFI, FnVarLocs);
5660fca6ea1SDimitry Andric
5670fca6ea1SDimitry Andric // Now get the optional analyzes if we want to.
5680fca6ea1SDimitry Andric // This is based on the possibly changed OptLevel (after optnone is taken
5690fca6ea1SDimitry Andric // into account). That's unfortunate but OK because it just means we won't
5700fca6ea1SDimitry Andric // ask for passes that have been required anyway.
5710fca6ea1SDimitry Andric
5720fca6ea1SDimitry Andric if (UseMBPI && OptLevel != CodeGenOptLevel::None)
5730fca6ea1SDimitry Andric FuncInfo->BPI =
5740fca6ea1SDimitry Andric &MFP.getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
5750fca6ea1SDimitry Andric else
5760fca6ea1SDimitry Andric FuncInfo->BPI = nullptr;
5770fca6ea1SDimitry Andric
5780fca6ea1SDimitry Andric if (OptLevel != CodeGenOptLevel::None)
5790fca6ea1SDimitry Andric AA = &MFP.getAnalysis<AAResultsWrapperPass>().getAAResults();
5800fca6ea1SDimitry Andric else
5810fca6ea1SDimitry Andric AA = nullptr;
5820fca6ea1SDimitry Andric
5830fca6ea1SDimitry Andric SP = &MFP.getAnalysis<StackProtector>().getLayoutInfo();
5840fca6ea1SDimitry Andric
5850fca6ea1SDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
5860fca6ea1SDimitry Andric TTI = &MFP.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
5870fca6ea1SDimitry Andric #endif
5880fca6ea1SDimitry Andric }
5890fca6ea1SDimitry Andric
runOnMachineFunction(MachineFunction & mf)5900fca6ea1SDimitry Andric bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
5910fca6ea1SDimitry Andric SwiftError->setFunction(mf);
5920fca6ea1SDimitry Andric const Function &Fn = mf.getFunction();
5930fca6ea1SDimitry Andric
5940fca6ea1SDimitry Andric bool InstrRef = mf.shouldUseDebugInstrRef();
5950fca6ea1SDimitry Andric
5960fca6ea1SDimitry Andric FuncInfo->set(MF->getFunction(), *MF, CurDAG);
5970fca6ea1SDimitry Andric
5980fca6ea1SDimitry Andric ISEL_DUMP(dbgs() << "\n\n\n=== " << FuncName << '\n');
5990fca6ea1SDimitry Andric
600bdd1243dSDimitry Andric SDB->init(GFI, AA, AC, LibInfo);
6010b57cec5SDimitry Andric
6020b57cec5SDimitry Andric MF->setHasInlineAsm(false);
6030b57cec5SDimitry Andric
6040b57cec5SDimitry Andric FuncInfo->SplitCSR = false;
6050b57cec5SDimitry Andric
6060b57cec5SDimitry Andric // We split CSR if the target supports it for the given function
6070b57cec5SDimitry Andric // and the function has only return exits.
6085f757f3fSDimitry Andric if (OptLevel != CodeGenOptLevel::None && TLI->supportSplitCSR(MF)) {
6090b57cec5SDimitry Andric FuncInfo->SplitCSR = true;
6100b57cec5SDimitry Andric
6110b57cec5SDimitry Andric // Collect all the return blocks.
6120b57cec5SDimitry Andric for (const BasicBlock &BB : Fn) {
6130b57cec5SDimitry Andric if (!succ_empty(&BB))
6140b57cec5SDimitry Andric continue;
6150b57cec5SDimitry Andric
6160b57cec5SDimitry Andric const Instruction *Term = BB.getTerminator();
6170b57cec5SDimitry Andric if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
6180b57cec5SDimitry Andric continue;
6190b57cec5SDimitry Andric
6200b57cec5SDimitry Andric // Bail out if the exit block is not Return nor Unreachable.
6210b57cec5SDimitry Andric FuncInfo->SplitCSR = false;
6220b57cec5SDimitry Andric break;
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric }
6250b57cec5SDimitry Andric
6260b57cec5SDimitry Andric MachineBasicBlock *EntryMBB = &MF->front();
6270b57cec5SDimitry Andric if (FuncInfo->SplitCSR)
6280b57cec5SDimitry Andric // This performs initialization so lowering for SplitCSR will be correct.
6290b57cec5SDimitry Andric TLI->initializeSplitCSR(EntryMBB);
6300b57cec5SDimitry Andric
6310b57cec5SDimitry Andric SelectAllBasicBlocks(Fn);
6320b57cec5SDimitry Andric if (FastISelFailed && EnableFastISelFallbackReport) {
6330b57cec5SDimitry Andric DiagnosticInfoISelFallback DiagFallback(Fn);
6340b57cec5SDimitry Andric Fn.getContext().diagnose(DiagFallback);
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric
6370b57cec5SDimitry Andric // Replace forward-declared registers with the registers containing
6380b57cec5SDimitry Andric // the desired value.
6390b57cec5SDimitry Andric // Note: it is important that this happens **before** the call to
6400b57cec5SDimitry Andric // EmitLiveInCopies, since implementations can skip copies of unused
6410b57cec5SDimitry Andric // registers. If we don't apply the reg fixups before, some registers may
6420b57cec5SDimitry Andric // appear as unused and will be skipped, resulting in bad MI.
6430b57cec5SDimitry Andric MachineRegisterInfo &MRI = MF->getRegInfo();
6445ffd83dbSDimitry Andric for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
6450b57cec5SDimitry Andric E = FuncInfo->RegFixups.end();
6460b57cec5SDimitry Andric I != E; ++I) {
6475ffd83dbSDimitry Andric Register From = I->first;
6485ffd83dbSDimitry Andric Register To = I->second;
6490b57cec5SDimitry Andric // If To is also scheduled to be replaced, find what its ultimate
6500b57cec5SDimitry Andric // replacement is.
6510b57cec5SDimitry Andric while (true) {
6525ffd83dbSDimitry Andric DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
6530b57cec5SDimitry Andric if (J == E)
6540b57cec5SDimitry Andric break;
6550b57cec5SDimitry Andric To = J->second;
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric // Make sure the new register has a sufficiently constrained register class.
658bdd1243dSDimitry Andric if (From.isVirtual() && To.isVirtual())
6590b57cec5SDimitry Andric MRI.constrainRegClass(To, MRI.getRegClass(From));
6600b57cec5SDimitry Andric // Replace it.
6610b57cec5SDimitry Andric
6620b57cec5SDimitry Andric // Replacing one register with another won't touch the kill flags.
6630b57cec5SDimitry Andric // We need to conservatively clear the kill flags as a kill on the old
6640b57cec5SDimitry Andric // register might dominate existing uses of the new register.
6650b57cec5SDimitry Andric if (!MRI.use_empty(To))
6660b57cec5SDimitry Andric MRI.clearKillFlags(From);
6670b57cec5SDimitry Andric MRI.replaceRegWith(From, To);
6680b57cec5SDimitry Andric }
6690b57cec5SDimitry Andric
6700b57cec5SDimitry Andric // If the first basic block in the function has live ins that need to be
6710b57cec5SDimitry Andric // copied into vregs, emit the copies into the top of the block before
6720b57cec5SDimitry Andric // emitting the code for the block.
6730b57cec5SDimitry Andric const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
6740b57cec5SDimitry Andric RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
6750b57cec5SDimitry Andric
6760b57cec5SDimitry Andric // Insert copies in the entry block and the return blocks.
6770b57cec5SDimitry Andric if (FuncInfo->SplitCSR) {
6780b57cec5SDimitry Andric SmallVector<MachineBasicBlock*, 4> Returns;
6790b57cec5SDimitry Andric // Collect all the return blocks.
6800b57cec5SDimitry Andric for (MachineBasicBlock &MBB : mf) {
6810b57cec5SDimitry Andric if (!MBB.succ_empty())
6820b57cec5SDimitry Andric continue;
6830b57cec5SDimitry Andric
6840b57cec5SDimitry Andric MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
6850b57cec5SDimitry Andric if (Term != MBB.end() && Term->isReturn()) {
6860b57cec5SDimitry Andric Returns.push_back(&MBB);
6870b57cec5SDimitry Andric continue;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric TLI->insertCopiesSplitCSR(EntryMBB, Returns);
6910b57cec5SDimitry Andric }
6920b57cec5SDimitry Andric
6930b57cec5SDimitry Andric DenseMap<unsigned, unsigned> LiveInMap;
6940b57cec5SDimitry Andric if (!FuncInfo->ArgDbgValues.empty())
6950b57cec5SDimitry Andric for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
6960b57cec5SDimitry Andric if (LI.second)
6970b57cec5SDimitry Andric LiveInMap.insert(LI);
6980b57cec5SDimitry Andric
6990b57cec5SDimitry Andric // Insert DBG_VALUE instructions for function arguments to the entry block.
7000b57cec5SDimitry Andric for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
7010b57cec5SDimitry Andric MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
702fe6060f1SDimitry Andric assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
703fe6060f1SDimitry Andric "Function parameters should not be described by DBG_VALUE_LIST.");
704bdd1243dSDimitry Andric bool hasFI = MI->getDebugOperand(0).isFI();
7050b57cec5SDimitry Andric Register Reg =
706bdd1243dSDimitry Andric hasFI ? TRI.getFrameRegister(*MF) : MI->getDebugOperand(0).getReg();
707bdd1243dSDimitry Andric if (Reg.isPhysical())
7080b57cec5SDimitry Andric EntryMBB->insert(EntryMBB->begin(), MI);
7090b57cec5SDimitry Andric else {
7100b57cec5SDimitry Andric MachineInstr *Def = RegInfo->getVRegDef(Reg);
7110b57cec5SDimitry Andric if (Def) {
7120b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = Def;
7130b57cec5SDimitry Andric // FIXME: VR def may not be in entry block.
7140b57cec5SDimitry Andric Def->getParent()->insert(std::next(InsertPos), MI);
7150b57cec5SDimitry Andric } else
7160b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
7178bcb0991SDimitry Andric << Register::virtReg2Index(Reg) << "\n");
7180b57cec5SDimitry Andric }
7190b57cec5SDimitry Andric
720fe6060f1SDimitry Andric // Don't try and extend through copies in instruction referencing mode.
721fe6060f1SDimitry Andric if (InstrRef)
722fe6060f1SDimitry Andric continue;
723fe6060f1SDimitry Andric
7240b57cec5SDimitry Andric // If Reg is live-in then update debug info to track its copy in a vreg.
7250b57cec5SDimitry Andric DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
7260b57cec5SDimitry Andric if (LDI != LiveInMap.end()) {
7270b57cec5SDimitry Andric assert(!hasFI && "There's no handling of frame pointer updating here yet "
7280b57cec5SDimitry Andric "- add if needed");
7290b57cec5SDimitry Andric MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
7300b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = Def;
7310b57cec5SDimitry Andric const MDNode *Variable = MI->getDebugVariable();
7320b57cec5SDimitry Andric const MDNode *Expr = MI->getDebugExpression();
7330b57cec5SDimitry Andric DebugLoc DL = MI->getDebugLoc();
7340b57cec5SDimitry Andric bool IsIndirect = MI->isIndirectDebugValue();
7350b57cec5SDimitry Andric if (IsIndirect)
736bdd1243dSDimitry Andric assert(MI->getDebugOffset().getImm() == 0 &&
7370b57cec5SDimitry Andric "DBG_VALUE with nonzero offset");
7380b57cec5SDimitry Andric assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
7390b57cec5SDimitry Andric "Expected inlined-at fields to agree");
740fe6060f1SDimitry Andric assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
741fe6060f1SDimitry Andric "Didn't expect to see a DBG_VALUE_LIST here");
7420b57cec5SDimitry Andric // Def is never a terminator here, so it is ok to increment InsertPos.
7430b57cec5SDimitry Andric BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
7440b57cec5SDimitry Andric IsIndirect, LDI->second, Variable, Expr);
7450b57cec5SDimitry Andric
7460b57cec5SDimitry Andric // If this vreg is directly copied into an exported register then
7470b57cec5SDimitry Andric // that COPY instructions also need DBG_VALUE, if it is the only
7480b57cec5SDimitry Andric // user of LDI->second.
7490b57cec5SDimitry Andric MachineInstr *CopyUseMI = nullptr;
7500fca6ea1SDimitry Andric for (MachineInstr &UseMI : RegInfo->use_instructions(LDI->second)) {
7510fca6ea1SDimitry Andric if (UseMI.isDebugValue())
7520fca6ea1SDimitry Andric continue;
7530fca6ea1SDimitry Andric if (UseMI.isCopy() && !CopyUseMI && UseMI.getParent() == EntryMBB) {
7540fca6ea1SDimitry Andric CopyUseMI = &UseMI;
7550fca6ea1SDimitry Andric continue;
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric // Otherwise this is another use or second copy use.
7580fca6ea1SDimitry Andric CopyUseMI = nullptr;
7590fca6ea1SDimitry Andric break;
7600b57cec5SDimitry Andric }
7615ffd83dbSDimitry Andric if (CopyUseMI &&
7625ffd83dbSDimitry Andric TRI.getRegSizeInBits(LDI->second, MRI) ==
7635ffd83dbSDimitry Andric TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
7640b57cec5SDimitry Andric // Use MI's debug location, which describes where Variable was
7650b57cec5SDimitry Andric // declared, rather than whatever is attached to CopyUseMI.
7660b57cec5SDimitry Andric MachineInstr *NewMI =
7670b57cec5SDimitry Andric BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
7680b57cec5SDimitry Andric CopyUseMI->getOperand(0).getReg(), Variable, Expr);
7690b57cec5SDimitry Andric MachineBasicBlock::iterator Pos = CopyUseMI;
7700b57cec5SDimitry Andric EntryMBB->insertAfter(Pos, NewMI);
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric }
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric
775fe6060f1SDimitry Andric // For debug-info, in instruction referencing mode, we need to perform some
776fe6060f1SDimitry Andric // post-isel maintenence.
777bdd1243dSDimitry Andric if (MF->useDebugInstrRef())
778fe6060f1SDimitry Andric MF->finalizeDebugInstrRefs();
779fe6060f1SDimitry Andric
7800b57cec5SDimitry Andric // Determine if there are any calls in this machine function.
7810b57cec5SDimitry Andric MachineFrameInfo &MFI = MF->getFrameInfo();
7820b57cec5SDimitry Andric for (const auto &MBB : *MF) {
7830b57cec5SDimitry Andric if (MFI.hasCalls() && MF->hasInlineAsm())
7840b57cec5SDimitry Andric break;
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric for (const auto &MI : MBB) {
7870b57cec5SDimitry Andric const MCInstrDesc &MCID = TII->get(MI.getOpcode());
7880b57cec5SDimitry Andric if ((MCID.isCall() && !MCID.isReturn()) ||
7890b57cec5SDimitry Andric MI.isStackAligningInlineAsm()) {
7900b57cec5SDimitry Andric MFI.setHasCalls(true);
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric if (MI.isInlineAsm()) {
7930b57cec5SDimitry Andric MF->setHasInlineAsm(true);
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric }
7970b57cec5SDimitry Andric
7980b57cec5SDimitry Andric // Determine if floating point is used for msvc
7990b57cec5SDimitry Andric computeUsesMSVCFloatingPoint(TM.getTargetTriple(), Fn, MF->getMMI());
8000b57cec5SDimitry Andric
8010b57cec5SDimitry Andric // Release function-specific state. SDB and CurDAG are already cleared
8020b57cec5SDimitry Andric // at this point.
8030b57cec5SDimitry Andric FuncInfo->clear();
8040b57cec5SDimitry Andric
8055f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "*** MachineFunction at end of ISel ***\n");
8065f757f3fSDimitry Andric ISEL_DUMP(MF->print(dbgs()));
8070b57cec5SDimitry Andric
8080b57cec5SDimitry Andric return true;
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric
reportFastISelFailure(MachineFunction & MF,OptimizationRemarkEmitter & ORE,OptimizationRemarkMissed & R,bool ShouldAbort)8110b57cec5SDimitry Andric static void reportFastISelFailure(MachineFunction &MF,
8120b57cec5SDimitry Andric OptimizationRemarkEmitter &ORE,
8130b57cec5SDimitry Andric OptimizationRemarkMissed &R,
8140b57cec5SDimitry Andric bool ShouldAbort) {
8150b57cec5SDimitry Andric // Print the function name explicitly if we don't have a debug location (which
8160b57cec5SDimitry Andric // makes the diagnostic less useful) or if we're going to emit a raw error.
8170b57cec5SDimitry Andric if (!R.getLocation().isValid() || ShouldAbort)
8180b57cec5SDimitry Andric R << (" (in function: " + MF.getName() + ")").str();
8190b57cec5SDimitry Andric
8200b57cec5SDimitry Andric if (ShouldAbort)
821349cc55cSDimitry Andric report_fatal_error(Twine(R.getMsg()));
8220b57cec5SDimitry Andric
8230b57cec5SDimitry Andric ORE.emit(R);
82481ad6265SDimitry Andric LLVM_DEBUG(dbgs() << R.getMsg() << "\n");
8250b57cec5SDimitry Andric }
8260b57cec5SDimitry Andric
SelectBasicBlock(BasicBlock::const_iterator Begin,BasicBlock::const_iterator End,bool & HadTailCall)8270b57cec5SDimitry Andric void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
8280b57cec5SDimitry Andric BasicBlock::const_iterator End,
8290b57cec5SDimitry Andric bool &HadTailCall) {
8300b57cec5SDimitry Andric // Allow creating illegal types during DAG building for the basic block.
8310b57cec5SDimitry Andric CurDAG->NewNodesMustHaveLegalTypes = false;
8320b57cec5SDimitry Andric
8330b57cec5SDimitry Andric // Lower the instructions. If a call is emitted as a tail call, cease emitting
8345f757f3fSDimitry Andric // nodes for this block. If an instruction is elided, don't emit it, but do
8355f757f3fSDimitry Andric // handle any debug-info attached to it.
8360b57cec5SDimitry Andric for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
8370b57cec5SDimitry Andric if (!ElidedArgCopyInstrs.count(&*I))
8380b57cec5SDimitry Andric SDB->visit(*I);
8395f757f3fSDimitry Andric else
8405f757f3fSDimitry Andric SDB->visitDbgInfo(*I);
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric
8430b57cec5SDimitry Andric // Make sure the root of the DAG is up-to-date.
8440b57cec5SDimitry Andric CurDAG->setRoot(SDB->getControlRoot());
8450b57cec5SDimitry Andric HadTailCall = SDB->HasTailCall;
8460b57cec5SDimitry Andric SDB->resolveOrClearDbgInfo();
8470b57cec5SDimitry Andric SDB->clear();
8480b57cec5SDimitry Andric
8490b57cec5SDimitry Andric // Final step, emit the lowered DAG as machine code.
8500b57cec5SDimitry Andric CodeGenAndEmitDAG();
8510b57cec5SDimitry Andric }
8520b57cec5SDimitry Andric
ComputeLiveOutVRegInfo()8530b57cec5SDimitry Andric void SelectionDAGISel::ComputeLiveOutVRegInfo() {
854480093f4SDimitry Andric SmallPtrSet<SDNode *, 16> Added;
8550b57cec5SDimitry Andric SmallVector<SDNode*, 128> Worklist;
8560b57cec5SDimitry Andric
8570b57cec5SDimitry Andric Worklist.push_back(CurDAG->getRoot().getNode());
858480093f4SDimitry Andric Added.insert(CurDAG->getRoot().getNode());
8590b57cec5SDimitry Andric
8600b57cec5SDimitry Andric KnownBits Known;
8610b57cec5SDimitry Andric
8620b57cec5SDimitry Andric do {
8630b57cec5SDimitry Andric SDNode *N = Worklist.pop_back_val();
8640b57cec5SDimitry Andric
8650b57cec5SDimitry Andric // Otherwise, add all chain operands to the worklist.
8660b57cec5SDimitry Andric for (const SDValue &Op : N->op_values())
867480093f4SDimitry Andric if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
8680b57cec5SDimitry Andric Worklist.push_back(Op.getNode());
8690b57cec5SDimitry Andric
8700b57cec5SDimitry Andric // If this is a CopyToReg with a vreg dest, process it.
8710b57cec5SDimitry Andric if (N->getOpcode() != ISD::CopyToReg)
8720b57cec5SDimitry Andric continue;
8730b57cec5SDimitry Andric
8740b57cec5SDimitry Andric unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
8758bcb0991SDimitry Andric if (!Register::isVirtualRegister(DestReg))
8760b57cec5SDimitry Andric continue;
8770b57cec5SDimitry Andric
8780b57cec5SDimitry Andric // Ignore non-integer values.
8790b57cec5SDimitry Andric SDValue Src = N->getOperand(2);
8800b57cec5SDimitry Andric EVT SrcVT = Src.getValueType();
8810b57cec5SDimitry Andric if (!SrcVT.isInteger())
8820b57cec5SDimitry Andric continue;
8830b57cec5SDimitry Andric
8840b57cec5SDimitry Andric unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
8850b57cec5SDimitry Andric Known = CurDAG->computeKnownBits(Src);
8860b57cec5SDimitry Andric FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
8870b57cec5SDimitry Andric } while (!Worklist.empty());
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric
CodeGenAndEmitDAG()8900b57cec5SDimitry Andric void SelectionDAGISel::CodeGenAndEmitDAG() {
8910b57cec5SDimitry Andric StringRef GroupName = "sdag";
8920b57cec5SDimitry Andric StringRef GroupDescription = "Instruction Selection and Scheduling";
8930b57cec5SDimitry Andric std::string BlockName;
8940fca6ea1SDimitry Andric bool MatchFilterBB = false;
8950fca6ea1SDimitry Andric (void)MatchFilterBB;
8960b57cec5SDimitry Andric
8970b57cec5SDimitry Andric // Pre-type legalization allow creation of any node types.
8980b57cec5SDimitry Andric CurDAG->NewNodesMustHaveLegalTypes = false;
8990b57cec5SDimitry Andric
9000b57cec5SDimitry Andric #ifndef NDEBUG
9010b57cec5SDimitry Andric MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
9020b57cec5SDimitry Andric FilterDAGBasicBlockName ==
9030b57cec5SDimitry Andric FuncInfo->MBB->getBasicBlock()->getName());
9040b57cec5SDimitry Andric #endif
9050b57cec5SDimitry Andric #ifdef NDEBUG
906480093f4SDimitry Andric if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewDAGCombineLT ||
907480093f4SDimitry Andric ViewLegalizeDAGs || ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs ||
9080b57cec5SDimitry Andric ViewSUnitDAGs)
9090b57cec5SDimitry Andric #endif
9100b57cec5SDimitry Andric {
9110b57cec5SDimitry Andric BlockName =
9120b57cec5SDimitry Andric (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
9130b57cec5SDimitry Andric }
9145f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nInitial selection DAG: "
9150b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9160b57cec5SDimitry Andric << "'\n";
9170b57cec5SDimitry Andric CurDAG->dump());
9180b57cec5SDimitry Andric
919*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
9200fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
921349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
922e8d8bef9SDimitry Andric #endif
923e8d8bef9SDimitry Andric
9240b57cec5SDimitry Andric if (ViewDAGCombine1 && MatchFilterBB)
9250b57cec5SDimitry Andric CurDAG->viewGraph("dag-combine1 input for " + BlockName);
9260b57cec5SDimitry Andric
9270b57cec5SDimitry Andric // Run the DAG combiner in pre-legalize mode.
9280b57cec5SDimitry Andric {
9290b57cec5SDimitry Andric NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
9300b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
9310b57cec5SDimitry Andric CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel);
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric
9345f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nOptimized lowered selection DAG: "
9350b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9360b57cec5SDimitry Andric << "'\n";
9370b57cec5SDimitry Andric CurDAG->dump());
9380b57cec5SDimitry Andric
939*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
9400fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
941349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
942e8d8bef9SDimitry Andric #endif
943e8d8bef9SDimitry Andric
9440b57cec5SDimitry Andric // Second step, hack on the DAG until it only uses operations and types that
9450b57cec5SDimitry Andric // the target supports.
9460b57cec5SDimitry Andric if (ViewLegalizeTypesDAGs && MatchFilterBB)
9470b57cec5SDimitry Andric CurDAG->viewGraph("legalize-types input for " + BlockName);
9480b57cec5SDimitry Andric
9490b57cec5SDimitry Andric bool Changed;
9500b57cec5SDimitry Andric {
9510b57cec5SDimitry Andric NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
9520b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
9530b57cec5SDimitry Andric Changed = CurDAG->LegalizeTypes();
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric
9565f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nType-legalized selection DAG: "
9570b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9580b57cec5SDimitry Andric << "'\n";
9590b57cec5SDimitry Andric CurDAG->dump());
9600b57cec5SDimitry Andric
961*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
9620fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
963349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
964e8d8bef9SDimitry Andric #endif
965e8d8bef9SDimitry Andric
9660b57cec5SDimitry Andric // Only allow creation of legal node types.
9670b57cec5SDimitry Andric CurDAG->NewNodesMustHaveLegalTypes = true;
9680b57cec5SDimitry Andric
9690b57cec5SDimitry Andric if (Changed) {
9700b57cec5SDimitry Andric if (ViewDAGCombineLT && MatchFilterBB)
9710b57cec5SDimitry Andric CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
9720b57cec5SDimitry Andric
9730b57cec5SDimitry Andric // Run the DAG combiner in post-type-legalize mode.
9740b57cec5SDimitry Andric {
9750b57cec5SDimitry Andric NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
9760b57cec5SDimitry Andric GroupName, GroupDescription, TimePassesIsEnabled);
9770b57cec5SDimitry Andric CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel);
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric
9805f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nOptimized type-legalized selection DAG: "
9810b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9820b57cec5SDimitry Andric << "'\n";
9830b57cec5SDimitry Andric CurDAG->dump());
984e8d8bef9SDimitry Andric
985*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
9860fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
987349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
988e8d8bef9SDimitry Andric #endif
9890b57cec5SDimitry Andric }
9900b57cec5SDimitry Andric
9910b57cec5SDimitry Andric {
9920b57cec5SDimitry Andric NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
9930b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
9940b57cec5SDimitry Andric Changed = CurDAG->LegalizeVectors();
9950b57cec5SDimitry Andric }
9960b57cec5SDimitry Andric
9970b57cec5SDimitry Andric if (Changed) {
9985f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nVector-legalized selection DAG: "
9990b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
10000b57cec5SDimitry Andric << "'\n";
10010b57cec5SDimitry Andric CurDAG->dump());
10020b57cec5SDimitry Andric
1003*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
10040fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
1005349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
1006e8d8bef9SDimitry Andric #endif
1007e8d8bef9SDimitry Andric
10080b57cec5SDimitry Andric {
10090b57cec5SDimitry Andric NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
10100b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
10110b57cec5SDimitry Andric CurDAG->LegalizeTypes();
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric
10145f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nVector/type-legalized selection DAG: "
10150b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
10160b57cec5SDimitry Andric << "'\n";
10170b57cec5SDimitry Andric CurDAG->dump());
10180b57cec5SDimitry Andric
1019*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
10200fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
1021349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
1022e8d8bef9SDimitry Andric #endif
1023e8d8bef9SDimitry Andric
10240b57cec5SDimitry Andric if (ViewDAGCombineLT && MatchFilterBB)
10250b57cec5SDimitry Andric CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
10260b57cec5SDimitry Andric
10270b57cec5SDimitry Andric // Run the DAG combiner in post-type-legalize mode.
10280b57cec5SDimitry Andric {
10290b57cec5SDimitry Andric NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
10300b57cec5SDimitry Andric GroupName, GroupDescription, TimePassesIsEnabled);
10310b57cec5SDimitry Andric CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel);
10320b57cec5SDimitry Andric }
10330b57cec5SDimitry Andric
10345f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nOptimized vector-legalized selection DAG: "
10350b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
10360b57cec5SDimitry Andric << "'\n";
10370b57cec5SDimitry Andric CurDAG->dump());
10380b57cec5SDimitry Andric
1039*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
10400fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
1041349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
10420b57cec5SDimitry Andric #endif
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric
10450b57cec5SDimitry Andric if (ViewLegalizeDAGs && MatchFilterBB)
10460b57cec5SDimitry Andric CurDAG->viewGraph("legalize input for " + BlockName);
10470b57cec5SDimitry Andric
10480b57cec5SDimitry Andric {
10490b57cec5SDimitry Andric NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
10500b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
10510b57cec5SDimitry Andric CurDAG->Legalize();
10520b57cec5SDimitry Andric }
10530b57cec5SDimitry Andric
10545f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nLegalized selection DAG: "
10550b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
10560b57cec5SDimitry Andric << "'\n";
10570b57cec5SDimitry Andric CurDAG->dump());
10580b57cec5SDimitry Andric
1059*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
10600fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
1061349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
1062e8d8bef9SDimitry Andric #endif
1063e8d8bef9SDimitry Andric
10640b57cec5SDimitry Andric if (ViewDAGCombine2 && MatchFilterBB)
10650b57cec5SDimitry Andric CurDAG->viewGraph("dag-combine2 input for " + BlockName);
10660b57cec5SDimitry Andric
10670b57cec5SDimitry Andric // Run the DAG combiner in post-legalize mode.
10680b57cec5SDimitry Andric {
10690b57cec5SDimitry Andric NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
10700b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
10710b57cec5SDimitry Andric CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel);
10720b57cec5SDimitry Andric }
10730b57cec5SDimitry Andric
10745f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nOptimized legalized selection DAG: "
10750b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
10760b57cec5SDimitry Andric << "'\n";
10770b57cec5SDimitry Andric CurDAG->dump());
10780b57cec5SDimitry Andric
1079*a5b1eecbSDimitry Andric #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
10800fca6ea1SDimitry Andric if (TTI->hasBranchDivergence())
1081349cc55cSDimitry Andric CurDAG->VerifyDAGDivergence();
1082e8d8bef9SDimitry Andric #endif
1083e8d8bef9SDimitry Andric
10845f757f3fSDimitry Andric if (OptLevel != CodeGenOptLevel::None)
10850b57cec5SDimitry Andric ComputeLiveOutVRegInfo();
10860b57cec5SDimitry Andric
10870b57cec5SDimitry Andric if (ViewISelDAGs && MatchFilterBB)
10880b57cec5SDimitry Andric CurDAG->viewGraph("isel input for " + BlockName);
10890b57cec5SDimitry Andric
10900b57cec5SDimitry Andric // Third, instruction select all of the operations to machine code, adding the
10910b57cec5SDimitry Andric // code to the MachineBasicBlock.
10920b57cec5SDimitry Andric {
10930b57cec5SDimitry Andric NamedRegionTimer T("isel", "Instruction Selection", GroupName,
10940b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
10950b57cec5SDimitry Andric DoInstructionSelection();
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric
10985f757f3fSDimitry Andric ISEL_DUMP(dbgs() << "\nSelected selection DAG: "
10990b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
11000b57cec5SDimitry Andric << "'\n";
11010b57cec5SDimitry Andric CurDAG->dump());
11020b57cec5SDimitry Andric
11030b57cec5SDimitry Andric if (ViewSchedDAGs && MatchFilterBB)
11040b57cec5SDimitry Andric CurDAG->viewGraph("scheduler input for " + BlockName);
11050b57cec5SDimitry Andric
11060b57cec5SDimitry Andric // Schedule machine code.
11070b57cec5SDimitry Andric ScheduleDAGSDNodes *Scheduler = CreateScheduler();
11080b57cec5SDimitry Andric {
11090b57cec5SDimitry Andric NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
11100b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
11110b57cec5SDimitry Andric Scheduler->Run(CurDAG, FuncInfo->MBB);
11120b57cec5SDimitry Andric }
11130b57cec5SDimitry Andric
11140b57cec5SDimitry Andric if (ViewSUnitDAGs && MatchFilterBB)
11150b57cec5SDimitry Andric Scheduler->viewGraph();
11160b57cec5SDimitry Andric
11170b57cec5SDimitry Andric // Emit machine code to BB. This can change 'BB' to the last block being
11180b57cec5SDimitry Andric // inserted into.
11190b57cec5SDimitry Andric MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
11200b57cec5SDimitry Andric {
11210b57cec5SDimitry Andric NamedRegionTimer T("emit", "Instruction Creation", GroupName,
11220b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
11230b57cec5SDimitry Andric
11240b57cec5SDimitry Andric // FuncInfo->InsertPt is passed by reference and set to the end of the
11250b57cec5SDimitry Andric // scheduled instructions.
11260b57cec5SDimitry Andric LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric
11290b57cec5SDimitry Andric // If the block was split, make sure we update any references that are used to
11300b57cec5SDimitry Andric // update PHI nodes later on.
11310b57cec5SDimitry Andric if (FirstMBB != LastMBB)
11320b57cec5SDimitry Andric SDB->UpdateSplitBlock(FirstMBB, LastMBB);
11330b57cec5SDimitry Andric
11340b57cec5SDimitry Andric // Free the scheduler state.
11350b57cec5SDimitry Andric {
11360b57cec5SDimitry Andric NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
11370b57cec5SDimitry Andric GroupDescription, TimePassesIsEnabled);
11380b57cec5SDimitry Andric delete Scheduler;
11390b57cec5SDimitry Andric }
11400b57cec5SDimitry Andric
11410b57cec5SDimitry Andric // Free the SelectionDAG state, now that we're finished with it.
11420b57cec5SDimitry Andric CurDAG->clear();
11430b57cec5SDimitry Andric }
11440b57cec5SDimitry Andric
11450b57cec5SDimitry Andric namespace {
11460b57cec5SDimitry Andric
11470b57cec5SDimitry Andric /// ISelUpdater - helper class to handle updates of the instruction selection
11480b57cec5SDimitry Andric /// graph.
11490b57cec5SDimitry Andric class ISelUpdater : public SelectionDAG::DAGUpdateListener {
11500b57cec5SDimitry Andric SelectionDAG::allnodes_iterator &ISelPosition;
11510b57cec5SDimitry Andric
11520b57cec5SDimitry Andric public:
ISelUpdater(SelectionDAG & DAG,SelectionDAG::allnodes_iterator & isp)11530b57cec5SDimitry Andric ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
11540b57cec5SDimitry Andric : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
11550b57cec5SDimitry Andric
11560b57cec5SDimitry Andric /// NodeDeleted - Handle nodes deleted from the graph. If the node being
11570b57cec5SDimitry Andric /// deleted is the current ISelPosition node, update ISelPosition.
11580b57cec5SDimitry Andric ///
NodeDeleted(SDNode * N,SDNode * E)11590b57cec5SDimitry Andric void NodeDeleted(SDNode *N, SDNode *E) override {
11600b57cec5SDimitry Andric if (ISelPosition == SelectionDAG::allnodes_iterator(N))
11610b57cec5SDimitry Andric ++ISelPosition;
11620b57cec5SDimitry Andric }
1163bdd1243dSDimitry Andric
1164bdd1243dSDimitry Andric /// NodeInserted - Handle new nodes inserted into the graph: propagate
1165bdd1243dSDimitry Andric /// metadata from root nodes that also applies to new nodes, in case the root
1166bdd1243dSDimitry Andric /// is later deleted.
NodeInserted(SDNode * N)1167bdd1243dSDimitry Andric void NodeInserted(SDNode *N) override {
1168bdd1243dSDimitry Andric SDNode *CurNode = &*ISelPosition;
1169bdd1243dSDimitry Andric if (MDNode *MD = DAG.getPCSections(CurNode))
1170bdd1243dSDimitry Andric DAG.addPCSections(N, MD);
11710fca6ea1SDimitry Andric if (MDNode *MMRA = DAG.getMMRAMetadata(CurNode))
11720fca6ea1SDimitry Andric DAG.addMMRAMetadata(N, MMRA);
1173bdd1243dSDimitry Andric }
11740b57cec5SDimitry Andric };
11750b57cec5SDimitry Andric
11760b57cec5SDimitry Andric } // end anonymous namespace
11770b57cec5SDimitry Andric
11780b57cec5SDimitry Andric // This function is used to enforce the topological node id property
1179349cc55cSDimitry Andric // leveraged during instruction selection. Before the selection process all
1180349cc55cSDimitry Andric // nodes are given a non-negative id such that all nodes have a greater id than
11810b57cec5SDimitry Andric // their operands. As this holds transitively we can prune checks that a node N
11820b57cec5SDimitry Andric // is a predecessor of M another by not recursively checking through M's
1183349cc55cSDimitry Andric // operands if N's ID is larger than M's ID. This significantly improves
1184349cc55cSDimitry Andric // performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
11850b57cec5SDimitry Andric
1186349cc55cSDimitry Andric // However, when we fuse multiple nodes into a single node during the
1187349cc55cSDimitry Andric // selection we may induce a predecessor relationship between inputs and
1188349cc55cSDimitry Andric // outputs of distinct nodes being merged, violating the topological property.
1189349cc55cSDimitry Andric // Should a fused node have a successor which has yet to be selected,
1190349cc55cSDimitry Andric // our legality checks would be incorrect. To avoid this we mark all unselected
1191349cc55cSDimitry Andric // successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
11920b57cec5SDimitry Andric // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
11930b57cec5SDimitry Andric // We use bit-negation to more clearly enforce that node id -1 can only be
1194349cc55cSDimitry Andric // achieved by selected nodes. As the conversion is reversable to the original
1195349cc55cSDimitry Andric // Id, topological pruning can still be leveraged when looking for unselected
1196349cc55cSDimitry Andric // nodes. This method is called internally in all ISel replacement related
1197349cc55cSDimitry Andric // functions.
EnforceNodeIdInvariant(SDNode * Node)11980b57cec5SDimitry Andric void SelectionDAGISel::EnforceNodeIdInvariant(SDNode *Node) {
11990b57cec5SDimitry Andric SmallVector<SDNode *, 4> Nodes;
12000b57cec5SDimitry Andric Nodes.push_back(Node);
12010b57cec5SDimitry Andric
12020b57cec5SDimitry Andric while (!Nodes.empty()) {
12030b57cec5SDimitry Andric SDNode *N = Nodes.pop_back_val();
12040b57cec5SDimitry Andric for (auto *U : N->uses()) {
12050b57cec5SDimitry Andric auto UId = U->getNodeId();
12060b57cec5SDimitry Andric if (UId > 0) {
12070b57cec5SDimitry Andric InvalidateNodeId(U);
12080b57cec5SDimitry Andric Nodes.push_back(U);
12090b57cec5SDimitry Andric }
12100b57cec5SDimitry Andric }
12110b57cec5SDimitry Andric }
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric
1214349cc55cSDimitry Andric // InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
12150b57cec5SDimitry Andric // NodeId with the equivalent node id which is invalid for topological
12160b57cec5SDimitry Andric // pruning.
InvalidateNodeId(SDNode * N)12170b57cec5SDimitry Andric void SelectionDAGISel::InvalidateNodeId(SDNode *N) {
12180b57cec5SDimitry Andric int InvalidId = -(N->getNodeId() + 1);
12190b57cec5SDimitry Andric N->setNodeId(InvalidId);
12200b57cec5SDimitry Andric }
12210b57cec5SDimitry Andric
12220b57cec5SDimitry Andric // getUninvalidatedNodeId - get original uninvalidated node id.
getUninvalidatedNodeId(SDNode * N)12230b57cec5SDimitry Andric int SelectionDAGISel::getUninvalidatedNodeId(SDNode *N) {
12240b57cec5SDimitry Andric int Id = N->getNodeId();
12250b57cec5SDimitry Andric if (Id < -1)
12260b57cec5SDimitry Andric return -(Id + 1);
12270b57cec5SDimitry Andric return Id;
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric
DoInstructionSelection()12300b57cec5SDimitry Andric void SelectionDAGISel::DoInstructionSelection() {
12310b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
12320b57cec5SDimitry Andric << printMBBReference(*FuncInfo->MBB) << " '"
12330b57cec5SDimitry Andric << FuncInfo->MBB->getName() << "'\n");
12340b57cec5SDimitry Andric
12350b57cec5SDimitry Andric PreprocessISelDAG();
12360b57cec5SDimitry Andric
12370b57cec5SDimitry Andric // Select target instructions for the DAG.
12380b57cec5SDimitry Andric {
12390b57cec5SDimitry Andric // Number all nodes with a topological order and set DAGSize.
12400b57cec5SDimitry Andric DAGSize = CurDAG->AssignTopologicalOrder();
12410b57cec5SDimitry Andric
12420b57cec5SDimitry Andric // Create a dummy node (which is not added to allnodes), that adds
12430b57cec5SDimitry Andric // a reference to the root node, preventing it from being deleted,
12440b57cec5SDimitry Andric // and tracking any changes of the root.
12450b57cec5SDimitry Andric HandleSDNode Dummy(CurDAG->getRoot());
12460b57cec5SDimitry Andric SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
12470b57cec5SDimitry Andric ++ISelPosition;
12480b57cec5SDimitry Andric
12490b57cec5SDimitry Andric // Make sure that ISelPosition gets properly updated when nodes are deleted
1250bdd1243dSDimitry Andric // in calls made from this function. New nodes inherit relevant metadata.
12510b57cec5SDimitry Andric ISelUpdater ISU(*CurDAG, ISelPosition);
12520b57cec5SDimitry Andric
12530b57cec5SDimitry Andric // The AllNodes list is now topological-sorted. Visit the
12540b57cec5SDimitry Andric // nodes by starting at the end of the list (the root of the
12550b57cec5SDimitry Andric // graph) and preceding back toward the beginning (the entry
12560b57cec5SDimitry Andric // node).
12570b57cec5SDimitry Andric while (ISelPosition != CurDAG->allnodes_begin()) {
12580b57cec5SDimitry Andric SDNode *Node = &*--ISelPosition;
12590b57cec5SDimitry Andric // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
12600b57cec5SDimitry Andric // but there are currently some corner cases that it misses. Also, this
12610b57cec5SDimitry Andric // makes it theoretically possible to disable the DAGCombiner.
12620b57cec5SDimitry Andric if (Node->use_empty())
12630b57cec5SDimitry Andric continue;
12640b57cec5SDimitry Andric
12650b57cec5SDimitry Andric #ifndef NDEBUG
12660b57cec5SDimitry Andric SmallVector<SDNode *, 4> Nodes;
12670b57cec5SDimitry Andric Nodes.push_back(Node);
12680b57cec5SDimitry Andric
12690b57cec5SDimitry Andric while (!Nodes.empty()) {
12700b57cec5SDimitry Andric auto N = Nodes.pop_back_val();
12710b57cec5SDimitry Andric if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
12720b57cec5SDimitry Andric continue;
12730b57cec5SDimitry Andric for (const SDValue &Op : N->op_values()) {
12740b57cec5SDimitry Andric if (Op->getOpcode() == ISD::TokenFactor)
12750b57cec5SDimitry Andric Nodes.push_back(Op.getNode());
12760b57cec5SDimitry Andric else {
12770b57cec5SDimitry Andric // We rely on topological ordering of node ids for checking for
12780b57cec5SDimitry Andric // cycles when fusing nodes during selection. All unselected nodes
12790b57cec5SDimitry Andric // successors of an already selected node should have a negative id.
12800b57cec5SDimitry Andric // This assertion will catch such cases. If this assertion triggers
12810b57cec5SDimitry Andric // it is likely you using DAG-level Value/Node replacement functions
12820b57cec5SDimitry Andric // (versus equivalent ISEL replacement) in backend-specific
12830b57cec5SDimitry Andric // selections. See comment in EnforceNodeIdInvariant for more
12840b57cec5SDimitry Andric // details.
12850b57cec5SDimitry Andric assert(Op->getNodeId() != -1 &&
12860b57cec5SDimitry Andric "Node has already selected predecessor node");
12870b57cec5SDimitry Andric }
12880b57cec5SDimitry Andric }
12890b57cec5SDimitry Andric }
12900b57cec5SDimitry Andric #endif
12910b57cec5SDimitry Andric
12920b57cec5SDimitry Andric // When we are using non-default rounding modes or FP exception behavior
12930b57cec5SDimitry Andric // FP operations are represented by StrictFP pseudo-operations. For
12940b57cec5SDimitry Andric // targets that do not (yet) understand strict FP operations directly,
12950b57cec5SDimitry Andric // we convert them to normal FP opcodes instead at this point. This
12960b57cec5SDimitry Andric // will allow them to be handled by existing target-specific instruction
12970b57cec5SDimitry Andric // selectors.
1298480093f4SDimitry Andric if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1299480093f4SDimitry Andric // For some opcodes, we need to call TLI->getOperationAction using
1300480093f4SDimitry Andric // the first operand type instead of the result type. Note that this
1301480093f4SDimitry Andric // must match what SelectionDAGLegalize::LegalizeOp is doing.
1302480093f4SDimitry Andric EVT ActionVT;
1303480093f4SDimitry Andric switch (Node->getOpcode()) {
1304480093f4SDimitry Andric case ISD::STRICT_SINT_TO_FP:
1305480093f4SDimitry Andric case ISD::STRICT_UINT_TO_FP:
1306480093f4SDimitry Andric case ISD::STRICT_LRINT:
1307480093f4SDimitry Andric case ISD::STRICT_LLRINT:
1308480093f4SDimitry Andric case ISD::STRICT_LROUND:
1309480093f4SDimitry Andric case ISD::STRICT_LLROUND:
1310480093f4SDimitry Andric case ISD::STRICT_FSETCC:
1311480093f4SDimitry Andric case ISD::STRICT_FSETCCS:
1312480093f4SDimitry Andric ActionVT = Node->getOperand(1).getValueType();
1313480093f4SDimitry Andric break;
1314480093f4SDimitry Andric default:
1315480093f4SDimitry Andric ActionVT = Node->getValueType(0);
1316480093f4SDimitry Andric break;
1317480093f4SDimitry Andric }
1318480093f4SDimitry Andric if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1319480093f4SDimitry Andric == TargetLowering::Expand)
13200b57cec5SDimitry Andric Node = CurDAG->mutateStrictFPToFP(Node);
1321480093f4SDimitry Andric }
13220b57cec5SDimitry Andric
13230b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
13240b57cec5SDimitry Andric Node->dump(CurDAG));
13250b57cec5SDimitry Andric
13260b57cec5SDimitry Andric Select(Node);
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric
13290b57cec5SDimitry Andric CurDAG->setRoot(Dummy.getValue());
13300b57cec5SDimitry Andric }
13310b57cec5SDimitry Andric
13320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
13330b57cec5SDimitry Andric
13340b57cec5SDimitry Andric PostprocessISelDAG();
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric
hasExceptionPointerOrCodeUser(const CatchPadInst * CPI)13370b57cec5SDimitry Andric static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
13380b57cec5SDimitry Andric for (const User *U : CPI->users()) {
13390b57cec5SDimitry Andric if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
13400b57cec5SDimitry Andric Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
13410b57cec5SDimitry Andric if (IID == Intrinsic::eh_exceptionpointer ||
13420b57cec5SDimitry Andric IID == Intrinsic::eh_exceptioncode)
13430b57cec5SDimitry Andric return true;
13440b57cec5SDimitry Andric }
13450b57cec5SDimitry Andric }
13460b57cec5SDimitry Andric return false;
13470b57cec5SDimitry Andric }
13480b57cec5SDimitry Andric
13490b57cec5SDimitry Andric // wasm.landingpad.index intrinsic is for associating a landing pad index number
13500b57cec5SDimitry Andric // with a catchpad instruction. Retrieve the landing pad index in the intrinsic
13510b57cec5SDimitry Andric // and store the mapping in the function.
mapWasmLandingPadIndex(MachineBasicBlock * MBB,const CatchPadInst * CPI)13520b57cec5SDimitry Andric static void mapWasmLandingPadIndex(MachineBasicBlock *MBB,
13530b57cec5SDimitry Andric const CatchPadInst *CPI) {
13540b57cec5SDimitry Andric MachineFunction *MF = MBB->getParent();
13550b57cec5SDimitry Andric // In case of single catch (...), we don't emit LSDA, so we don't need
13560b57cec5SDimitry Andric // this information.
13570b57cec5SDimitry Andric bool IsSingleCatchAllClause =
1358bdd1243dSDimitry Andric CPI->arg_size() == 1 &&
13590b57cec5SDimitry Andric cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1360349cc55cSDimitry Andric // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
1361349cc55cSDimitry Andric // and they don't need LSDA info
1362bdd1243dSDimitry Andric bool IsCatchLongjmp = CPI->arg_size() == 0;
1363349cc55cSDimitry Andric if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
13640b57cec5SDimitry Andric // Create a mapping from landing pad label to landing pad index.
13650b57cec5SDimitry Andric bool IntrFound = false;
13660b57cec5SDimitry Andric for (const User *U : CPI->users()) {
13670b57cec5SDimitry Andric if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
13680b57cec5SDimitry Andric Intrinsic::ID IID = Call->getIntrinsicID();
13690b57cec5SDimitry Andric if (IID == Intrinsic::wasm_landingpad_index) {
13700b57cec5SDimitry Andric Value *IndexArg = Call->getArgOperand(1);
13710b57cec5SDimitry Andric int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
13720b57cec5SDimitry Andric MF->setWasmLandingPadIndex(MBB, Index);
13730b57cec5SDimitry Andric IntrFound = true;
13740b57cec5SDimitry Andric break;
13750b57cec5SDimitry Andric }
13760b57cec5SDimitry Andric }
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
13790b57cec5SDimitry Andric (void)IntrFound;
13800b57cec5SDimitry Andric }
13810b57cec5SDimitry Andric }
13820b57cec5SDimitry Andric
13830b57cec5SDimitry Andric /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
13840b57cec5SDimitry Andric /// do other setup for EH landing-pad blocks.
PrepareEHLandingPad()13850b57cec5SDimitry Andric bool SelectionDAGISel::PrepareEHLandingPad() {
13860b57cec5SDimitry Andric MachineBasicBlock *MBB = FuncInfo->MBB;
13870b57cec5SDimitry Andric const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
13880b57cec5SDimitry Andric const BasicBlock *LLVMBB = MBB->getBasicBlock();
13890b57cec5SDimitry Andric const TargetRegisterClass *PtrRC =
13900b57cec5SDimitry Andric TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
13910b57cec5SDimitry Andric
13920b57cec5SDimitry Andric auto Pers = classifyEHPersonality(PersonalityFn);
13930b57cec5SDimitry Andric
13940b57cec5SDimitry Andric // Catchpads have one live-in register, which typically holds the exception
13950b57cec5SDimitry Andric // pointer or code.
13960b57cec5SDimitry Andric if (isFuncletEHPersonality(Pers)) {
13970b57cec5SDimitry Andric if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
13980b57cec5SDimitry Andric if (hasExceptionPointerOrCodeUser(CPI)) {
13990b57cec5SDimitry Andric // Get or create the virtual register to hold the pointer or code. Mark
14000b57cec5SDimitry Andric // the live in physreg and copy into the vreg.
14010b57cec5SDimitry Andric MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
14020b57cec5SDimitry Andric assert(EHPhysReg && "target lacks exception pointer register");
14030b57cec5SDimitry Andric MBB->addLiveIn(EHPhysReg);
14040b57cec5SDimitry Andric unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
14050b57cec5SDimitry Andric BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
14060b57cec5SDimitry Andric TII->get(TargetOpcode::COPY), VReg)
14070b57cec5SDimitry Andric .addReg(EHPhysReg, RegState::Kill);
14080b57cec5SDimitry Andric }
14090b57cec5SDimitry Andric }
14100b57cec5SDimitry Andric return true;
14110b57cec5SDimitry Andric }
14120b57cec5SDimitry Andric
14130b57cec5SDimitry Andric // Add a label to mark the beginning of the landing pad. Deletion of the
14140b57cec5SDimitry Andric // landing pad can thus be detected via the MachineModuleInfo.
14150b57cec5SDimitry Andric MCSymbol *Label = MF->addLandingPad(MBB);
14160b57cec5SDimitry Andric
14170b57cec5SDimitry Andric const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
14180b57cec5SDimitry Andric BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
14190b57cec5SDimitry Andric .addSym(Label);
14200b57cec5SDimitry Andric
1421e8d8bef9SDimitry Andric // If the unwinder does not preserve all registers, ensure that the
1422e8d8bef9SDimitry Andric // function marks the clobbered registers as used.
1423e8d8bef9SDimitry Andric const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
1424e8d8bef9SDimitry Andric if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1425e8d8bef9SDimitry Andric MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
1426e8d8bef9SDimitry Andric
14270b57cec5SDimitry Andric if (Pers == EHPersonality::Wasm_CXX) {
14280b57cec5SDimitry Andric if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
14290b57cec5SDimitry Andric mapWasmLandingPadIndex(MBB, CPI);
14300b57cec5SDimitry Andric } else {
14310b57cec5SDimitry Andric // Assign the call site to the landing pad's begin label.
14320b57cec5SDimitry Andric MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
14330b57cec5SDimitry Andric // Mark exception register as live in.
14340b57cec5SDimitry Andric if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
14350b57cec5SDimitry Andric FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
14360b57cec5SDimitry Andric // Mark exception selector register as live in.
14370b57cec5SDimitry Andric if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
14380b57cec5SDimitry Andric FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
14390b57cec5SDimitry Andric }
14400b57cec5SDimitry Andric
14410b57cec5SDimitry Andric return true;
14420b57cec5SDimitry Andric }
14430b57cec5SDimitry Andric
144406c3fb27SDimitry Andric // Mark and Report IPToState for each Block under IsEHa
reportIPToStateForBlocks(MachineFunction * MF)144506c3fb27SDimitry Andric void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
144606c3fb27SDimitry Andric MachineModuleInfo &MMI = MF->getMMI();
144706c3fb27SDimitry Andric llvm::WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
144806c3fb27SDimitry Andric if (!EHInfo)
144906c3fb27SDimitry Andric return;
14500fca6ea1SDimitry Andric for (MachineBasicBlock &MBB : *MF) {
14510fca6ea1SDimitry Andric const BasicBlock *BB = MBB.getBasicBlock();
145206c3fb27SDimitry Andric int State = EHInfo->BlockToStateMap[BB];
145306c3fb27SDimitry Andric if (BB->getFirstMayFaultInst()) {
145406c3fb27SDimitry Andric // Report IP range only for blocks with Faulty inst
14550fca6ea1SDimitry Andric auto MBBb = MBB.getFirstNonPHI();
1456c80e69b0SDimitry Andric
1457c80e69b0SDimitry Andric if (MBBb == MBB.end())
1458c80e69b0SDimitry Andric continue;
1459c80e69b0SDimitry Andric
146006c3fb27SDimitry Andric MachineInstr *MIb = &*MBBb;
146106c3fb27SDimitry Andric if (MIb->isTerminator())
146206c3fb27SDimitry Andric continue;
146306c3fb27SDimitry Andric
146406c3fb27SDimitry Andric // Insert EH Labels
146506c3fb27SDimitry Andric MCSymbol *BeginLabel = MMI.getContext().createTempSymbol();
146606c3fb27SDimitry Andric MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
146706c3fb27SDimitry Andric EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
14680fca6ea1SDimitry Andric BuildMI(MBB, MBBb, SDB->getCurDebugLoc(),
146906c3fb27SDimitry Andric TII->get(TargetOpcode::EH_LABEL))
147006c3fb27SDimitry Andric .addSym(BeginLabel);
14710fca6ea1SDimitry Andric auto MBBe = MBB.instr_end();
147206c3fb27SDimitry Andric MachineInstr *MIe = &*(--MBBe);
147306c3fb27SDimitry Andric // insert before (possible multiple) terminators
147406c3fb27SDimitry Andric while (MIe->isTerminator())
147506c3fb27SDimitry Andric MIe = &*(--MBBe);
147606c3fb27SDimitry Andric ++MBBe;
14770fca6ea1SDimitry Andric BuildMI(MBB, MBBe, SDB->getCurDebugLoc(),
147806c3fb27SDimitry Andric TII->get(TargetOpcode::EH_LABEL))
147906c3fb27SDimitry Andric .addSym(EndLabel);
148006c3fb27SDimitry Andric }
148106c3fb27SDimitry Andric }
148206c3fb27SDimitry Andric }
148306c3fb27SDimitry Andric
14840b57cec5SDimitry Andric /// isFoldedOrDeadInstruction - Return true if the specified instruction is
14850b57cec5SDimitry Andric /// side-effect free and is either dead or folded into a generated instruction.
14860b57cec5SDimitry Andric /// Return false if it needs to be emitted.
isFoldedOrDeadInstruction(const Instruction * I,const FunctionLoweringInfo & FuncInfo)14870b57cec5SDimitry Andric static bool isFoldedOrDeadInstruction(const Instruction *I,
1488480093f4SDimitry Andric const FunctionLoweringInfo &FuncInfo) {
14890b57cec5SDimitry Andric return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
14900b57cec5SDimitry Andric !I->isTerminator() && // Terminators aren't folded.
14910b57cec5SDimitry Andric !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
14920b57cec5SDimitry Andric !I->isEHPad() && // EH pad instructions aren't folded.
1493480093f4SDimitry Andric !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric
processIfEntryValueDbgDeclare(FunctionLoweringInfo & FuncInfo,const Value * Arg,DIExpression * Expr,DILocalVariable * Var,DebugLoc DbgLoc)149606c3fb27SDimitry Andric static bool processIfEntryValueDbgDeclare(FunctionLoweringInfo &FuncInfo,
149706c3fb27SDimitry Andric const Value *Arg, DIExpression *Expr,
149806c3fb27SDimitry Andric DILocalVariable *Var,
149906c3fb27SDimitry Andric DebugLoc DbgLoc) {
150006c3fb27SDimitry Andric if (!Expr->isEntryValue() || !isa<Argument>(Arg))
150106c3fb27SDimitry Andric return false;
150206c3fb27SDimitry Andric
150306c3fb27SDimitry Andric auto ArgIt = FuncInfo.ValueMap.find(Arg);
150406c3fb27SDimitry Andric if (ArgIt == FuncInfo.ValueMap.end())
150506c3fb27SDimitry Andric return false;
150606c3fb27SDimitry Andric Register ArgVReg = ArgIt->getSecond();
150706c3fb27SDimitry Andric
150806c3fb27SDimitry Andric // Find the corresponding livein physical register to this argument.
150906c3fb27SDimitry Andric for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
151006c3fb27SDimitry Andric if (VirtReg == ArgVReg) {
15115f757f3fSDimitry Andric // Append an op deref to account for the fact that this is a dbg_declare.
15125f757f3fSDimitry Andric Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
151306c3fb27SDimitry Andric FuncInfo.MF->setVariableDbgInfo(Var, Expr, PhysReg, DbgLoc);
151406c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
151506c3fb27SDimitry Andric << ", Expr=" << *Expr << ", MCRegister=" << PhysReg
151606c3fb27SDimitry Andric << ", DbgLoc=" << DbgLoc << "\n");
151706c3fb27SDimitry Andric return true;
151806c3fb27SDimitry Andric }
151906c3fb27SDimitry Andric return false;
152006c3fb27SDimitry Andric }
152106c3fb27SDimitry Andric
processDbgDeclare(FunctionLoweringInfo & FuncInfo,const Value * Address,DIExpression * Expr,DILocalVariable * Var,DebugLoc DbgLoc)152206c3fb27SDimitry Andric static bool processDbgDeclare(FunctionLoweringInfo &FuncInfo,
1523bdd1243dSDimitry Andric const Value *Address, DIExpression *Expr,
1524bdd1243dSDimitry Andric DILocalVariable *Var, DebugLoc DbgLoc) {
152506c3fb27SDimitry Andric if (!Address) {
152606c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *Var
152706c3fb27SDimitry Andric << " (bad address)\n");
152806c3fb27SDimitry Andric return false;
152906c3fb27SDimitry Andric }
153006c3fb27SDimitry Andric
153106c3fb27SDimitry Andric if (processIfEntryValueDbgDeclare(FuncInfo, Address, Expr, Var, DbgLoc))
153206c3fb27SDimitry Andric return true;
153306c3fb27SDimitry Andric
1534480093f4SDimitry Andric MachineFunction *MF = FuncInfo.MF;
15350b57cec5SDimitry Andric const DataLayout &DL = MF->getDataLayout();
15360b57cec5SDimitry Andric
1537bdd1243dSDimitry Andric assert(Var && "Missing variable");
1538bdd1243dSDimitry Andric assert(DbgLoc && "Missing location");
15390b57cec5SDimitry Andric
15400b57cec5SDimitry Andric // Look through casts and constant offset GEPs. These mostly come from
15410b57cec5SDimitry Andric // inalloca.
15420b57cec5SDimitry Andric APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
15430b57cec5SDimitry Andric Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
15440b57cec5SDimitry Andric
15450b57cec5SDimitry Andric // Check if the variable is a static alloca or a byval or inalloca
15460b57cec5SDimitry Andric // argument passed in memory. If it is not, then we will ignore this
15470b57cec5SDimitry Andric // intrinsic and handle this during isel like dbg.value.
15480b57cec5SDimitry Andric int FI = std::numeric_limits<int>::max();
15490b57cec5SDimitry Andric if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1550480093f4SDimitry Andric auto SI = FuncInfo.StaticAllocaMap.find(AI);
1551480093f4SDimitry Andric if (SI != FuncInfo.StaticAllocaMap.end())
15520b57cec5SDimitry Andric FI = SI->second;
15530b57cec5SDimitry Andric } else if (const auto *Arg = dyn_cast<Argument>(Address))
1554480093f4SDimitry Andric FI = FuncInfo.getArgumentFrameIndex(Arg);
15550b57cec5SDimitry Andric
15560b57cec5SDimitry Andric if (FI == std::numeric_limits<int>::max())
155706c3fb27SDimitry Andric return false;
15580b57cec5SDimitry Andric
15590b57cec5SDimitry Andric if (Offset.getBoolValue())
15600b57cec5SDimitry Andric Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset,
15610b57cec5SDimitry Andric Offset.getZExtValue());
1562bdd1243dSDimitry Andric
1563bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1564bdd1243dSDimitry Andric << ", Expr=" << *Expr << ", FI=" << FI
1565bdd1243dSDimitry Andric << ", DbgLoc=" << DbgLoc << "\n");
1566bdd1243dSDimitry Andric MF->setVariableDbgInfo(Var, Expr, FI, DbgLoc);
156706c3fb27SDimitry Andric return true;
1568bdd1243dSDimitry Andric }
1569bdd1243dSDimitry Andric
1570bdd1243dSDimitry Andric /// Collect llvm.dbg.declare information. This is done after argument lowering
1571bdd1243dSDimitry Andric /// in case the declarations refer to arguments.
processDbgDeclares(FunctionLoweringInfo & FuncInfo)1572bdd1243dSDimitry Andric static void processDbgDeclares(FunctionLoweringInfo &FuncInfo) {
157306c3fb27SDimitry Andric for (const auto &I : instructions(*FuncInfo.Fn)) {
157406c3fb27SDimitry Andric const auto *DI = dyn_cast<DbgDeclareInst>(&I);
157506c3fb27SDimitry Andric if (DI && processDbgDeclare(FuncInfo, DI->getAddress(), DI->getExpression(),
157606c3fb27SDimitry Andric DI->getVariable(), DI->getDebugLoc()))
157706c3fb27SDimitry Andric FuncInfo.PreprocessedDbgDeclares.insert(DI);
15780fca6ea1SDimitry Andric for (const DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
15790fca6ea1SDimitry Andric if (DVR.Type == DbgVariableRecord::LocationType::Declare &&
15800fca6ea1SDimitry Andric processDbgDeclare(FuncInfo, DVR.getVariableLocationOp(0),
15810fca6ea1SDimitry Andric DVR.getExpression(), DVR.getVariable(),
15820fca6ea1SDimitry Andric DVR.getDebugLoc()))
15830fca6ea1SDimitry Andric FuncInfo.PreprocessedDVRDeclares.insert(&DVR);
15845f757f3fSDimitry Andric }
15850b57cec5SDimitry Andric }
1586bdd1243dSDimitry Andric }
1587bdd1243dSDimitry Andric
1588bdd1243dSDimitry Andric /// Collect single location variable information generated with assignment
1589bdd1243dSDimitry Andric /// tracking. This is done after argument lowering in case the declarations
1590bdd1243dSDimitry Andric /// refer to arguments.
processSingleLocVars(FunctionLoweringInfo & FuncInfo,FunctionVarLocs const * FnVarLocs)1591bdd1243dSDimitry Andric static void processSingleLocVars(FunctionLoweringInfo &FuncInfo,
1592bdd1243dSDimitry Andric FunctionVarLocs const *FnVarLocs) {
1593bdd1243dSDimitry Andric for (auto It = FnVarLocs->single_locs_begin(),
1594bdd1243dSDimitry Andric End = FnVarLocs->single_locs_end();
159506c3fb27SDimitry Andric It != End; ++It) {
159606c3fb27SDimitry Andric assert(!It->Values.hasArgList() && "Single loc variadic ops not supported");
159706c3fb27SDimitry Andric processDbgDeclare(FuncInfo, It->Values.getVariableLocationOp(0), It->Expr,
1598bdd1243dSDimitry Andric FnVarLocs->getDILocalVariable(It->VariableID), It->DL);
1599bdd1243dSDimitry Andric }
160006c3fb27SDimitry Andric }
16010b57cec5SDimitry Andric
SelectAllBasicBlocks(const Function & Fn)16020b57cec5SDimitry Andric void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
16030b57cec5SDimitry Andric FastISelFailed = false;
16040b57cec5SDimitry Andric // Initialize the Fast-ISel state, if needed.
16050b57cec5SDimitry Andric FastISel *FastIS = nullptr;
16060b57cec5SDimitry Andric if (TM.Options.EnableFastISel) {
16070b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
16080b57cec5SDimitry Andric FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
16090b57cec5SDimitry Andric }
16100b57cec5SDimitry Andric
16110b57cec5SDimitry Andric ReversePostOrderTraversal<const Function*> RPOT(&Fn);
16120b57cec5SDimitry Andric
16130b57cec5SDimitry Andric // Lower arguments up front. An RPO iteration always visits the entry block
16140b57cec5SDimitry Andric // first.
16150b57cec5SDimitry Andric assert(*RPOT.begin() == &Fn.getEntryBlock());
16160b57cec5SDimitry Andric ++NumEntryBlocks;
16170b57cec5SDimitry Andric
16180b57cec5SDimitry Andric // Set up FuncInfo for ISel. Entry blocks never have PHIs.
16190b57cec5SDimitry Andric FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
16200b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->begin();
16210b57cec5SDimitry Andric
1622480093f4SDimitry Andric CurDAG->setFunctionLoweringInfo(FuncInfo.get());
16230b57cec5SDimitry Andric
16240b57cec5SDimitry Andric if (!FastIS) {
16250b57cec5SDimitry Andric LowerArguments(Fn);
16260b57cec5SDimitry Andric } else {
16270b57cec5SDimitry Andric // See if fast isel can lower the arguments.
16280b57cec5SDimitry Andric FastIS->startNewBlock();
16290b57cec5SDimitry Andric if (!FastIS->lowerArguments()) {
16300b57cec5SDimitry Andric FastISelFailed = true;
16310b57cec5SDimitry Andric // Fast isel failed to lower these arguments
16320b57cec5SDimitry Andric ++NumFastIselFailLowerArguments;
16330b57cec5SDimitry Andric
16340b57cec5SDimitry Andric OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
16350b57cec5SDimitry Andric Fn.getSubprogram(),
16360b57cec5SDimitry Andric &Fn.getEntryBlock());
16370b57cec5SDimitry Andric R << "FastISel didn't lower all arguments: "
163806c3fb27SDimitry Andric << ore::NV("Prototype", Fn.getFunctionType());
16390b57cec5SDimitry Andric reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
16400b57cec5SDimitry Andric
16410b57cec5SDimitry Andric // Use SelectionDAG argument lowering
16420b57cec5SDimitry Andric LowerArguments(Fn);
16430b57cec5SDimitry Andric CurDAG->setRoot(SDB->getControlRoot());
16440b57cec5SDimitry Andric SDB->clear();
16450b57cec5SDimitry Andric CodeGenAndEmitDAG();
16460b57cec5SDimitry Andric }
16470b57cec5SDimitry Andric
16480b57cec5SDimitry Andric // If we inserted any instructions at the beginning, make a note of
16490b57cec5SDimitry Andric // where they are, so we can be sure to emit subsequent instructions
16500b57cec5SDimitry Andric // after them.
16510b57cec5SDimitry Andric if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
16520b57cec5SDimitry Andric FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
16530b57cec5SDimitry Andric else
16540b57cec5SDimitry Andric FastIS->setLastLocalValue(nullptr);
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric
16570b57cec5SDimitry Andric bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
16580b57cec5SDimitry Andric
16590b57cec5SDimitry Andric if (FastIS && Inserted)
16600b57cec5SDimitry Andric FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
16610b57cec5SDimitry Andric
1662bdd1243dSDimitry Andric if (isAssignmentTrackingEnabled(*Fn.getParent())) {
1663bdd1243dSDimitry Andric assert(CurDAG->getFunctionVarLocs() &&
1664bdd1243dSDimitry Andric "expected AssignmentTrackingAnalysis pass results");
1665bdd1243dSDimitry Andric processSingleLocVars(*FuncInfo, CurDAG->getFunctionVarLocs());
1666bdd1243dSDimitry Andric } else {
1667480093f4SDimitry Andric processDbgDeclares(*FuncInfo);
1668bdd1243dSDimitry Andric }
16690b57cec5SDimitry Andric
16700b57cec5SDimitry Andric // Iterate over all basic blocks in the function.
16710b57cec5SDimitry Andric for (const BasicBlock *LLVMBB : RPOT) {
16725f757f3fSDimitry Andric if (OptLevel != CodeGenOptLevel::None) {
16730b57cec5SDimitry Andric bool AllPredsVisited = true;
1674fe6060f1SDimitry Andric for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1675fe6060f1SDimitry Andric if (!FuncInfo->VisitedBBs.count(Pred)) {
16760b57cec5SDimitry Andric AllPredsVisited = false;
16770b57cec5SDimitry Andric break;
16780b57cec5SDimitry Andric }
16790b57cec5SDimitry Andric }
16800b57cec5SDimitry Andric
16810b57cec5SDimitry Andric if (AllPredsVisited) {
16820b57cec5SDimitry Andric for (const PHINode &PN : LLVMBB->phis())
16830b57cec5SDimitry Andric FuncInfo->ComputePHILiveOutRegInfo(&PN);
16840b57cec5SDimitry Andric } else {
16850b57cec5SDimitry Andric for (const PHINode &PN : LLVMBB->phis())
16860b57cec5SDimitry Andric FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
16870b57cec5SDimitry Andric }
16880b57cec5SDimitry Andric
16890b57cec5SDimitry Andric FuncInfo->VisitedBBs.insert(LLVMBB);
16900b57cec5SDimitry Andric }
16910b57cec5SDimitry Andric
16920b57cec5SDimitry Andric BasicBlock::const_iterator const Begin =
16930b57cec5SDimitry Andric LLVMBB->getFirstNonPHI()->getIterator();
16940b57cec5SDimitry Andric BasicBlock::const_iterator const End = LLVMBB->end();
16950b57cec5SDimitry Andric BasicBlock::const_iterator BI = End;
16960b57cec5SDimitry Andric
16970b57cec5SDimitry Andric FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
16980b57cec5SDimitry Andric if (!FuncInfo->MBB)
16990b57cec5SDimitry Andric continue; // Some blocks like catchpads have no code or MBB.
17000b57cec5SDimitry Andric
17010b57cec5SDimitry Andric // Insert new instructions after any phi or argument setup code.
17020b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
17030b57cec5SDimitry Andric
17040b57cec5SDimitry Andric // Setup an EH landing-pad block.
17050b57cec5SDimitry Andric FuncInfo->ExceptionPointerVirtReg = 0;
17060b57cec5SDimitry Andric FuncInfo->ExceptionSelectorVirtReg = 0;
17070b57cec5SDimitry Andric if (LLVMBB->isEHPad())
17080b57cec5SDimitry Andric if (!PrepareEHLandingPad())
17090b57cec5SDimitry Andric continue;
17100b57cec5SDimitry Andric
17110b57cec5SDimitry Andric // Before doing SelectionDAG ISel, see if FastISel has been requested.
17120b57cec5SDimitry Andric if (FastIS) {
17130b57cec5SDimitry Andric if (LLVMBB != &Fn.getEntryBlock())
17140b57cec5SDimitry Andric FastIS->startNewBlock();
17150b57cec5SDimitry Andric
17160b57cec5SDimitry Andric unsigned NumFastIselRemaining = std::distance(Begin, End);
17170b57cec5SDimitry Andric
17180b57cec5SDimitry Andric // Pre-assign swifterror vregs.
17190b57cec5SDimitry Andric SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
17200b57cec5SDimitry Andric
17210b57cec5SDimitry Andric // Do FastISel on as many instructions as possible.
17220b57cec5SDimitry Andric for (; BI != Begin; --BI) {
17230b57cec5SDimitry Andric const Instruction *Inst = &*std::prev(BI);
17240b57cec5SDimitry Andric
17250b57cec5SDimitry Andric // If we no longer require this instruction, skip it.
1726480093f4SDimitry Andric if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
17270b57cec5SDimitry Andric ElidedArgCopyInstrs.count(Inst)) {
17280b57cec5SDimitry Andric --NumFastIselRemaining;
17291db9f3b2SDimitry Andric FastIS->handleDbgInfo(Inst);
17300b57cec5SDimitry Andric continue;
17310b57cec5SDimitry Andric }
17320b57cec5SDimitry Andric
17330b57cec5SDimitry Andric // Bottom-up: reset the insert pos at the top, after any local-value
17340b57cec5SDimitry Andric // instructions.
17350b57cec5SDimitry Andric FastIS->recomputeInsertPt();
17360b57cec5SDimitry Andric
17370b57cec5SDimitry Andric // Try to select the instruction with FastISel.
17380b57cec5SDimitry Andric if (FastIS->selectInstruction(Inst)) {
17390b57cec5SDimitry Andric --NumFastIselRemaining;
17400b57cec5SDimitry Andric ++NumFastIselSuccess;
17411db9f3b2SDimitry Andric
17421db9f3b2SDimitry Andric FastIS->handleDbgInfo(Inst);
17430b57cec5SDimitry Andric // If fast isel succeeded, skip over all the folded instructions, and
17440b57cec5SDimitry Andric // then see if there is a load right before the selected instructions.
17450b57cec5SDimitry Andric // Try to fold the load if so.
17460b57cec5SDimitry Andric const Instruction *BeforeInst = Inst;
17470b57cec5SDimitry Andric while (BeforeInst != &*Begin) {
17480b57cec5SDimitry Andric BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1749480093f4SDimitry Andric if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
17500b57cec5SDimitry Andric break;
17510b57cec5SDimitry Andric }
17520b57cec5SDimitry Andric if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
17530b57cec5SDimitry Andric BeforeInst->hasOneUse() &&
17540b57cec5SDimitry Andric FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
17550b57cec5SDimitry Andric // If we succeeded, don't re-select the load.
175681ad6265SDimitry Andric LLVM_DEBUG(dbgs()
175781ad6265SDimitry Andric << "FastISel folded load: " << *BeforeInst << "\n");
17581db9f3b2SDimitry Andric FastIS->handleDbgInfo(BeforeInst);
17590b57cec5SDimitry Andric BI = std::next(BasicBlock::const_iterator(BeforeInst));
17600b57cec5SDimitry Andric --NumFastIselRemaining;
17610b57cec5SDimitry Andric ++NumFastIselSuccess;
17620b57cec5SDimitry Andric }
17630b57cec5SDimitry Andric continue;
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric
17660b57cec5SDimitry Andric FastISelFailed = true;
17670b57cec5SDimitry Andric
17680b57cec5SDimitry Andric // Then handle certain instructions as single-LLVM-Instruction blocks.
17690b57cec5SDimitry Andric // We cannot separate out GCrelocates to their own blocks since we need
17700b57cec5SDimitry Andric // to keep track of gc-relocates for a particular gc-statepoint. This is
17710b57cec5SDimitry Andric // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
17720b57cec5SDimitry Andric // visitGCRelocate.
17735ffd83dbSDimitry Andric if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
17745ffd83dbSDimitry Andric !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
17750b57cec5SDimitry Andric OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
17760b57cec5SDimitry Andric Inst->getDebugLoc(), LLVMBB);
17770b57cec5SDimitry Andric
17780b57cec5SDimitry Andric R << "FastISel missed call";
17790b57cec5SDimitry Andric
17800b57cec5SDimitry Andric if (R.isEnabled() || EnableFastISelAbort) {
17810b57cec5SDimitry Andric std::string InstStrStorage;
17820b57cec5SDimitry Andric raw_string_ostream InstStr(InstStrStorage);
17830b57cec5SDimitry Andric InstStr << *Inst;
17840b57cec5SDimitry Andric
17850fca6ea1SDimitry Andric R << ": " << InstStrStorage;
17860b57cec5SDimitry Andric }
17870b57cec5SDimitry Andric
17880b57cec5SDimitry Andric reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
17890b57cec5SDimitry Andric
17900b57cec5SDimitry Andric if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
17910b57cec5SDimitry Andric !Inst->use_empty()) {
17925ffd83dbSDimitry Andric Register &R = FuncInfo->ValueMap[Inst];
17930b57cec5SDimitry Andric if (!R)
17940b57cec5SDimitry Andric R = FuncInfo->CreateRegs(Inst);
17950b57cec5SDimitry Andric }
17960b57cec5SDimitry Andric
17970b57cec5SDimitry Andric bool HadTailCall = false;
17980b57cec5SDimitry Andric MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
17990b57cec5SDimitry Andric SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
18000b57cec5SDimitry Andric
18010b57cec5SDimitry Andric // If the call was emitted as a tail call, we're done with the block.
18020b57cec5SDimitry Andric // We also need to delete any previously emitted instructions.
18030b57cec5SDimitry Andric if (HadTailCall) {
18040b57cec5SDimitry Andric FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
18050b57cec5SDimitry Andric --BI;
18060b57cec5SDimitry Andric break;
18070b57cec5SDimitry Andric }
18080b57cec5SDimitry Andric
18090b57cec5SDimitry Andric // Recompute NumFastIselRemaining as Selection DAG instruction
18100b57cec5SDimitry Andric // selection may have handled the call, input args, etc.
18110b57cec5SDimitry Andric unsigned RemainingNow = std::distance(Begin, BI);
18120b57cec5SDimitry Andric NumFastIselFailures += NumFastIselRemaining - RemainingNow;
18130b57cec5SDimitry Andric NumFastIselRemaining = RemainingNow;
18140b57cec5SDimitry Andric continue;
18150b57cec5SDimitry Andric }
18160b57cec5SDimitry Andric
18170b57cec5SDimitry Andric OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
18180b57cec5SDimitry Andric Inst->getDebugLoc(), LLVMBB);
18190b57cec5SDimitry Andric
18200b57cec5SDimitry Andric bool ShouldAbort = EnableFastISelAbort;
18210b57cec5SDimitry Andric if (Inst->isTerminator()) {
18220b57cec5SDimitry Andric // Use a different message for terminator misses.
18230b57cec5SDimitry Andric R << "FastISel missed terminator";
18240b57cec5SDimitry Andric // Don't abort for terminator unless the level is really high
18250b57cec5SDimitry Andric ShouldAbort = (EnableFastISelAbort > 2);
18260b57cec5SDimitry Andric } else {
18270b57cec5SDimitry Andric R << "FastISel missed";
18280b57cec5SDimitry Andric }
18290b57cec5SDimitry Andric
18300b57cec5SDimitry Andric if (R.isEnabled() || EnableFastISelAbort) {
18310b57cec5SDimitry Andric std::string InstStrStorage;
18320b57cec5SDimitry Andric raw_string_ostream InstStr(InstStrStorage);
18330b57cec5SDimitry Andric InstStr << *Inst;
18340fca6ea1SDimitry Andric R << ": " << InstStrStorage;
18350b57cec5SDimitry Andric }
18360b57cec5SDimitry Andric
18370b57cec5SDimitry Andric reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
18380b57cec5SDimitry Andric
18390b57cec5SDimitry Andric NumFastIselFailures += NumFastIselRemaining;
18400b57cec5SDimitry Andric break;
18410b57cec5SDimitry Andric }
18420b57cec5SDimitry Andric
18430b57cec5SDimitry Andric FastIS->recomputeInsertPt();
18440b57cec5SDimitry Andric }
18450b57cec5SDimitry Andric
18460fca6ea1SDimitry Andric if (SP->shouldEmitSDCheck(*LLVMBB)) {
18470b57cec5SDimitry Andric bool FunctionBasedInstrumentation =
18480b57cec5SDimitry Andric TLI->getSSPStackGuardCheck(*Fn.getParent());
18490b57cec5SDimitry Andric SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
18500b57cec5SDimitry Andric FunctionBasedInstrumentation);
18510b57cec5SDimitry Andric }
18520b57cec5SDimitry Andric
18530b57cec5SDimitry Andric if (Begin != BI)
18540b57cec5SDimitry Andric ++NumDAGBlocks;
18550b57cec5SDimitry Andric else
18560b57cec5SDimitry Andric ++NumFastIselBlocks;
18570b57cec5SDimitry Andric
18580b57cec5SDimitry Andric if (Begin != BI) {
18590b57cec5SDimitry Andric // Run SelectionDAG instruction selection on the remainder of the block
18600b57cec5SDimitry Andric // not handled by FastISel. If FastISel is not run, this is the entire
18610b57cec5SDimitry Andric // block.
18620b57cec5SDimitry Andric bool HadTailCall;
18630b57cec5SDimitry Andric SelectBasicBlock(Begin, BI, HadTailCall);
18640b57cec5SDimitry Andric
18650b57cec5SDimitry Andric // But if FastISel was run, we already selected some of the block.
18660b57cec5SDimitry Andric // If we emitted a tail-call, we need to delete any previously emitted
18670b57cec5SDimitry Andric // instruction that follows it.
1868480093f4SDimitry Andric if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
18690b57cec5SDimitry Andric FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
18700b57cec5SDimitry Andric }
18710b57cec5SDimitry Andric
18720b57cec5SDimitry Andric if (FastIS)
18730b57cec5SDimitry Andric FastIS->finishBasicBlock();
18740b57cec5SDimitry Andric FinishBasicBlock();
18750b57cec5SDimitry Andric FuncInfo->PHINodesToUpdate.clear();
18760b57cec5SDimitry Andric ElidedArgCopyInstrs.clear();
18770b57cec5SDimitry Andric }
18780b57cec5SDimitry Andric
187906c3fb27SDimitry Andric // AsynchEH: Report Block State under -AsynchEH
188006c3fb27SDimitry Andric if (Fn.getParent()->getModuleFlag("eh-asynch"))
188106c3fb27SDimitry Andric reportIPToStateForBlocks(MF);
188206c3fb27SDimitry Andric
18830fca6ea1SDimitry Andric SP->copyToMachineFrameInfo(MF->getFrameInfo());
18840b57cec5SDimitry Andric
18850b57cec5SDimitry Andric SwiftError->propagateVRegs();
18860b57cec5SDimitry Andric
18870b57cec5SDimitry Andric delete FastIS;
18880b57cec5SDimitry Andric SDB->clearDanglingDebugInfo();
18890b57cec5SDimitry Andric SDB->SPDescriptor.resetPerFunctionState();
18900b57cec5SDimitry Andric }
18910b57cec5SDimitry Andric
18920b57cec5SDimitry Andric void
FinishBasicBlock()18930b57cec5SDimitry Andric SelectionDAGISel::FinishBasicBlock() {
18940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
18950b57cec5SDimitry Andric << FuncInfo->PHINodesToUpdate.size() << "\n";
18960b57cec5SDimitry Andric for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
18970b57cec5SDimitry Andric ++i) dbgs()
18980b57cec5SDimitry Andric << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
18990b57cec5SDimitry Andric << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
19000b57cec5SDimitry Andric
19010b57cec5SDimitry Andric // Next, now that we know what the last MBB the LLVM BB expanded is, update
19020b57cec5SDimitry Andric // PHI nodes in successors.
19030b57cec5SDimitry Andric for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
19040b57cec5SDimitry Andric MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
19050b57cec5SDimitry Andric assert(PHI->isPHI() &&
19060b57cec5SDimitry Andric "This is not a machine PHI node that we are updating!");
19070b57cec5SDimitry Andric if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
19080b57cec5SDimitry Andric continue;
19090b57cec5SDimitry Andric PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
19100b57cec5SDimitry Andric }
19110b57cec5SDimitry Andric
19120b57cec5SDimitry Andric // Handle stack protector.
19130b57cec5SDimitry Andric if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
19140b57cec5SDimitry Andric // The target provides a guard check function. There is no need to
19150b57cec5SDimitry Andric // generate error handling code or to split current basic block.
19160b57cec5SDimitry Andric MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
19170b57cec5SDimitry Andric
19180b57cec5SDimitry Andric // Add load and check to the basicblock.
19190b57cec5SDimitry Andric FuncInfo->MBB = ParentMBB;
19200b57cec5SDimitry Andric FuncInfo->InsertPt =
1921349cc55cSDimitry Andric findSplitPointForStackProtector(ParentMBB, *TII);
19220b57cec5SDimitry Andric SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
19230b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
19240b57cec5SDimitry Andric SDB->clear();
19250b57cec5SDimitry Andric CodeGenAndEmitDAG();
19260b57cec5SDimitry Andric
19270b57cec5SDimitry Andric // Clear the Per-BB State.
19280b57cec5SDimitry Andric SDB->SPDescriptor.resetPerBBState();
19290b57cec5SDimitry Andric } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
19300b57cec5SDimitry Andric MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
19310b57cec5SDimitry Andric MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
19320b57cec5SDimitry Andric
19330b57cec5SDimitry Andric // Find the split point to split the parent mbb. At the same time copy all
19340b57cec5SDimitry Andric // physical registers used in the tail of parent mbb into virtual registers
19350b57cec5SDimitry Andric // before the split point and back into physical registers after the split
19360b57cec5SDimitry Andric // point. This prevents us needing to deal with Live-ins and many other
19370b57cec5SDimitry Andric // register allocation issues caused by us splitting the parent mbb. The
19380b57cec5SDimitry Andric // register allocator will clean up said virtual copies later on.
19390b57cec5SDimitry Andric MachineBasicBlock::iterator SplitPoint =
1940349cc55cSDimitry Andric findSplitPointForStackProtector(ParentMBB, *TII);
19410b57cec5SDimitry Andric
19420b57cec5SDimitry Andric // Splice the terminator of ParentMBB into SuccessMBB.
19430b57cec5SDimitry Andric SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
19440b57cec5SDimitry Andric SplitPoint,
19450b57cec5SDimitry Andric ParentMBB->end());
19460b57cec5SDimitry Andric
19470b57cec5SDimitry Andric // Add compare/jump on neq/jump to the parent BB.
19480b57cec5SDimitry Andric FuncInfo->MBB = ParentMBB;
19490b57cec5SDimitry Andric FuncInfo->InsertPt = ParentMBB->end();
19500b57cec5SDimitry Andric SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
19510b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
19520b57cec5SDimitry Andric SDB->clear();
19530b57cec5SDimitry Andric CodeGenAndEmitDAG();
19540b57cec5SDimitry Andric
19550b57cec5SDimitry Andric // CodeGen Failure MBB if we have not codegened it yet.
19560b57cec5SDimitry Andric MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
19570b57cec5SDimitry Andric if (FailureMBB->empty()) {
19580b57cec5SDimitry Andric FuncInfo->MBB = FailureMBB;
19590b57cec5SDimitry Andric FuncInfo->InsertPt = FailureMBB->end();
19600b57cec5SDimitry Andric SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
19610b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
19620b57cec5SDimitry Andric SDB->clear();
19630b57cec5SDimitry Andric CodeGenAndEmitDAG();
19640b57cec5SDimitry Andric }
19650b57cec5SDimitry Andric
19660b57cec5SDimitry Andric // Clear the Per-BB State.
19670b57cec5SDimitry Andric SDB->SPDescriptor.resetPerBBState();
19680b57cec5SDimitry Andric }
19690b57cec5SDimitry Andric
19700b57cec5SDimitry Andric // Lower each BitTestBlock.
19710b57cec5SDimitry Andric for (auto &BTB : SDB->SL->BitTestCases) {
19720b57cec5SDimitry Andric // Lower header first, if it wasn't already lowered
19730b57cec5SDimitry Andric if (!BTB.Emitted) {
19740b57cec5SDimitry Andric // Set the current basic block to the mbb we wish to insert the code into
19750b57cec5SDimitry Andric FuncInfo->MBB = BTB.Parent;
19760b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
19770b57cec5SDimitry Andric // Emit the code
19780b57cec5SDimitry Andric SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
19790b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
19800b57cec5SDimitry Andric SDB->clear();
19810b57cec5SDimitry Andric CodeGenAndEmitDAG();
19820b57cec5SDimitry Andric }
19830b57cec5SDimitry Andric
19840b57cec5SDimitry Andric BranchProbability UnhandledProb = BTB.Prob;
19850b57cec5SDimitry Andric for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
19860b57cec5SDimitry Andric UnhandledProb -= BTB.Cases[j].ExtraProb;
19870b57cec5SDimitry Andric // Set the current basic block to the mbb we wish to insert the code into
19880b57cec5SDimitry Andric FuncInfo->MBB = BTB.Cases[j].ThisBB;
19890b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
19900b57cec5SDimitry Andric // Emit the code
19910b57cec5SDimitry Andric
19920b57cec5SDimitry Andric // If all cases cover a contiguous range, it is not necessary to jump to
19930b57cec5SDimitry Andric // the default block after the last bit test fails. This is because the
19940b57cec5SDimitry Andric // range check during bit test header creation has guaranteed that every
19950b57cec5SDimitry Andric // case here doesn't go outside the range. In this case, there is no need
19960b57cec5SDimitry Andric // to perform the last bit test, as it will always be true. Instead, make
19970b57cec5SDimitry Andric // the second-to-last bit-test fall through to the target of the last bit
19980b57cec5SDimitry Andric // test, and delete the last bit test.
19990b57cec5SDimitry Andric
20000b57cec5SDimitry Andric MachineBasicBlock *NextMBB;
2001349cc55cSDimitry Andric if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2002349cc55cSDimitry Andric // Second-to-last bit-test with contiguous range or omitted range
2003349cc55cSDimitry Andric // check: fall through to the target of the final bit test.
20040b57cec5SDimitry Andric NextMBB = BTB.Cases[j + 1].TargetBB;
20050b57cec5SDimitry Andric } else if (j + 1 == ej) {
20060b57cec5SDimitry Andric // For the last bit test, fall through to Default.
20070b57cec5SDimitry Andric NextMBB = BTB.Default;
20080b57cec5SDimitry Andric } else {
20090b57cec5SDimitry Andric // Otherwise, fall through to the next bit test.
20100b57cec5SDimitry Andric NextMBB = BTB.Cases[j + 1].ThisBB;
20110b57cec5SDimitry Andric }
20120b57cec5SDimitry Andric
20130b57cec5SDimitry Andric SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
20140b57cec5SDimitry Andric FuncInfo->MBB);
20150b57cec5SDimitry Andric
20160b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
20170b57cec5SDimitry Andric SDB->clear();
20180b57cec5SDimitry Andric CodeGenAndEmitDAG();
20190b57cec5SDimitry Andric
2020349cc55cSDimitry Andric if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
20210b57cec5SDimitry Andric // Since we're not going to use the final bit test, remove it.
20220b57cec5SDimitry Andric BTB.Cases.pop_back();
20230b57cec5SDimitry Andric break;
20240b57cec5SDimitry Andric }
20250b57cec5SDimitry Andric }
20260b57cec5SDimitry Andric
20270b57cec5SDimitry Andric // Update PHI Nodes
20280eae32dcSDimitry Andric for (const std::pair<MachineInstr *, unsigned> &P :
20290eae32dcSDimitry Andric FuncInfo->PHINodesToUpdate) {
20300eae32dcSDimitry Andric MachineInstrBuilder PHI(*MF, P.first);
20310b57cec5SDimitry Andric MachineBasicBlock *PHIBB = PHI->getParent();
20320b57cec5SDimitry Andric assert(PHI->isPHI() &&
20330b57cec5SDimitry Andric "This is not a machine PHI node that we are updating!");
20340b57cec5SDimitry Andric // This is "default" BB. We have two jumps to it. From "header" BB and
20350b57cec5SDimitry Andric // from last "case" BB, unless the latter was skipped.
20360b57cec5SDimitry Andric if (PHIBB == BTB.Default) {
20370eae32dcSDimitry Andric PHI.addReg(P.second).addMBB(BTB.Parent);
20380b57cec5SDimitry Andric if (!BTB.ContiguousRange) {
20390eae32dcSDimitry Andric PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
20400b57cec5SDimitry Andric }
20410b57cec5SDimitry Andric }
20420b57cec5SDimitry Andric // One of "cases" BB.
20430eae32dcSDimitry Andric for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
20440eae32dcSDimitry Andric MachineBasicBlock* cBB = BT.ThisBB;
20450b57cec5SDimitry Andric if (cBB->isSuccessor(PHIBB))
20460eae32dcSDimitry Andric PHI.addReg(P.second).addMBB(cBB);
20470b57cec5SDimitry Andric }
20480b57cec5SDimitry Andric }
20490b57cec5SDimitry Andric }
20500b57cec5SDimitry Andric SDB->SL->BitTestCases.clear();
20510b57cec5SDimitry Andric
20520b57cec5SDimitry Andric // If the JumpTable record is filled in, then we need to emit a jump table.
20530b57cec5SDimitry Andric // Updating the PHI nodes is tricky in this case, since we need to determine
20540b57cec5SDimitry Andric // whether the PHI is a successor of the range check MBB or the jump table MBB
20550b57cec5SDimitry Andric for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
20560b57cec5SDimitry Andric // Lower header first, if it wasn't already lowered
20570b57cec5SDimitry Andric if (!SDB->SL->JTCases[i].first.Emitted) {
20580b57cec5SDimitry Andric // Set the current basic block to the mbb we wish to insert the code into
20590b57cec5SDimitry Andric FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
20600b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
20610b57cec5SDimitry Andric // Emit the code
20620b57cec5SDimitry Andric SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
20630b57cec5SDimitry Andric SDB->SL->JTCases[i].first, FuncInfo->MBB);
20640b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
20650b57cec5SDimitry Andric SDB->clear();
20660b57cec5SDimitry Andric CodeGenAndEmitDAG();
20670b57cec5SDimitry Andric }
20680b57cec5SDimitry Andric
20690b57cec5SDimitry Andric // Set the current basic block to the mbb we wish to insert the code into
20700b57cec5SDimitry Andric FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
20710b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
20720b57cec5SDimitry Andric // Emit the code
20730b57cec5SDimitry Andric SDB->visitJumpTable(SDB->SL->JTCases[i].second);
20740b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
20750b57cec5SDimitry Andric SDB->clear();
20760b57cec5SDimitry Andric CodeGenAndEmitDAG();
20770b57cec5SDimitry Andric
20780b57cec5SDimitry Andric // Update PHI Nodes
20790b57cec5SDimitry Andric for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
20800b57cec5SDimitry Andric pi != pe; ++pi) {
20810b57cec5SDimitry Andric MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
20820b57cec5SDimitry Andric MachineBasicBlock *PHIBB = PHI->getParent();
20830b57cec5SDimitry Andric assert(PHI->isPHI() &&
20840b57cec5SDimitry Andric "This is not a machine PHI node that we are updating!");
20850b57cec5SDimitry Andric // "default" BB. We can go there only from header BB.
20860b57cec5SDimitry Andric if (PHIBB == SDB->SL->JTCases[i].second.Default)
20870b57cec5SDimitry Andric PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
20880b57cec5SDimitry Andric .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
20890b57cec5SDimitry Andric // JT BB. Just iterate over successors here
20900b57cec5SDimitry Andric if (FuncInfo->MBB->isSuccessor(PHIBB))
20910b57cec5SDimitry Andric PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
20920b57cec5SDimitry Andric }
20930b57cec5SDimitry Andric }
20940b57cec5SDimitry Andric SDB->SL->JTCases.clear();
20950b57cec5SDimitry Andric
20960b57cec5SDimitry Andric // If we generated any switch lowering information, build and codegen any
20970b57cec5SDimitry Andric // additional DAGs necessary.
20980b57cec5SDimitry Andric for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
20990b57cec5SDimitry Andric // Set the current basic block to the mbb we wish to insert the code into
21000b57cec5SDimitry Andric FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
21010b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
21020b57cec5SDimitry Andric
21030b57cec5SDimitry Andric // Determine the unique successors.
21040b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 2> Succs;
21050b57cec5SDimitry Andric Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
21060b57cec5SDimitry Andric if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
21070b57cec5SDimitry Andric Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
21080b57cec5SDimitry Andric
21090b57cec5SDimitry Andric // Emit the code. Note that this could result in FuncInfo->MBB being split.
21100b57cec5SDimitry Andric SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
21110b57cec5SDimitry Andric CurDAG->setRoot(SDB->getRoot());
21120b57cec5SDimitry Andric SDB->clear();
21130b57cec5SDimitry Andric CodeGenAndEmitDAG();
21140b57cec5SDimitry Andric
21150b57cec5SDimitry Andric // Remember the last block, now that any splitting is done, for use in
21160b57cec5SDimitry Andric // populating PHI nodes in successors.
21170b57cec5SDimitry Andric MachineBasicBlock *ThisBB = FuncInfo->MBB;
21180b57cec5SDimitry Andric
21190b57cec5SDimitry Andric // Handle any PHI nodes in successors of this chunk, as if we were coming
21200b57cec5SDimitry Andric // from the original BB before switch expansion. Note that PHI nodes can
21210b57cec5SDimitry Andric // occur multiple times in PHINodesToUpdate. We have to be very careful to
21220b57cec5SDimitry Andric // handle them the right number of times.
21230fca6ea1SDimitry Andric for (MachineBasicBlock *Succ : Succs) {
21240fca6ea1SDimitry Andric FuncInfo->MBB = Succ;
21250b57cec5SDimitry Andric FuncInfo->InsertPt = FuncInfo->MBB->end();
21260b57cec5SDimitry Andric // FuncInfo->MBB may have been removed from the CFG if a branch was
21270b57cec5SDimitry Andric // constant folded.
21280b57cec5SDimitry Andric if (ThisBB->isSuccessor(FuncInfo->MBB)) {
21290b57cec5SDimitry Andric for (MachineBasicBlock::iterator
21300b57cec5SDimitry Andric MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
21310b57cec5SDimitry Andric MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
21320b57cec5SDimitry Andric MachineInstrBuilder PHI(*MF, MBBI);
21330b57cec5SDimitry Andric // This value for this PHI node is recorded in PHINodesToUpdate.
21340b57cec5SDimitry Andric for (unsigned pn = 0; ; ++pn) {
21350b57cec5SDimitry Andric assert(pn != FuncInfo->PHINodesToUpdate.size() &&
21360b57cec5SDimitry Andric "Didn't find PHI entry!");
21370b57cec5SDimitry Andric if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
21380b57cec5SDimitry Andric PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
21390b57cec5SDimitry Andric break;
21400b57cec5SDimitry Andric }
21410b57cec5SDimitry Andric }
21420b57cec5SDimitry Andric }
21430b57cec5SDimitry Andric }
21440b57cec5SDimitry Andric }
21450b57cec5SDimitry Andric }
21460b57cec5SDimitry Andric SDB->SL->SwitchCases.clear();
21470b57cec5SDimitry Andric }
21480b57cec5SDimitry Andric
21490b57cec5SDimitry Andric /// Create the scheduler. If a specific scheduler was specified
21500b57cec5SDimitry Andric /// via the SchedulerRegistry, use it, otherwise select the
21510b57cec5SDimitry Andric /// one preferred by the target.
21520b57cec5SDimitry Andric ///
CreateScheduler()21530b57cec5SDimitry Andric ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
21540b57cec5SDimitry Andric return ISHeuristic(this, OptLevel);
21550b57cec5SDimitry Andric }
21560b57cec5SDimitry Andric
21570b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
21580b57cec5SDimitry Andric // Helper functions used by the generated instruction selector.
21590b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
21600b57cec5SDimitry Andric // Calls to these methods are generated by tblgen.
21610b57cec5SDimitry Andric
21620b57cec5SDimitry Andric /// CheckAndMask - The isel is trying to match something like (and X, 255). If
21630b57cec5SDimitry Andric /// the dag combiner simplified the 255, we still want to match. RHS is the
21640b57cec5SDimitry Andric /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
21650b57cec5SDimitry Andric /// specified in the .td file (e.g. 255).
CheckAndMask(SDValue LHS,ConstantSDNode * RHS,int64_t DesiredMaskS) const21660b57cec5SDimitry Andric bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
21670b57cec5SDimitry Andric int64_t DesiredMaskS) const {
21680b57cec5SDimitry Andric const APInt &ActualMask = RHS->getAPIntValue();
21690b57cec5SDimitry Andric const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
21700b57cec5SDimitry Andric
21710b57cec5SDimitry Andric // If the actual mask exactly matches, success!
21720b57cec5SDimitry Andric if (ActualMask == DesiredMask)
21730b57cec5SDimitry Andric return true;
21740b57cec5SDimitry Andric
21750b57cec5SDimitry Andric // If the actual AND mask is allowing unallowed bits, this doesn't match.
21760b57cec5SDimitry Andric if (!ActualMask.isSubsetOf(DesiredMask))
21770b57cec5SDimitry Andric return false;
21780b57cec5SDimitry Andric
21790b57cec5SDimitry Andric // Otherwise, the DAG Combiner may have proven that the value coming in is
21800b57cec5SDimitry Andric // either already zero or is not demanded. Check for known zero input bits.
21810b57cec5SDimitry Andric APInt NeededMask = DesiredMask & ~ActualMask;
21820b57cec5SDimitry Andric if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
21830b57cec5SDimitry Andric return true;
21840b57cec5SDimitry Andric
21850b57cec5SDimitry Andric // TODO: check to see if missing bits are just not demanded.
21860b57cec5SDimitry Andric
21870b57cec5SDimitry Andric // Otherwise, this pattern doesn't match.
21880b57cec5SDimitry Andric return false;
21890b57cec5SDimitry Andric }
21900b57cec5SDimitry Andric
21910b57cec5SDimitry Andric /// CheckOrMask - The isel is trying to match something like (or X, 255). If
21920b57cec5SDimitry Andric /// the dag combiner simplified the 255, we still want to match. RHS is the
21930b57cec5SDimitry Andric /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
21940b57cec5SDimitry Andric /// specified in the .td file (e.g. 255).
CheckOrMask(SDValue LHS,ConstantSDNode * RHS,int64_t DesiredMaskS) const21950b57cec5SDimitry Andric bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
21960b57cec5SDimitry Andric int64_t DesiredMaskS) const {
21970b57cec5SDimitry Andric const APInt &ActualMask = RHS->getAPIntValue();
21980b57cec5SDimitry Andric const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
21990b57cec5SDimitry Andric
22000b57cec5SDimitry Andric // If the actual mask exactly matches, success!
22010b57cec5SDimitry Andric if (ActualMask == DesiredMask)
22020b57cec5SDimitry Andric return true;
22030b57cec5SDimitry Andric
22040b57cec5SDimitry Andric // If the actual AND mask is allowing unallowed bits, this doesn't match.
22050b57cec5SDimitry Andric if (!ActualMask.isSubsetOf(DesiredMask))
22060b57cec5SDimitry Andric return false;
22070b57cec5SDimitry Andric
22080b57cec5SDimitry Andric // Otherwise, the DAG Combiner may have proven that the value coming in is
22090b57cec5SDimitry Andric // either already zero or is not demanded. Check for known zero input bits.
22100b57cec5SDimitry Andric APInt NeededMask = DesiredMask & ~ActualMask;
22110b57cec5SDimitry Andric KnownBits Known = CurDAG->computeKnownBits(LHS);
22120b57cec5SDimitry Andric
22130b57cec5SDimitry Andric // If all the missing bits in the or are already known to be set, match!
22140b57cec5SDimitry Andric if (NeededMask.isSubsetOf(Known.One))
22150b57cec5SDimitry Andric return true;
22160b57cec5SDimitry Andric
22170b57cec5SDimitry Andric // TODO: check to see if missing bits are just not demanded.
22180b57cec5SDimitry Andric
22190b57cec5SDimitry Andric // Otherwise, this pattern doesn't match.
22200b57cec5SDimitry Andric return false;
22210b57cec5SDimitry Andric }
22220b57cec5SDimitry Andric
22230b57cec5SDimitry Andric /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
22240b57cec5SDimitry Andric /// by tblgen. Others should not call it.
SelectInlineAsmMemoryOperands(std::vector<SDValue> & Ops,const SDLoc & DL)22250b57cec5SDimitry Andric void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
22260b57cec5SDimitry Andric const SDLoc &DL) {
22270fca6ea1SDimitry Andric // Change the vector of SDValue into a list of SDNodeHandle for x86 might call
22280fca6ea1SDimitry Andric // replaceAllUses when matching address.
22290b57cec5SDimitry Andric
22300fca6ea1SDimitry Andric std::list<HandleSDNode> Handles;
22310b57cec5SDimitry Andric
22320fca6ea1SDimitry Andric Handles.emplace_back(Ops[InlineAsm::Op_InputChain]); // 0
22330fca6ea1SDimitry Andric Handles.emplace_back(Ops[InlineAsm::Op_AsmString]); // 1
22340fca6ea1SDimitry Andric Handles.emplace_back(Ops[InlineAsm::Op_MDNode]); // 2, !srcloc
22350fca6ea1SDimitry Andric Handles.emplace_back(
22360fca6ea1SDimitry Andric Ops[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
22370fca6ea1SDimitry Andric
22380fca6ea1SDimitry Andric unsigned i = InlineAsm::Op_FirstOperand, e = Ops.size();
22390fca6ea1SDimitry Andric if (Ops[e - 1].getValueType() == MVT::Glue)
22400b57cec5SDimitry Andric --e; // Don't process a glue operand if it is here.
22410b57cec5SDimitry Andric
22420b57cec5SDimitry Andric while (i != e) {
22430fca6ea1SDimitry Andric InlineAsm::Flag Flags(Ops[i]->getAsZExtVal());
22445f757f3fSDimitry Andric if (!Flags.isMemKind() && !Flags.isFuncKind()) {
22450b57cec5SDimitry Andric // Just skip over this operand, copying the operands verbatim.
22460fca6ea1SDimitry Andric Handles.insert(Handles.end(), Ops.begin() + i,
22470fca6ea1SDimitry Andric Ops.begin() + i + Flags.getNumOperandRegisters() + 1);
22485f757f3fSDimitry Andric i += Flags.getNumOperandRegisters() + 1;
22490b57cec5SDimitry Andric } else {
22505f757f3fSDimitry Andric assert(Flags.getNumOperandRegisters() == 1 &&
22510b57cec5SDimitry Andric "Memory operand with multiple values?");
22520b57cec5SDimitry Andric
22530b57cec5SDimitry Andric unsigned TiedToOperand;
22545f757f3fSDimitry Andric if (Flags.isUseOperandTiedToDef(TiedToOperand)) {
22550b57cec5SDimitry Andric // We need the constraint ID from the operand this is tied to.
22560b57cec5SDimitry Andric unsigned CurOp = InlineAsm::Op_FirstOperand;
22570fca6ea1SDimitry Andric Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
22580b57cec5SDimitry Andric for (; TiedToOperand; --TiedToOperand) {
22595f757f3fSDimitry Andric CurOp += Flags.getNumOperandRegisters() + 1;
22600fca6ea1SDimitry Andric Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
22610b57cec5SDimitry Andric }
22620b57cec5SDimitry Andric }
22630b57cec5SDimitry Andric
22640b57cec5SDimitry Andric // Otherwise, this is a memory operand. Ask the target to select it.
22650b57cec5SDimitry Andric std::vector<SDValue> SelOps;
22665f757f3fSDimitry Andric const InlineAsm::ConstraintCode ConstraintID =
22675f757f3fSDimitry Andric Flags.getMemoryConstraintID();
22680fca6ea1SDimitry Andric if (SelectInlineAsmMemoryOperand(Ops[i + 1], ConstraintID, SelOps))
22690b57cec5SDimitry Andric report_fatal_error("Could not match memory address. Inline asm"
22700b57cec5SDimitry Andric " failure!");
22710b57cec5SDimitry Andric
22720b57cec5SDimitry Andric // Add this to the output node.
22735f757f3fSDimitry Andric Flags = InlineAsm::Flag(Flags.isMemKind() ? InlineAsm::Kind::Mem
22745f757f3fSDimitry Andric : InlineAsm::Kind::Func,
22755f757f3fSDimitry Andric SelOps.size());
22765f757f3fSDimitry Andric Flags.setMemConstraint(ConstraintID);
22770fca6ea1SDimitry Andric Handles.emplace_back(CurDAG->getTargetConstant(Flags, DL, MVT::i32));
22780fca6ea1SDimitry Andric Handles.insert(Handles.end(), SelOps.begin(), SelOps.end());
22790b57cec5SDimitry Andric i += 2;
22800b57cec5SDimitry Andric }
22810b57cec5SDimitry Andric }
22820b57cec5SDimitry Andric
22830b57cec5SDimitry Andric // Add the glue input back if present.
22840fca6ea1SDimitry Andric if (e != Ops.size())
22850fca6ea1SDimitry Andric Handles.emplace_back(Ops.back());
22860fca6ea1SDimitry Andric
22870fca6ea1SDimitry Andric Ops.clear();
22880fca6ea1SDimitry Andric for (auto &handle : Handles)
22890fca6ea1SDimitry Andric Ops.push_back(handle.getValue());
22900b57cec5SDimitry Andric }
22910b57cec5SDimitry Andric
22920b57cec5SDimitry Andric /// findGlueUse - Return use of MVT::Glue value produced by the specified
22930b57cec5SDimitry Andric /// SDNode.
22940b57cec5SDimitry Andric ///
findGlueUse(SDNode * N)22950b57cec5SDimitry Andric static SDNode *findGlueUse(SDNode *N) {
22960b57cec5SDimitry Andric unsigned FlagResNo = N->getNumValues()-1;
22970b57cec5SDimitry Andric for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
22980b57cec5SDimitry Andric SDUse &Use = I.getUse();
22990b57cec5SDimitry Andric if (Use.getResNo() == FlagResNo)
23000b57cec5SDimitry Andric return Use.getUser();
23010b57cec5SDimitry Andric }
23020b57cec5SDimitry Andric return nullptr;
23030b57cec5SDimitry Andric }
23040b57cec5SDimitry Andric
23050b57cec5SDimitry Andric /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
23060b57cec5SDimitry Andric /// beyond "ImmedUse". We may ignore chains as they are checked separately.
findNonImmUse(SDNode * Root,SDNode * Def,SDNode * ImmedUse,bool IgnoreChains)23070b57cec5SDimitry Andric static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
23080b57cec5SDimitry Andric bool IgnoreChains) {
23090b57cec5SDimitry Andric SmallPtrSet<const SDNode *, 16> Visited;
23100b57cec5SDimitry Andric SmallVector<const SDNode *, 16> WorkList;
23110b57cec5SDimitry Andric // Only check if we have non-immediate uses of Def.
23120b57cec5SDimitry Andric if (ImmedUse->isOnlyUserOf(Def))
23130b57cec5SDimitry Andric return false;
23140b57cec5SDimitry Andric
23150b57cec5SDimitry Andric // We don't care about paths to Def that go through ImmedUse so mark it
23160b57cec5SDimitry Andric // visited and mark non-def operands as used.
23170b57cec5SDimitry Andric Visited.insert(ImmedUse);
23180b57cec5SDimitry Andric for (const SDValue &Op : ImmedUse->op_values()) {
23190b57cec5SDimitry Andric SDNode *N = Op.getNode();
23200b57cec5SDimitry Andric // Ignore chain deps (they are validated by
23210b57cec5SDimitry Andric // HandleMergeInputChains) and immediate uses
23220b57cec5SDimitry Andric if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
23230b57cec5SDimitry Andric continue;
23240b57cec5SDimitry Andric if (!Visited.insert(N).second)
23250b57cec5SDimitry Andric continue;
23260b57cec5SDimitry Andric WorkList.push_back(N);
23270b57cec5SDimitry Andric }
23280b57cec5SDimitry Andric
23290b57cec5SDimitry Andric // Initialize worklist to operands of Root.
23300b57cec5SDimitry Andric if (Root != ImmedUse) {
23310b57cec5SDimitry Andric for (const SDValue &Op : Root->op_values()) {
23320b57cec5SDimitry Andric SDNode *N = Op.getNode();
23330b57cec5SDimitry Andric // Ignore chains (they are validated by HandleMergeInputChains)
23340b57cec5SDimitry Andric if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
23350b57cec5SDimitry Andric continue;
23360b57cec5SDimitry Andric if (!Visited.insert(N).second)
23370b57cec5SDimitry Andric continue;
23380b57cec5SDimitry Andric WorkList.push_back(N);
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric }
23410b57cec5SDimitry Andric
23420b57cec5SDimitry Andric return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
23430b57cec5SDimitry Andric }
23440b57cec5SDimitry Andric
23450b57cec5SDimitry Andric /// IsProfitableToFold - Returns true if it's profitable to fold the specific
23460b57cec5SDimitry Andric /// operand node N of U during instruction selection that starts at Root.
IsProfitableToFold(SDValue N,SDNode * U,SDNode * Root) const23470b57cec5SDimitry Andric bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
23480b57cec5SDimitry Andric SDNode *Root) const {
23495f757f3fSDimitry Andric if (OptLevel == CodeGenOptLevel::None)
23505f757f3fSDimitry Andric return false;
23510b57cec5SDimitry Andric return N.hasOneUse();
23520b57cec5SDimitry Andric }
23530b57cec5SDimitry Andric
23540b57cec5SDimitry Andric /// IsLegalToFold - Returns true if the specific operand node N of
23550b57cec5SDimitry Andric /// U can be folded during instruction selection that starts at Root.
IsLegalToFold(SDValue N,SDNode * U,SDNode * Root,CodeGenOptLevel OptLevel,bool IgnoreChains)23560b57cec5SDimitry Andric bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
23575f757f3fSDimitry Andric CodeGenOptLevel OptLevel,
23580b57cec5SDimitry Andric bool IgnoreChains) {
23595f757f3fSDimitry Andric if (OptLevel == CodeGenOptLevel::None)
23605f757f3fSDimitry Andric return false;
23610b57cec5SDimitry Andric
23625f757f3fSDimitry Andric // If Root use can somehow reach N through a path that doesn't contain
23630b57cec5SDimitry Andric // U then folding N would create a cycle. e.g. In the following
23640b57cec5SDimitry Andric // diagram, Root can reach N through X. If N is folded into Root, then
23650b57cec5SDimitry Andric // X is both a predecessor and a successor of U.
23660b57cec5SDimitry Andric //
23670b57cec5SDimitry Andric // [N*] //
23680b57cec5SDimitry Andric // ^ ^ //
23690b57cec5SDimitry Andric // / \ //
23700b57cec5SDimitry Andric // [U*] [X]? //
23710b57cec5SDimitry Andric // ^ ^ //
23720b57cec5SDimitry Andric // \ / //
23730b57cec5SDimitry Andric // \ / //
23740b57cec5SDimitry Andric // [Root*] //
23750b57cec5SDimitry Andric //
23760b57cec5SDimitry Andric // * indicates nodes to be folded together.
23770b57cec5SDimitry Andric //
23780b57cec5SDimitry Andric // If Root produces glue, then it gets (even more) interesting. Since it
23790b57cec5SDimitry Andric // will be "glued" together with its glue use in the scheduler, we need to
23800b57cec5SDimitry Andric // check if it might reach N.
23810b57cec5SDimitry Andric //
23820b57cec5SDimitry Andric // [N*] //
23830b57cec5SDimitry Andric // ^ ^ //
23840b57cec5SDimitry Andric // / \ //
23850b57cec5SDimitry Andric // [U*] [X]? //
23860b57cec5SDimitry Andric // ^ ^ //
23870b57cec5SDimitry Andric // \ \ //
23880b57cec5SDimitry Andric // \ | //
23890b57cec5SDimitry Andric // [Root*] | //
23900b57cec5SDimitry Andric // ^ | //
23910b57cec5SDimitry Andric // f | //
23920b57cec5SDimitry Andric // | / //
23930b57cec5SDimitry Andric // [Y] / //
23940b57cec5SDimitry Andric // ^ / //
23950b57cec5SDimitry Andric // f / //
23960b57cec5SDimitry Andric // | / //
23970b57cec5SDimitry Andric // [GU] //
23980b57cec5SDimitry Andric //
23990b57cec5SDimitry Andric // If GU (glue use) indirectly reaches N (the load), and Root folds N
24000b57cec5SDimitry Andric // (call it Fold), then X is a predecessor of GU and a successor of
24010b57cec5SDimitry Andric // Fold. But since Fold and GU are glued together, this will create
24020b57cec5SDimitry Andric // a cycle in the scheduling graph.
24030b57cec5SDimitry Andric
24040b57cec5SDimitry Andric // If the node has glue, walk down the graph to the "lowest" node in the
24050b57cec5SDimitry Andric // glueged set.
24060b57cec5SDimitry Andric EVT VT = Root->getValueType(Root->getNumValues()-1);
24070b57cec5SDimitry Andric while (VT == MVT::Glue) {
24080b57cec5SDimitry Andric SDNode *GU = findGlueUse(Root);
24090b57cec5SDimitry Andric if (!GU)
24100b57cec5SDimitry Andric break;
24110b57cec5SDimitry Andric Root = GU;
24120b57cec5SDimitry Andric VT = Root->getValueType(Root->getNumValues()-1);
24130b57cec5SDimitry Andric
24140b57cec5SDimitry Andric // If our query node has a glue result with a use, we've walked up it. If
24150b57cec5SDimitry Andric // the user (which has already been selected) has a chain or indirectly uses
24160b57cec5SDimitry Andric // the chain, HandleMergeInputChains will not consider it. Because of
24170b57cec5SDimitry Andric // this, we cannot ignore chains in this predicate.
24180b57cec5SDimitry Andric IgnoreChains = false;
24190b57cec5SDimitry Andric }
24200b57cec5SDimitry Andric
24210b57cec5SDimitry Andric return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
24220b57cec5SDimitry Andric }
24230b57cec5SDimitry Andric
Select_INLINEASM(SDNode * N)24245ffd83dbSDimitry Andric void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
24250b57cec5SDimitry Andric SDLoc DL(N);
24260b57cec5SDimitry Andric
24270b57cec5SDimitry Andric std::vector<SDValue> Ops(N->op_begin(), N->op_end());
24280b57cec5SDimitry Andric SelectInlineAsmMemoryOperands(Ops, DL);
24290b57cec5SDimitry Andric
24300b57cec5SDimitry Andric const EVT VTs[] = {MVT::Other, MVT::Glue};
24315ffd83dbSDimitry Andric SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
24320b57cec5SDimitry Andric New->setNodeId(-1);
24330b57cec5SDimitry Andric ReplaceUses(N, New.getNode());
24340b57cec5SDimitry Andric CurDAG->RemoveDeadNode(N);
24350b57cec5SDimitry Andric }
24360b57cec5SDimitry Andric
Select_READ_REGISTER(SDNode * Op)24370b57cec5SDimitry Andric void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
24380b57cec5SDimitry Andric SDLoc dl(Op);
2439480093f4SDimitry Andric MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2440480093f4SDimitry Andric const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2441480093f4SDimitry Andric
2442480093f4SDimitry Andric EVT VT = Op->getValueType(0);
2443480093f4SDimitry Andric LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
24448bcb0991SDimitry Andric Register Reg =
2445480093f4SDimitry Andric TLI->getRegisterByName(RegStr->getString().data(), Ty,
24468bcb0991SDimitry Andric CurDAG->getMachineFunction());
24470b57cec5SDimitry Andric SDValue New = CurDAG->getCopyFromReg(
24480b57cec5SDimitry Andric Op->getOperand(0), dl, Reg, Op->getValueType(0));
24490b57cec5SDimitry Andric New->setNodeId(-1);
24500b57cec5SDimitry Andric ReplaceUses(Op, New.getNode());
24510b57cec5SDimitry Andric CurDAG->RemoveDeadNode(Op);
24520b57cec5SDimitry Andric }
24530b57cec5SDimitry Andric
Select_WRITE_REGISTER(SDNode * Op)24540b57cec5SDimitry Andric void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
24550b57cec5SDimitry Andric SDLoc dl(Op);
2456480093f4SDimitry Andric MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2457480093f4SDimitry Andric const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2458480093f4SDimitry Andric
2459480093f4SDimitry Andric EVT VT = Op->getOperand(2).getValueType();
2460480093f4SDimitry Andric LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2461480093f4SDimitry Andric
2462480093f4SDimitry Andric Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
24638bcb0991SDimitry Andric CurDAG->getMachineFunction());
24640b57cec5SDimitry Andric SDValue New = CurDAG->getCopyToReg(
24650b57cec5SDimitry Andric Op->getOperand(0), dl, Reg, Op->getOperand(2));
24660b57cec5SDimitry Andric New->setNodeId(-1);
24670b57cec5SDimitry Andric ReplaceUses(Op, New.getNode());
24680b57cec5SDimitry Andric CurDAG->RemoveDeadNode(Op);
24690b57cec5SDimitry Andric }
24700b57cec5SDimitry Andric
Select_UNDEF(SDNode * N)24710b57cec5SDimitry Andric void SelectionDAGISel::Select_UNDEF(SDNode *N) {
24720b57cec5SDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
24730b57cec5SDimitry Andric }
24740b57cec5SDimitry Andric
Select_FREEZE(SDNode * N)24755ffd83dbSDimitry Andric void SelectionDAGISel::Select_FREEZE(SDNode *N) {
24765ffd83dbSDimitry Andric // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
24775ffd83dbSDimitry Andric // If FREEZE instruction is added later, the code below must be changed as
24785ffd83dbSDimitry Andric // well.
24795ffd83dbSDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
24805ffd83dbSDimitry Andric N->getOperand(0));
24815ffd83dbSDimitry Andric }
24825ffd83dbSDimitry Andric
Select_ARITH_FENCE(SDNode * N)2483fe6060f1SDimitry Andric void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2484fe6060f1SDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2485fe6060f1SDimitry Andric N->getOperand(0));
2486fe6060f1SDimitry Andric }
2487fe6060f1SDimitry Andric
Select_MEMBARRIER(SDNode * N)2488bdd1243dSDimitry Andric void SelectionDAGISel::Select_MEMBARRIER(SDNode *N) {
2489bdd1243dSDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::MEMBARRIER, N->getValueType(0),
2490bdd1243dSDimitry Andric N->getOperand(0));
2491bdd1243dSDimitry Andric }
2492bdd1243dSDimitry Andric
Select_CONVERGENCECTRL_ANCHOR(SDNode * N)24930fca6ea1SDimitry Andric void SelectionDAGISel::Select_CONVERGENCECTRL_ANCHOR(SDNode *N) {
24940fca6ea1SDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ANCHOR,
24950fca6ea1SDimitry Andric N->getValueType(0));
24960fca6ea1SDimitry Andric }
24970fca6ea1SDimitry Andric
Select_CONVERGENCECTRL_ENTRY(SDNode * N)24980fca6ea1SDimitry Andric void SelectionDAGISel::Select_CONVERGENCECTRL_ENTRY(SDNode *N) {
24990fca6ea1SDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ENTRY,
25000fca6ea1SDimitry Andric N->getValueType(0));
25010fca6ea1SDimitry Andric }
25020fca6ea1SDimitry Andric
Select_CONVERGENCECTRL_LOOP(SDNode * N)25030fca6ea1SDimitry Andric void SelectionDAGISel::Select_CONVERGENCECTRL_LOOP(SDNode *N) {
25040fca6ea1SDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_LOOP,
25050fca6ea1SDimitry Andric N->getValueType(0), N->getOperand(0));
25060fca6ea1SDimitry Andric }
25070fca6ea1SDimitry Andric
pushStackMapLiveVariable(SmallVectorImpl<SDValue> & Ops,SDValue OpVal,SDLoc DL)2508fcaf7f86SDimitry Andric void SelectionDAGISel::pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops,
2509fcaf7f86SDimitry Andric SDValue OpVal, SDLoc DL) {
2510fcaf7f86SDimitry Andric SDNode *OpNode = OpVal.getNode();
2511fcaf7f86SDimitry Andric
2512fcaf7f86SDimitry Andric // FrameIndex nodes should have been directly emitted to TargetFrameIndex
2513fcaf7f86SDimitry Andric // nodes at DAG-construction time.
2514fcaf7f86SDimitry Andric assert(OpNode->getOpcode() != ISD::FrameIndex);
2515fcaf7f86SDimitry Andric
2516fcaf7f86SDimitry Andric if (OpNode->getOpcode() == ISD::Constant) {
2517fcaf7f86SDimitry Andric Ops.push_back(
2518fcaf7f86SDimitry Andric CurDAG->getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
25191db9f3b2SDimitry Andric Ops.push_back(CurDAG->getTargetConstant(OpNode->getAsZExtVal(), DL,
25201db9f3b2SDimitry Andric OpVal.getValueType()));
2521fcaf7f86SDimitry Andric } else {
2522fcaf7f86SDimitry Andric Ops.push_back(OpVal);
2523fcaf7f86SDimitry Andric }
2524fcaf7f86SDimitry Andric }
2525fcaf7f86SDimitry Andric
Select_STACKMAP(SDNode * N)2526753f127fSDimitry Andric void SelectionDAGISel::Select_STACKMAP(SDNode *N) {
2527fcaf7f86SDimitry Andric SmallVector<SDValue, 32> Ops;
2528753f127fSDimitry Andric auto *It = N->op_begin();
2529753f127fSDimitry Andric SDLoc DL(N);
2530753f127fSDimitry Andric
2531753f127fSDimitry Andric // Stash the chain and glue operands so we can move them to the end.
2532753f127fSDimitry Andric SDValue Chain = *It++;
253306c3fb27SDimitry Andric SDValue InGlue = *It++;
2534753f127fSDimitry Andric
2535753f127fSDimitry Andric // <id> operand.
2536753f127fSDimitry Andric SDValue ID = *It++;
2537753f127fSDimitry Andric assert(ID.getValueType() == MVT::i64);
2538753f127fSDimitry Andric Ops.push_back(ID);
2539753f127fSDimitry Andric
2540753f127fSDimitry Andric // <numShadowBytes> operand.
2541753f127fSDimitry Andric SDValue Shad = *It++;
2542753f127fSDimitry Andric assert(Shad.getValueType() == MVT::i32);
2543753f127fSDimitry Andric Ops.push_back(Shad);
2544753f127fSDimitry Andric
2545753f127fSDimitry Andric // Live variable operands.
2546fcaf7f86SDimitry Andric for (; It != N->op_end(); It++)
2547fcaf7f86SDimitry Andric pushStackMapLiveVariable(Ops, *It, DL);
2548753f127fSDimitry Andric
2549753f127fSDimitry Andric Ops.push_back(Chain);
255006c3fb27SDimitry Andric Ops.push_back(InGlue);
2551753f127fSDimitry Andric
2552753f127fSDimitry Andric SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
2553753f127fSDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::STACKMAP, NodeTys, Ops);
2554753f127fSDimitry Andric }
2555753f127fSDimitry Andric
Select_PATCHPOINT(SDNode * N)2556fcaf7f86SDimitry Andric void SelectionDAGISel::Select_PATCHPOINT(SDNode *N) {
2557fcaf7f86SDimitry Andric SmallVector<SDValue, 32> Ops;
2558fcaf7f86SDimitry Andric auto *It = N->op_begin();
2559fcaf7f86SDimitry Andric SDLoc DL(N);
2560fcaf7f86SDimitry Andric
2561fcaf7f86SDimitry Andric // Cache arguments that will be moved to the end in the target node.
2562fcaf7f86SDimitry Andric SDValue Chain = *It++;
2563bdd1243dSDimitry Andric std::optional<SDValue> Glue;
2564fcaf7f86SDimitry Andric if (It->getValueType() == MVT::Glue)
2565fcaf7f86SDimitry Andric Glue = *It++;
2566fcaf7f86SDimitry Andric SDValue RegMask = *It++;
2567fcaf7f86SDimitry Andric
2568fcaf7f86SDimitry Andric // <id> operand.
2569fcaf7f86SDimitry Andric SDValue ID = *It++;
2570fcaf7f86SDimitry Andric assert(ID.getValueType() == MVT::i64);
2571fcaf7f86SDimitry Andric Ops.push_back(ID);
2572fcaf7f86SDimitry Andric
2573fcaf7f86SDimitry Andric // <numShadowBytes> operand.
2574fcaf7f86SDimitry Andric SDValue Shad = *It++;
2575fcaf7f86SDimitry Andric assert(Shad.getValueType() == MVT::i32);
2576fcaf7f86SDimitry Andric Ops.push_back(Shad);
2577fcaf7f86SDimitry Andric
2578fcaf7f86SDimitry Andric // Add the callee.
2579fcaf7f86SDimitry Andric Ops.push_back(*It++);
2580fcaf7f86SDimitry Andric
2581fcaf7f86SDimitry Andric // Add <numArgs>.
2582fcaf7f86SDimitry Andric SDValue NumArgs = *It++;
2583fcaf7f86SDimitry Andric assert(NumArgs.getValueType() == MVT::i32);
2584fcaf7f86SDimitry Andric Ops.push_back(NumArgs);
2585fcaf7f86SDimitry Andric
2586fcaf7f86SDimitry Andric // Calling convention.
2587fcaf7f86SDimitry Andric Ops.push_back(*It++);
2588fcaf7f86SDimitry Andric
2589fcaf7f86SDimitry Andric // Push the args for the call.
25901db9f3b2SDimitry Andric for (uint64_t I = NumArgs->getAsZExtVal(); I != 0; I--)
2591fcaf7f86SDimitry Andric Ops.push_back(*It++);
2592fcaf7f86SDimitry Andric
2593fcaf7f86SDimitry Andric // Now push the live variables.
2594fcaf7f86SDimitry Andric for (; It != N->op_end(); It++)
2595fcaf7f86SDimitry Andric pushStackMapLiveVariable(Ops, *It, DL);
2596fcaf7f86SDimitry Andric
2597fcaf7f86SDimitry Andric // Finally, the regmask, chain and (if present) glue are moved to the end.
2598fcaf7f86SDimitry Andric Ops.push_back(RegMask);
2599fcaf7f86SDimitry Andric Ops.push_back(Chain);
2600fcaf7f86SDimitry Andric if (Glue.has_value())
2601bdd1243dSDimitry Andric Ops.push_back(*Glue);
2602fcaf7f86SDimitry Andric
2603fcaf7f86SDimitry Andric SDVTList NodeTys = N->getVTList();
2604fcaf7f86SDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::PATCHPOINT, NodeTys, Ops);
2605fcaf7f86SDimitry Andric }
2606fcaf7f86SDimitry Andric
26070b57cec5SDimitry Andric /// GetVBR - decode a vbr encoding whose top bit is set.
2608e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
GetVBR(uint64_t Val,const unsigned char * MatcherTable,unsigned & Idx)26090b57cec5SDimitry Andric GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
26100b57cec5SDimitry Andric assert(Val >= 128 && "Not a VBR");
26110b57cec5SDimitry Andric Val &= 127; // Remove first vbr bit.
26120b57cec5SDimitry Andric
26130b57cec5SDimitry Andric unsigned Shift = 7;
26140b57cec5SDimitry Andric uint64_t NextBits;
26150b57cec5SDimitry Andric do {
26160b57cec5SDimitry Andric NextBits = MatcherTable[Idx++];
26170b57cec5SDimitry Andric Val |= (NextBits&127) << Shift;
26180b57cec5SDimitry Andric Shift += 7;
26190b57cec5SDimitry Andric } while (NextBits & 128);
26200b57cec5SDimitry Andric
26210b57cec5SDimitry Andric return Val;
26220b57cec5SDimitry Andric }
26230b57cec5SDimitry Andric
Select_JUMP_TABLE_DEBUG_INFO(SDNode * N)26245f757f3fSDimitry Andric void SelectionDAGISel::Select_JUMP_TABLE_DEBUG_INFO(SDNode *N) {
26255f757f3fSDimitry Andric SDLoc dl(N);
26265f757f3fSDimitry Andric CurDAG->SelectNodeTo(N, TargetOpcode::JUMP_TABLE_DEBUG_INFO, MVT::Glue,
26275f757f3fSDimitry Andric CurDAG->getTargetConstant(N->getConstantOperandVal(1),
26285f757f3fSDimitry Andric dl, MVT::i64, true));
26295f757f3fSDimitry Andric }
26305f757f3fSDimitry Andric
26310b57cec5SDimitry Andric /// When a match is complete, this method updates uses of interior chain results
26320b57cec5SDimitry Andric /// to use the new results.
UpdateChains(SDNode * NodeToMatch,SDValue InputChain,SmallVectorImpl<SDNode * > & ChainNodesMatched,bool isMorphNodeTo)26330b57cec5SDimitry Andric void SelectionDAGISel::UpdateChains(
26340b57cec5SDimitry Andric SDNode *NodeToMatch, SDValue InputChain,
26350b57cec5SDimitry Andric SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
26360b57cec5SDimitry Andric SmallVector<SDNode*, 4> NowDeadNodes;
26370b57cec5SDimitry Andric
26380b57cec5SDimitry Andric // Now that all the normal results are replaced, we replace the chain and
26390b57cec5SDimitry Andric // glue results if present.
26400b57cec5SDimitry Andric if (!ChainNodesMatched.empty()) {
26410b57cec5SDimitry Andric assert(InputChain.getNode() &&
26420b57cec5SDimitry Andric "Matched input chains but didn't produce a chain");
26430b57cec5SDimitry Andric // Loop over all of the nodes we matched that produced a chain result.
26440b57cec5SDimitry Andric // Replace all the chain results with the final chain we ended up with.
26450b57cec5SDimitry Andric for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
26460b57cec5SDimitry Andric SDNode *ChainNode = ChainNodesMatched[i];
26470b57cec5SDimitry Andric // If ChainNode is null, it's because we replaced it on a previous
26480b57cec5SDimitry Andric // iteration and we cleared it out of the map. Just skip it.
26490b57cec5SDimitry Andric if (!ChainNode)
26500b57cec5SDimitry Andric continue;
26510b57cec5SDimitry Andric
26520b57cec5SDimitry Andric assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
26530b57cec5SDimitry Andric "Deleted node left in chain");
26540b57cec5SDimitry Andric
26550b57cec5SDimitry Andric // Don't replace the results of the root node if we're doing a
26560b57cec5SDimitry Andric // MorphNodeTo.
26570b57cec5SDimitry Andric if (ChainNode == NodeToMatch && isMorphNodeTo)
26580b57cec5SDimitry Andric continue;
26590b57cec5SDimitry Andric
26600b57cec5SDimitry Andric SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
26610b57cec5SDimitry Andric if (ChainVal.getValueType() == MVT::Glue)
26620b57cec5SDimitry Andric ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
26630b57cec5SDimitry Andric assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
26640b57cec5SDimitry Andric SelectionDAG::DAGNodeDeletedListener NDL(
26650b57cec5SDimitry Andric *CurDAG, [&](SDNode *N, SDNode *E) {
26660b57cec5SDimitry Andric std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
26670b57cec5SDimitry Andric static_cast<SDNode *>(nullptr));
26680b57cec5SDimitry Andric });
26690b57cec5SDimitry Andric if (ChainNode->getOpcode() != ISD::TokenFactor)
26700b57cec5SDimitry Andric ReplaceUses(ChainVal, InputChain);
26710b57cec5SDimitry Andric
26720b57cec5SDimitry Andric // If the node became dead and we haven't already seen it, delete it.
26730b57cec5SDimitry Andric if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2674e8d8bef9SDimitry Andric !llvm::is_contained(NowDeadNodes, ChainNode))
26750b57cec5SDimitry Andric NowDeadNodes.push_back(ChainNode);
26760b57cec5SDimitry Andric }
26770b57cec5SDimitry Andric }
26780b57cec5SDimitry Andric
26790b57cec5SDimitry Andric if (!NowDeadNodes.empty())
26800b57cec5SDimitry Andric CurDAG->RemoveDeadNodes(NowDeadNodes);
26810b57cec5SDimitry Andric
26820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
26830b57cec5SDimitry Andric }
26840b57cec5SDimitry Andric
26850b57cec5SDimitry Andric /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
26860b57cec5SDimitry Andric /// operation for when the pattern matched at least one node with a chains. The
26870b57cec5SDimitry Andric /// input vector contains a list of all of the chained nodes that we match. We
26880b57cec5SDimitry Andric /// must determine if this is a valid thing to cover (i.e. matching it won't
26890b57cec5SDimitry Andric /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
26900b57cec5SDimitry Andric /// be used as the input node chain for the generated nodes.
26910b57cec5SDimitry Andric static SDValue
HandleMergeInputChains(SmallVectorImpl<SDNode * > & ChainNodesMatched,SelectionDAG * CurDAG)26920b57cec5SDimitry Andric HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
26930b57cec5SDimitry Andric SelectionDAG *CurDAG) {
26940b57cec5SDimitry Andric
26950b57cec5SDimitry Andric SmallPtrSet<const SDNode *, 16> Visited;
26960b57cec5SDimitry Andric SmallVector<const SDNode *, 8> Worklist;
26970b57cec5SDimitry Andric SmallVector<SDValue, 3> InputChains;
26980b57cec5SDimitry Andric unsigned int Max = 8192;
26990b57cec5SDimitry Andric
27000b57cec5SDimitry Andric // Quick exit on trivial merge.
27010b57cec5SDimitry Andric if (ChainNodesMatched.size() == 1)
27020b57cec5SDimitry Andric return ChainNodesMatched[0]->getOperand(0);
27030b57cec5SDimitry Andric
27040b57cec5SDimitry Andric // Add chains that aren't already added (internal). Peek through
27050b57cec5SDimitry Andric // token factors.
27060b57cec5SDimitry Andric std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
27070b57cec5SDimitry Andric if (V.getValueType() != MVT::Other)
27080b57cec5SDimitry Andric return;
27090b57cec5SDimitry Andric if (V->getOpcode() == ISD::EntryToken)
27100b57cec5SDimitry Andric return;
27110b57cec5SDimitry Andric if (!Visited.insert(V.getNode()).second)
27120b57cec5SDimitry Andric return;
27130b57cec5SDimitry Andric if (V->getOpcode() == ISD::TokenFactor) {
27140b57cec5SDimitry Andric for (const SDValue &Op : V->op_values())
27150b57cec5SDimitry Andric AddChains(Op);
27160b57cec5SDimitry Andric } else
27170b57cec5SDimitry Andric InputChains.push_back(V);
27180b57cec5SDimitry Andric };
27190b57cec5SDimitry Andric
27200b57cec5SDimitry Andric for (auto *N : ChainNodesMatched) {
27210b57cec5SDimitry Andric Worklist.push_back(N);
27220b57cec5SDimitry Andric Visited.insert(N);
27230b57cec5SDimitry Andric }
27240b57cec5SDimitry Andric
27250b57cec5SDimitry Andric while (!Worklist.empty())
27260b57cec5SDimitry Andric AddChains(Worklist.pop_back_val()->getOperand(0));
27270b57cec5SDimitry Andric
27280b57cec5SDimitry Andric // Skip the search if there are no chain dependencies.
27290b57cec5SDimitry Andric if (InputChains.size() == 0)
27300b57cec5SDimitry Andric return CurDAG->getEntryNode();
27310b57cec5SDimitry Andric
27320b57cec5SDimitry Andric // If one of these chains is a successor of input, we must have a
27330b57cec5SDimitry Andric // node that is both the predecessor and successor of the
27340b57cec5SDimitry Andric // to-be-merged nodes. Fail.
27350b57cec5SDimitry Andric Visited.clear();
27360b57cec5SDimitry Andric for (SDValue V : InputChains)
27370b57cec5SDimitry Andric Worklist.push_back(V.getNode());
27380b57cec5SDimitry Andric
27390b57cec5SDimitry Andric for (auto *N : ChainNodesMatched)
27400b57cec5SDimitry Andric if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
27410b57cec5SDimitry Andric return SDValue();
27420b57cec5SDimitry Andric
27430b57cec5SDimitry Andric // Return merged chain.
27440b57cec5SDimitry Andric if (InputChains.size() == 1)
27450b57cec5SDimitry Andric return InputChains[0];
27460b57cec5SDimitry Andric return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
27470b57cec5SDimitry Andric MVT::Other, InputChains);
27480b57cec5SDimitry Andric }
27490b57cec5SDimitry Andric
27500b57cec5SDimitry Andric /// MorphNode - Handle morphing a node in place for the selector.
27510b57cec5SDimitry Andric SDNode *SelectionDAGISel::
MorphNode(SDNode * Node,unsigned TargetOpc,SDVTList VTList,ArrayRef<SDValue> Ops,unsigned EmitNodeInfo)27520b57cec5SDimitry Andric MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
27530b57cec5SDimitry Andric ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
27540b57cec5SDimitry Andric // It is possible we're using MorphNodeTo to replace a node with no
27550b57cec5SDimitry Andric // normal results with one that has a normal result (or we could be
27560b57cec5SDimitry Andric // adding a chain) and the input could have glue and chains as well.
27570b57cec5SDimitry Andric // In this case we need to shift the operands down.
27580b57cec5SDimitry Andric // FIXME: This is a horrible hack and broken in obscure cases, no worse
27590b57cec5SDimitry Andric // than the old isel though.
27600b57cec5SDimitry Andric int OldGlueResultNo = -1, OldChainResultNo = -1;
27610b57cec5SDimitry Andric
27620b57cec5SDimitry Andric unsigned NTMNumResults = Node->getNumValues();
27630b57cec5SDimitry Andric if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
27640b57cec5SDimitry Andric OldGlueResultNo = NTMNumResults-1;
27650b57cec5SDimitry Andric if (NTMNumResults != 1 &&
27660b57cec5SDimitry Andric Node->getValueType(NTMNumResults-2) == MVT::Other)
27670b57cec5SDimitry Andric OldChainResultNo = NTMNumResults-2;
27680b57cec5SDimitry Andric } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
27690b57cec5SDimitry Andric OldChainResultNo = NTMNumResults-1;
27700b57cec5SDimitry Andric
27710b57cec5SDimitry Andric // Call the underlying SelectionDAG routine to do the transmogrification. Note
27720b57cec5SDimitry Andric // that this deletes operands of the old node that become dead.
27730b57cec5SDimitry Andric SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
27740b57cec5SDimitry Andric
27750b57cec5SDimitry Andric // MorphNodeTo can operate in two ways: if an existing node with the
27760b57cec5SDimitry Andric // specified operands exists, it can just return it. Otherwise, it
27770b57cec5SDimitry Andric // updates the node in place to have the requested operands.
27780b57cec5SDimitry Andric if (Res == Node) {
27790b57cec5SDimitry Andric // If we updated the node in place, reset the node ID. To the isel,
27800b57cec5SDimitry Andric // this should be just like a newly allocated machine node.
27810b57cec5SDimitry Andric Res->setNodeId(-1);
27820b57cec5SDimitry Andric }
27830b57cec5SDimitry Andric
27840b57cec5SDimitry Andric unsigned ResNumResults = Res->getNumValues();
27850b57cec5SDimitry Andric // Move the glue if needed.
27860b57cec5SDimitry Andric if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
27875f757f3fSDimitry Andric static_cast<unsigned>(OldGlueResultNo) != ResNumResults - 1)
27880b57cec5SDimitry Andric ReplaceUses(SDValue(Node, OldGlueResultNo),
27890b57cec5SDimitry Andric SDValue(Res, ResNumResults - 1));
27900b57cec5SDimitry Andric
27910b57cec5SDimitry Andric if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
27920b57cec5SDimitry Andric --ResNumResults;
27930b57cec5SDimitry Andric
27940b57cec5SDimitry Andric // Move the chain reference if needed.
27950b57cec5SDimitry Andric if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
27965f757f3fSDimitry Andric static_cast<unsigned>(OldChainResultNo) != ResNumResults - 1)
27970b57cec5SDimitry Andric ReplaceUses(SDValue(Node, OldChainResultNo),
27980b57cec5SDimitry Andric SDValue(Res, ResNumResults - 1));
27990b57cec5SDimitry Andric
28000b57cec5SDimitry Andric // Otherwise, no replacement happened because the node already exists. Replace
28010b57cec5SDimitry Andric // Uses of the old node with the new one.
28020b57cec5SDimitry Andric if (Res != Node) {
28030b57cec5SDimitry Andric ReplaceNode(Node, Res);
28040b57cec5SDimitry Andric } else {
28050b57cec5SDimitry Andric EnforceNodeIdInvariant(Res);
28060b57cec5SDimitry Andric }
28070b57cec5SDimitry Andric
28080b57cec5SDimitry Andric return Res;
28090b57cec5SDimitry Andric }
28100b57cec5SDimitry Andric
28110b57cec5SDimitry Andric /// CheckSame - Implements OP_CheckSame.
2812e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckSame(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N,const SmallVectorImpl<std::pair<SDValue,SDNode * >> & RecordedNodes)2813e8d8bef9SDimitry Andric CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
28140b57cec5SDimitry Andric const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
28150b57cec5SDimitry Andric // Accept if it is exactly the same as a previously recorded node.
28160b57cec5SDimitry Andric unsigned RecNo = MatcherTable[MatcherIndex++];
28170b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
28180b57cec5SDimitry Andric return N == RecordedNodes[RecNo].first;
28190b57cec5SDimitry Andric }
28200b57cec5SDimitry Andric
28210b57cec5SDimitry Andric /// CheckChildSame - Implements OP_CheckChildXSame.
CheckChildSame(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N,const SmallVectorImpl<std::pair<SDValue,SDNode * >> & RecordedNodes,unsigned ChildNo)2822e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool CheckChildSame(
2823e8d8bef9SDimitry Andric const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
28240b57cec5SDimitry Andric const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
28250b57cec5SDimitry Andric unsigned ChildNo) {
28260b57cec5SDimitry Andric if (ChildNo >= N.getNumOperands())
28270b57cec5SDimitry Andric return false; // Match fails if out of range child #.
28280b57cec5SDimitry Andric return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
28290b57cec5SDimitry Andric RecordedNodes);
28300b57cec5SDimitry Andric }
28310b57cec5SDimitry Andric
28320b57cec5SDimitry Andric /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2833e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckPatternPredicate(unsigned Opcode,const unsigned char * MatcherTable,unsigned & MatcherIndex,const SelectionDAGISel & SDISel)2834297eecfbSDimitry Andric CheckPatternPredicate(unsigned Opcode, const unsigned char *MatcherTable,
2835297eecfbSDimitry Andric unsigned &MatcherIndex, const SelectionDAGISel &SDISel) {
2836297eecfbSDimitry Andric bool TwoBytePredNo =
2837297eecfbSDimitry Andric Opcode == SelectionDAGISel::OPC_CheckPatternPredicateTwoByte;
2838297eecfbSDimitry Andric unsigned PredNo =
2839297eecfbSDimitry Andric TwoBytePredNo || Opcode == SelectionDAGISel::OPC_CheckPatternPredicate
2840297eecfbSDimitry Andric ? MatcherTable[MatcherIndex++]
2841297eecfbSDimitry Andric : Opcode - SelectionDAGISel::OPC_CheckPatternPredicate0;
28425f757f3fSDimitry Andric if (TwoBytePredNo)
28435f757f3fSDimitry Andric PredNo |= MatcherTable[MatcherIndex++] << 8;
28445f757f3fSDimitry Andric return SDISel.CheckPatternPredicate(PredNo);
28450b57cec5SDimitry Andric }
28460b57cec5SDimitry Andric
28470b57cec5SDimitry Andric /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2848e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckNodePredicate(unsigned Opcode,const unsigned char * MatcherTable,unsigned & MatcherIndex,const SelectionDAGISel & SDISel,SDNode * N)28497a6dacacSDimitry Andric CheckNodePredicate(unsigned Opcode, const unsigned char *MatcherTable,
28507a6dacacSDimitry Andric unsigned &MatcherIndex, const SelectionDAGISel &SDISel,
28517a6dacacSDimitry Andric SDNode *N) {
28527a6dacacSDimitry Andric unsigned PredNo = Opcode == SelectionDAGISel::OPC_CheckPredicate
28537a6dacacSDimitry Andric ? MatcherTable[MatcherIndex++]
28547a6dacacSDimitry Andric : Opcode - SelectionDAGISel::OPC_CheckPredicate0;
28557a6dacacSDimitry Andric return SDISel.CheckNodePredicate(N, PredNo);
28560b57cec5SDimitry Andric }
28570b57cec5SDimitry Andric
2858e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckOpcode(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDNode * N)28590b57cec5SDimitry Andric CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
28600b57cec5SDimitry Andric SDNode *N) {
28610b57cec5SDimitry Andric uint16_t Opc = MatcherTable[MatcherIndex++];
28625f757f3fSDimitry Andric Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
28630b57cec5SDimitry Andric return N->getOpcode() == Opc;
28640b57cec5SDimitry Andric }
28650b57cec5SDimitry Andric
CheckType(MVT::SimpleValueType VT,SDValue N,const TargetLowering * TLI,const DataLayout & DL)28665f757f3fSDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool CheckType(MVT::SimpleValueType VT,
28675f757f3fSDimitry Andric SDValue N,
28685f757f3fSDimitry Andric const TargetLowering *TLI,
28695f757f3fSDimitry Andric const DataLayout &DL) {
28705f757f3fSDimitry Andric if (N.getValueType() == VT)
28715f757f3fSDimitry Andric return true;
28720b57cec5SDimitry Andric
28730b57cec5SDimitry Andric // Handle the case when VT is iPTR.
28740b57cec5SDimitry Andric return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
28750b57cec5SDimitry Andric }
28760b57cec5SDimitry Andric
2877e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckChildType(MVT::SimpleValueType VT,SDValue N,const TargetLowering * TLI,const DataLayout & DL,unsigned ChildNo)28785f757f3fSDimitry Andric CheckChildType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI,
28795f757f3fSDimitry Andric const DataLayout &DL, unsigned ChildNo) {
28800b57cec5SDimitry Andric if (ChildNo >= N.getNumOperands())
28810b57cec5SDimitry Andric return false; // Match fails if out of range child #.
28825f757f3fSDimitry Andric return ::CheckType(VT, N.getOperand(ChildNo), TLI, DL);
28830b57cec5SDimitry Andric }
28840b57cec5SDimitry Andric
2885e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckCondCode(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N)28860b57cec5SDimitry Andric CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
28870b57cec5SDimitry Andric SDValue N) {
28880b57cec5SDimitry Andric return cast<CondCodeSDNode>(N)->get() ==
28895f757f3fSDimitry Andric static_cast<ISD::CondCode>(MatcherTable[MatcherIndex++]);
28900b57cec5SDimitry Andric }
28910b57cec5SDimitry Andric
2892e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckChild2CondCode(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N)28930b57cec5SDimitry Andric CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
28940b57cec5SDimitry Andric SDValue N) {
28950b57cec5SDimitry Andric if (2 >= N.getNumOperands())
28960b57cec5SDimitry Andric return false;
28970b57cec5SDimitry Andric return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
28980b57cec5SDimitry Andric }
28990b57cec5SDimitry Andric
2900e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckValueType(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N,const TargetLowering * TLI,const DataLayout & DL)29010b57cec5SDimitry Andric CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
29020b57cec5SDimitry Andric SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
29035f757f3fSDimitry Andric MVT::SimpleValueType VT =
29045f757f3fSDimitry Andric static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
29050b57cec5SDimitry Andric if (cast<VTSDNode>(N)->getVT() == VT)
29060b57cec5SDimitry Andric return true;
29070b57cec5SDimitry Andric
29080b57cec5SDimitry Andric // Handle the case when VT is iPTR.
29090b57cec5SDimitry Andric return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
29100b57cec5SDimitry Andric }
29110b57cec5SDimitry Andric
2912fe6060f1SDimitry Andric // Bit 0 stores the sign of the immediate. The upper bits contain the magnitude
2913fe6060f1SDimitry Andric // shifted left by 1.
decodeSignRotatedValue(uint64_t V)2914fe6060f1SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V) {
2915fe6060f1SDimitry Andric if ((V & 1) == 0)
2916fe6060f1SDimitry Andric return V >> 1;
2917fe6060f1SDimitry Andric if (V != 1)
2918fe6060f1SDimitry Andric return -(V >> 1);
2919fe6060f1SDimitry Andric // There is no such thing as -0 with integers. "-0" really means MININT.
2920fe6060f1SDimitry Andric return 1ULL << 63;
2921fe6060f1SDimitry Andric }
2922fe6060f1SDimitry Andric
2923e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckInteger(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N)29240b57cec5SDimitry Andric CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
29250b57cec5SDimitry Andric SDValue N) {
29260b57cec5SDimitry Andric int64_t Val = MatcherTable[MatcherIndex++];
29270b57cec5SDimitry Andric if (Val & 128)
29280b57cec5SDimitry Andric Val = GetVBR(Val, MatcherTable, MatcherIndex);
29290b57cec5SDimitry Andric
2930fe6060f1SDimitry Andric Val = decodeSignRotatedValue(Val);
2931fe6060f1SDimitry Andric
29320b57cec5SDimitry Andric ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2933cb14a3feSDimitry Andric return C && C->getAPIntValue().trySExtValue() == Val;
29340b57cec5SDimitry Andric }
29350b57cec5SDimitry Andric
2936e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckChildInteger(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N,unsigned ChildNo)29370b57cec5SDimitry Andric CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
29380b57cec5SDimitry Andric SDValue N, unsigned ChildNo) {
29390b57cec5SDimitry Andric if (ChildNo >= N.getNumOperands())
29400b57cec5SDimitry Andric return false; // Match fails if out of range child #.
29410b57cec5SDimitry Andric return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
29420b57cec5SDimitry Andric }
29430b57cec5SDimitry Andric
2944e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckAndImm(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N,const SelectionDAGISel & SDISel)29450b57cec5SDimitry Andric CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
29460b57cec5SDimitry Andric SDValue N, const SelectionDAGISel &SDISel) {
29470b57cec5SDimitry Andric int64_t Val = MatcherTable[MatcherIndex++];
29480b57cec5SDimitry Andric if (Val & 128)
29490b57cec5SDimitry Andric Val = GetVBR(Val, MatcherTable, MatcherIndex);
29500b57cec5SDimitry Andric
29510b57cec5SDimitry Andric if (N->getOpcode() != ISD::AND) return false;
29520b57cec5SDimitry Andric
29530b57cec5SDimitry Andric ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
29540b57cec5SDimitry Andric return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
29550b57cec5SDimitry Andric }
29560b57cec5SDimitry Andric
2957e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
CheckOrImm(const unsigned char * MatcherTable,unsigned & MatcherIndex,SDValue N,const SelectionDAGISel & SDISel)2958e8d8bef9SDimitry Andric CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2959e8d8bef9SDimitry Andric const SelectionDAGISel &SDISel) {
29600b57cec5SDimitry Andric int64_t Val = MatcherTable[MatcherIndex++];
29610b57cec5SDimitry Andric if (Val & 128)
29620b57cec5SDimitry Andric Val = GetVBR(Val, MatcherTable, MatcherIndex);
29630b57cec5SDimitry Andric
29640b57cec5SDimitry Andric if (N->getOpcode() != ISD::OR) return false;
29650b57cec5SDimitry Andric
29660b57cec5SDimitry Andric ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
29670b57cec5SDimitry Andric return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
29680b57cec5SDimitry Andric }
29690b57cec5SDimitry Andric
29700b57cec5SDimitry Andric /// IsPredicateKnownToFail - If we know how and can do so without pushing a
29710b57cec5SDimitry Andric /// scope, evaluate the current node. If the current predicate is known to
29720b57cec5SDimitry Andric /// fail, set Result=true and return anything. If the current predicate is
29730b57cec5SDimitry Andric /// known to pass, set Result=false and return the MatcherIndex to continue
29740b57cec5SDimitry Andric /// with. If the current predicate is unknown, set Result=false and return the
29750b57cec5SDimitry Andric /// MatcherIndex to continue with.
IsPredicateKnownToFail(const unsigned char * Table,unsigned Index,SDValue N,bool & Result,const SelectionDAGISel & SDISel,SmallVectorImpl<std::pair<SDValue,SDNode * >> & RecordedNodes)29760b57cec5SDimitry Andric static unsigned IsPredicateKnownToFail(const unsigned char *Table,
29770b57cec5SDimitry Andric unsigned Index, SDValue N,
29780b57cec5SDimitry Andric bool &Result,
29790b57cec5SDimitry Andric const SelectionDAGISel &SDISel,
29800b57cec5SDimitry Andric SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
29815f757f3fSDimitry Andric unsigned Opcode = Table[Index++];
29825f757f3fSDimitry Andric switch (Opcode) {
29830b57cec5SDimitry Andric default:
29840b57cec5SDimitry Andric Result = false;
29850b57cec5SDimitry Andric return Index-1; // Could not evaluate this predicate.
29860b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckSame:
29870b57cec5SDimitry Andric Result = !::CheckSame(Table, Index, N, RecordedNodes);
29880b57cec5SDimitry Andric return Index;
29890b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild0Same:
29900b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild1Same:
29910b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild2Same:
29920b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild3Same:
29930b57cec5SDimitry Andric Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
29940b57cec5SDimitry Andric Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
29950b57cec5SDimitry Andric return Index;
29960b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate:
2997297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate0:
2998297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate1:
29995f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate2:
3000297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate3:
3001297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate4:
3002297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate5:
3003297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate6:
3004297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicate7:
3005297eecfbSDimitry Andric case SelectionDAGISel::OPC_CheckPatternPredicateTwoByte:
3006297eecfbSDimitry Andric Result = !::CheckPatternPredicate(Opcode, Table, Index, SDISel);
30070b57cec5SDimitry Andric return Index;
30080b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckPredicate:
30097a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate0:
30107a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate1:
30117a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate2:
30127a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate3:
30137a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate4:
30147a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate5:
30157a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate6:
30167a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate7:
30177a6dacacSDimitry Andric Result = !::CheckNodePredicate(Opcode, Table, Index, SDISel, N.getNode());
30180b57cec5SDimitry Andric return Index;
30190b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckOpcode:
30200b57cec5SDimitry Andric Result = !::CheckOpcode(Table, Index, N.getNode());
30210b57cec5SDimitry Andric return Index;
30220b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckType:
30235f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckTypeI32:
30245f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckTypeI64: {
30255f757f3fSDimitry Andric MVT::SimpleValueType VT;
30265f757f3fSDimitry Andric switch (Opcode) {
30275f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckTypeI32:
30285f757f3fSDimitry Andric VT = MVT::i32;
30295f757f3fSDimitry Andric break;
30305f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckTypeI64:
30315f757f3fSDimitry Andric VT = MVT::i64;
30325f757f3fSDimitry Andric break;
30335f757f3fSDimitry Andric default:
30345f757f3fSDimitry Andric VT = static_cast<MVT::SimpleValueType>(Table[Index++]);
30355f757f3fSDimitry Andric break;
30365f757f3fSDimitry Andric }
30375f757f3fSDimitry Andric Result = !::CheckType(VT, N, SDISel.TLI, SDISel.CurDAG->getDataLayout());
30380b57cec5SDimitry Andric return Index;
30395f757f3fSDimitry Andric }
30400b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckTypeRes: {
30410b57cec5SDimitry Andric unsigned Res = Table[Index++];
30425f757f3fSDimitry Andric Result = !::CheckType(static_cast<MVT::SimpleValueType>(Table[Index++]),
30435f757f3fSDimitry Andric N.getValue(Res), SDISel.TLI,
30440b57cec5SDimitry Andric SDISel.CurDAG->getDataLayout());
30450b57cec5SDimitry Andric return Index;
30460b57cec5SDimitry Andric }
30470b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild0Type:
30480b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild1Type:
30490b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild2Type:
30500b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild3Type:
30510b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild4Type:
30520b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild5Type:
30530b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild6Type:
30540b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild7Type:
30555f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild0TypeI32:
30565f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild1TypeI32:
30575f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild2TypeI32:
30585f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild3TypeI32:
30595f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild4TypeI32:
30605f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild5TypeI32:
30615f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild6TypeI32:
30625f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild7TypeI32:
30635f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild0TypeI64:
30645f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild1TypeI64:
30655f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild2TypeI64:
30665f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild3TypeI64:
30675f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild4TypeI64:
30685f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild5TypeI64:
30695f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild6TypeI64:
30705f757f3fSDimitry Andric case SelectionDAGISel::OPC_CheckChild7TypeI64: {
30715f757f3fSDimitry Andric MVT::SimpleValueType VT;
30725f757f3fSDimitry Andric unsigned ChildNo;
30735f757f3fSDimitry Andric if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI32 &&
30745f757f3fSDimitry Andric Opcode <= SelectionDAGISel::OPC_CheckChild7TypeI32) {
30755f757f3fSDimitry Andric VT = MVT::i32;
30765f757f3fSDimitry Andric ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0TypeI32;
30775f757f3fSDimitry Andric } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
30785f757f3fSDimitry Andric Opcode <= SelectionDAGISel::OPC_CheckChild7TypeI64) {
30795f757f3fSDimitry Andric VT = MVT::i64;
30805f757f3fSDimitry Andric ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0TypeI64;
30815f757f3fSDimitry Andric } else {
30825f757f3fSDimitry Andric VT = static_cast<MVT::SimpleValueType>(Table[Index++]);
30835f757f3fSDimitry Andric ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
30845f757f3fSDimitry Andric }
30855f757f3fSDimitry Andric Result = !::CheckChildType(VT, N, SDISel.TLI,
30865f757f3fSDimitry Andric SDISel.CurDAG->getDataLayout(), ChildNo);
30870b57cec5SDimitry Andric return Index;
30885f757f3fSDimitry Andric }
30890b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckCondCode:
30900b57cec5SDimitry Andric Result = !::CheckCondCode(Table, Index, N);
30910b57cec5SDimitry Andric return Index;
30920b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild2CondCode:
30930b57cec5SDimitry Andric Result = !::CheckChild2CondCode(Table, Index, N);
30940b57cec5SDimitry Andric return Index;
30950b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckValueType:
30960b57cec5SDimitry Andric Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
30970b57cec5SDimitry Andric SDISel.CurDAG->getDataLayout());
30980b57cec5SDimitry Andric return Index;
30990b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckInteger:
31000b57cec5SDimitry Andric Result = !::CheckInteger(Table, Index, N);
31010b57cec5SDimitry Andric return Index;
31020b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild0Integer:
31030b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild1Integer:
31040b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild2Integer:
31050b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild3Integer:
31060b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckChild4Integer:
31070b57cec5SDimitry Andric Result = !::CheckChildInteger(Table, Index, N,
31080b57cec5SDimitry Andric Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
31090b57cec5SDimitry Andric return Index;
31100b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckAndImm:
31110b57cec5SDimitry Andric Result = !::CheckAndImm(Table, Index, N, SDISel);
31120b57cec5SDimitry Andric return Index;
31130b57cec5SDimitry Andric case SelectionDAGISel::OPC_CheckOrImm:
31140b57cec5SDimitry Andric Result = !::CheckOrImm(Table, Index, N, SDISel);
31150b57cec5SDimitry Andric return Index;
31160b57cec5SDimitry Andric }
31170b57cec5SDimitry Andric }
31180b57cec5SDimitry Andric
31190b57cec5SDimitry Andric namespace {
31200b57cec5SDimitry Andric
31210b57cec5SDimitry Andric struct MatchScope {
31220b57cec5SDimitry Andric /// FailIndex - If this match fails, this is the index to continue with.
31230b57cec5SDimitry Andric unsigned FailIndex;
31240b57cec5SDimitry Andric
31250b57cec5SDimitry Andric /// NodeStack - The node stack when the scope was formed.
31260b57cec5SDimitry Andric SmallVector<SDValue, 4> NodeStack;
31270b57cec5SDimitry Andric
31280b57cec5SDimitry Andric /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
31290b57cec5SDimitry Andric unsigned NumRecordedNodes;
31300b57cec5SDimitry Andric
31310b57cec5SDimitry Andric /// NumMatchedMemRefs - The number of matched memref entries.
31320b57cec5SDimitry Andric unsigned NumMatchedMemRefs;
31330b57cec5SDimitry Andric
31340b57cec5SDimitry Andric /// InputChain/InputGlue - The current chain/glue
31350b57cec5SDimitry Andric SDValue InputChain, InputGlue;
31360b57cec5SDimitry Andric
31370b57cec5SDimitry Andric /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
31380b57cec5SDimitry Andric bool HasChainNodesMatched;
31390b57cec5SDimitry Andric };
31400b57cec5SDimitry Andric
31410b57cec5SDimitry Andric /// \A DAG update listener to keep the matching state
31420b57cec5SDimitry Andric /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
31430b57cec5SDimitry Andric /// change the DAG while matching. X86 addressing mode matcher is an example
31440b57cec5SDimitry Andric /// for this.
31450b57cec5SDimitry Andric class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
31460b57cec5SDimitry Andric {
31470b57cec5SDimitry Andric SDNode **NodeToMatch;
31480b57cec5SDimitry Andric SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
31490b57cec5SDimitry Andric SmallVectorImpl<MatchScope> &MatchScopes;
31500b57cec5SDimitry Andric
31510b57cec5SDimitry Andric public:
MatchStateUpdater(SelectionDAG & DAG,SDNode ** NodeToMatch,SmallVectorImpl<std::pair<SDValue,SDNode * >> & RN,SmallVectorImpl<MatchScope> & MS)31520b57cec5SDimitry Andric MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
31530b57cec5SDimitry Andric SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
31540b57cec5SDimitry Andric SmallVectorImpl<MatchScope> &MS)
31550b57cec5SDimitry Andric : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
31560b57cec5SDimitry Andric RecordedNodes(RN), MatchScopes(MS) {}
31570b57cec5SDimitry Andric
NodeDeleted(SDNode * N,SDNode * E)31580b57cec5SDimitry Andric void NodeDeleted(SDNode *N, SDNode *E) override {
31590b57cec5SDimitry Andric // Some early-returns here to avoid the search if we deleted the node or
31600b57cec5SDimitry Andric // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
31610b57cec5SDimitry Andric // do, so it's unnecessary to update matching state at that point).
31620b57cec5SDimitry Andric // Neither of these can occur currently because we only install this
31630b57cec5SDimitry Andric // update listener during matching a complex patterns.
31640b57cec5SDimitry Andric if (!E || E->isMachineOpcode())
31650b57cec5SDimitry Andric return;
31660b57cec5SDimitry Andric // Check if NodeToMatch was updated.
31670b57cec5SDimitry Andric if (N == *NodeToMatch)
31680b57cec5SDimitry Andric *NodeToMatch = E;
31690b57cec5SDimitry Andric // Performing linear search here does not matter because we almost never
31700b57cec5SDimitry Andric // run this code. You'd have to have a CSE during complex pattern
31710b57cec5SDimitry Andric // matching.
31720b57cec5SDimitry Andric for (auto &I : RecordedNodes)
31730b57cec5SDimitry Andric if (I.first.getNode() == N)
31740b57cec5SDimitry Andric I.first.setNode(E);
31750b57cec5SDimitry Andric
31760b57cec5SDimitry Andric for (auto &I : MatchScopes)
31770b57cec5SDimitry Andric for (auto &J : I.NodeStack)
31780b57cec5SDimitry Andric if (J.getNode() == N)
31790b57cec5SDimitry Andric J.setNode(E);
31800b57cec5SDimitry Andric }
31810b57cec5SDimitry Andric };
31820b57cec5SDimitry Andric
31830b57cec5SDimitry Andric } // end anonymous namespace
31840b57cec5SDimitry Andric
SelectCodeCommon(SDNode * NodeToMatch,const unsigned char * MatcherTable,unsigned TableSize)31850b57cec5SDimitry Andric void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
31860b57cec5SDimitry Andric const unsigned char *MatcherTable,
31870b57cec5SDimitry Andric unsigned TableSize) {
31880b57cec5SDimitry Andric // FIXME: Should these even be selected? Handle these cases in the caller?
31890b57cec5SDimitry Andric switch (NodeToMatch->getOpcode()) {
31900b57cec5SDimitry Andric default:
31910b57cec5SDimitry Andric break;
31920b57cec5SDimitry Andric case ISD::EntryToken: // These nodes remain the same.
31930b57cec5SDimitry Andric case ISD::BasicBlock:
31940b57cec5SDimitry Andric case ISD::Register:
31950b57cec5SDimitry Andric case ISD::RegisterMask:
31960b57cec5SDimitry Andric case ISD::HANDLENODE:
31970b57cec5SDimitry Andric case ISD::MDNODE_SDNODE:
31980b57cec5SDimitry Andric case ISD::TargetConstant:
31990b57cec5SDimitry Andric case ISD::TargetConstantFP:
32000b57cec5SDimitry Andric case ISD::TargetConstantPool:
32010b57cec5SDimitry Andric case ISD::TargetFrameIndex:
32020b57cec5SDimitry Andric case ISD::TargetExternalSymbol:
32030b57cec5SDimitry Andric case ISD::MCSymbol:
32040b57cec5SDimitry Andric case ISD::TargetBlockAddress:
32050b57cec5SDimitry Andric case ISD::TargetJumpTable:
32060b57cec5SDimitry Andric case ISD::TargetGlobalTLSAddress:
32070b57cec5SDimitry Andric case ISD::TargetGlobalAddress:
32080b57cec5SDimitry Andric case ISD::TokenFactor:
32090b57cec5SDimitry Andric case ISD::CopyFromReg:
32100b57cec5SDimitry Andric case ISD::CopyToReg:
32110b57cec5SDimitry Andric case ISD::EH_LABEL:
32120b57cec5SDimitry Andric case ISD::ANNOTATION_LABEL:
32130b57cec5SDimitry Andric case ISD::LIFETIME_START:
32140b57cec5SDimitry Andric case ISD::LIFETIME_END:
3215e8d8bef9SDimitry Andric case ISD::PSEUDO_PROBE:
32160b57cec5SDimitry Andric NodeToMatch->setNodeId(-1); // Mark selected.
32170b57cec5SDimitry Andric return;
32180b57cec5SDimitry Andric case ISD::AssertSext:
32190b57cec5SDimitry Andric case ISD::AssertZext:
32205ffd83dbSDimitry Andric case ISD::AssertAlign:
32210b57cec5SDimitry Andric ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
32220b57cec5SDimitry Andric CurDAG->RemoveDeadNode(NodeToMatch);
32230b57cec5SDimitry Andric return;
32240b57cec5SDimitry Andric case ISD::INLINEASM:
32250b57cec5SDimitry Andric case ISD::INLINEASM_BR:
32265ffd83dbSDimitry Andric Select_INLINEASM(NodeToMatch);
32270b57cec5SDimitry Andric return;
32280b57cec5SDimitry Andric case ISD::READ_REGISTER:
32290b57cec5SDimitry Andric Select_READ_REGISTER(NodeToMatch);
32300b57cec5SDimitry Andric return;
32310b57cec5SDimitry Andric case ISD::WRITE_REGISTER:
32320b57cec5SDimitry Andric Select_WRITE_REGISTER(NodeToMatch);
32330b57cec5SDimitry Andric return;
32340b57cec5SDimitry Andric case ISD::UNDEF:
32350b57cec5SDimitry Andric Select_UNDEF(NodeToMatch);
32360b57cec5SDimitry Andric return;
32375ffd83dbSDimitry Andric case ISD::FREEZE:
32385ffd83dbSDimitry Andric Select_FREEZE(NodeToMatch);
32395ffd83dbSDimitry Andric return;
3240fe6060f1SDimitry Andric case ISD::ARITH_FENCE:
3241fe6060f1SDimitry Andric Select_ARITH_FENCE(NodeToMatch);
3242fe6060f1SDimitry Andric return;
3243bdd1243dSDimitry Andric case ISD::MEMBARRIER:
3244bdd1243dSDimitry Andric Select_MEMBARRIER(NodeToMatch);
3245bdd1243dSDimitry Andric return;
3246753f127fSDimitry Andric case ISD::STACKMAP:
3247753f127fSDimitry Andric Select_STACKMAP(NodeToMatch);
3248753f127fSDimitry Andric return;
3249fcaf7f86SDimitry Andric case ISD::PATCHPOINT:
3250fcaf7f86SDimitry Andric Select_PATCHPOINT(NodeToMatch);
3251fcaf7f86SDimitry Andric return;
32525f757f3fSDimitry Andric case ISD::JUMP_TABLE_DEBUG_INFO:
32535f757f3fSDimitry Andric Select_JUMP_TABLE_DEBUG_INFO(NodeToMatch);
32545f757f3fSDimitry Andric return;
32550fca6ea1SDimitry Andric case ISD::CONVERGENCECTRL_ANCHOR:
32560fca6ea1SDimitry Andric Select_CONVERGENCECTRL_ANCHOR(NodeToMatch);
32570fca6ea1SDimitry Andric return;
32580fca6ea1SDimitry Andric case ISD::CONVERGENCECTRL_ENTRY:
32590fca6ea1SDimitry Andric Select_CONVERGENCECTRL_ENTRY(NodeToMatch);
32600fca6ea1SDimitry Andric return;
32610fca6ea1SDimitry Andric case ISD::CONVERGENCECTRL_LOOP:
32620fca6ea1SDimitry Andric Select_CONVERGENCECTRL_LOOP(NodeToMatch);
32630fca6ea1SDimitry Andric return;
32640b57cec5SDimitry Andric }
32650b57cec5SDimitry Andric
32660b57cec5SDimitry Andric assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
32670b57cec5SDimitry Andric
32680b57cec5SDimitry Andric // Set up the node stack with NodeToMatch as the only node on the stack.
32690b57cec5SDimitry Andric SmallVector<SDValue, 8> NodeStack;
32700b57cec5SDimitry Andric SDValue N = SDValue(NodeToMatch, 0);
32710b57cec5SDimitry Andric NodeStack.push_back(N);
32720b57cec5SDimitry Andric
32730b57cec5SDimitry Andric // MatchScopes - Scopes used when matching, if a match failure happens, this
32740b57cec5SDimitry Andric // indicates where to continue checking.
32750b57cec5SDimitry Andric SmallVector<MatchScope, 8> MatchScopes;
32760b57cec5SDimitry Andric
32770b57cec5SDimitry Andric // RecordedNodes - This is the set of nodes that have been recorded by the
32780b57cec5SDimitry Andric // state machine. The second value is the parent of the node, or null if the
32790b57cec5SDimitry Andric // root is recorded.
32800b57cec5SDimitry Andric SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
32810b57cec5SDimitry Andric
32820b57cec5SDimitry Andric // MatchedMemRefs - This is the set of MemRef's we've seen in the input
32830b57cec5SDimitry Andric // pattern.
32840b57cec5SDimitry Andric SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
32850b57cec5SDimitry Andric
32860b57cec5SDimitry Andric // These are the current input chain and glue for use when generating nodes.
32870b57cec5SDimitry Andric // Various Emit operations change these. For example, emitting a copytoreg
32880b57cec5SDimitry Andric // uses and updates these.
32890b57cec5SDimitry Andric SDValue InputChain, InputGlue;
32900b57cec5SDimitry Andric
32910b57cec5SDimitry Andric // ChainNodesMatched - If a pattern matches nodes that have input/output
32920b57cec5SDimitry Andric // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
32930b57cec5SDimitry Andric // which ones they are. The result is captured into this list so that we can
32940b57cec5SDimitry Andric // update the chain results when the pattern is complete.
32950b57cec5SDimitry Andric SmallVector<SDNode*, 3> ChainNodesMatched;
32960b57cec5SDimitry Andric
32970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
32980b57cec5SDimitry Andric
32990b57cec5SDimitry Andric // Determine where to start the interpreter. Normally we start at opcode #0,
33000b57cec5SDimitry Andric // but if the state machine starts with an OPC_SwitchOpcode, then we
33010b57cec5SDimitry Andric // accelerate the first lookup (which is guaranteed to be hot) with the
33020b57cec5SDimitry Andric // OpcodeOffset table.
33030b57cec5SDimitry Andric unsigned MatcherIndex = 0;
33040b57cec5SDimitry Andric
33050b57cec5SDimitry Andric if (!OpcodeOffset.empty()) {
33060b57cec5SDimitry Andric // Already computed the OpcodeOffset table, just index into it.
33070b57cec5SDimitry Andric if (N.getOpcode() < OpcodeOffset.size())
33080b57cec5SDimitry Andric MatcherIndex = OpcodeOffset[N.getOpcode()];
33090b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
33100b57cec5SDimitry Andric
33110b57cec5SDimitry Andric } else if (MatcherTable[0] == OPC_SwitchOpcode) {
33120b57cec5SDimitry Andric // Otherwise, the table isn't computed, but the state machine does start
33130b57cec5SDimitry Andric // with an OPC_SwitchOpcode instruction. Populate the table now, since this
33140b57cec5SDimitry Andric // is the first time we're selecting an instruction.
33150b57cec5SDimitry Andric unsigned Idx = 1;
33160b57cec5SDimitry Andric while (true) {
33170b57cec5SDimitry Andric // Get the size of this case.
33180b57cec5SDimitry Andric unsigned CaseSize = MatcherTable[Idx++];
33190b57cec5SDimitry Andric if (CaseSize & 128)
33200b57cec5SDimitry Andric CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
33210b57cec5SDimitry Andric if (CaseSize == 0) break;
33220b57cec5SDimitry Andric
33230b57cec5SDimitry Andric // Get the opcode, add the index to the table.
33240b57cec5SDimitry Andric uint16_t Opc = MatcherTable[Idx++];
33255f757f3fSDimitry Andric Opc |= static_cast<uint16_t>(MatcherTable[Idx++]) << 8;
33260b57cec5SDimitry Andric if (Opc >= OpcodeOffset.size())
33270b57cec5SDimitry Andric OpcodeOffset.resize((Opc+1)*2);
33280b57cec5SDimitry Andric OpcodeOffset[Opc] = Idx;
33290b57cec5SDimitry Andric Idx += CaseSize;
33300b57cec5SDimitry Andric }
33310b57cec5SDimitry Andric
33320b57cec5SDimitry Andric // Okay, do the lookup for the first opcode.
33330b57cec5SDimitry Andric if (N.getOpcode() < OpcodeOffset.size())
33340b57cec5SDimitry Andric MatcherIndex = OpcodeOffset[N.getOpcode()];
33350b57cec5SDimitry Andric }
33360b57cec5SDimitry Andric
33370b57cec5SDimitry Andric while (true) {
33380b57cec5SDimitry Andric assert(MatcherIndex < TableSize && "Invalid index");
33390b57cec5SDimitry Andric #ifndef NDEBUG
33400b57cec5SDimitry Andric unsigned CurrentOpcodeIndex = MatcherIndex;
33410b57cec5SDimitry Andric #endif
33425f757f3fSDimitry Andric BuiltinOpcodes Opcode =
33435f757f3fSDimitry Andric static_cast<BuiltinOpcodes>(MatcherTable[MatcherIndex++]);
33440b57cec5SDimitry Andric switch (Opcode) {
33450b57cec5SDimitry Andric case OPC_Scope: {
33460b57cec5SDimitry Andric // Okay, the semantics of this operation are that we should push a scope
33470b57cec5SDimitry Andric // then evaluate the first child. However, pushing a scope only to have
33480b57cec5SDimitry Andric // the first check fail (which then pops it) is inefficient. If we can
33490b57cec5SDimitry Andric // determine immediately that the first check (or first several) will
33500b57cec5SDimitry Andric // immediately fail, don't even bother pushing a scope for them.
33510b57cec5SDimitry Andric unsigned FailIndex;
33520b57cec5SDimitry Andric
33530b57cec5SDimitry Andric while (true) {
33540b57cec5SDimitry Andric unsigned NumToSkip = MatcherTable[MatcherIndex++];
33550b57cec5SDimitry Andric if (NumToSkip & 128)
33560b57cec5SDimitry Andric NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
33570b57cec5SDimitry Andric // Found the end of the scope with no match.
33580b57cec5SDimitry Andric if (NumToSkip == 0) {
33590b57cec5SDimitry Andric FailIndex = 0;
33600b57cec5SDimitry Andric break;
33610b57cec5SDimitry Andric }
33620b57cec5SDimitry Andric
33630b57cec5SDimitry Andric FailIndex = MatcherIndex+NumToSkip;
33640b57cec5SDimitry Andric
33650b57cec5SDimitry Andric unsigned MatcherIndexOfPredicate = MatcherIndex;
33660b57cec5SDimitry Andric (void)MatcherIndexOfPredicate; // silence warning.
33670b57cec5SDimitry Andric
33680b57cec5SDimitry Andric // If we can't evaluate this predicate without pushing a scope (e.g. if
33690b57cec5SDimitry Andric // it is a 'MoveParent') or if the predicate succeeds on this node, we
33700b57cec5SDimitry Andric // push the scope and evaluate the full predicate chain.
33710b57cec5SDimitry Andric bool Result;
33720b57cec5SDimitry Andric MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
33730b57cec5SDimitry Andric Result, *this, RecordedNodes);
33740b57cec5SDimitry Andric if (!Result)
33750b57cec5SDimitry Andric break;
33760b57cec5SDimitry Andric
33770b57cec5SDimitry Andric LLVM_DEBUG(
33780b57cec5SDimitry Andric dbgs() << " Skipped scope entry (due to false predicate) at "
33790b57cec5SDimitry Andric << "index " << MatcherIndexOfPredicate << ", continuing at "
33800b57cec5SDimitry Andric << FailIndex << "\n");
33810b57cec5SDimitry Andric ++NumDAGIselRetries;
33820b57cec5SDimitry Andric
33830b57cec5SDimitry Andric // Otherwise, we know that this case of the Scope is guaranteed to fail,
33840b57cec5SDimitry Andric // move to the next case.
33850b57cec5SDimitry Andric MatcherIndex = FailIndex;
33860b57cec5SDimitry Andric }
33870b57cec5SDimitry Andric
33880b57cec5SDimitry Andric // If the whole scope failed to match, bail.
33890b57cec5SDimitry Andric if (FailIndex == 0) break;
33900b57cec5SDimitry Andric
33910b57cec5SDimitry Andric // Push a MatchScope which indicates where to go if the first child fails
33920b57cec5SDimitry Andric // to match.
33930b57cec5SDimitry Andric MatchScope NewEntry;
33940b57cec5SDimitry Andric NewEntry.FailIndex = FailIndex;
33950b57cec5SDimitry Andric NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
33960b57cec5SDimitry Andric NewEntry.NumRecordedNodes = RecordedNodes.size();
33970b57cec5SDimitry Andric NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
33980b57cec5SDimitry Andric NewEntry.InputChain = InputChain;
33990b57cec5SDimitry Andric NewEntry.InputGlue = InputGlue;
34000b57cec5SDimitry Andric NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
34010b57cec5SDimitry Andric MatchScopes.push_back(NewEntry);
34020b57cec5SDimitry Andric continue;
34030b57cec5SDimitry Andric }
34040b57cec5SDimitry Andric case OPC_RecordNode: {
34050b57cec5SDimitry Andric // Remember this node, it may end up being an operand in the pattern.
34060b57cec5SDimitry Andric SDNode *Parent = nullptr;
34070b57cec5SDimitry Andric if (NodeStack.size() > 1)
34080b57cec5SDimitry Andric Parent = NodeStack[NodeStack.size()-2].getNode();
34090b57cec5SDimitry Andric RecordedNodes.push_back(std::make_pair(N, Parent));
34100b57cec5SDimitry Andric continue;
34110b57cec5SDimitry Andric }
34120b57cec5SDimitry Andric
34130b57cec5SDimitry Andric case OPC_RecordChild0: case OPC_RecordChild1:
34140b57cec5SDimitry Andric case OPC_RecordChild2: case OPC_RecordChild3:
34150b57cec5SDimitry Andric case OPC_RecordChild4: case OPC_RecordChild5:
34160b57cec5SDimitry Andric case OPC_RecordChild6: case OPC_RecordChild7: {
34170b57cec5SDimitry Andric unsigned ChildNo = Opcode-OPC_RecordChild0;
34180b57cec5SDimitry Andric if (ChildNo >= N.getNumOperands())
34190b57cec5SDimitry Andric break; // Match fails if out of range child #.
34200b57cec5SDimitry Andric
34210b57cec5SDimitry Andric RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
34220b57cec5SDimitry Andric N.getNode()));
34230b57cec5SDimitry Andric continue;
34240b57cec5SDimitry Andric }
34250b57cec5SDimitry Andric case OPC_RecordMemRef:
34260b57cec5SDimitry Andric if (auto *MN = dyn_cast<MemSDNode>(N))
34270b57cec5SDimitry Andric MatchedMemRefs.push_back(MN->getMemOperand());
34280b57cec5SDimitry Andric else {
34290b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
34300b57cec5SDimitry Andric dbgs() << '\n');
34310b57cec5SDimitry Andric }
34320b57cec5SDimitry Andric
34330b57cec5SDimitry Andric continue;
34340b57cec5SDimitry Andric
34350b57cec5SDimitry Andric case OPC_CaptureGlueInput:
34360b57cec5SDimitry Andric // If the current node has an input glue, capture it in InputGlue.
34370b57cec5SDimitry Andric if (N->getNumOperands() != 0 &&
34380b57cec5SDimitry Andric N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
34390b57cec5SDimitry Andric InputGlue = N->getOperand(N->getNumOperands()-1);
34400b57cec5SDimitry Andric continue;
34410b57cec5SDimitry Andric
34420b57cec5SDimitry Andric case OPC_MoveChild: {
34430b57cec5SDimitry Andric unsigned ChildNo = MatcherTable[MatcherIndex++];
34440b57cec5SDimitry Andric if (ChildNo >= N.getNumOperands())
34450b57cec5SDimitry Andric break; // Match fails if out of range child #.
34460b57cec5SDimitry Andric N = N.getOperand(ChildNo);
34470b57cec5SDimitry Andric NodeStack.push_back(N);
34480b57cec5SDimitry Andric continue;
34490b57cec5SDimitry Andric }
34500b57cec5SDimitry Andric
34510b57cec5SDimitry Andric case OPC_MoveChild0: case OPC_MoveChild1:
34520b57cec5SDimitry Andric case OPC_MoveChild2: case OPC_MoveChild3:
34530b57cec5SDimitry Andric case OPC_MoveChild4: case OPC_MoveChild5:
34540b57cec5SDimitry Andric case OPC_MoveChild6: case OPC_MoveChild7: {
34550b57cec5SDimitry Andric unsigned ChildNo = Opcode-OPC_MoveChild0;
34560b57cec5SDimitry Andric if (ChildNo >= N.getNumOperands())
34570b57cec5SDimitry Andric break; // Match fails if out of range child #.
34580b57cec5SDimitry Andric N = N.getOperand(ChildNo);
34590b57cec5SDimitry Andric NodeStack.push_back(N);
34600b57cec5SDimitry Andric continue;
34610b57cec5SDimitry Andric }
34620b57cec5SDimitry Andric
34635f757f3fSDimitry Andric case OPC_MoveSibling:
34645f757f3fSDimitry Andric case OPC_MoveSibling0:
34655f757f3fSDimitry Andric case OPC_MoveSibling1:
34665f757f3fSDimitry Andric case OPC_MoveSibling2:
34675f757f3fSDimitry Andric case OPC_MoveSibling3:
34685f757f3fSDimitry Andric case OPC_MoveSibling4:
34695f757f3fSDimitry Andric case OPC_MoveSibling5:
34705f757f3fSDimitry Andric case OPC_MoveSibling6:
34715f757f3fSDimitry Andric case OPC_MoveSibling7: {
34725f757f3fSDimitry Andric // Pop the current node off the NodeStack.
34735f757f3fSDimitry Andric NodeStack.pop_back();
34745f757f3fSDimitry Andric assert(!NodeStack.empty() && "Node stack imbalance!");
34755f757f3fSDimitry Andric N = NodeStack.back();
34765f757f3fSDimitry Andric
34775f757f3fSDimitry Andric unsigned SiblingNo = Opcode == OPC_MoveSibling
34785f757f3fSDimitry Andric ? MatcherTable[MatcherIndex++]
34795f757f3fSDimitry Andric : Opcode - OPC_MoveSibling0;
34805f757f3fSDimitry Andric if (SiblingNo >= N.getNumOperands())
34815f757f3fSDimitry Andric break; // Match fails if out of range sibling #.
34825f757f3fSDimitry Andric N = N.getOperand(SiblingNo);
34835f757f3fSDimitry Andric NodeStack.push_back(N);
34845f757f3fSDimitry Andric continue;
34855f757f3fSDimitry Andric }
34860b57cec5SDimitry Andric case OPC_MoveParent:
34870b57cec5SDimitry Andric // Pop the current node off the NodeStack.
34880b57cec5SDimitry Andric NodeStack.pop_back();
34890b57cec5SDimitry Andric assert(!NodeStack.empty() && "Node stack imbalance!");
34900b57cec5SDimitry Andric N = NodeStack.back();
34910b57cec5SDimitry Andric continue;
34920b57cec5SDimitry Andric
34930b57cec5SDimitry Andric case OPC_CheckSame:
34940b57cec5SDimitry Andric if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
34950b57cec5SDimitry Andric continue;
34960b57cec5SDimitry Andric
34970b57cec5SDimitry Andric case OPC_CheckChild0Same: case OPC_CheckChild1Same:
34980b57cec5SDimitry Andric case OPC_CheckChild2Same: case OPC_CheckChild3Same:
34990b57cec5SDimitry Andric if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
35000b57cec5SDimitry Andric Opcode-OPC_CheckChild0Same))
35010b57cec5SDimitry Andric break;
35020b57cec5SDimitry Andric continue;
35030b57cec5SDimitry Andric
35040b57cec5SDimitry Andric case OPC_CheckPatternPredicate:
3505297eecfbSDimitry Andric case OPC_CheckPatternPredicate0:
3506297eecfbSDimitry Andric case OPC_CheckPatternPredicate1:
35075f757f3fSDimitry Andric case OPC_CheckPatternPredicate2:
3508297eecfbSDimitry Andric case OPC_CheckPatternPredicate3:
3509297eecfbSDimitry Andric case OPC_CheckPatternPredicate4:
3510297eecfbSDimitry Andric case OPC_CheckPatternPredicate5:
3511297eecfbSDimitry Andric case OPC_CheckPatternPredicate6:
3512297eecfbSDimitry Andric case OPC_CheckPatternPredicate7:
3513297eecfbSDimitry Andric case OPC_CheckPatternPredicateTwoByte:
3514297eecfbSDimitry Andric if (!::CheckPatternPredicate(Opcode, MatcherTable, MatcherIndex, *this))
35155f757f3fSDimitry Andric break;
35160b57cec5SDimitry Andric continue;
35177a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate0:
35187a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate1:
35197a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate2:
35207a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate3:
35217a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate4:
35227a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate5:
35237a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate6:
35247a6dacacSDimitry Andric case SelectionDAGISel::OPC_CheckPredicate7:
35250b57cec5SDimitry Andric case OPC_CheckPredicate:
35267a6dacacSDimitry Andric if (!::CheckNodePredicate(Opcode, MatcherTable, MatcherIndex, *this,
35270b57cec5SDimitry Andric N.getNode()))
35280b57cec5SDimitry Andric break;
35290b57cec5SDimitry Andric continue;
35300b57cec5SDimitry Andric case OPC_CheckPredicateWithOperands: {
35310b57cec5SDimitry Andric unsigned OpNum = MatcherTable[MatcherIndex++];
35320b57cec5SDimitry Andric SmallVector<SDValue, 8> Operands;
35330b57cec5SDimitry Andric
35340b57cec5SDimitry Andric for (unsigned i = 0; i < OpNum; ++i)
35350b57cec5SDimitry Andric Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
35360b57cec5SDimitry Andric
35370b57cec5SDimitry Andric unsigned PredNo = MatcherTable[MatcherIndex++];
35380b57cec5SDimitry Andric if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
35390b57cec5SDimitry Andric break;
35400b57cec5SDimitry Andric continue;
35410b57cec5SDimitry Andric }
3542297eecfbSDimitry Andric case OPC_CheckComplexPat:
3543297eecfbSDimitry Andric case OPC_CheckComplexPat0:
3544297eecfbSDimitry Andric case OPC_CheckComplexPat1:
3545297eecfbSDimitry Andric case OPC_CheckComplexPat2:
3546297eecfbSDimitry Andric case OPC_CheckComplexPat3:
3547297eecfbSDimitry Andric case OPC_CheckComplexPat4:
3548297eecfbSDimitry Andric case OPC_CheckComplexPat5:
3549297eecfbSDimitry Andric case OPC_CheckComplexPat6:
3550297eecfbSDimitry Andric case OPC_CheckComplexPat7: {
3551297eecfbSDimitry Andric unsigned CPNum = Opcode == OPC_CheckComplexPat
3552297eecfbSDimitry Andric ? MatcherTable[MatcherIndex++]
3553297eecfbSDimitry Andric : Opcode - OPC_CheckComplexPat0;
35540b57cec5SDimitry Andric unsigned RecNo = MatcherTable[MatcherIndex++];
35550b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
35560b57cec5SDimitry Andric
35570b57cec5SDimitry Andric // If target can modify DAG during matching, keep the matching state
35580b57cec5SDimitry Andric // consistent.
35590b57cec5SDimitry Andric std::unique_ptr<MatchStateUpdater> MSU;
35600b57cec5SDimitry Andric if (ComplexPatternFuncMutatesDAG())
35610b57cec5SDimitry Andric MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
35620b57cec5SDimitry Andric MatchScopes));
35630b57cec5SDimitry Andric
35640b57cec5SDimitry Andric if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
35650b57cec5SDimitry Andric RecordedNodes[RecNo].first, CPNum,
35660b57cec5SDimitry Andric RecordedNodes))
35670b57cec5SDimitry Andric break;
35680b57cec5SDimitry Andric continue;
35690b57cec5SDimitry Andric }
35700b57cec5SDimitry Andric case OPC_CheckOpcode:
35710b57cec5SDimitry Andric if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
35720b57cec5SDimitry Andric continue;
35730b57cec5SDimitry Andric
35740b57cec5SDimitry Andric case OPC_CheckType:
35755f757f3fSDimitry Andric case OPC_CheckTypeI32:
35765f757f3fSDimitry Andric case OPC_CheckTypeI64:
35775f757f3fSDimitry Andric MVT::SimpleValueType VT;
35785f757f3fSDimitry Andric switch (Opcode) {
35795f757f3fSDimitry Andric case OPC_CheckTypeI32:
35805f757f3fSDimitry Andric VT = MVT::i32;
35815f757f3fSDimitry Andric break;
35825f757f3fSDimitry Andric case OPC_CheckTypeI64:
35835f757f3fSDimitry Andric VT = MVT::i64;
35845f757f3fSDimitry Andric break;
35855f757f3fSDimitry Andric default:
35865f757f3fSDimitry Andric VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
35875f757f3fSDimitry Andric break;
35885f757f3fSDimitry Andric }
35895f757f3fSDimitry Andric if (!::CheckType(VT, N, TLI, CurDAG->getDataLayout()))
35900b57cec5SDimitry Andric break;
35910b57cec5SDimitry Andric continue;
35920b57cec5SDimitry Andric
35930b57cec5SDimitry Andric case OPC_CheckTypeRes: {
35940b57cec5SDimitry Andric unsigned Res = MatcherTable[MatcherIndex++];
35955f757f3fSDimitry Andric if (!::CheckType(
35965f757f3fSDimitry Andric static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]),
35975f757f3fSDimitry Andric N.getValue(Res), TLI, CurDAG->getDataLayout()))
35980b57cec5SDimitry Andric break;
35990b57cec5SDimitry Andric continue;
36000b57cec5SDimitry Andric }
36010b57cec5SDimitry Andric
36020b57cec5SDimitry Andric case OPC_SwitchOpcode: {
36030b57cec5SDimitry Andric unsigned CurNodeOpcode = N.getOpcode();
36040b57cec5SDimitry Andric unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
36050b57cec5SDimitry Andric unsigned CaseSize;
36060b57cec5SDimitry Andric while (true) {
36070b57cec5SDimitry Andric // Get the size of this case.
36080b57cec5SDimitry Andric CaseSize = MatcherTable[MatcherIndex++];
36090b57cec5SDimitry Andric if (CaseSize & 128)
36100b57cec5SDimitry Andric CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
36110b57cec5SDimitry Andric if (CaseSize == 0) break;
36120b57cec5SDimitry Andric
36130b57cec5SDimitry Andric uint16_t Opc = MatcherTable[MatcherIndex++];
36145f757f3fSDimitry Andric Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
36150b57cec5SDimitry Andric
36160b57cec5SDimitry Andric // If the opcode matches, then we will execute this case.
36170b57cec5SDimitry Andric if (CurNodeOpcode == Opc)
36180b57cec5SDimitry Andric break;
36190b57cec5SDimitry Andric
36200b57cec5SDimitry Andric // Otherwise, skip over this case.
36210b57cec5SDimitry Andric MatcherIndex += CaseSize;
36220b57cec5SDimitry Andric }
36230b57cec5SDimitry Andric
36240b57cec5SDimitry Andric // If no cases matched, bail out.
36250b57cec5SDimitry Andric if (CaseSize == 0) break;
36260b57cec5SDimitry Andric
36270b57cec5SDimitry Andric // Otherwise, execute the case we found.
36280b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
36290b57cec5SDimitry Andric << MatcherIndex << "\n");
36300b57cec5SDimitry Andric continue;
36310b57cec5SDimitry Andric }
36320b57cec5SDimitry Andric
36330b57cec5SDimitry Andric case OPC_SwitchType: {
36340b57cec5SDimitry Andric MVT CurNodeVT = N.getSimpleValueType();
36350b57cec5SDimitry Andric unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
36360b57cec5SDimitry Andric unsigned CaseSize;
36370b57cec5SDimitry Andric while (true) {
36380b57cec5SDimitry Andric // Get the size of this case.
36390b57cec5SDimitry Andric CaseSize = MatcherTable[MatcherIndex++];
36400b57cec5SDimitry Andric if (CaseSize & 128)
36410b57cec5SDimitry Andric CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
36420b57cec5SDimitry Andric if (CaseSize == 0) break;
36430b57cec5SDimitry Andric
36445f757f3fSDimitry Andric MVT CaseVT =
36455f757f3fSDimitry Andric static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
36460b57cec5SDimitry Andric if (CaseVT == MVT::iPTR)
36470b57cec5SDimitry Andric CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
36480b57cec5SDimitry Andric
36490b57cec5SDimitry Andric // If the VT matches, then we will execute this case.
36500b57cec5SDimitry Andric if (CurNodeVT == CaseVT)
36510b57cec5SDimitry Andric break;
36520b57cec5SDimitry Andric
36530b57cec5SDimitry Andric // Otherwise, skip over this case.
36540b57cec5SDimitry Andric MatcherIndex += CaseSize;
36550b57cec5SDimitry Andric }
36560b57cec5SDimitry Andric
36570b57cec5SDimitry Andric // If no cases matched, bail out.
36580b57cec5SDimitry Andric if (CaseSize == 0) break;
36590b57cec5SDimitry Andric
36600b57cec5SDimitry Andric // Otherwise, execute the case we found.
366106c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << " TypeSwitch[" << CurNodeVT
36620b57cec5SDimitry Andric << "] from " << SwitchStart << " to " << MatcherIndex
36630b57cec5SDimitry Andric << '\n');
36640b57cec5SDimitry Andric continue;
36650b57cec5SDimitry Andric }
36665f757f3fSDimitry Andric case OPC_CheckChild0Type:
36675f757f3fSDimitry Andric case OPC_CheckChild1Type:
36685f757f3fSDimitry Andric case OPC_CheckChild2Type:
36695f757f3fSDimitry Andric case OPC_CheckChild3Type:
36705f757f3fSDimitry Andric case OPC_CheckChild4Type:
36715f757f3fSDimitry Andric case OPC_CheckChild5Type:
36725f757f3fSDimitry Andric case OPC_CheckChild6Type:
36735f757f3fSDimitry Andric case OPC_CheckChild7Type:
36745f757f3fSDimitry Andric case OPC_CheckChild0TypeI32:
36755f757f3fSDimitry Andric case OPC_CheckChild1TypeI32:
36765f757f3fSDimitry Andric case OPC_CheckChild2TypeI32:
36775f757f3fSDimitry Andric case OPC_CheckChild3TypeI32:
36785f757f3fSDimitry Andric case OPC_CheckChild4TypeI32:
36795f757f3fSDimitry Andric case OPC_CheckChild5TypeI32:
36805f757f3fSDimitry Andric case OPC_CheckChild6TypeI32:
36815f757f3fSDimitry Andric case OPC_CheckChild7TypeI32:
36825f757f3fSDimitry Andric case OPC_CheckChild0TypeI64:
36835f757f3fSDimitry Andric case OPC_CheckChild1TypeI64:
36845f757f3fSDimitry Andric case OPC_CheckChild2TypeI64:
36855f757f3fSDimitry Andric case OPC_CheckChild3TypeI64:
36865f757f3fSDimitry Andric case OPC_CheckChild4TypeI64:
36875f757f3fSDimitry Andric case OPC_CheckChild5TypeI64:
36885f757f3fSDimitry Andric case OPC_CheckChild6TypeI64:
36895f757f3fSDimitry Andric case OPC_CheckChild7TypeI64: {
36905f757f3fSDimitry Andric MVT::SimpleValueType VT;
36915f757f3fSDimitry Andric unsigned ChildNo;
36925f757f3fSDimitry Andric if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI32 &&
36935f757f3fSDimitry Andric Opcode <= SelectionDAGISel::OPC_CheckChild7TypeI32) {
36945f757f3fSDimitry Andric VT = MVT::i32;
36955f757f3fSDimitry Andric ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0TypeI32;
36965f757f3fSDimitry Andric } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
36975f757f3fSDimitry Andric Opcode <= SelectionDAGISel::OPC_CheckChild7TypeI64) {
36985f757f3fSDimitry Andric VT = MVT::i64;
36995f757f3fSDimitry Andric ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0TypeI64;
37005f757f3fSDimitry Andric } else {
37015f757f3fSDimitry Andric VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
37025f757f3fSDimitry Andric ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
37035f757f3fSDimitry Andric }
37045f757f3fSDimitry Andric if (!::CheckChildType(VT, N, TLI, CurDAG->getDataLayout(), ChildNo))
37050b57cec5SDimitry Andric break;
37060b57cec5SDimitry Andric continue;
37075f757f3fSDimitry Andric }
37080b57cec5SDimitry Andric case OPC_CheckCondCode:
37090b57cec5SDimitry Andric if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
37100b57cec5SDimitry Andric continue;
37110b57cec5SDimitry Andric case OPC_CheckChild2CondCode:
37120b57cec5SDimitry Andric if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
37130b57cec5SDimitry Andric continue;
37140b57cec5SDimitry Andric case OPC_CheckValueType:
37150b57cec5SDimitry Andric if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
37160b57cec5SDimitry Andric CurDAG->getDataLayout()))
37170b57cec5SDimitry Andric break;
37180b57cec5SDimitry Andric continue;
37190b57cec5SDimitry Andric case OPC_CheckInteger:
37200b57cec5SDimitry Andric if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
37210b57cec5SDimitry Andric continue;
37220b57cec5SDimitry Andric case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
37230b57cec5SDimitry Andric case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
37240b57cec5SDimitry Andric case OPC_CheckChild4Integer:
37250b57cec5SDimitry Andric if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
37260b57cec5SDimitry Andric Opcode-OPC_CheckChild0Integer)) break;
37270b57cec5SDimitry Andric continue;
37280b57cec5SDimitry Andric case OPC_CheckAndImm:
37290b57cec5SDimitry Andric if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
37300b57cec5SDimitry Andric continue;
37310b57cec5SDimitry Andric case OPC_CheckOrImm:
37320b57cec5SDimitry Andric if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
37330b57cec5SDimitry Andric continue;
37340b57cec5SDimitry Andric case OPC_CheckImmAllOnesV:
3735e8d8bef9SDimitry Andric if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3736e8d8bef9SDimitry Andric break;
37370b57cec5SDimitry Andric continue;
37380b57cec5SDimitry Andric case OPC_CheckImmAllZerosV:
3739e8d8bef9SDimitry Andric if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3740e8d8bef9SDimitry Andric break;
37410b57cec5SDimitry Andric continue;
37420b57cec5SDimitry Andric
37430b57cec5SDimitry Andric case OPC_CheckFoldableChainNode: {
37440b57cec5SDimitry Andric assert(NodeStack.size() != 1 && "No parent node");
37450b57cec5SDimitry Andric // Verify that all intermediate nodes between the root and this one have
3746480093f4SDimitry Andric // a single use (ignoring chains, which are handled in UpdateChains).
37470b57cec5SDimitry Andric bool HasMultipleUses = false;
3748480093f4SDimitry Andric for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3749480093f4SDimitry Andric unsigned NNonChainUses = 0;
3750480093f4SDimitry Andric SDNode *NS = NodeStack[i].getNode();
3751480093f4SDimitry Andric for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
3752480093f4SDimitry Andric if (UI.getUse().getValueType() != MVT::Other)
3753480093f4SDimitry Andric if (++NNonChainUses > 1) {
37540b57cec5SDimitry Andric HasMultipleUses = true;
37550b57cec5SDimitry Andric break;
37560b57cec5SDimitry Andric }
37570b57cec5SDimitry Andric if (HasMultipleUses) break;
3758480093f4SDimitry Andric }
3759480093f4SDimitry Andric if (HasMultipleUses) break;
37600b57cec5SDimitry Andric
37610b57cec5SDimitry Andric // Check to see that the target thinks this is profitable to fold and that
37620b57cec5SDimitry Andric // we can fold it without inducing cycles in the graph.
37630b57cec5SDimitry Andric if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
37640b57cec5SDimitry Andric NodeToMatch) ||
37650b57cec5SDimitry Andric !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
37660b57cec5SDimitry Andric NodeToMatch, OptLevel,
37670b57cec5SDimitry Andric true/*We validate our own chains*/))
37680b57cec5SDimitry Andric break;
37690b57cec5SDimitry Andric
37700b57cec5SDimitry Andric continue;
37710b57cec5SDimitry Andric }
3772fe6060f1SDimitry Andric case OPC_EmitInteger:
37735f757f3fSDimitry Andric case OPC_EmitInteger8:
37745f757f3fSDimitry Andric case OPC_EmitInteger16:
37755f757f3fSDimitry Andric case OPC_EmitInteger32:
37765f757f3fSDimitry Andric case OPC_EmitInteger64:
37775f757f3fSDimitry Andric case OPC_EmitStringInteger:
37785f757f3fSDimitry Andric case OPC_EmitStringInteger32: {
37795f757f3fSDimitry Andric MVT::SimpleValueType VT;
37805f757f3fSDimitry Andric switch (Opcode) {
37815f757f3fSDimitry Andric case OPC_EmitInteger8:
37825f757f3fSDimitry Andric VT = MVT::i8;
37835f757f3fSDimitry Andric break;
37845f757f3fSDimitry Andric case OPC_EmitInteger16:
37855f757f3fSDimitry Andric VT = MVT::i16;
37865f757f3fSDimitry Andric break;
37875f757f3fSDimitry Andric case OPC_EmitInteger32:
37885f757f3fSDimitry Andric case OPC_EmitStringInteger32:
37895f757f3fSDimitry Andric VT = MVT::i32;
37905f757f3fSDimitry Andric break;
37915f757f3fSDimitry Andric case OPC_EmitInteger64:
37925f757f3fSDimitry Andric VT = MVT::i64;
37935f757f3fSDimitry Andric break;
37945f757f3fSDimitry Andric default:
37955f757f3fSDimitry Andric VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
37965f757f3fSDimitry Andric break;
37975f757f3fSDimitry Andric }
37980b57cec5SDimitry Andric int64_t Val = MatcherTable[MatcherIndex++];
37990b57cec5SDimitry Andric if (Val & 128)
38000b57cec5SDimitry Andric Val = GetVBR(Val, MatcherTable, MatcherIndex);
38015f757f3fSDimitry Andric if (Opcode >= OPC_EmitInteger && Opcode <= OPC_EmitInteger64)
3802fe6060f1SDimitry Andric Val = decodeSignRotatedValue(Val);
38030b57cec5SDimitry Andric RecordedNodes.push_back(std::pair<SDValue, SDNode *>(
38045f757f3fSDimitry Andric CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), VT), nullptr));
38050b57cec5SDimitry Andric continue;
38060b57cec5SDimitry Andric }
3807cb14a3feSDimitry Andric case OPC_EmitRegister:
3808cb14a3feSDimitry Andric case OPC_EmitRegisterI32:
3809cb14a3feSDimitry Andric case OPC_EmitRegisterI64: {
3810cb14a3feSDimitry Andric MVT::SimpleValueType VT;
3811cb14a3feSDimitry Andric switch (Opcode) {
3812cb14a3feSDimitry Andric case OPC_EmitRegisterI32:
3813cb14a3feSDimitry Andric VT = MVT::i32;
3814cb14a3feSDimitry Andric break;
3815cb14a3feSDimitry Andric case OPC_EmitRegisterI64:
3816cb14a3feSDimitry Andric VT = MVT::i64;
3817cb14a3feSDimitry Andric break;
3818cb14a3feSDimitry Andric default:
3819cb14a3feSDimitry Andric VT = static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
3820cb14a3feSDimitry Andric break;
3821cb14a3feSDimitry Andric }
38220b57cec5SDimitry Andric unsigned RegNo = MatcherTable[MatcherIndex++];
38230b57cec5SDimitry Andric RecordedNodes.push_back(std::pair<SDValue, SDNode *>(
38240b57cec5SDimitry Andric CurDAG->getRegister(RegNo, VT), nullptr));
38250b57cec5SDimitry Andric continue;
38260b57cec5SDimitry Andric }
38270b57cec5SDimitry Andric case OPC_EmitRegister2: {
38280b57cec5SDimitry Andric // For targets w/ more than 256 register names, the register enum
38290b57cec5SDimitry Andric // values are stored in two bytes in the matcher table (just like
38300b57cec5SDimitry Andric // opcodes).
38310b57cec5SDimitry Andric MVT::SimpleValueType VT =
38325f757f3fSDimitry Andric static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
38330b57cec5SDimitry Andric unsigned RegNo = MatcherTable[MatcherIndex++];
38340b57cec5SDimitry Andric RegNo |= MatcherTable[MatcherIndex++] << 8;
38350b57cec5SDimitry Andric RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
38360b57cec5SDimitry Andric CurDAG->getRegister(RegNo, VT), nullptr));
38370b57cec5SDimitry Andric continue;
38380b57cec5SDimitry Andric }
38390b57cec5SDimitry Andric
38405f757f3fSDimitry Andric case OPC_EmitConvertToTarget:
38415f757f3fSDimitry Andric case OPC_EmitConvertToTarget0:
38425f757f3fSDimitry Andric case OPC_EmitConvertToTarget1:
38435f757f3fSDimitry Andric case OPC_EmitConvertToTarget2:
38445f757f3fSDimitry Andric case OPC_EmitConvertToTarget3:
38455f757f3fSDimitry Andric case OPC_EmitConvertToTarget4:
38465f757f3fSDimitry Andric case OPC_EmitConvertToTarget5:
38475f757f3fSDimitry Andric case OPC_EmitConvertToTarget6:
38485f757f3fSDimitry Andric case OPC_EmitConvertToTarget7: {
38490b57cec5SDimitry Andric // Convert from IMM/FPIMM to target version.
38505f757f3fSDimitry Andric unsigned RecNo = Opcode == OPC_EmitConvertToTarget
38515f757f3fSDimitry Andric ? MatcherTable[MatcherIndex++]
38525f757f3fSDimitry Andric : Opcode - OPC_EmitConvertToTarget0;
38530b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
38540b57cec5SDimitry Andric SDValue Imm = RecordedNodes[RecNo].first;
38550b57cec5SDimitry Andric
38560b57cec5SDimitry Andric if (Imm->getOpcode() == ISD::Constant) {
38570b57cec5SDimitry Andric const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
38580b57cec5SDimitry Andric Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
38590b57cec5SDimitry Andric Imm.getValueType());
38600b57cec5SDimitry Andric } else if (Imm->getOpcode() == ISD::ConstantFP) {
38610b57cec5SDimitry Andric const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
38620b57cec5SDimitry Andric Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
38630b57cec5SDimitry Andric Imm.getValueType());
38640b57cec5SDimitry Andric }
38650b57cec5SDimitry Andric
38660b57cec5SDimitry Andric RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
38670b57cec5SDimitry Andric continue;
38680b57cec5SDimitry Andric }
38690b57cec5SDimitry Andric
38700b57cec5SDimitry Andric case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
38710b57cec5SDimitry Andric case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
38720b57cec5SDimitry Andric case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
38730b57cec5SDimitry Andric // These are space-optimized forms of OPC_EmitMergeInputChains.
38740b57cec5SDimitry Andric assert(!InputChain.getNode() &&
38750b57cec5SDimitry Andric "EmitMergeInputChains should be the first chain producing node");
38760b57cec5SDimitry Andric assert(ChainNodesMatched.empty() &&
38770b57cec5SDimitry Andric "Should only have one EmitMergeInputChains per match");
38780b57cec5SDimitry Andric
38790b57cec5SDimitry Andric // Read all of the chained nodes.
38800b57cec5SDimitry Andric unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
38810b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
38820b57cec5SDimitry Andric ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
38830b57cec5SDimitry Andric
388481ad6265SDimitry Andric // If the chained node is not the root, we can't fold it if it has
388581ad6265SDimitry Andric // multiple uses.
38860b57cec5SDimitry Andric // FIXME: What if other value results of the node have uses not matched
38870b57cec5SDimitry Andric // by this pattern?
38880b57cec5SDimitry Andric if (ChainNodesMatched.back() != NodeToMatch &&
38890b57cec5SDimitry Andric !RecordedNodes[RecNo].first.hasOneUse()) {
38900b57cec5SDimitry Andric ChainNodesMatched.clear();
38910b57cec5SDimitry Andric break;
38920b57cec5SDimitry Andric }
38930b57cec5SDimitry Andric
38940b57cec5SDimitry Andric // Merge the input chains if they are not intra-pattern references.
38950b57cec5SDimitry Andric InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
38960b57cec5SDimitry Andric
38970b57cec5SDimitry Andric if (!InputChain.getNode())
38980b57cec5SDimitry Andric break; // Failed to merge.
38990b57cec5SDimitry Andric continue;
39000b57cec5SDimitry Andric }
39010b57cec5SDimitry Andric
39020b57cec5SDimitry Andric case OPC_EmitMergeInputChains: {
39030b57cec5SDimitry Andric assert(!InputChain.getNode() &&
39040b57cec5SDimitry Andric "EmitMergeInputChains should be the first chain producing node");
39050b57cec5SDimitry Andric // This node gets a list of nodes we matched in the input that have
39060b57cec5SDimitry Andric // chains. We want to token factor all of the input chains to these nodes
39070b57cec5SDimitry Andric // together. However, if any of the input chains is actually one of the
39080b57cec5SDimitry Andric // nodes matched in this pattern, then we have an intra-match reference.
39090b57cec5SDimitry Andric // Ignore these because the newly token factored chain should not refer to
39100b57cec5SDimitry Andric // the old nodes.
39110b57cec5SDimitry Andric unsigned NumChains = MatcherTable[MatcherIndex++];
39120b57cec5SDimitry Andric assert(NumChains != 0 && "Can't TF zero chains");
39130b57cec5SDimitry Andric
39140b57cec5SDimitry Andric assert(ChainNodesMatched.empty() &&
39150b57cec5SDimitry Andric "Should only have one EmitMergeInputChains per match");
39160b57cec5SDimitry Andric
39170b57cec5SDimitry Andric // Read all of the chained nodes.
39180b57cec5SDimitry Andric for (unsigned i = 0; i != NumChains; ++i) {
39190b57cec5SDimitry Andric unsigned RecNo = MatcherTable[MatcherIndex++];
39200b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
39210b57cec5SDimitry Andric ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
39220b57cec5SDimitry Andric
392381ad6265SDimitry Andric // If the chained node is not the root, we can't fold it if it has
392481ad6265SDimitry Andric // multiple uses.
39250b57cec5SDimitry Andric // FIXME: What if other value results of the node have uses not matched
39260b57cec5SDimitry Andric // by this pattern?
39270b57cec5SDimitry Andric if (ChainNodesMatched.back() != NodeToMatch &&
39280b57cec5SDimitry Andric !RecordedNodes[RecNo].first.hasOneUse()) {
39290b57cec5SDimitry Andric ChainNodesMatched.clear();
39300b57cec5SDimitry Andric break;
39310b57cec5SDimitry Andric }
39320b57cec5SDimitry Andric }
39330b57cec5SDimitry Andric
39340b57cec5SDimitry Andric // If the inner loop broke out, the match fails.
39350b57cec5SDimitry Andric if (ChainNodesMatched.empty())
39360b57cec5SDimitry Andric break;
39370b57cec5SDimitry Andric
39380b57cec5SDimitry Andric // Merge the input chains if they are not intra-pattern references.
39390b57cec5SDimitry Andric InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
39400b57cec5SDimitry Andric
39410b57cec5SDimitry Andric if (!InputChain.getNode())
39420b57cec5SDimitry Andric break; // Failed to merge.
39430b57cec5SDimitry Andric
39440b57cec5SDimitry Andric continue;
39450b57cec5SDimitry Andric }
39460b57cec5SDimitry Andric
39478bcb0991SDimitry Andric case OPC_EmitCopyToReg:
39485f757f3fSDimitry Andric case OPC_EmitCopyToReg0:
39495f757f3fSDimitry Andric case OPC_EmitCopyToReg1:
39505f757f3fSDimitry Andric case OPC_EmitCopyToReg2:
39515f757f3fSDimitry Andric case OPC_EmitCopyToReg3:
39525f757f3fSDimitry Andric case OPC_EmitCopyToReg4:
39535f757f3fSDimitry Andric case OPC_EmitCopyToReg5:
39545f757f3fSDimitry Andric case OPC_EmitCopyToReg6:
39555f757f3fSDimitry Andric case OPC_EmitCopyToReg7:
39565f757f3fSDimitry Andric case OPC_EmitCopyToRegTwoByte: {
39575f757f3fSDimitry Andric unsigned RecNo =
39585f757f3fSDimitry Andric Opcode >= OPC_EmitCopyToReg0 && Opcode <= OPC_EmitCopyToReg7
39595f757f3fSDimitry Andric ? Opcode - OPC_EmitCopyToReg0
39605f757f3fSDimitry Andric : MatcherTable[MatcherIndex++];
39610b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
39620b57cec5SDimitry Andric unsigned DestPhysReg = MatcherTable[MatcherIndex++];
39635f757f3fSDimitry Andric if (Opcode == OPC_EmitCopyToRegTwoByte)
39648bcb0991SDimitry Andric DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
39650b57cec5SDimitry Andric
39660b57cec5SDimitry Andric if (!InputChain.getNode())
39670b57cec5SDimitry Andric InputChain = CurDAG->getEntryNode();
39680b57cec5SDimitry Andric
39690b57cec5SDimitry Andric InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
39700b57cec5SDimitry Andric DestPhysReg, RecordedNodes[RecNo].first,
39710b57cec5SDimitry Andric InputGlue);
39720b57cec5SDimitry Andric
39730b57cec5SDimitry Andric InputGlue = InputChain.getValue(1);
39740b57cec5SDimitry Andric continue;
39750b57cec5SDimitry Andric }
39760b57cec5SDimitry Andric
39770b57cec5SDimitry Andric case OPC_EmitNodeXForm: {
39780b57cec5SDimitry Andric unsigned XFormNo = MatcherTable[MatcherIndex++];
39790b57cec5SDimitry Andric unsigned RecNo = MatcherTable[MatcherIndex++];
39800b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
39810b57cec5SDimitry Andric SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
39820b57cec5SDimitry Andric RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
39830b57cec5SDimitry Andric continue;
39840b57cec5SDimitry Andric }
39850b57cec5SDimitry Andric case OPC_Coverage: {
39860b57cec5SDimitry Andric // This is emitted right before MorphNode/EmitNode.
39870b57cec5SDimitry Andric // So it should be safe to assume that this node has been selected
39880b57cec5SDimitry Andric unsigned index = MatcherTable[MatcherIndex++];
39890b57cec5SDimitry Andric index |= (MatcherTable[MatcherIndex++] << 8);
39900b57cec5SDimitry Andric dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
39910b57cec5SDimitry Andric dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
39920b57cec5SDimitry Andric continue;
39930b57cec5SDimitry Andric }
39940b57cec5SDimitry Andric
39955f757f3fSDimitry Andric case OPC_EmitNode:
39965f757f3fSDimitry Andric case OPC_EmitNode0:
39975f757f3fSDimitry Andric case OPC_EmitNode1:
39985f757f3fSDimitry Andric case OPC_EmitNode2:
39995f757f3fSDimitry Andric case OPC_EmitNode0None:
40005f757f3fSDimitry Andric case OPC_EmitNode1None:
40015f757f3fSDimitry Andric case OPC_EmitNode2None:
40025f757f3fSDimitry Andric case OPC_EmitNode0Chain:
40035f757f3fSDimitry Andric case OPC_EmitNode1Chain:
40045f757f3fSDimitry Andric case OPC_EmitNode2Chain:
40055f757f3fSDimitry Andric case OPC_MorphNodeTo:
40065f757f3fSDimitry Andric case OPC_MorphNodeTo0:
40075f757f3fSDimitry Andric case OPC_MorphNodeTo1:
40085f757f3fSDimitry Andric case OPC_MorphNodeTo2:
40095f757f3fSDimitry Andric case OPC_MorphNodeTo0None:
40105f757f3fSDimitry Andric case OPC_MorphNodeTo1None:
40115f757f3fSDimitry Andric case OPC_MorphNodeTo2None:
40125f757f3fSDimitry Andric case OPC_MorphNodeTo0Chain:
40135f757f3fSDimitry Andric case OPC_MorphNodeTo1Chain:
40145f757f3fSDimitry Andric case OPC_MorphNodeTo2Chain:
40155f757f3fSDimitry Andric case OPC_MorphNodeTo0GlueInput:
40165f757f3fSDimitry Andric case OPC_MorphNodeTo1GlueInput:
40175f757f3fSDimitry Andric case OPC_MorphNodeTo2GlueInput:
40185f757f3fSDimitry Andric case OPC_MorphNodeTo0GlueOutput:
40195f757f3fSDimitry Andric case OPC_MorphNodeTo1GlueOutput:
40205f757f3fSDimitry Andric case OPC_MorphNodeTo2GlueOutput: {
40210b57cec5SDimitry Andric uint16_t TargetOpc = MatcherTable[MatcherIndex++];
40225f757f3fSDimitry Andric TargetOpc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
40235f757f3fSDimitry Andric unsigned EmitNodeInfo;
40245f757f3fSDimitry Andric if (Opcode >= OPC_EmitNode0None && Opcode <= OPC_EmitNode2Chain) {
40255f757f3fSDimitry Andric if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
40265f757f3fSDimitry Andric EmitNodeInfo = OPFL_Chain;
40275f757f3fSDimitry Andric else
40285f757f3fSDimitry Andric EmitNodeInfo = OPFL_None;
40295f757f3fSDimitry Andric } else if (Opcode >= OPC_MorphNodeTo0None &&
40305f757f3fSDimitry Andric Opcode <= OPC_MorphNodeTo2GlueOutput) {
40315f757f3fSDimitry Andric if (Opcode >= OPC_MorphNodeTo0Chain && Opcode <= OPC_MorphNodeTo2Chain)
40325f757f3fSDimitry Andric EmitNodeInfo = OPFL_Chain;
40335f757f3fSDimitry Andric else if (Opcode >= OPC_MorphNodeTo0GlueInput &&
40345f757f3fSDimitry Andric Opcode <= OPC_MorphNodeTo2GlueInput)
40355f757f3fSDimitry Andric EmitNodeInfo = OPFL_GlueInput;
40365f757f3fSDimitry Andric else if (Opcode >= OPC_MorphNodeTo0GlueOutput &&
40375f757f3fSDimitry Andric Opcode <= OPC_MorphNodeTo2GlueOutput)
40385f757f3fSDimitry Andric EmitNodeInfo = OPFL_GlueOutput;
40395f757f3fSDimitry Andric else
40405f757f3fSDimitry Andric EmitNodeInfo = OPFL_None;
40415f757f3fSDimitry Andric } else
40425f757f3fSDimitry Andric EmitNodeInfo = MatcherTable[MatcherIndex++];
40430b57cec5SDimitry Andric // Get the result VT list.
40440b57cec5SDimitry Andric unsigned NumVTs;
40450b57cec5SDimitry Andric // If this is one of the compressed forms, get the number of VTs based
40460b57cec5SDimitry Andric // on the Opcode. Otherwise read the next byte from the table.
40470b57cec5SDimitry Andric if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
40480b57cec5SDimitry Andric NumVTs = Opcode - OPC_MorphNodeTo0;
40495f757f3fSDimitry Andric else if (Opcode >= OPC_MorphNodeTo0None && Opcode <= OPC_MorphNodeTo2None)
40505f757f3fSDimitry Andric NumVTs = Opcode - OPC_MorphNodeTo0None;
40515f757f3fSDimitry Andric else if (Opcode >= OPC_MorphNodeTo0Chain &&
40525f757f3fSDimitry Andric Opcode <= OPC_MorphNodeTo2Chain)
40535f757f3fSDimitry Andric NumVTs = Opcode - OPC_MorphNodeTo0Chain;
40545f757f3fSDimitry Andric else if (Opcode >= OPC_MorphNodeTo0GlueInput &&
40555f757f3fSDimitry Andric Opcode <= OPC_MorphNodeTo2GlueInput)
40565f757f3fSDimitry Andric NumVTs = Opcode - OPC_MorphNodeTo0GlueInput;
40575f757f3fSDimitry Andric else if (Opcode >= OPC_MorphNodeTo0GlueOutput &&
40585f757f3fSDimitry Andric Opcode <= OPC_MorphNodeTo2GlueOutput)
40595f757f3fSDimitry Andric NumVTs = Opcode - OPC_MorphNodeTo0GlueOutput;
40600b57cec5SDimitry Andric else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
40610b57cec5SDimitry Andric NumVTs = Opcode - OPC_EmitNode0;
40625f757f3fSDimitry Andric else if (Opcode >= OPC_EmitNode0None && Opcode <= OPC_EmitNode2None)
40635f757f3fSDimitry Andric NumVTs = Opcode - OPC_EmitNode0None;
40645f757f3fSDimitry Andric else if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
40655f757f3fSDimitry Andric NumVTs = Opcode - OPC_EmitNode0Chain;
40660b57cec5SDimitry Andric else
40670b57cec5SDimitry Andric NumVTs = MatcherTable[MatcherIndex++];
40680b57cec5SDimitry Andric SmallVector<EVT, 4> VTs;
40690b57cec5SDimitry Andric for (unsigned i = 0; i != NumVTs; ++i) {
40700b57cec5SDimitry Andric MVT::SimpleValueType VT =
40715f757f3fSDimitry Andric static_cast<MVT::SimpleValueType>(MatcherTable[MatcherIndex++]);
40720b57cec5SDimitry Andric if (VT == MVT::iPTR)
40730b57cec5SDimitry Andric VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
40740b57cec5SDimitry Andric VTs.push_back(VT);
40750b57cec5SDimitry Andric }
40760b57cec5SDimitry Andric
40770b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_Chain)
40780b57cec5SDimitry Andric VTs.push_back(MVT::Other);
40790b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_GlueOutput)
40800b57cec5SDimitry Andric VTs.push_back(MVT::Glue);
40810b57cec5SDimitry Andric
40820b57cec5SDimitry Andric // This is hot code, so optimize the two most common cases of 1 and 2
40830b57cec5SDimitry Andric // results.
40840b57cec5SDimitry Andric SDVTList VTList;
40850b57cec5SDimitry Andric if (VTs.size() == 1)
40860b57cec5SDimitry Andric VTList = CurDAG->getVTList(VTs[0]);
40870b57cec5SDimitry Andric else if (VTs.size() == 2)
40880b57cec5SDimitry Andric VTList = CurDAG->getVTList(VTs[0], VTs[1]);
40890b57cec5SDimitry Andric else
40900b57cec5SDimitry Andric VTList = CurDAG->getVTList(VTs);
40910b57cec5SDimitry Andric
40920b57cec5SDimitry Andric // Get the operand list.
40930b57cec5SDimitry Andric unsigned NumOps = MatcherTable[MatcherIndex++];
40940b57cec5SDimitry Andric SmallVector<SDValue, 8> Ops;
40950b57cec5SDimitry Andric for (unsigned i = 0; i != NumOps; ++i) {
40960b57cec5SDimitry Andric unsigned RecNo = MatcherTable[MatcherIndex++];
40970b57cec5SDimitry Andric if (RecNo & 128)
40980b57cec5SDimitry Andric RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
40990b57cec5SDimitry Andric
41000b57cec5SDimitry Andric assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
41010b57cec5SDimitry Andric Ops.push_back(RecordedNodes[RecNo].first);
41020b57cec5SDimitry Andric }
41030b57cec5SDimitry Andric
41040b57cec5SDimitry Andric // If there are variadic operands to add, handle them now.
41050b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_VariadicInfo) {
41060b57cec5SDimitry Andric // Determine the start index to copy from.
41070b57cec5SDimitry Andric unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
41080b57cec5SDimitry Andric FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
41090b57cec5SDimitry Andric assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
41100b57cec5SDimitry Andric "Invalid variadic node");
41110b57cec5SDimitry Andric // Copy all of the variadic operands, not including a potential glue
41120b57cec5SDimitry Andric // input.
41130b57cec5SDimitry Andric for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
41140b57cec5SDimitry Andric i != e; ++i) {
41150b57cec5SDimitry Andric SDValue V = NodeToMatch->getOperand(i);
41160b57cec5SDimitry Andric if (V.getValueType() == MVT::Glue) break;
41170b57cec5SDimitry Andric Ops.push_back(V);
41180b57cec5SDimitry Andric }
41190b57cec5SDimitry Andric }
41200b57cec5SDimitry Andric
41210b57cec5SDimitry Andric // If this has chain/glue inputs, add them.
41220b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_Chain)
41230b57cec5SDimitry Andric Ops.push_back(InputChain);
41240b57cec5SDimitry Andric if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
41250b57cec5SDimitry Andric Ops.push_back(InputGlue);
41260b57cec5SDimitry Andric
4127480093f4SDimitry Andric // Check whether any matched node could raise an FP exception. Since all
4128480093f4SDimitry Andric // such nodes must have a chain, it suffices to check ChainNodesMatched.
4129480093f4SDimitry Andric // We need to perform this check before potentially modifying one of the
4130480093f4SDimitry Andric // nodes via MorphNode.
413181ad6265SDimitry Andric bool MayRaiseFPException =
413281ad6265SDimitry Andric llvm::any_of(ChainNodesMatched, [this](SDNode *N) {
413381ad6265SDimitry Andric return mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept();
413481ad6265SDimitry Andric });
4135480093f4SDimitry Andric
41360b57cec5SDimitry Andric // Create the node.
41370b57cec5SDimitry Andric MachineSDNode *Res = nullptr;
41385f757f3fSDimitry Andric bool IsMorphNodeTo =
41395f757f3fSDimitry Andric Opcode == OPC_MorphNodeTo ||
41405f757f3fSDimitry Andric (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2GlueOutput);
41410b57cec5SDimitry Andric if (!IsMorphNodeTo) {
41420b57cec5SDimitry Andric // If this is a normal EmitNode command, just create the new node and
41430b57cec5SDimitry Andric // add the results to the RecordedNodes list.
41440b57cec5SDimitry Andric Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
41450b57cec5SDimitry Andric VTList, Ops);
41460b57cec5SDimitry Andric
41470b57cec5SDimitry Andric // Add all the non-glue/non-chain results to the RecordedNodes list.
41480b57cec5SDimitry Andric for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
41490b57cec5SDimitry Andric if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
41500b57cec5SDimitry Andric RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
41510b57cec5SDimitry Andric nullptr));
41520b57cec5SDimitry Andric }
41530b57cec5SDimitry Andric } else {
41540b57cec5SDimitry Andric assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
41550b57cec5SDimitry Andric "NodeToMatch was removed partway through selection");
41560b57cec5SDimitry Andric SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
41570b57cec5SDimitry Andric SDNode *E) {
41580b57cec5SDimitry Andric CurDAG->salvageDebugInfo(*N);
41590b57cec5SDimitry Andric auto &Chain = ChainNodesMatched;
41600b57cec5SDimitry Andric assert((!E || !is_contained(Chain, N)) &&
41610b57cec5SDimitry Andric "Chain node replaced during MorphNode");
41625f757f3fSDimitry Andric llvm::erase(Chain, N);
41630b57cec5SDimitry Andric });
41640b57cec5SDimitry Andric Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
41650b57cec5SDimitry Andric Ops, EmitNodeInfo));
41660b57cec5SDimitry Andric }
41670b57cec5SDimitry Andric
4168480093f4SDimitry Andric // Set the NoFPExcept flag when no original matched node could
4169480093f4SDimitry Andric // raise an FP exception, but the new node potentially might.
4170480093f4SDimitry Andric if (!MayRaiseFPException && mayRaiseFPException(Res)) {
4171480093f4SDimitry Andric SDNodeFlags Flags = Res->getFlags();
4172480093f4SDimitry Andric Flags.setNoFPExcept(true);
4173480093f4SDimitry Andric Res->setFlags(Flags);
4174480093f4SDimitry Andric }
4175480093f4SDimitry Andric
41760b57cec5SDimitry Andric // If the node had chain/glue results, update our notion of the current
41770b57cec5SDimitry Andric // chain and glue.
41780b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_GlueOutput) {
41790b57cec5SDimitry Andric InputGlue = SDValue(Res, VTs.size()-1);
41800b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_Chain)
41810b57cec5SDimitry Andric InputChain = SDValue(Res, VTs.size()-2);
41820b57cec5SDimitry Andric } else if (EmitNodeInfo & OPFL_Chain)
41830b57cec5SDimitry Andric InputChain = SDValue(Res, VTs.size()-1);
41840b57cec5SDimitry Andric
41850b57cec5SDimitry Andric // If the OPFL_MemRefs glue is set on this node, slap all of the
41860b57cec5SDimitry Andric // accumulated memrefs onto it.
41870b57cec5SDimitry Andric //
41880b57cec5SDimitry Andric // FIXME: This is vastly incorrect for patterns with multiple outputs
41890b57cec5SDimitry Andric // instructions that access memory and for ComplexPatterns that match
41900b57cec5SDimitry Andric // loads.
41910b57cec5SDimitry Andric if (EmitNodeInfo & OPFL_MemRefs) {
41920b57cec5SDimitry Andric // Only attach load or store memory operands if the generated
41930b57cec5SDimitry Andric // instruction may load or store.
41940b57cec5SDimitry Andric const MCInstrDesc &MCID = TII->get(TargetOpc);
41950b57cec5SDimitry Andric bool mayLoad = MCID.mayLoad();
41960b57cec5SDimitry Andric bool mayStore = MCID.mayStore();
41970b57cec5SDimitry Andric
41980b57cec5SDimitry Andric // We expect to have relatively few of these so just filter them into a
41990b57cec5SDimitry Andric // temporary buffer so that we can easily add them to the instruction.
42000b57cec5SDimitry Andric SmallVector<MachineMemOperand *, 4> FilteredMemRefs;
42010b57cec5SDimitry Andric for (MachineMemOperand *MMO : MatchedMemRefs) {
42020b57cec5SDimitry Andric if (MMO->isLoad()) {
42030b57cec5SDimitry Andric if (mayLoad)
42040b57cec5SDimitry Andric FilteredMemRefs.push_back(MMO);
42050b57cec5SDimitry Andric } else if (MMO->isStore()) {
42060b57cec5SDimitry Andric if (mayStore)
42070b57cec5SDimitry Andric FilteredMemRefs.push_back(MMO);
42080b57cec5SDimitry Andric } else {
42090b57cec5SDimitry Andric FilteredMemRefs.push_back(MMO);
42100b57cec5SDimitry Andric }
42110b57cec5SDimitry Andric }
42120b57cec5SDimitry Andric
42130b57cec5SDimitry Andric CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
42140b57cec5SDimitry Andric }
42150b57cec5SDimitry Andric
42160b57cec5SDimitry Andric LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
42170b57cec5SDimitry Andric << " Dropping mem operands\n";
42180b57cec5SDimitry Andric dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created")
42190b57cec5SDimitry Andric << " node: ";
42200b57cec5SDimitry Andric Res->dump(CurDAG););
42210b57cec5SDimitry Andric
42220b57cec5SDimitry Andric // If this was a MorphNodeTo then we're completely done!
42230b57cec5SDimitry Andric if (IsMorphNodeTo) {
42240b57cec5SDimitry Andric // Update chain uses.
42250b57cec5SDimitry Andric UpdateChains(Res, InputChain, ChainNodesMatched, true);
42260b57cec5SDimitry Andric return;
42270b57cec5SDimitry Andric }
42280b57cec5SDimitry Andric continue;
42290b57cec5SDimitry Andric }
42300b57cec5SDimitry Andric
42310b57cec5SDimitry Andric case OPC_CompleteMatch: {
42320b57cec5SDimitry Andric // The match has been completed, and any new nodes (if any) have been
42330b57cec5SDimitry Andric // created. Patch up references to the matched dag to use the newly
42340b57cec5SDimitry Andric // created nodes.
42350b57cec5SDimitry Andric unsigned NumResults = MatcherTable[MatcherIndex++];
42360b57cec5SDimitry Andric
42370b57cec5SDimitry Andric for (unsigned i = 0; i != NumResults; ++i) {
42380b57cec5SDimitry Andric unsigned ResSlot = MatcherTable[MatcherIndex++];
42390b57cec5SDimitry Andric if (ResSlot & 128)
42400b57cec5SDimitry Andric ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
42410b57cec5SDimitry Andric
42420b57cec5SDimitry Andric assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
42430b57cec5SDimitry Andric SDValue Res = RecordedNodes[ResSlot].first;
42440b57cec5SDimitry Andric
42450b57cec5SDimitry Andric assert(i < NodeToMatch->getNumValues() &&
42460b57cec5SDimitry Andric NodeToMatch->getValueType(i) != MVT::Other &&
42470b57cec5SDimitry Andric NodeToMatch->getValueType(i) != MVT::Glue &&
42480b57cec5SDimitry Andric "Invalid number of results to complete!");
42490b57cec5SDimitry Andric assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
42500b57cec5SDimitry Andric NodeToMatch->getValueType(i) == MVT::iPTR ||
42510b57cec5SDimitry Andric Res.getValueType() == MVT::iPTR ||
42520b57cec5SDimitry Andric NodeToMatch->getValueType(i).getSizeInBits() ==
42530b57cec5SDimitry Andric Res.getValueSizeInBits()) &&
42540b57cec5SDimitry Andric "invalid replacement");
42550b57cec5SDimitry Andric ReplaceUses(SDValue(NodeToMatch, i), Res);
42560b57cec5SDimitry Andric }
42570b57cec5SDimitry Andric
42580b57cec5SDimitry Andric // Update chain uses.
42590b57cec5SDimitry Andric UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
42600b57cec5SDimitry Andric
42610b57cec5SDimitry Andric // If the root node defines glue, we need to update it to the glue result.
42620b57cec5SDimitry Andric // TODO: This never happens in our tests and I think it can be removed /
42630b57cec5SDimitry Andric // replaced with an assert, but if we do it this the way the change is
42640b57cec5SDimitry Andric // NFC.
42650b57cec5SDimitry Andric if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
42660b57cec5SDimitry Andric MVT::Glue &&
42670b57cec5SDimitry Andric InputGlue.getNode())
42680b57cec5SDimitry Andric ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
42690b57cec5SDimitry Andric InputGlue);
42700b57cec5SDimitry Andric
42710b57cec5SDimitry Andric assert(NodeToMatch->use_empty() &&
42720b57cec5SDimitry Andric "Didn't replace all uses of the node?");
42730b57cec5SDimitry Andric CurDAG->RemoveDeadNode(NodeToMatch);
42740b57cec5SDimitry Andric
42750b57cec5SDimitry Andric return;
42760b57cec5SDimitry Andric }
42770b57cec5SDimitry Andric }
42780b57cec5SDimitry Andric
42790b57cec5SDimitry Andric // If the code reached this point, then the match failed. See if there is
42800b57cec5SDimitry Andric // another child to try in the current 'Scope', otherwise pop it until we
42810b57cec5SDimitry Andric // find a case to check.
42820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
42830b57cec5SDimitry Andric << "\n");
42840b57cec5SDimitry Andric ++NumDAGIselRetries;
42850b57cec5SDimitry Andric while (true) {
42860b57cec5SDimitry Andric if (MatchScopes.empty()) {
42870b57cec5SDimitry Andric CannotYetSelect(NodeToMatch);
42880b57cec5SDimitry Andric return;
42890b57cec5SDimitry Andric }
42900b57cec5SDimitry Andric
42910b57cec5SDimitry Andric // Restore the interpreter state back to the point where the scope was
42920b57cec5SDimitry Andric // formed.
42930b57cec5SDimitry Andric MatchScope &LastScope = MatchScopes.back();
42940b57cec5SDimitry Andric RecordedNodes.resize(LastScope.NumRecordedNodes);
42950b57cec5SDimitry Andric NodeStack.clear();
42960b57cec5SDimitry Andric NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
42970b57cec5SDimitry Andric N = NodeStack.back();
42980b57cec5SDimitry Andric
42990b57cec5SDimitry Andric if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
43000b57cec5SDimitry Andric MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
43010b57cec5SDimitry Andric MatcherIndex = LastScope.FailIndex;
43020b57cec5SDimitry Andric
43030b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
43040b57cec5SDimitry Andric
43050b57cec5SDimitry Andric InputChain = LastScope.InputChain;
43060b57cec5SDimitry Andric InputGlue = LastScope.InputGlue;
43070b57cec5SDimitry Andric if (!LastScope.HasChainNodesMatched)
43080b57cec5SDimitry Andric ChainNodesMatched.clear();
43090b57cec5SDimitry Andric
43100b57cec5SDimitry Andric // Check to see what the offset is at the new MatcherIndex. If it is zero
43110b57cec5SDimitry Andric // we have reached the end of this scope, otherwise we have another child
43120b57cec5SDimitry Andric // in the current scope to try.
43130b57cec5SDimitry Andric unsigned NumToSkip = MatcherTable[MatcherIndex++];
43140b57cec5SDimitry Andric if (NumToSkip & 128)
43150b57cec5SDimitry Andric NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
43160b57cec5SDimitry Andric
43170b57cec5SDimitry Andric // If we have another child in this scope to match, update FailIndex and
43180b57cec5SDimitry Andric // try it.
43190b57cec5SDimitry Andric if (NumToSkip != 0) {
43200b57cec5SDimitry Andric LastScope.FailIndex = MatcherIndex+NumToSkip;
43210b57cec5SDimitry Andric break;
43220b57cec5SDimitry Andric }
43230b57cec5SDimitry Andric
43240b57cec5SDimitry Andric // End of this scope, pop it and try the next child in the containing
43250b57cec5SDimitry Andric // scope.
43260b57cec5SDimitry Andric MatchScopes.pop_back();
43270b57cec5SDimitry Andric }
43280b57cec5SDimitry Andric }
43290b57cec5SDimitry Andric }
43300b57cec5SDimitry Andric
4331480093f4SDimitry Andric /// Return whether the node may raise an FP exception.
mayRaiseFPException(SDNode * N) const4332480093f4SDimitry Andric bool SelectionDAGISel::mayRaiseFPException(SDNode *N) const {
4333480093f4SDimitry Andric // For machine opcodes, consult the MCID flag.
4334480093f4SDimitry Andric if (N->isMachineOpcode()) {
4335480093f4SDimitry Andric const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
4336480093f4SDimitry Andric return MCID.mayRaiseFPException();
4337480093f4SDimitry Andric }
4338480093f4SDimitry Andric
4339480093f4SDimitry Andric // For ISD opcodes, only StrictFP opcodes may raise an FP
4340480093f4SDimitry Andric // exception.
4341480093f4SDimitry Andric if (N->isTargetOpcode())
4342480093f4SDimitry Andric return N->isTargetStrictFPOpcode();
4343480093f4SDimitry Andric return N->isStrictFPOpcode();
4344480093f4SDimitry Andric }
4345480093f4SDimitry Andric
isOrEquivalentToAdd(const SDNode * N) const43460b57cec5SDimitry Andric bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
43470b57cec5SDimitry Andric assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
43480b57cec5SDimitry Andric auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
43490b57cec5SDimitry Andric if (!C)
43500b57cec5SDimitry Andric return false;
43510b57cec5SDimitry Andric
43520b57cec5SDimitry Andric // Detect when "or" is used to add an offset to a stack object.
43530b57cec5SDimitry Andric if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
43540b57cec5SDimitry Andric MachineFrameInfo &MFI = MF->getFrameInfo();
43555ffd83dbSDimitry Andric Align A = MFI.getObjectAlign(FN->getIndex());
43560b57cec5SDimitry Andric int32_t Off = C->getSExtValue();
43570b57cec5SDimitry Andric // If the alleged offset fits in the zero bits guaranteed by
43580b57cec5SDimitry Andric // the alignment, then this or is really an add.
43595ffd83dbSDimitry Andric return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
43600b57cec5SDimitry Andric }
43610b57cec5SDimitry Andric return false;
43620b57cec5SDimitry Andric }
43630b57cec5SDimitry Andric
CannotYetSelect(SDNode * N)43640b57cec5SDimitry Andric void SelectionDAGISel::CannotYetSelect(SDNode *N) {
43650b57cec5SDimitry Andric std::string msg;
43660b57cec5SDimitry Andric raw_string_ostream Msg(msg);
43670b57cec5SDimitry Andric Msg << "Cannot select: ";
43680b57cec5SDimitry Andric
43690b57cec5SDimitry Andric if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
43700b57cec5SDimitry Andric N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
43710b57cec5SDimitry Andric N->getOpcode() != ISD::INTRINSIC_VOID) {
43720b57cec5SDimitry Andric N->printrFull(Msg, CurDAG);
43730b57cec5SDimitry Andric Msg << "\nIn function: " << MF->getName();
43740b57cec5SDimitry Andric } else {
43750b57cec5SDimitry Andric bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
4376647cbc5dSDimitry Andric unsigned iid = N->getConstantOperandVal(HasInputChain);
43770b57cec5SDimitry Andric if (iid < Intrinsic::num_intrinsics)
4378fe6060f1SDimitry Andric Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
43790b57cec5SDimitry Andric else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
43800b57cec5SDimitry Andric Msg << "target intrinsic %" << TII->getName(iid);
43810b57cec5SDimitry Andric else
43820b57cec5SDimitry Andric Msg << "unknown intrinsic #" << iid;
43830b57cec5SDimitry Andric }
43840fca6ea1SDimitry Andric report_fatal_error(Twine(msg));
43850b57cec5SDimitry Andric }
4386