LLVM 24.0.0git
SelectionDAGISel.cpp
Go to the documentation of this file.
1//===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAGISel class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ScheduleDAGSDNodes.h"
15#include "SelectionDAGBuilder.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/ADT/StringRef.h"
27#include "llvm/Analysis/CFG.h"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/DebugInfo.h"
70#include "llvm/IR/DebugLoc.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/InlineAsm.h"
76#include "llvm/IR/Instruction.h"
79#include "llvm/IR/Intrinsics.h"
80#include "llvm/IR/IntrinsicsWebAssembly.h"
81#include "llvm/IR/Metadata.h"
82#include "llvm/IR/Module.h"
84#include "llvm/IR/PrintPasses.h"
85#include "llvm/IR/Statepoint.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
90#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/Pass.h"
97#include "llvm/Support/Debug.h"
100#include "llvm/Support/Timer.h"
105#include <cassert>
106#include <cstdint>
107#include <iterator>
108#include <limits>
109#include <list>
110#include <memory>
111#include <optional>
112#include <string>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117
118#define DEBUG_TYPE "isel"
119#define ISEL_DUMP_DEBUG_TYPE DEBUG_TYPE "-dump"
120
121STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
122STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
123STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
124STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
125STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
126STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
127STATISTIC(NumFastIselFailLowerArguments,
128 "Number of entry blocks where fast isel failed to lower arguments");
129
131 "fast-isel-abort", cl::Hidden,
132 cl::desc("Enable abort calls when \"fast\" instruction selection "
133 "fails to lower an instruction: 0 disable the abort, 1 will "
134 "abort but for args, calls and terminators, 2 will also "
135 "abort for argument lowering, and 3 will never fallback "
136 "to SelectionDAG."));
137
139 "fast-isel-report-on-fallback", cl::Hidden,
140 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
141 "falls back to SelectionDAG."));
142
143static cl::opt<bool>
144UseMBPI("use-mbpi",
145 cl::desc("use Machine Branch Probability Info"),
146 cl::init(true), cl::Hidden);
147
148#ifndef NDEBUG
149static cl::opt<bool>
150 DumpSortedDAG("dump-sorted-dags", cl::Hidden,
151 cl::desc("Print DAGs with sorted nodes in debug dump"),
152 cl::init(false));
153
156 cl::desc("Only display the basic block whose name "
157 "matches this for all view-*-dags options"));
158static cl::opt<bool>
159ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
160 cl::desc("Pop up a window to show dags before the first "
161 "dag combine pass"));
162static cl::opt<bool>
163ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
164 cl::desc("Pop up a window to show dags before legalize types"));
165static cl::opt<bool>
166 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
167 cl::desc("Pop up a window to show dags before the post "
168 "legalize types dag combine pass"));
169static cl::opt<bool>
170 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
171 cl::desc("Pop up a window to show dags before legalize"));
172static cl::opt<bool>
173ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
174 cl::desc("Pop up a window to show dags before the second "
175 "dag combine pass"));
176static cl::opt<bool>
177ViewISelDAGs("view-isel-dags", cl::Hidden,
178 cl::desc("Pop up a window to show isel dags as they are selected"));
179static cl::opt<bool>
180ViewSchedDAGs("view-sched-dags", cl::Hidden,
181 cl::desc("Pop up a window to show sched dags as they are processed"));
182static cl::opt<bool>
183ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
184 cl::desc("Pop up a window to show SUnit dags after they are processed"));
185#else
186static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
187 ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
188 ViewDAGCombine2 = false, ViewISelDAGs = false,
189 ViewSchedDAGs = false, ViewSUnitDAGs = false;
190#endif
191
192#ifndef NDEBUG
193#define ISEL_DUMP(X) \
194 do { \
195 if (llvm::DebugFlag && \
196 (isCurrentDebugType(DEBUG_TYPE) || \
197 (isCurrentDebugType(ISEL_DUMP_DEBUG_TYPE) && MatchFilterFuncName))) { \
198 X; \
199 } \
200 } while (false)
201#else
202#define ISEL_DUMP(X) do { } while (false)
203#endif
204
205//===---------------------------------------------------------------------===//
206///
207/// RegisterScheduler class - Track the registration of instruction schedulers.
208///
209//===---------------------------------------------------------------------===//
212
213//===---------------------------------------------------------------------===//
214///
215/// ISHeuristic command line option for instruction schedulers.
216///
217//===---------------------------------------------------------------------===//
220ISHeuristic("pre-RA-sched",
222 cl::desc("Instruction schedulers available (before register"
223 " allocation):"));
224
226defaultListDAGScheduler("default", "Best scheduler for the target",
228
229static bool dontUseFastISelFor(const Function &Fn) {
230 // Don't enable FastISel for functions with swiftasync Arguments.
231 // Debug info on those is reliant on good Argument lowering, and FastISel is
232 // not capable of lowering the entire function. Mixing the two selectors tend
233 // to result in poor lowering of Arguments.
234 return any_of(Fn.args(), [](const Argument &Arg) {
235 return Arg.hasAttribute(Attribute::AttrKind::SwiftAsync);
236 });
237}
238
239static bool maintainPGOProfile(const TargetMachine &TM,
240 CodeGenOptLevel OptLevel) {
241 if (OptLevel != CodeGenOptLevel::None)
242 return true;
243 if (TM.getPGOOption()) {
244 const PGOOptions &Options = *TM.getPGOOption();
245 return Options.Action == PGOOptions::PGOAction::IRUse ||
248 }
249 return false;
250}
251
252namespace llvm {
253
254 //===--------------------------------------------------------------------===//
255 /// This class is used by SelectionDAGISel to temporarily override
256 /// the optimization level on a per-function basis.
259 CodeGenOptLevel SavedOptLevel;
260 bool SavedFastISel;
261
262 public:
264 : IS(ISel) {
265 SavedOptLevel = IS.OptLevel;
266 SavedFastISel = IS.TM.Options.EnableFastISel;
267 if (NewOptLevel != SavedOptLevel) {
268 IS.OptLevel = NewOptLevel;
269 IS.TM.setOptLevel(NewOptLevel);
270 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
271 << IS.MF->getFunction().getName() << "\n");
272 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(SavedOptLevel)
273 << " ; After: -O" << static_cast<int>(NewOptLevel)
274 << "\n");
275 if (NewOptLevel == CodeGenOptLevel::None)
276 IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
277 }
278 if (dontUseFastISelFor(IS.MF->getFunction()))
279 IS.TM.setFastISel(false);
281 dbgs() << "\tFastISel is "
282 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
283 << "\n");
284 }
285
287 if (IS.OptLevel == SavedOptLevel)
288 return;
289 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
290 << IS.MF->getFunction().getName() << "\n");
291 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(IS.OptLevel)
292 << " ; After: -O" << static_cast<int>(SavedOptLevel) << "\n");
293 IS.OptLevel = SavedOptLevel;
294 IS.TM.setOptLevel(SavedOptLevel);
295 IS.TM.setFastISel(SavedFastISel);
296 }
297 };
298
299 //===--------------------------------------------------------------------===//
300 /// createDefaultScheduler - This creates an instruction scheduler appropriate
301 /// for the target.
303 CodeGenOptLevel OptLevel) {
304 const TargetLowering *TLI = IS->TLI;
305 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
306
307 // Try first to see if the Target has its own way of selecting a scheduler
308 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
309 return SchedulerCtor(IS, OptLevel);
310 }
311
312 if (OptLevel == CodeGenOptLevel::None ||
313 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
314 TLI->getSchedulingPreference() == Sched::Source)
315 return createSourceListDAGScheduler(IS, OptLevel);
316 if (TLI->getSchedulingPreference() == Sched::RegPressure)
317 return createBURRListDAGScheduler(IS, OptLevel);
318 if (TLI->getSchedulingPreference() == Sched::Hybrid)
319 return createHybridListDAGScheduler(IS, OptLevel);
320 if (TLI->getSchedulingPreference() == Sched::VLIW)
321 return createVLIWDAGScheduler(IS, OptLevel);
322 if (TLI->getSchedulingPreference() == Sched::Fast)
323 return createFastDAGScheduler(IS, OptLevel);
324 if (TLI->getSchedulingPreference() == Sched::Linearize)
325 return createDAGLinearizer(IS, OptLevel);
326 assert(TLI->getSchedulingPreference() == Sched::ILP &&
327 "Unknown sched type!");
328 return createILPListDAGScheduler(IS, OptLevel);
329 }
330
331} // end namespace llvm
332
335 MachineBasicBlock *MBB) const {
336 switch (MI.getOpcode()) {
337 case TargetOpcode::STATEPOINT:
338 // As an implementation detail, STATEPOINT shares the STACKMAP format at
339 // this point in the process. We diverge later.
340 case TargetOpcode::STACKMAP:
341 case TargetOpcode::PATCHPOINT:
342 return emitPatchPoint(MI, MBB);
343 default:
344 break;
345 }
346
347#ifndef NDEBUG
348 dbgs() << "If a target marks an instruction with "
349 "'usesCustomInserter', it must implement "
350 "TargetLowering::EmitInstrWithCustomInserter!\n";
351#endif
352 llvm_unreachable(nullptr);
353}
354
356 SDNode *Node) const {
357 assert(!MI.hasPostISelHook() &&
358 "If a target marks an instruction with 'hasPostISelHook', "
359 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
360}
361
362//===----------------------------------------------------------------------===//
363// SelectionDAGISel code
364//===----------------------------------------------------------------------===//
365
374
376 // If we already selected that function, we do not need to run SDISel.
377 if (MF.getProperties().hasSelected())
378 return false;
379
380 // Do some sanity-checking on the command-line options.
381 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
382 reportFatalUsageError("-fast-isel-abort > 0 requires -fast-isel");
383
384 // Decide what flavour of variable location debug-info will be used, before
385 // we change the optimisation level.
387
388 // Reset OptLevel to None for optnone functions.
389 CodeGenOptLevel NewOptLevel = skipFunction(MF.getFunction())
391 : Selector->OptLevel;
392
393 Selector->MF = &MF;
394 OptLevelChanger OLC(*Selector, NewOptLevel);
395 Selector->initializeAnalysisResults(*this);
396 return Selector->runOnMachineFunction(MF);
397}
398
411
413
415 CodeGenOptLevel OptLevel = Selector->OptLevel;
416 bool RegisterPGOPasses = maintainPGOProfile(Selector->TM, Selector->OptLevel);
417 if (OptLevel != CodeGenOptLevel::None)
425 if (UseMBPI && RegisterPGOPasses)
428 // AssignmentTrackingAnalysis only runs if assignment tracking is enabled for
429 // the module.
432 if (RegisterPGOPasses)
434
436
438}
439
443 // If we already selected that function, we do not need to run SDISel.
444 if (MF.getProperties().hasSelected())
445 return PreservedAnalyses::all();
446
447 // Do some sanity-checking on the command-line options.
448 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
449 reportFatalUsageError("-fast-isel-abort > 0 requires -fast-isel");
450
451 // Decide what flavour of variable location debug-info will be used, before
452 // we change the optimisation level.
454
455 // Reset OptLevel to None for optnone functions or when opt-bisect skips.
456 // TODO: Add a function analysis to handle this.
457 Selector->MF = &MF;
458 CodeGenOptLevel NewOptLevel =
459 (MF.getFunction().hasOptNone() ||
462 : Selector->OptLevel;
463
464 OptLevelChanger OLC(*Selector, NewOptLevel);
465 Selector->initializeAnalysisResults(MFAM);
466 Selector->runOnMachineFunction(MF);
467
469}
470
474 .getManager();
476 Function &Fn = MF->getFunction();
477#ifndef NDEBUG
478 FuncName = Fn.getName();
480#else
482#endif
483
484 const TargetSubtargetInfo &Subtarget = MF->getSubtarget();
485 bool RegisterPGOPasses = maintainPGOProfile(TM, OptLevel);
486 TII = Subtarget.getInstrInfo();
487 TLI = Subtarget.getTargetLowering();
488 RegInfo = &MF->getRegInfo();
489 LibInfo = &FAM.getResult<TargetLibraryAnalysis>(Fn);
490
491 GFI = Fn.hasGC() ? &FAM.getResult<GCFunctionAnalysis>(Fn) : nullptr;
492 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
493 AC = &FAM.getResult<AssumptionAnalysis>(Fn);
494 auto *PSI = MAMP.getCachedResult<ProfileSummaryAnalysis>(*Fn.getParent());
495 BlockFrequencyInfo *BFI = nullptr;
496 if (PSI && PSI->hasProfileSummary() && RegisterPGOPasses)
497 BFI = &FAM.getResult<BlockFrequencyAnalysis>(Fn);
498
499 FunctionVarLocs const *FnVarLocs = nullptr;
501 FnVarLocs = &FAM.getResult<DebugAssignmentTrackingAnalysis>(Fn);
502
503 auto *UA = FAM.getCachedResult<UniformityInfoAnalysis>(Fn);
504
505 const ModuleLibcallLoweringInfo *LibcallResult =
506 MAMP.getCachedResult<LibcallLoweringModuleAnalysis>(*Fn.getParent());
507 if (!LibcallResult) {
509 "' analysis required");
510 }
511
512 LibcallLowering = &getLibcallLowering(*LibcallResult, Subtarget);
513 CurDAG->init(*MF, MFAM, LibInfo, LibcallLowering, UA, PSI, BFI, FnVarLocs);
514
515 // Now get the optional analyzes if we want to.
516 // This is based on the possibly changed OptLevel (after optnone is taken
517 // into account). That's unfortunate but OK because it just means we won't
518 // ask for passes that have been required anyway.
519
520 if (UseMBPI && RegisterPGOPasses)
521 FuncInfo->BPI = &FAM.getResult<BranchProbabilityAnalysis>(Fn);
522 else
523 FuncInfo->BPI = nullptr;
524
526 BatchAA.emplace(FAM.getResult<AAManager>(Fn));
527 else
528 BatchAA = std::nullopt;
529
530 SP = &FAM.getResult<SSPLayoutAnalysis>(Fn);
531
532 TTI = &FAM.getResult<TargetIRAnalysis>(Fn);
533
534 HwMode = Subtarget.getHwMode();
535}
536
538 Function &Fn = MF->getFunction();
539#ifndef NDEBUG
540 FuncName = Fn.getName();
542#else
544#endif
545
546 const TargetSubtargetInfo &Subtarget = MF->getSubtarget();
547
548 bool RegisterPGOPasses = maintainPGOProfile(TM, OptLevel);
549 TII = Subtarget.getInstrInfo();
550 TLI = Subtarget.getTargetLowering();
551 RegInfo = &MF->getRegInfo();
553
554 GFI = Fn.hasGC() ? &MFP.getAnalysis<GCModuleInfo>().getFunctionInfo(Fn)
555 : nullptr;
556 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
557 AC = &MFP.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(Fn);
558 auto *PSI = &MFP.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
559 BlockFrequencyInfo *BFI = nullptr;
560 if (PSI && PSI->hasProfileSummary() && RegisterPGOPasses)
561 BFI = &MFP.getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
562
563 FunctionVarLocs const *FnVarLocs = nullptr;
565 FnVarLocs = MFP.getAnalysis<AssignmentTrackingAnalysis>().getResults();
566
567 UniformityInfo *UA = nullptr;
568 if (auto *UAPass = MFP.getAnalysisIfAvailable<UniformityInfoWrapperPass>())
569 UA = &UAPass->getUniformityInfo();
570
573 *Fn.getParent(), Subtarget);
574
575 CurDAG->init(*MF, LibInfo, LibcallLowering, UA, PSI, BFI, FnVarLocs);
576
577 // Now get the optional analyzes if we want to.
578 // This is based on the possibly changed OptLevel (after optnone is taken
579 // into account). That's unfortunate but OK because it just means we won't
580 // ask for passes that have been required anyway.
581
582 if (UseMBPI && RegisterPGOPasses)
583 FuncInfo->BPI =
585 else
586 FuncInfo->BPI = nullptr;
587
590 else
591 BatchAA = std::nullopt;
592
593 SP = &MFP.getAnalysis<StackProtector>().getLayoutInfo();
594
596
597 HwMode = Subtarget.getHwMode();
598}
599
601 SwiftError->setFunction(mf);
602 const Function &Fn = mf.getFunction();
603
604 bool InstrRef = mf.useDebugInstrRef();
605
606 FuncInfo->set(MF->getFunction(), *MF, CurDAG);
607
608 ISEL_DUMP(dbgs() << "\n\n\n=== " << FuncName << '\n');
609
610 SDB->init(GFI, getBatchAA(), AC, LibInfo, *TTI);
611
612 MF->setHasInlineAsm(false);
613
614 FuncInfo->SplitCSR = false;
615
616 // We split CSR if the target supports it for the given function
617 // and the function has only return exits.
618 if (OptLevel != CodeGenOptLevel::None && TLI->supportSplitCSR(MF)) {
619 FuncInfo->SplitCSR = true;
620
621 // Collect all the return blocks.
622 for (const BasicBlock &BB : Fn) {
623 if (!succ_empty(&BB))
624 continue;
625
626 const Instruction *Term = BB.getTerminator();
627 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
628 continue;
629
630 // Bail out if the exit block is not Return nor Unreachable.
631 FuncInfo->SplitCSR = false;
632 break;
633 }
634 }
635
636 MachineBasicBlock *EntryMBB = &MF->front();
637 if (FuncInfo->SplitCSR)
638 // This performs initialization so lowering for SplitCSR will be correct.
639 TLI->initializeSplitCSR(EntryMBB);
640
641 SelectAllBasicBlocks(Fn);
643 DiagnosticInfoISelFallback DiagFallback(Fn);
644 Fn.getContext().diagnose(DiagFallback);
645 }
646
647 // Replace forward-declared registers with the registers containing
648 // the desired value.
649 // Note: it is important that this happens **before** the call to
650 // EmitLiveInCopies, since implementations can skip copies of unused
651 // registers. If we don't apply the reg fixups before, some registers may
652 // appear as unused and will be skipped, resulting in bad MI.
653 MachineRegisterInfo &MRI = MF->getRegInfo();
654 for (auto I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
655 I != E; ++I) {
656 Register From = I->first;
657 Register To = I->second;
658 // If To is also scheduled to be replaced, find what its ultimate
659 // replacement is.
660 while (true) {
661 auto J = FuncInfo->RegFixups.find(To);
662 if (J == E)
663 break;
664 To = J->second;
665 }
666 // Make sure the new register has a sufficiently constrained register class.
667 if (From.isVirtual() && To.isVirtual())
668 MRI.constrainRegClass(To, MRI.getRegClass(From));
669 // Replace it.
670 MRI.replaceRegWith(From, To);
671 }
672
673 // If the first basic block in the function has live ins that need to be
674 // copied into vregs, emit the copies into the top of the block before
675 // emitting the code for the block.
676 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
677 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
678
679 // Insert copies in the entry block and the return blocks.
680 if (FuncInfo->SplitCSR) {
682 // Collect all the return blocks.
683 for (MachineBasicBlock &MBB : mf) {
684 if (!MBB.succ_empty())
685 continue;
686
687 MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
688 if (Term != MBB.end() && Term->isReturn()) {
689 Returns.push_back(&MBB);
690 continue;
691 }
692 }
693 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
694 }
695
697 if (!FuncInfo->ArgDbgValues.empty())
698 for (std::pair<MCRegister, Register> LI : RegInfo->liveins())
699 if (LI.second)
700 LiveInMap.insert(LI);
701
702 // Insert DBG_VALUE instructions for function arguments to the entry block.
703 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
704 MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
705 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
706 "Function parameters should not be described by DBG_VALUE_LIST.");
707 bool hasFI = MI->getDebugOperand(0).isFI();
708 Register Reg =
709 hasFI ? TRI.getFrameRegister(*MF) : MI->getDebugOperand(0).getReg();
710 if (Reg.isPhysical())
711 EntryMBB->insert(EntryMBB->begin(), MI);
712 else {
713 MachineInstr *Def = RegInfo->getVRegDef(Reg);
714 if (Def) {
715 MachineBasicBlock::iterator InsertPos = Def;
716 // FIXME: VR def may not be in entry block.
717 Def->getParent()->insert(std::next(InsertPos), MI);
718 } else
719 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
720 << printReg(Reg) << '\n');
721 }
722
723 // Don't try and extend through copies in instruction referencing mode.
724 if (InstrRef)
725 continue;
726
727 // If Reg is live-in then update debug info to track its copy in a vreg.
728 if (!Reg.isPhysical())
729 continue;
730 auto LDI = LiveInMap.find(Reg);
731 if (LDI != LiveInMap.end()) {
732 assert(!hasFI && "There's no handling of frame pointer updating here yet "
733 "- add if needed");
734 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
735 MachineBasicBlock::iterator InsertPos = Def;
736 const MDNode *Variable = MI->getDebugVariable();
737 const MDNode *Expr = MI->getDebugExpression();
738 DebugLoc DL = MI->getDebugLoc();
739 bool IsIndirect = MI->isIndirectDebugValue();
740 if (IsIndirect)
741 assert(MI->getDebugOffset().getImm() == 0 &&
742 "DBG_VALUE with nonzero offset");
743 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
744 "Expected inlined-at fields to agree");
745 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
746 "Didn't expect to see a DBG_VALUE_LIST here");
747 // Def is never a terminator here, so it is ok to increment InsertPos.
748 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
749 IsIndirect, LDI->second, Variable, Expr);
750
751 // If this vreg is directly copied into an exported register then
752 // that COPY instructions also need DBG_VALUE, if it is the only
753 // user of LDI->second.
754 MachineInstr *CopyUseMI = nullptr;
755 for (MachineInstr &UseMI : RegInfo->use_instructions(LDI->second)) {
756 if (UseMI.isDebugValue())
757 continue;
758 if (UseMI.isCopy() && !CopyUseMI && UseMI.getParent() == EntryMBB) {
759 CopyUseMI = &UseMI;
760 continue;
761 }
762 // Otherwise this is another use or second copy use.
763 CopyUseMI = nullptr;
764 break;
765 }
766 if (CopyUseMI &&
767 TRI.getRegSizeInBits(LDI->second, MRI) ==
768 TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
769 // Use MI's debug location, which describes where Variable was
770 // declared, rather than whatever is attached to CopyUseMI.
771 MachineInstr *NewMI =
772 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
773 CopyUseMI->getOperand(0).getReg(), Variable, Expr);
774 MachineBasicBlock::iterator Pos = CopyUseMI;
775 EntryMBB->insertAfter(Pos, NewMI);
776 }
777 }
778 }
779
780 // For debug-info, in instruction referencing mode, we need to perform some
781 // post-isel maintenence.
782 if (MF->useDebugInstrRef())
783 MF->finalizeDebugInstrRefs();
784
785 // Determine if there are any calls in this machine function.
786 MachineFrameInfo &MFI = MF->getFrameInfo();
787 for (const auto &MBB : *MF) {
788 if (MFI.hasCalls() && MF->hasInlineAsm())
789 break;
790
791 for (const auto &MI : MBB) {
792 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
793 if ((MCID.isCall() && !MCID.isReturn()) ||
794 MI.isStackAligningInlineAsm()) {
795 MFI.setHasCalls(true);
796 }
797 if (MI.isInlineAsm()) {
798 MF->setHasInlineAsm(true);
799 }
800 }
801 }
802
803 // Release function-specific state. SDB and CurDAG are already cleared
804 // at this point.
805 FuncInfo->clear();
806
807 ISEL_DUMP(dbgs() << "*** MachineFunction at end of ISel ***\n");
808 ISEL_DUMP(MF->print(dbgs()));
809
810 return true;
811}
812
816 bool ShouldAbort) {
817 // Print the function name explicitly if we don't have a debug location (which
818 // makes the diagnostic less useful) or if we're going to emit a raw error.
819 if (!R.getLocation().isValid() || ShouldAbort)
820 R << (" (in function: " + MF.getName() + ")").str();
821
822 if (ShouldAbort)
823 reportFatalUsageError(Twine(R.getMsg()));
824
825 ORE.emit(R);
826 LLVM_DEBUG(dbgs() << R.getMsg() << "\n");
827}
828
829// Detect any fake uses that follow a tail call and move them before the tail
830// call. Ignore fake uses that use values that are def'd by or after the tail
831// call.
835 if (--I == Begin || !isa<ReturnInst>(*I))
836 return;
837 // Detect whether there are any fake uses trailing a (potential) tail call.
838 bool HaveFakeUse = false;
839 bool HaveTailCall = false;
840 do {
841 if (const CallInst *CI = dyn_cast<CallInst>(--I))
842 if (CI->isTailCall()) {
843 HaveTailCall = true;
844 break;
845 }
847 if (II->getIntrinsicID() == Intrinsic::fake_use)
848 HaveFakeUse = true;
849 } while (I != Begin);
850
851 // If we didn't find any tail calls followed by fake uses, we are done.
852 if (!HaveTailCall || !HaveFakeUse)
853 return;
854
856 // Record the fake uses we found so we can move them to the front of the
857 // tail call. Ignore them if they use a value that is def'd by or after
858 // the tail call.
859 for (BasicBlock::iterator Inst = I; Inst != End; Inst++) {
860 if (IntrinsicInst *FakeUse = dyn_cast<IntrinsicInst>(Inst);
861 FakeUse && FakeUse->getIntrinsicID() == Intrinsic::fake_use) {
862 if (auto UsedDef = dyn_cast<Instruction>(FakeUse->getOperand(0));
863 !UsedDef || UsedDef->getParent() != I->getParent() ||
864 UsedDef->comesBefore(&*I))
865 FakeUses.push_back(FakeUse);
866 }
867 }
868
869 for (auto *Inst : FakeUses)
870 Inst->moveBefore(*Inst->getParent(), I);
871}
872
873void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
875 bool &HadTailCall) {
876 // Allow creating illegal types during DAG building for the basic block.
877 CurDAG->NewNodesMustHaveLegalTypes = false;
878
879 // Lower the instructions. If a call is emitted as a tail call, cease emitting
880 // nodes for this block. If an instruction is elided, don't emit it, but do
881 // handle any debug-info attached to it.
882 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
883 if (!ElidedArgCopyInstrs.count(&*I))
884 SDB->visit(*I);
885 else
886 SDB->visitDbgInfo(*I);
887 }
888
889 // Make sure the root of the DAG is up-to-date.
890 CurDAG->setRoot(SDB->getControlRoot());
891 HadTailCall = SDB->HasTailCall;
892 SDB->resolveOrClearDbgInfo();
893 SDB->clear();
894
895 // Final step, emit the lowered DAG as machine code.
896 CodeGenAndEmitDAG();
897}
898
899void SelectionDAGISel::ComputeLiveOutVRegInfo() {
900 SmallPtrSet<SDNode *, 16> Added;
902
903 Worklist.push_back(CurDAG->getRoot().getNode());
904 Added.insert(CurDAG->getRoot().getNode());
905
906 KnownBits Known;
907
908 do {
909 SDNode *N = Worklist.pop_back_val();
910
911 // Otherwise, add all chain operands to the worklist.
912 for (const SDValue &Op : N->op_values())
913 if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
914 Worklist.push_back(Op.getNode());
915
916 // If this is a CopyToReg with a vreg dest, process it.
917 if (N->getOpcode() != ISD::CopyToReg)
918 continue;
919
920 Register DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
921 if (!DestReg.isVirtual())
922 continue;
923
924 // Ignore non-integer values.
925 SDValue Src = N->getOperand(2);
926 EVT SrcVT = Src.getValueType();
927 if (!SrcVT.isInteger())
928 continue;
929
930 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
931 Known = CurDAG->computeKnownBits(Src);
932 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
933 } while (!Worklist.empty());
934}
935
936void SelectionDAGISel::CodeGenAndEmitDAG() {
937 StringRef GroupName = "sdag";
938 StringRef GroupDescription = "Instruction Selection and Scheduling";
939 std::string BlockName;
940 bool MatchFilterBB = false;
941 (void)MatchFilterBB;
942
943 // Pre-type legalization allow creation of any node types.
944 CurDAG->NewNodesMustHaveLegalTypes = false;
945
946#ifndef NDEBUG
947 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
949 FuncInfo->MBB->getBasicBlock()->getName());
950#endif
951#ifdef NDEBUG
955#endif
956 {
957 BlockName =
958 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
959 }
960 ISEL_DUMP(dbgs() << "\nInitial selection DAG: "
961 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
962 << "'\n";
963 CurDAG->dump(DumpSortedDAG));
964
965#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
966 if (TTI->hasBranchDivergence())
967 CurDAG->VerifyDAGDivergence();
968#endif
969
970 if (ViewDAGCombine1 && MatchFilterBB)
971 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
972
973 // Run the DAG combiner in pre-legalize mode.
974 {
975 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
976 GroupDescription, TimePassesIsEnabled);
978 }
979
980 ISEL_DUMP(dbgs() << "\nOptimized lowered selection DAG: "
981 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
982 << "'\n";
983 CurDAG->dump(DumpSortedDAG));
984
985#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
986 if (TTI->hasBranchDivergence())
987 CurDAG->VerifyDAGDivergence();
988#endif
989
990 // Second step, hack on the DAG until it only uses operations and types that
991 // the target supports.
992 if (ViewLegalizeTypesDAGs && MatchFilterBB)
993 CurDAG->viewGraph("legalize-types input for " + BlockName);
994
995 bool Changed;
996 {
997 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
998 GroupDescription, TimePassesIsEnabled);
999 Changed = CurDAG->LegalizeTypes();
1000 }
1001
1002 ISEL_DUMP(dbgs() << "\nType-legalized selection DAG: "
1003 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1004 << "'\n";
1005 CurDAG->dump(DumpSortedDAG));
1006
1007#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1008 if (TTI->hasBranchDivergence())
1009 CurDAG->VerifyDAGDivergence();
1010#endif
1011
1012 // Only allow creation of legal node types.
1013 CurDAG->NewNodesMustHaveLegalTypes = true;
1014
1015 if (Changed) {
1016 if (ViewDAGCombineLT && MatchFilterBB)
1017 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
1018
1019 // Run the DAG combiner in post-type-legalize mode.
1020 {
1021 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
1022 GroupName, GroupDescription, TimePassesIsEnabled);
1024 }
1025
1026 ISEL_DUMP(dbgs() << "\nOptimized type-legalized selection DAG: "
1027 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1028 << "'\n";
1029 CurDAG->dump(DumpSortedDAG));
1030
1031#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1032 if (TTI->hasBranchDivergence())
1033 CurDAG->VerifyDAGDivergence();
1034#endif
1035 }
1036
1037 {
1038 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
1039 GroupDescription, TimePassesIsEnabled);
1040 Changed = CurDAG->LegalizeVectors();
1041 }
1042
1043 if (Changed) {
1044 ISEL_DUMP(dbgs() << "\nVector-legalized selection DAG: "
1045 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1046 << "'\n";
1047 CurDAG->dump(DumpSortedDAG));
1048
1049#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1050 if (TTI->hasBranchDivergence())
1051 CurDAG->VerifyDAGDivergence();
1052#endif
1053
1054 {
1055 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
1056 GroupDescription, TimePassesIsEnabled);
1057 CurDAG->LegalizeTypes();
1058 }
1059
1060 ISEL_DUMP(dbgs() << "\nVector/type-legalized selection DAG: "
1061 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1062 << "'\n";
1063 CurDAG->dump(DumpSortedDAG));
1064
1065#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1066 if (TTI->hasBranchDivergence())
1067 CurDAG->VerifyDAGDivergence();
1068#endif
1069
1070 if (ViewDAGCombineLT && MatchFilterBB)
1071 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
1072
1073 // Run the DAG combiner in post-type-legalize mode.
1074 {
1075 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
1076 GroupName, GroupDescription, TimePassesIsEnabled);
1078 }
1079
1080 ISEL_DUMP(dbgs() << "\nOptimized vector-legalized selection DAG: "
1081 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1082 << "'\n";
1083 CurDAG->dump(DumpSortedDAG));
1084
1085#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1086 if (TTI->hasBranchDivergence())
1087 CurDAG->VerifyDAGDivergence();
1088#endif
1089 }
1090
1091 if (ViewLegalizeDAGs && MatchFilterBB)
1092 CurDAG->viewGraph("legalize input for " + BlockName);
1093
1094 {
1095 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
1096 GroupDescription, TimePassesIsEnabled);
1097 CurDAG->Legalize();
1098 }
1099
1100 ISEL_DUMP(dbgs() << "\nLegalized selection DAG: "
1101 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1102 << "'\n";
1103 CurDAG->dump(DumpSortedDAG));
1104
1105#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1106 if (TTI->hasBranchDivergence())
1107 CurDAG->VerifyDAGDivergence();
1108#endif
1109
1110 if (ViewDAGCombine2 && MatchFilterBB)
1111 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
1112
1113 // Run the DAG combiner in post-legalize mode.
1114 {
1115 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
1116 GroupDescription, TimePassesIsEnabled);
1118 }
1119
1120 ISEL_DUMP(dbgs() << "\nOptimized legalized selection DAG: "
1121 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1122 << "'\n";
1123 CurDAG->dump(DumpSortedDAG));
1124
1125#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1126 if (TTI->hasBranchDivergence())
1127 CurDAG->VerifyDAGDivergence();
1128#endif
1129
1131 ComputeLiveOutVRegInfo();
1132
1133 if (ViewISelDAGs && MatchFilterBB)
1134 CurDAG->viewGraph("isel input for " + BlockName);
1135
1136 // Third, instruction select all of the operations to machine code, adding the
1137 // code to the MachineBasicBlock.
1138 {
1139 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
1140 GroupDescription, TimePassesIsEnabled);
1141 DoInstructionSelection();
1142 }
1143
1144 ISEL_DUMP(dbgs() << "\nSelected selection DAG: "
1145 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1146 << "'\n";
1147 CurDAG->dump(DumpSortedDAG));
1148
1149 if (ViewSchedDAGs && MatchFilterBB)
1150 CurDAG->viewGraph("scheduler input for " + BlockName);
1151
1152 // Schedule machine code.
1153 if (!Scheduler)
1154 Scheduler.reset(CreateScheduler());
1155 {
1156 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
1157 GroupDescription, TimePassesIsEnabled);
1158 Scheduler->Run(CurDAG, FuncInfo->MBB);
1159 }
1160
1161 if (ViewSUnitDAGs && MatchFilterBB)
1162 Scheduler->viewGraph();
1163
1164 // Emit machine code to BB. This can change 'BB' to the last block being
1165 // inserted into.
1166 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
1167 {
1168 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
1169 GroupDescription, TimePassesIsEnabled);
1170
1171 // FuncInfo->InsertPt is passed by reference and set to the end of the
1172 // scheduled instructions.
1173 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
1174 }
1175
1176 // If the block was split, make sure we update any references that are used to
1177 // update PHI nodes later on.
1178 if (FirstMBB != LastMBB)
1179 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
1180
1181 // Free the SelectionDAG state, now that we're finished with it.
1182 CurDAG->clear();
1183}
1184
1185namespace {
1186
1187/// ISelUpdater - helper class to handle updates of the instruction selection
1188/// graph.
1189class ISelUpdater : public SelectionDAG::DAGUpdateListener {
1190 SelectionDAG::allnodes_iterator &ISelPosition;
1191
1192public:
1193 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1194 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1195
1196 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1197 /// deleted is the current ISelPosition node, update ISelPosition.
1198 ///
1199 void NodeDeleted(SDNode *N, SDNode *E) override {
1200 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1201 ++ISelPosition;
1202 }
1203
1204 /// NodeInserted - Handle new nodes inserted into the graph: propagate
1205 /// metadata from root nodes that also applies to new nodes, in case the root
1206 /// is later deleted.
1207 void NodeInserted(SDNode *N) override {
1208 SDNode *CurNode = &*ISelPosition;
1209 if (MDNode *MD = DAG.getPCSections(CurNode))
1210 DAG.addPCSections(N, MD);
1211 if (MDNode *MMRA = DAG.getMMRAMetadata(CurNode))
1212 DAG.addMMRAMetadata(N, MMRA);
1213 }
1214};
1215
1216} // end anonymous namespace
1217
1218// This function is used to enforce the topological node id property
1219// leveraged during instruction selection. Before the selection process all
1220// nodes are given a non-negative id such that all nodes have a greater id than
1221// their operands. As this holds transitively we can prune checks that a node N
1222// is a predecessor of M another by not recursively checking through M's
1223// operands if N's ID is larger than M's ID. This significantly improves
1224// performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
1225
1226// However, when we fuse multiple nodes into a single node during the
1227// selection we may induce a predecessor relationship between inputs and
1228// outputs of distinct nodes being merged, violating the topological property.
1229// Should a fused node have a successor which has yet to be selected,
1230// our legality checks would be incorrect. To avoid this we mark all unselected
1231// successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
1232// (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1233// We use bit-negation to more clearly enforce that node id -1 can only be
1234// achieved by selected nodes. As the conversion is reversable to the original
1235// Id, topological pruning can still be leveraged when looking for unselected
1236// nodes. This method is called internally in all ISel replacement related
1237// functions.
1240 Nodes.push_back(Node);
1241
1242 while (!Nodes.empty()) {
1243 SDNode *N = Nodes.pop_back_val();
1244 for (auto *U : N->users()) {
1245 auto UId = U->getNodeId();
1246 if (UId > 0) {
1248 Nodes.push_back(U);
1249 }
1250 }
1251 }
1252}
1253
1254// InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
1255// NodeId with the equivalent node id which is invalid for topological
1256// pruning.
1258 int InvalidId = -(N->getNodeId() + 1);
1259 N->setNodeId(InvalidId);
1260}
1261
1262// getUninvalidatedNodeId - get original uninvalidated node id.
1264 int Id = N->getNodeId();
1265 if (Id < -1)
1266 return -(Id + 1);
1267 return Id;
1268}
1269
1270void SelectionDAGISel::DoInstructionSelection() {
1271 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1272 << printMBBReference(*FuncInfo->MBB) << " '"
1273 << FuncInfo->MBB->getName() << "'\n");
1274
1276
1277 // Select target instructions for the DAG.
1278 {
1279 // Number all nodes with a topological order and set DAGSize.
1281
1282 // Create a dummy node (which is not added to allnodes), that adds
1283 // a reference to the root node, preventing it from being deleted,
1284 // and tracking any changes of the root.
1285 HandleSDNode Dummy(CurDAG->getRoot());
1287 ++ISelPosition;
1288
1289 // Make sure that ISelPosition gets properly updated when nodes are deleted
1290 // in calls made from this function. New nodes inherit relevant metadata.
1291 ISelUpdater ISU(*CurDAG, ISelPosition);
1292
1293 // The AllNodes list is now topological-sorted. Visit the
1294 // nodes by starting at the end of the list (the root of the
1295 // graph) and preceding back toward the beginning (the entry
1296 // node).
1297 while (ISelPosition != CurDAG->allnodes_begin()) {
1298 SDNode *Node = &*--ISelPosition;
1299 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1300 // but there are currently some corner cases that it misses. Also, this
1301 // makes it theoretically possible to disable the DAGCombiner.
1302 if (Node->use_empty())
1303 continue;
1304
1305#ifndef NDEBUG
1307 Nodes.push_back(Node);
1308
1309 while (!Nodes.empty()) {
1310 auto N = Nodes.pop_back_val();
1311 if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1312 continue;
1313 for (const SDValue &Op : N->op_values()) {
1314 if (Op->getOpcode() == ISD::TokenFactor)
1315 Nodes.push_back(Op.getNode());
1316 else {
1317 // We rely on topological ordering of node ids for checking for
1318 // cycles when fusing nodes during selection. All unselected nodes
1319 // successors of an already selected node should have a negative id.
1320 // This assertion will catch such cases. If this assertion triggers
1321 // it is likely you using DAG-level Value/Node replacement functions
1322 // (versus equivalent ISEL replacement) in backend-specific
1323 // selections. See comment in EnforceNodeIdInvariant for more
1324 // details.
1325 assert(Op->getNodeId() != -1 &&
1326 "Node has already selected predecessor node");
1327 }
1328 }
1329 }
1330#endif
1331
1332 // When we are using non-default rounding modes or FP exception behavior
1333 // FP operations are represented by StrictFP pseudo-operations. For
1334 // targets that do not (yet) understand strict FP operations directly,
1335 // we convert them to normal FP opcodes instead at this point. This
1336 // will allow them to be handled by existing target-specific instruction
1337 // selectors.
1338 if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1339 // For some opcodes, we need to call TLI->getOperationAction using
1340 // the first operand type instead of the result type. Note that this
1341 // must match what SelectionDAGLegalize::LegalizeOp is doing.
1342 EVT ActionVT;
1343 switch (Node->getOpcode()) {
1346 case ISD::STRICT_LRINT:
1347 case ISD::STRICT_LLRINT:
1348 case ISD::STRICT_LROUND:
1350 case ISD::STRICT_FSETCC:
1352 ActionVT = Node->getOperand(1).getValueType();
1353 break;
1354 default:
1355 ActionVT = Node->getValueType(0);
1356 break;
1357 }
1358 if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1360 Node = CurDAG->mutateStrictFPToFP(Node);
1361 }
1362
1363 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1364 Node->dump(CurDAG));
1365
1366 Select(Node);
1367 }
1368
1369 CurDAG->setRoot(Dummy.getValue());
1370 }
1371
1372 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1373
1375}
1376
1378 for (const User *U : CPI->users()) {
1379 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1380 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1381 if (IID == Intrinsic::eh_exceptionpointer ||
1382 IID == Intrinsic::eh_exceptioncode)
1383 return true;
1384 }
1385 }
1386 return false;
1387}
1388
1389// wasm.landingpad.index intrinsic is for associating a landing pad index number
1390// with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1391// and store the mapping in the function.
1393 const CatchPadInst *CPI) {
1394 MachineFunction *MF = MBB->getParent();
1395 // In case of single catch (...), we don't emit LSDA, so we don't need
1396 // this information.
1397 bool IsSingleCatchAllClause =
1398 CPI->arg_size() == 1 &&
1399 cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1400 // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
1401 // and they don't need LSDA info
1402 bool IsCatchLongjmp = CPI->arg_size() == 0;
1403 if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
1404 // Create a mapping from landing pad label to landing pad index.
1405 bool IntrFound = false;
1406 for (const User *U : CPI->users()) {
1407 if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1408 Intrinsic::ID IID = Call->getIntrinsicID();
1409 if (IID == Intrinsic::wasm_landingpad_index) {
1410 Value *IndexArg = Call->getArgOperand(1);
1411 int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1412 MF->setWasmLandingPadIndex(MBB, Index);
1413 IntrFound = true;
1414 break;
1415 }
1416 }
1417 }
1418 assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1419 (void)IntrFound;
1420 }
1421}
1422
1423/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1424/// do other setup for EH landing-pad blocks.
1425bool SelectionDAGISel::PrepareEHLandingPad() {
1426 MachineBasicBlock *MBB = FuncInfo->MBB;
1427 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1428 const BasicBlock *LLVMBB = MBB->getBasicBlock();
1429 const TargetRegisterClass *PtrRC =
1430 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
1431
1432 auto Pers = classifyEHPersonality(PersonalityFn);
1433
1434 // Catchpads have one live-in register, which typically holds the exception
1435 // pointer or code.
1436 if (isFuncletEHPersonality(Pers)) {
1437 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHIIt())) {
1439 // Get or create the virtual register to hold the pointer or code. Mark
1440 // the live in physreg and copy into the vreg.
1441 MCRegister EHPhysReg = TLI->getExceptionPointerRegister(
1442 FuncInfo->ExceptionModel, PersonalityFn);
1443 assert(EHPhysReg && "target lacks exception pointer register");
1444 MBB->addLiveIn(EHPhysReg);
1445 Register VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1446 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1447 TII->get(TargetOpcode::COPY), VReg)
1448 .addReg(EHPhysReg, RegState::Kill);
1449 }
1450 }
1451 return true;
1452 }
1453
1454 // Add a label to mark the beginning of the landing pad. Deletion of the
1455 // landing pad can thus be detected via the MachineModuleInfo.
1456 MCSymbol *Label = MF->addLandingPad(MBB);
1457
1458 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1459 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1460 .addSym(Label);
1461
1462 // If the unwinder does not preserve all registers, ensure that the
1463 // function marks the clobbered registers as used.
1464 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
1465 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1466 MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
1467
1468 if (Pers == EHPersonality::Wasm_CXX || Pers == EHPersonality::Wasm_D) {
1469 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHIIt()))
1471 } else {
1472 // Assign the call site to the landing pad's begin label.
1473 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1474 // Mark exception register as live in.
1475 if (MCRegister Reg = TLI->getExceptionPointerRegister(
1476 FuncInfo->ExceptionModel, PersonalityFn))
1477 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1478 // Mark exception selector register as live in.
1479 if (MCRegister Reg = TLI->getExceptionSelectorRegister(
1480 FuncInfo->ExceptionModel, PersonalityFn))
1481 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1482 }
1483
1484 return true;
1485}
1486
1487// Mark and Report IPToState for each Block under IsEHa
1488void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
1489 llvm::WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo();
1490 if (!EHInfo)
1491 return;
1492 for (MachineBasicBlock &MBB : *MF) {
1493 const BasicBlock *BB = MBB.getBasicBlock();
1494 int State = EHInfo->BlockToStateMap[BB];
1495 if (BB->getFirstMayFaultInst()) {
1496 // Report IP range only for blocks with Faulty inst
1497 auto MBBb = MBB.getFirstNonPHI();
1498
1499 if (MBBb == MBB.end())
1500 continue;
1501
1502 MachineInstr *MIb = &*MBBb;
1503 if (MIb->isTerminator())
1504 continue;
1505
1506 // Insert EH Labels
1507 MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
1508 MCSymbol *EndLabel = MF->getContext().createTempSymbol();
1509 EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
1510 BuildMI(MBB, MBBb, SDB->getCurDebugLoc(),
1511 TII->get(TargetOpcode::EH_LABEL))
1512 .addSym(BeginLabel);
1513 auto MBBe = MBB.instr_end();
1514 MachineInstr *MIe = &*(--MBBe);
1515 // insert before (possible multiple) terminators
1516 while (MIe->isTerminator())
1517 MIe = &*(--MBBe);
1518 ++MBBe;
1519 BuildMI(MBB, MBBe, SDB->getCurDebugLoc(),
1520 TII->get(TargetOpcode::EH_LABEL))
1521 .addSym(EndLabel);
1522 }
1523 }
1524}
1525
1526/// isFoldedOrDeadInstruction - Return true if the specified instruction is
1527/// side-effect free and is either dead or folded into a generated instruction.
1528/// Return false if it needs to be emitted.
1530 const FunctionLoweringInfo &FuncInfo) {
1531 return !I->mayHaveSideEffects() && // Side-effecting instrs aren't folded.
1532 !I->isTerminator() && // Terminators aren't folded.
1533 !I->isEHPad() && // EH pad instructions aren't folded.
1534 !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1535}
1536
1538 const Value *Arg, DIExpression *Expr,
1539 DILocalVariable *Var,
1540 DebugLoc DbgLoc) {
1541 if (!Expr->isEntryValue() || !isa<Argument>(Arg))
1542 return false;
1543
1544 auto ArgIt = FuncInfo.ValueMap.find(Arg);
1545 if (ArgIt == FuncInfo.ValueMap.end())
1546 return false;
1547 Register ArgVReg = ArgIt->getSecond();
1548
1549 // Find the corresponding livein physical register to this argument.
1550 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
1551 if (VirtReg == ArgVReg) {
1552 // Append an op deref to account for the fact that this is a dbg_declare.
1553 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
1554 FuncInfo.MF->setVariableDbgInfo(Var, Expr, PhysReg, DbgLoc);
1555 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1556 << ", Expr=" << *Expr << ", MCRegister=" << PhysReg
1557 << ", DbgLoc=" << DbgLoc << "\n");
1558 return true;
1559 }
1560 return false;
1561}
1562
1564 const Value *Address, DIExpression *Expr,
1565 DILocalVariable *Var, DebugLoc DbgLoc) {
1566 if (!Address) {
1567 LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *Var
1568 << " (bad address)\n");
1569 return false;
1570 }
1571
1572 if (processIfEntryValueDbgDeclare(FuncInfo, Address, Expr, Var, DbgLoc))
1573 return true;
1574
1575 if (!Address->getType()->isPointerTy())
1576 return false;
1577
1578 MachineFunction *MF = FuncInfo.MF;
1579 const DataLayout &DL = MF->getDataLayout();
1580
1581 assert(Var && "Missing variable");
1582 assert(DbgLoc && "Missing location");
1583
1584 // Look through casts and constant offset GEPs. These mostly come from
1585 // inalloca.
1586 APInt Offset(DL.getIndexTypeSizeInBits(Address->getType()), 0);
1587 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1588
1589 // Check if the variable is a static alloca or a byval or inalloca
1590 // argument passed in memory. If it is not, then we will ignore this
1591 // intrinsic and handle this during isel like dbg.value.
1592 int FI = std::numeric_limits<int>::max();
1593 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1594 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1595 if (SI != FuncInfo.StaticAllocaMap.end())
1596 FI = SI->second;
1597 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1598 FI = FuncInfo.getArgumentFrameIndex(Arg);
1599
1600 if (FI == std::numeric_limits<int>::max())
1601 return false;
1602
1603 if (Offset.getBoolValue())
1605 Offset.getZExtValue());
1606
1607 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1608 << ", Expr=" << *Expr << ", FI=" << FI
1609 << ", DbgLoc=" << DbgLoc << "\n");
1610 MF->setVariableDbgInfo(Var, Expr, FI, DbgLoc);
1611 return true;
1612}
1613
1614/// Collect llvm.dbg.declare information. This is done after argument lowering
1615/// in case the declarations refer to arguments.
1617 for (const auto &I : instructions(*FuncInfo.Fn)) {
1618 for (const DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1620 processDbgDeclare(FuncInfo, DVR.getVariableLocationOp(0),
1621 DVR.getExpression(), DVR.getVariable(),
1622 DVR.getDebugLoc()))
1623 FuncInfo.PreprocessedDVRDeclares.insert(&DVR);
1624 }
1625 }
1626}
1627
1628/// Collect single location variable information generated with assignment
1629/// tracking. This is done after argument lowering in case the declarations
1630/// refer to arguments.
1632 FunctionVarLocs const *FnVarLocs) {
1633 for (auto It = FnVarLocs->single_locs_begin(),
1634 End = FnVarLocs->single_locs_end();
1635 It != End; ++It) {
1636 assert(!It->Values.hasArgList() && "Single loc variadic ops not supported");
1637 processDbgDeclare(FuncInfo, It->Values.getVariableLocationOp(0), It->Expr,
1638 FnVarLocs->getDILocalVariable(It->VariableID), It->DL);
1639 }
1640}
1641
1642void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1643 assert(!Scheduler && "scheduler leaked from previous function");
1644 FastISelFailed = false;
1645 // Initialize the Fast-ISel state, if needed.
1646 FastISel *FastIS = nullptr;
1647 if (TM.Options.EnableFastISel) {
1648 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1649 FastIS = TLI->createFastISel(*FuncInfo, LibInfo, LibcallLowering);
1650 }
1651
1652 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1653
1654 // Lower arguments up front. An RPO iteration always visits the entry block
1655 // first.
1656 assert(*RPOT.begin() == &Fn.getEntryBlock());
1657 ++NumEntryBlocks;
1658
1659 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1660 FuncInfo->MBB = FuncInfo->getMBB(&Fn.getEntryBlock());
1661 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1662
1663 CurDAG->setFunctionLoweringInfo(FuncInfo.get());
1664
1665 if (!FastIS) {
1666 LowerArguments(Fn, /*FastISel=*/false);
1667 } else {
1668 // See if fast isel can lower the arguments.
1669 FastIS->startNewBlock();
1670 if (!FastIS->lowerArguments()) {
1671 FastISelFailed = true;
1672 // Fast isel failed to lower these arguments
1673 ++NumFastIselFailLowerArguments;
1674
1675 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1676 Fn.getSubprogram(),
1677 &Fn.getEntryBlock());
1678 R << "FastISel didn't lower all arguments: "
1679 << ore::NV("Prototype", Fn.getFunctionType());
1681
1682 // Use SelectionDAG argument lowering
1683 LowerArguments(Fn, /*FastISel=*/true);
1684 CurDAG->setRoot(SDB->getControlRoot());
1685 SDB->clear();
1686 CodeGenAndEmitDAG();
1687 }
1688
1689 // If we inserted any instructions at the beginning, make a note of
1690 // where they are, so we can be sure to emit subsequent instructions
1691 // after them.
1692 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1693 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1694 else
1695 FastIS->setLastLocalValue(nullptr);
1696 }
1697
1698 bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1699
1700 if (FastIS && Inserted)
1701 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1702
1704 assert(CurDAG->getFunctionVarLocs() &&
1705 "expected AssignmentTrackingAnalysis pass results");
1706 processSingleLocVars(*FuncInfo, CurDAG->getFunctionVarLocs());
1707 } else {
1709 }
1710
1711 // Iterate over all basic blocks in the function.
1712 FuncInfo->VisitedBBs.assign(Fn.getMaxBlockNumber(), false);
1713 for (const BasicBlock *LLVMBB : RPOT) {
1715 bool AllPredsVisited = true;
1716 for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1717 if (!FuncInfo->VisitedBBs[Pred->getNumber()]) {
1718 AllPredsVisited = false;
1719 break;
1720 }
1721 }
1722
1723 if (AllPredsVisited) {
1724 for (const PHINode &PN : LLVMBB->phis())
1725 FuncInfo->ComputePHILiveOutRegInfo(&PN);
1726 } else {
1727 for (const PHINode &PN : LLVMBB->phis())
1728 FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1729 }
1730
1731 FuncInfo->VisitedBBs[LLVMBB->getNumber()] = true;
1732 }
1733
1734 // Fake uses that follow tail calls are dropped. To avoid this, move
1735 // such fake uses in front of the tail call, provided they don't
1736 // use anything def'd by or after the tail call.
1737 {
1738 BasicBlock::iterator BBStart =
1739 const_cast<BasicBlock *>(LLVMBB)->getFirstNonPHIIt();
1740 BasicBlock::iterator BBEnd = const_cast<BasicBlock *>(LLVMBB)->end();
1741 preserveFakeUses(BBStart, BBEnd);
1742 }
1743
1744 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHIIt();
1745 BasicBlock::const_iterator const End = LLVMBB->end();
1747
1748 FuncInfo->MBB = FuncInfo->getMBB(LLVMBB);
1749 if (!FuncInfo->MBB)
1750 continue; // Some blocks like catchpads have no code or MBB.
1751
1752 // Insert new instructions after any phi or argument setup code.
1753 FuncInfo->InsertPt = FuncInfo->MBB->end();
1754
1755 // Setup an EH landing-pad block.
1756 FuncInfo->ExceptionPointerVirtReg = Register();
1757 FuncInfo->ExceptionSelectorVirtReg = Register();
1758 if (LLVMBB->isEHPad()) {
1759 if (!PrepareEHLandingPad())
1760 continue;
1761
1762 if (!FastIS) {
1763 SDValue NewRoot = TLI->lowerEHPadEntry(CurDAG->getRoot(),
1764 SDB->getCurSDLoc(), *CurDAG);
1765 if (NewRoot && NewRoot != CurDAG->getRoot())
1766 CurDAG->setRoot(NewRoot);
1767 }
1768 }
1769
1770 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1771 if (FastIS) {
1772 if (LLVMBB != &Fn.getEntryBlock())
1773 FastIS->startNewBlock();
1774
1775 unsigned NumFastIselRemaining = std::distance(Begin, End);
1776
1777 // Pre-assign swifterror vregs.
1778 SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1779
1780 // Do FastISel on as many instructions as possible.
1781 for (; BI != Begin; --BI) {
1782 const Instruction *Inst = &*std::prev(BI);
1783
1784 // If we no longer require this instruction, skip it.
1785 if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1786 ElidedArgCopyInstrs.count(Inst)) {
1787 --NumFastIselRemaining;
1788 FastIS->handleDbgInfo(Inst);
1789 continue;
1790 }
1791
1792 // Bottom-up: reset the insert pos at the top, after any local-value
1793 // instructions.
1794 FastIS->recomputeInsertPt();
1795
1796 // Try to select the instruction with FastISel.
1797 if (FastIS->selectInstruction(Inst)) {
1798 --NumFastIselRemaining;
1799 ++NumFastIselSuccess;
1800
1801 FastIS->handleDbgInfo(Inst);
1802 // If fast isel succeeded, skip over all the folded instructions, and
1803 // then see if there is a load right before the selected instructions.
1804 // Try to fold the load if so.
1805 const Instruction *BeforeInst = Inst;
1806 while (BeforeInst != &*Begin) {
1807 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1808 if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1809 break;
1810 }
1811 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1812 BeforeInst->hasOneUse() &&
1813 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1814 // If we succeeded, don't re-select the load.
1816 << "FastISel folded load: " << *BeforeInst << "\n");
1817 FastIS->handleDbgInfo(BeforeInst);
1818 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1819 --NumFastIselRemaining;
1820 ++NumFastIselSuccess;
1821 }
1822 continue;
1823 }
1824
1825 FastISelFailed = true;
1826
1827 // Then handle certain instructions as single-LLVM-Instruction blocks.
1828 // We cannot separate out GCrelocates to their own blocks since we need
1829 // to keep track of gc-relocates for a particular gc-statepoint. This is
1830 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1831 // visitGCRelocate.
1832 if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1833 !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1834 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1835 Inst->getDebugLoc(), LLVMBB);
1836
1837 R << "FastISel missed call";
1838
1839 if (R.isEnabled() || EnableFastISelAbort) {
1840 std::string InstStrStorage;
1841 raw_string_ostream InstStr(InstStrStorage);
1842 InstStr << *Inst;
1843
1844 R << ": " << InstStrStorage;
1845 }
1846
1848
1849 // If the call has operand bundles, then it's best if they are handled
1850 // together with the call instead of selecting the call as its own
1851 // block.
1852 if (cast<CallInst>(Inst)->hasOperandBundles()) {
1853 NumFastIselFailures += NumFastIselRemaining;
1854 break;
1855 }
1856
1857 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1858 !Inst->use_empty()) {
1859 Register &R = FuncInfo->ValueMap[Inst];
1860 if (!R)
1861 R = FuncInfo->CreateRegs(Inst);
1862 }
1863
1864 bool HadTailCall = false;
1865 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1866 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1867
1868 // If the call was emitted as a tail call, we're done with the block.
1869 // We also need to delete any previously emitted instructions.
1870 if (HadTailCall) {
1871 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1872 --BI;
1873 break;
1874 }
1875
1876 // Recompute NumFastIselRemaining as Selection DAG instruction
1877 // selection may have handled the call, input args, etc.
1878 unsigned RemainingNow = std::distance(Begin, BI);
1879 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1880 NumFastIselRemaining = RemainingNow;
1881 continue;
1882 }
1883
1884 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1885 Inst->getDebugLoc(), LLVMBB);
1886
1887 bool ShouldAbort = EnableFastISelAbort;
1888 if (Inst->isTerminator()) {
1889 // Use a different message for terminator misses.
1890 R << "FastISel missed terminator";
1891 // Don't abort for terminator unless the level is really high
1892 ShouldAbort = (EnableFastISelAbort > 2);
1893 } else {
1894 R << "FastISel missed";
1895 }
1896
1897 if (R.isEnabled() || EnableFastISelAbort) {
1898 std::string InstStrStorage;
1899 raw_string_ostream InstStr(InstStrStorage);
1900 InstStr << *Inst;
1901 R << ": " << InstStrStorage;
1902 }
1903
1904 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1905
1906 NumFastIselFailures += NumFastIselRemaining;
1907 break;
1908 }
1909
1910 FastIS->recomputeInsertPt();
1911 }
1912
1913 if (SP->shouldEmitSDCheck(*LLVMBB)) {
1914 bool FunctionBasedInstrumentation =
1915 TLI->getSSPStackGuardCheck(*Fn.getParent(), *LibcallLowering) &&
1916 Fn.hasMinSize();
1917 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->getMBB(LLVMBB),
1918 FunctionBasedInstrumentation);
1919 }
1920
1921 if (Begin != BI)
1922 ++NumDAGBlocks;
1923 else
1924 ++NumFastIselBlocks;
1925
1926 if (Begin != BI) {
1927 // Run SelectionDAG instruction selection on the remainder of the block
1928 // not handled by FastISel. If FastISel is not run, this is the entire
1929 // block.
1930 bool HadTailCall;
1931 SelectBasicBlock(Begin, BI, HadTailCall);
1932
1933 // But if FastISel was run, we already selected some of the block.
1934 // If we emitted a tail-call, we need to delete any previously emitted
1935 // instruction that follows it.
1936 if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1937 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1938 }
1939
1940 if (FastIS)
1941 FastIS->finishBasicBlock();
1942 FinishBasicBlock();
1943 FuncInfo->PHINodesToUpdate.clear();
1944 ElidedArgCopyInstrs.clear();
1945 }
1946
1947 // AsynchEH: Report Block State under -AsynchEH
1948 if (Fn.getParent()->getModuleFlag("eh-asynch"))
1949 reportIPToStateForBlocks(MF);
1950
1951 SP->copyToMachineFrameInfo(MF->getFrameInfo());
1952
1953 SwiftError->propagateVRegs();
1954
1955 delete FastIS;
1956 Scheduler.reset();
1957 SDB->clearDanglingDebugInfo();
1958 SDB->SPDescriptor.resetPerFunctionState();
1959}
1960
1961void
1962SelectionDAGISel::FinishBasicBlock() {
1963 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1964 << FuncInfo->PHINodesToUpdate.size() << "\n";
1965 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1966 ++i) dbgs()
1967 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1968 << ", " << printReg(FuncInfo->PHINodesToUpdate[i].second)
1969 << ")\n");
1970
1971 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1972 // PHI nodes in successors.
1973 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1974 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1975 assert(PHI->isPHI() &&
1976 "This is not a machine PHI node that we are updating!");
1977 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1978 continue;
1979 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1980 }
1981
1982 // Handle stack protector.
1983 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1984 // The target provides a guard check function. There is no need to
1985 // generate error handling code or to split current basic block.
1986 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1987
1988 // Add load and check to the basicblock.
1989 FuncInfo->MBB = ParentMBB;
1990 FuncInfo->InsertPt = findSplitPointForStackProtector(ParentMBB, *TII);
1991 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1992 CurDAG->setRoot(SDB->getRoot());
1993 SDB->clear();
1994 CodeGenAndEmitDAG();
1995
1996 // Clear the Per-BB State.
1997 SDB->SPDescriptor.resetPerBBState();
1998 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1999 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
2000 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
2001
2002 // Find the split point to split the parent mbb. At the same time copy all
2003 // physical registers used in the tail of parent mbb into virtual registers
2004 // before the split point and back into physical registers after the split
2005 // point. This prevents us needing to deal with Live-ins and many other
2006 // register allocation issues caused by us splitting the parent mbb. The
2007 // register allocator will clean up said virtual copies later on.
2008 MachineBasicBlock::iterator SplitPoint =
2010
2011 // Splice the terminator of ParentMBB into SuccessMBB.
2012 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
2013 ParentMBB->end());
2014
2015 // Add compare/jump on neq/jump to the parent BB.
2016 FuncInfo->MBB = ParentMBB;
2017 FuncInfo->InsertPt = ParentMBB->end();
2018 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
2019 CurDAG->setRoot(SDB->getRoot());
2020 SDB->clear();
2021 CodeGenAndEmitDAG();
2022
2023 // CodeGen Failure MBB if we have not codegened it yet.
2024 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
2025 if (FailureMBB->empty()) {
2026 FuncInfo->MBB = FailureMBB;
2027 FuncInfo->InsertPt = FailureMBB->end();
2028 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
2029 CurDAG->setRoot(SDB->getRoot());
2030 SDB->clear();
2031 CodeGenAndEmitDAG();
2032 }
2033
2034 // Clear the Per-BB State.
2035 SDB->SPDescriptor.resetPerBBState();
2036 }
2037
2038 // Lower each BitTestBlock.
2039 for (auto &BTB : SDB->SL->BitTestCases) {
2040 // Lower header first, if it wasn't already lowered
2041 if (!BTB.Emitted) {
2042 // Set the current basic block to the mbb we wish to insert the code into
2043 FuncInfo->MBB = BTB.Parent;
2044 FuncInfo->InsertPt = FuncInfo->MBB->end();
2045 // Emit the code
2046 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
2047 CurDAG->setRoot(SDB->getRoot());
2048 SDB->clear();
2049 CodeGenAndEmitDAG();
2050 }
2051
2052 BranchProbability UnhandledProb = BTB.Prob;
2053 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
2054 UnhandledProb -= BTB.Cases[j].ExtraProb;
2055 // Set the current basic block to the mbb we wish to insert the code into
2056 FuncInfo->MBB = BTB.Cases[j].ThisBB;
2057 FuncInfo->InsertPt = FuncInfo->MBB->end();
2058 // Emit the code
2059
2060 // If all cases cover a contiguous range, it is not necessary to jump to
2061 // the default block after the last bit test fails. This is because the
2062 // range check during bit test header creation has guaranteed that every
2063 // case here doesn't go outside the range. In this case, there is no need
2064 // to perform the last bit test, as it will always be true. Instead, make
2065 // the second-to-last bit-test fall through to the target of the last bit
2066 // test, and delete the last bit test.
2067
2068 MachineBasicBlock *NextMBB;
2069 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2070 // Second-to-last bit-test with contiguous range or omitted range
2071 // check: fall through to the target of the final bit test.
2072 NextMBB = BTB.Cases[j + 1].TargetBB;
2073 } else if (j + 1 == ej) {
2074 // For the last bit test, fall through to Default.
2075 NextMBB = BTB.Default;
2076 } else {
2077 // Otherwise, fall through to the next bit test.
2078 NextMBB = BTB.Cases[j + 1].ThisBB;
2079 }
2080
2081 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
2082 FuncInfo->MBB);
2083
2084 CurDAG->setRoot(SDB->getRoot());
2085 SDB->clear();
2086 CodeGenAndEmitDAG();
2087
2088 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2089 // Since we're not going to use the final bit test, remove it.
2090 BTB.Cases.pop_back();
2091 break;
2092 }
2093 }
2094
2095 // Update PHI Nodes
2096 for (const std::pair<MachineInstr *, Register> &P :
2097 FuncInfo->PHINodesToUpdate) {
2098 MachineInstrBuilder PHI(*MF, P.first);
2099 MachineBasicBlock *PHIBB = PHI->getParent();
2100 assert(PHI->isPHI() &&
2101 "This is not a machine PHI node that we are updating!");
2102 // This is "default" BB. We have two jumps to it. From "header" BB and
2103 // from last "case" BB, unless the latter was skipped.
2104 if (PHIBB == BTB.Default) {
2105 PHI.addReg(P.second).addMBB(BTB.Parent);
2106 if (!BTB.ContiguousRange) {
2107 PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
2108 }
2109 }
2110 // One of "cases" BB.
2111 for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
2112 MachineBasicBlock* cBB = BT.ThisBB;
2113 if (cBB->isSuccessor(PHIBB))
2114 PHI.addReg(P.second).addMBB(cBB);
2115 }
2116 }
2117 }
2118 SDB->SL->BitTestCases.clear();
2119
2120 // If the JumpTable record is filled in, then we need to emit a jump table.
2121 // Updating the PHI nodes is tricky in this case, since we need to determine
2122 // whether the PHI is a successor of the range check MBB or the jump table MBB
2123 for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
2124 // Lower header first, if it wasn't already lowered
2125 if (!SDB->SL->JTCases[i].first.Emitted) {
2126 // Set the current basic block to the mbb we wish to insert the code into
2127 FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
2128 FuncInfo->InsertPt = FuncInfo->MBB->end();
2129 // Emit the code
2130 SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
2131 SDB->SL->JTCases[i].first, FuncInfo->MBB);
2132 CurDAG->setRoot(SDB->getRoot());
2133 SDB->clear();
2134 CodeGenAndEmitDAG();
2135 }
2136
2137 // Set the current basic block to the mbb we wish to insert the code into
2138 FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
2139 FuncInfo->InsertPt = FuncInfo->MBB->end();
2140 // Emit the code
2141 SDB->visitJumpTable(SDB->SL->JTCases[i].second);
2142 CurDAG->setRoot(SDB->getRoot());
2143 SDB->clear();
2144 CodeGenAndEmitDAG();
2145
2146 // Update PHI Nodes
2147 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
2148 pi != pe; ++pi) {
2149 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
2150 MachineBasicBlock *PHIBB = PHI->getParent();
2151 assert(PHI->isPHI() &&
2152 "This is not a machine PHI node that we are updating!");
2153 // "default" BB. We can go there only from header BB.
2154 if (PHIBB == SDB->SL->JTCases[i].second.Default)
2155 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
2156 .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
2157 // JT BB. Just iterate over successors here
2158 if (FuncInfo->MBB->isSuccessor(PHIBB))
2159 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
2160 }
2161 }
2162 SDB->SL->JTCases.clear();
2163
2164 // If we generated any switch lowering information, build and codegen any
2165 // additional DAGs necessary.
2166 for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
2167 // Set the current basic block to the mbb we wish to insert the code into
2168 FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
2169 FuncInfo->InsertPt = FuncInfo->MBB->end();
2170
2171 // Determine the unique successors.
2172 SmallVector<MachineBasicBlock *, 2> Succs;
2173 Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
2174 if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
2175 Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
2176
2177 // Emit the code. Note that this could result in FuncInfo->MBB being split.
2178 SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
2179 CurDAG->setRoot(SDB->getRoot());
2180 SDB->clear();
2181 CodeGenAndEmitDAG();
2182
2183 // Remember the last block, now that any splitting is done, for use in
2184 // populating PHI nodes in successors.
2185 MachineBasicBlock *ThisBB = FuncInfo->MBB;
2186
2187 // Handle any PHI nodes in successors of this chunk, as if we were coming
2188 // from the original BB before switch expansion. Note that PHI nodes can
2189 // occur multiple times in PHINodesToUpdate. We have to be very careful to
2190 // handle them the right number of times.
2191 for (MachineBasicBlock *Succ : Succs) {
2192 FuncInfo->MBB = Succ;
2193 FuncInfo->InsertPt = FuncInfo->MBB->end();
2194 // FuncInfo->MBB may have been removed from the CFG if a branch was
2195 // constant folded.
2196 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
2198 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
2199 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
2200 MachineInstrBuilder PHI(*MF, MBBI);
2201 // This value for this PHI node is recorded in PHINodesToUpdate.
2202 for (unsigned pn = 0; ; ++pn) {
2203 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
2204 "Didn't find PHI entry!");
2205 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
2206 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
2207 break;
2208 }
2209 }
2210 }
2211 }
2212 }
2213 }
2214 SDB->SL->SwitchCases.clear();
2215}
2216
2217/// Create the scheduler. If a specific scheduler was specified
2218/// via the SchedulerRegistry, use it, otherwise select the
2219/// one preferred by the target.
2220///
2221ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
2222 return ISHeuristic(this, OptLevel);
2223}
2224
2225//===----------------------------------------------------------------------===//
2226// Helper functions used by the generated instruction selector.
2227//===----------------------------------------------------------------------===//
2228// Calls to these methods are generated by tblgen.
2229
2230/// CheckAndMask - The isel is trying to match something like (and X, 255). If
2231/// the dag combiner simplified the 255, we still want to match. RHS is the
2232/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2233/// specified in the .td file (e.g. 255).
2235 int64_t DesiredMaskS) const {
2236 const APInt &ActualMask = RHS->getAPIntValue();
2237 // TODO: Avoid implicit trunc?
2238 // See https://github.com/llvm/llvm-project/issues/112510.
2239 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS,
2240 /*isSigned=*/false, /*implicitTrunc=*/true);
2241
2242 // If the actual mask exactly matches, success!
2243 if (ActualMask == DesiredMask)
2244 return true;
2245
2246 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2247 if (!ActualMask.isSubsetOf(DesiredMask))
2248 return false;
2249
2250 // Otherwise, the DAG Combiner may have proven that the value coming in is
2251 // either already zero or is not demanded. Check for known zero input bits.
2252 APInt NeededMask = DesiredMask & ~ActualMask;
2253 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2254 return true;
2255
2256 // TODO: check to see if missing bits are just not demanded.
2257
2258 // Otherwise, this pattern doesn't match.
2259 return false;
2260}
2261
2262/// CheckOrMask - The isel is trying to match something like (or X, 255). If
2263/// the dag combiner simplified the 255, we still want to match. RHS is the
2264/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2265/// specified in the .td file (e.g. 255).
2267 int64_t DesiredMaskS) const {
2268 const APInt &ActualMask = RHS->getAPIntValue();
2269 // TODO: Avoid implicit trunc?
2270 // See https://github.com/llvm/llvm-project/issues/112510.
2271 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS,
2272 /*isSigned=*/false, /*implicitTrunc=*/true);
2273
2274 // If the actual mask exactly matches, success!
2275 if (ActualMask == DesiredMask)
2276 return true;
2277
2278 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2279 if (!ActualMask.isSubsetOf(DesiredMask))
2280 return false;
2281
2282 // Otherwise, the DAG Combiner may have proven that the value coming in is
2283 // either already zero or is not demanded. Check for known zero input bits.
2284 APInt NeededMask = DesiredMask & ~ActualMask;
2285 KnownBits Known = CurDAG->computeKnownBits(LHS);
2286
2287 // If all the missing bits in the or are already known to be set, match!
2288 if (NeededMask.isSubsetOf(Known.One))
2289 return true;
2290
2291 // TODO: check to see if missing bits are just not demanded.
2292
2293 // Otherwise, this pattern doesn't match.
2294 return false;
2295}
2296
2297/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2298/// by tblgen. Others should not call it.
2300 const SDLoc &DL) {
2301 // Change the vector of SDValue into a list of SDNodeHandle for x86 might call
2302 // replaceAllUses when matching address.
2303
2304 std::list<HandleSDNode> Handles;
2305
2306 Handles.emplace_back(Ops[InlineAsm::Op_InputChain]); // 0
2307 Handles.emplace_back(Ops[InlineAsm::Op_AsmString]); // 1
2308 Handles.emplace_back(Ops[InlineAsm::Op_MDNode]); // 2, !srcloc
2309 Handles.emplace_back(
2310 Ops[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2311
2312 unsigned i = InlineAsm::Op_FirstOperand, e = Ops.size();
2313 if (Ops[e - 1].getValueType() == MVT::Glue)
2314 --e; // Don't process a glue operand if it is here.
2315
2316 while (i != e) {
2317 InlineAsm::Flag Flags(Ops[i]->getAsZExtVal());
2318 if (!Flags.isMemKind() && !Flags.isFuncKind()) {
2319 // Just skip over this operand, copying the operands verbatim.
2320 Handles.insert(Handles.end(), Ops.begin() + i,
2321 Ops.begin() + i + Flags.getNumOperandRegisters() + 1);
2322 i += Flags.getNumOperandRegisters() + 1;
2323 } else {
2324 assert(Flags.getNumOperandRegisters() == 1 &&
2325 "Memory operand with multiple values?");
2326
2327 unsigned TiedToOperand;
2328 if (Flags.isUseOperandTiedToDef(TiedToOperand)) {
2329 // We need the constraint ID from the operand this is tied to.
2330 unsigned CurOp = InlineAsm::Op_FirstOperand;
2331 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2332 for (; TiedToOperand; --TiedToOperand) {
2333 CurOp += Flags.getNumOperandRegisters() + 1;
2334 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2335 }
2336 }
2337
2338 // Otherwise, this is a memory operand. Ask the target to select it.
2339 std::vector<SDValue> SelOps;
2340 const InlineAsm::ConstraintCode ConstraintID =
2341 Flags.getMemoryConstraintID();
2342 if (SelectInlineAsmMemoryOperand(Ops[i + 1], ConstraintID, SelOps))
2343 report_fatal_error("Could not match memory address. Inline asm"
2344 " failure!");
2345
2346 // Add this to the output node.
2347 Flags = InlineAsm::Flag(Flags.isMemKind() ? InlineAsm::Kind::Mem
2349 SelOps.size());
2350 Flags.setMemConstraint(ConstraintID);
2351 Handles.emplace_back(CurDAG->getTargetConstant(Flags, DL, MVT::i32));
2352 llvm::append_range(Handles, SelOps);
2353 i += 2;
2354 }
2355 }
2356
2357 // Add the glue input back if present.
2358 if (e != Ops.size())
2359 Handles.emplace_back(Ops.back());
2360
2361 Ops.clear();
2362 for (auto &handle : Handles)
2363 Ops.push_back(handle.getValue());
2364}
2365
2366/// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2367/// beyond "ImmedUse". We may ignore chains as they are checked separately.
2368static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2369 bool IgnoreChains) {
2372 // Only check if we have non-immediate uses of Def.
2373 if (ImmedUse->isOnlyUserOf(Def))
2374 return false;
2375
2376 // We don't care about paths to Def that go through ImmedUse so mark it
2377 // visited and mark non-def operands as used.
2378 Visited.insert(ImmedUse);
2379 for (const SDValue &Op : ImmedUse->op_values()) {
2380 SDNode *N = Op.getNode();
2381 // Ignore chain deps (they are validated by
2382 // HandleMergeInputChains) and immediate uses
2383 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2384 continue;
2385 if (!Visited.insert(N).second)
2386 continue;
2387 WorkList.push_back(N);
2388 }
2389
2390 // Initialize worklist to operands of Root.
2391 if (Root != ImmedUse) {
2392 for (const SDValue &Op : Root->op_values()) {
2393 SDNode *N = Op.getNode();
2394 // Ignore chains (they are validated by HandleMergeInputChains)
2395 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2396 continue;
2397 if (!Visited.insert(N).second)
2398 continue;
2399 WorkList.push_back(N);
2400 }
2401 }
2402
2403 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2404}
2405
2406/// IsProfitableToFold - Returns true if it's profitable to fold the specific
2407/// operand node N of U during instruction selection that starts at Root.
2409 SDNode *Root) const {
2411 return false;
2412 return N.hasOneUse();
2413}
2414
2415/// IsLegalToFold - Returns true if the specific operand node N of
2416/// U can be folded during instruction selection that starts at Root.
2419 bool IgnoreChains) {
2421 return false;
2422
2423 // If Root use can somehow reach N through a path that doesn't contain
2424 // U then folding N would create a cycle. e.g. In the following
2425 // diagram, Root can reach N through X. If N is folded into Root, then
2426 // X is both a predecessor and a successor of U.
2427 //
2428 // [N*] //
2429 // ^ ^ //
2430 // / \ //
2431 // [U*] [X]? //
2432 // ^ ^ //
2433 // \ / //
2434 // \ / //
2435 // [Root*] //
2436 //
2437 // * indicates nodes to be folded together.
2438 //
2439 // If Root produces glue, then it gets (even more) interesting. Since it
2440 // will be "glued" together with its glue use in the scheduler, we need to
2441 // check if it might reach N.
2442 //
2443 // [N*] //
2444 // ^ ^ //
2445 // / \ //
2446 // [U*] [X]? //
2447 // ^ ^ //
2448 // \ \ //
2449 // \ | //
2450 // [Root*] | //
2451 // ^ | //
2452 // f | //
2453 // | / //
2454 // [Y] / //
2455 // ^ / //
2456 // f / //
2457 // | / //
2458 // [GU] //
2459 //
2460 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2461 // (call it Fold), then X is a predecessor of GU and a successor of
2462 // Fold. But since Fold and GU are glued together, this will create
2463 // a cycle in the scheduling graph.
2464
2465 // If the node has glue, walk down the graph to the "lowest" node in the
2466 // glued set.
2467 EVT VT = Root->getValueType(Root->getNumValues()-1);
2468 while (VT == MVT::Glue) {
2469 SDNode *GU = Root->getGluedUser();
2470 if (!GU)
2471 break;
2472 Root = GU;
2473 VT = Root->getValueType(Root->getNumValues()-1);
2474
2475 // If our query node has a glue result with a use, we've walked up it. If
2476 // the user (which has already been selected) has a chain or indirectly uses
2477 // the chain, HandleMergeInputChains will not consider it. Because of
2478 // this, we cannot ignore chains in this predicate.
2479 IgnoreChains = false;
2480 }
2481
2482 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2483}
2484
2485void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2486 SDLoc DL(N);
2487
2488 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2490
2491 const EVT VTs[] = {MVT::Other, MVT::Glue};
2492 SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2493 New->setNodeId(-1);
2494 ReplaceUses(N, New.getNode());
2496}
2497
2498void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2499 SDLoc dl(Op);
2500 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2501 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2502
2503 EVT VT = Op->getValueType(0);
2504 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2505
2506 const MachineFunction &MF = CurDAG->getMachineFunction();
2507 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty, MF);
2508
2509 SDValue New;
2510 if (!Reg) {
2511 const Function &Fn = MF.getFunction();
2512 Fn.getContext().diagnose(DiagnosticInfoGenericWithLoc(
2513 "invalid register \"" + Twine(RegStr->getString().data()) +
2514 "\" for llvm.read_register",
2515 Fn, Op->getDebugLoc()));
2516 New =
2517 SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0);
2518 ReplaceUses(SDValue(Op, 1), Op->getOperand(0));
2519 } else {
2520 New =
2521 CurDAG->getCopyFromReg(Op->getOperand(0), dl, Reg, Op->getValueType(0));
2522 }
2523
2524 New->setNodeId(-1);
2525 ReplaceUses(Op, New.getNode());
2526 CurDAG->RemoveDeadNode(Op);
2527}
2528
2529void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2530 SDLoc dl(Op);
2531 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2532 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2533
2534 EVT VT = Op->getOperand(2).getValueType();
2535 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2536
2537 const MachineFunction &MF = CurDAG->getMachineFunction();
2538 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty, MF);
2539
2540 if (!Reg) {
2541 const Function &Fn = MF.getFunction();
2542 Fn.getContext().diagnose(DiagnosticInfoGenericWithLoc(
2543 "invalid register \"" + Twine(RegStr->getString().data()) +
2544 "\" for llvm.write_register",
2545 Fn, Op->getDebugLoc()));
2546 ReplaceUses(SDValue(Op, 0), Op->getOperand(0));
2547 } else {
2548 SDValue New =
2549 CurDAG->getCopyToReg(Op->getOperand(0), dl, Reg, Op->getOperand(2));
2550 New->setNodeId(-1);
2551 ReplaceUses(Op, New.getNode());
2552 }
2553
2554 CurDAG->RemoveDeadNode(Op);
2555}
2556
2557void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2558 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2559}
2560
2561// Use the generic target FAKE_USE target opcode. The chain operand
2562// must come last, because InstrEmitter::AddOperand() requires it.
2563void SelectionDAGISel::Select_FAKE_USE(SDNode *N) {
2564 CurDAG->SelectNodeTo(N, TargetOpcode::FAKE_USE, N->getValueType(0),
2565 N->getOperand(1), N->getOperand(0));
2566}
2567
2568void SelectionDAGISel::Select_RELOC_NONE(SDNode *N) {
2569 CurDAG->SelectNodeTo(N, TargetOpcode::RELOC_NONE, N->getValueType(0),
2570 N->getOperand(1), N->getOperand(0));
2571}
2572
2573void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2574 // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2575 // If FREEZE instruction is added later, the code below must be changed as
2576 // well.
2577 CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2578 N->getOperand(0));
2579}
2580
2581void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2582 CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2583 N->getOperand(0));
2584}
2585
2586void SelectionDAGISel::Select_MEMBARRIER(SDNode *N) {
2587 CurDAG->SelectNodeTo(N, TargetOpcode::MEMBARRIER, N->getValueType(0),
2588 N->getOperand(0));
2589}
2590
2591void SelectionDAGISel::Select_CONVERGENCECTRL_ANCHOR(SDNode *N) {
2592 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ANCHOR,
2593 N->getValueType(0));
2594}
2595
2596void SelectionDAGISel::Select_CONVERGENCECTRL_ENTRY(SDNode *N) {
2597 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ENTRY,
2598 N->getValueType(0));
2599}
2600
2601void SelectionDAGISel::Select_CONVERGENCECTRL_LOOP(SDNode *N) {
2602 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_LOOP,
2603 N->getValueType(0), N->getOperand(0));
2604}
2605
2606void SelectionDAGISel::pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops,
2607 SDValue OpVal, SDLoc DL) {
2608 SDNode *OpNode = OpVal.getNode();
2609
2610 // FrameIndex nodes should have been directly emitted to TargetFrameIndex
2611 // nodes at DAG-construction time.
2612 assert(OpNode->getOpcode() != ISD::FrameIndex);
2613
2614 if (OpNode->getOpcode() == ISD::Constant) {
2615 Ops.push_back(
2616 CurDAG->getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
2617 Ops.push_back(CurDAG->getTargetConstant(OpNode->getAsZExtVal(), DL,
2618 OpVal.getValueType()));
2619 } else {
2620 Ops.push_back(OpVal);
2621 }
2622}
2623
2624void SelectionDAGISel::Select_STACKMAP(SDNode *N) {
2626 auto *It = N->op_begin();
2627 SDLoc DL(N);
2628
2629 // Stash the chain and glue operands so we can move them to the end.
2630 SDValue Chain = *It++;
2631 SDValue InGlue = *It++;
2632
2633 // <id> operand.
2634 SDValue ID = *It++;
2635 assert(ID.getValueType() == MVT::i64);
2636 Ops.push_back(ID);
2637
2638 // <numShadowBytes> operand.
2639 SDValue Shad = *It++;
2640 assert(Shad.getValueType() == MVT::i32);
2641 Ops.push_back(Shad);
2642
2643 // Live variable operands.
2644 for (; It != N->op_end(); It++)
2645 pushStackMapLiveVariable(Ops, *It, DL);
2646
2647 Ops.push_back(Chain);
2648 Ops.push_back(InGlue);
2649
2650 SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
2651 CurDAG->SelectNodeTo(N, TargetOpcode::STACKMAP, NodeTys, Ops);
2652}
2653
2654void SelectionDAGISel::Select_PATCHPOINT(SDNode *N) {
2656 auto *It = N->op_begin();
2657 SDLoc DL(N);
2658
2659 // Cache arguments that will be moved to the end in the target node.
2660 SDValue Chain = *It++;
2661 std::optional<SDValue> Glue;
2662 if (It->getValueType() == MVT::Glue)
2663 Glue = *It++;
2664 SDValue RegMask = *It++;
2665
2666 // <id> operand.
2667 SDValue ID = *It++;
2668 assert(ID.getValueType() == MVT::i64);
2669 Ops.push_back(ID);
2670
2671 // <numShadowBytes> operand.
2672 SDValue Shad = *It++;
2673 assert(Shad.getValueType() == MVT::i32);
2674 Ops.push_back(Shad);
2675
2676 // Add the callee.
2677 Ops.push_back(*It++);
2678
2679 // Add <numArgs>.
2680 SDValue NumArgs = *It++;
2681 assert(NumArgs.getValueType() == MVT::i32);
2682 Ops.push_back(NumArgs);
2683
2684 // Calling convention.
2685 Ops.push_back(*It++);
2686
2687 // Push the args for the call.
2688 for (uint64_t I = NumArgs->getAsZExtVal(); I != 0; I--)
2689 Ops.push_back(*It++);
2690
2691 // Now push the live variables.
2692 for (; It != N->op_end(); It++)
2693 pushStackMapLiveVariable(Ops, *It, DL);
2694
2695 // Finally, the regmask, chain and (if present) glue are moved to the end.
2696 Ops.push_back(RegMask);
2697 Ops.push_back(Chain);
2698 if (Glue.has_value())
2699 Ops.push_back(*Glue);
2700
2701 SDVTList NodeTys = N->getVTList();
2702 CurDAG->SelectNodeTo(N, TargetOpcode::PATCHPOINT, NodeTys, Ops);
2703}
2704
2705/// GetVBR - decode a vbr encoding whose top bit is set.
2707GetVBR(uint64_t Val, const uint8_t *MatcherTable, size_t &Idx) {
2708 assert(Val >= 128 && "Not a VBR");
2709 Val &= 127; // Remove first vbr bit.
2710
2711 unsigned Shift = 7;
2712 uint64_t NextBits;
2713 do {
2714 NextBits = MatcherTable[Idx++];
2715 Val |= (NextBits&127) << Shift;
2716 Shift += 7;
2717 } while (NextBits & 128);
2718
2719 return Val;
2720}
2721
2722LLVM_ATTRIBUTE_ALWAYS_INLINE static int64_t
2723GetSignedVBR(const unsigned char *MatcherTable, size_t &Idx) {
2724 int64_t Val = 0;
2725 unsigned Shift = 0;
2726 uint64_t NextBits;
2727 do {
2728 NextBits = MatcherTable[Idx++];
2729 Val |= (NextBits & 127) << Shift;
2730 Shift += 7;
2731 } while (NextBits & 128);
2732
2733 if (Shift < 64 && (NextBits & 0x40))
2734 Val |= UINT64_MAX << Shift;
2735
2736 return Val;
2737}
2738
2739/// getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value,
2740/// use GetVBR to decode it.
2742getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex) {
2743 unsigned SimpleVT = MatcherTable[MatcherIndex++];
2744 if (SimpleVT & 128)
2745 SimpleVT = GetVBR(SimpleVT, MatcherTable, MatcherIndex);
2746
2747 return static_cast<MVT::SimpleValueType>(SimpleVT);
2748}
2749
2750/// Decode a HwMode VT in MatcherTable by calling getValueTypeForHwMode.
2752getHwModeVT(const uint8_t *MatcherTable, size_t &MatcherIndex,
2753 const SelectionDAGISel &SDISel) {
2754 unsigned Index = MatcherTable[MatcherIndex++];
2755 return SDISel.getValueTypeForHwMode(Index);
2756}
2757
2758void SelectionDAGISel::Select_JUMP_TABLE_DEBUG_INFO(SDNode *N) {
2759 SDLoc dl(N);
2760 CurDAG->SelectNodeTo(N, TargetOpcode::JUMP_TABLE_DEBUG_INFO, MVT::Glue,
2761 CurDAG->getTargetConstant(N->getConstantOperandVal(1),
2762 dl, MVT::i64, true));
2763}
2764
2765/// When a match is complete, this method updates uses of interior chain results
2766/// to use the new results.
2767void SelectionDAGISel::UpdateChains(
2768 SDNode *NodeToMatch, SDValue InputChain,
2769 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2770 SmallVector<SDNode*, 4> NowDeadNodes;
2771
2772 // Now that all the normal results are replaced, we replace the chain and
2773 // glue results if present.
2774 if (!ChainNodesMatched.empty()) {
2775 assert(InputChain.getNode() &&
2776 "Matched input chains but didn't produce a chain");
2777 // Loop over all of the nodes we matched that produced a chain result.
2778 // Replace all the chain results with the final chain we ended up with.
2779 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2780 SDNode *ChainNode = ChainNodesMatched[i];
2781 // If ChainNode is null, it's because we replaced it on a previous
2782 // iteration and we cleared it out of the map. Just skip it.
2783 if (!ChainNode)
2784 continue;
2785
2786 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2787 "Deleted node left in chain");
2788
2789 // Don't replace the results of the root node if we're doing a
2790 // MorphNodeTo.
2791 if (ChainNode == NodeToMatch && isMorphNodeTo)
2792 continue;
2793
2794 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2795 if (ChainVal.getValueType() == MVT::Glue)
2796 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2797 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2798 SelectionDAG::DAGNodeDeletedListener NDL(
2799 *CurDAG, [&](SDNode *N, SDNode *E) {
2800 llvm::replace(ChainNodesMatched, N, static_cast<SDNode *>(nullptr));
2801 });
2802 if (ChainNode->getOpcode() != ISD::TokenFactor)
2803 ReplaceUses(ChainVal, InputChain);
2804
2805 // If the node became dead and we haven't already seen it, delete it.
2806 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2807 !llvm::is_contained(NowDeadNodes, ChainNode))
2808 NowDeadNodes.push_back(ChainNode);
2809 }
2810 }
2811
2812 if (!NowDeadNodes.empty())
2813 CurDAG->RemoveDeadNodes(NowDeadNodes);
2814
2815 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2816}
2817
2818/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2819/// operation for when the pattern matched at least one node with a chains. The
2820/// input vector contains a list of all of the chained nodes that we match. We
2821/// must determine if this is a valid thing to cover (i.e. matching it won't
2822/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2823/// be used as the input node chain for the generated nodes.
2824static SDValue
2826 SDValue InputGlue, SelectionDAG *CurDAG) {
2827
2830 SmallVector<SDValue, 3> InputChains;
2831 unsigned int Max = 8192;
2832
2833 // Quick exit on trivial merge.
2834 if (ChainNodesMatched.size() == 1)
2835 return ChainNodesMatched[0]->getOperand(0);
2836
2837 // Add chains that aren't already added (internal). Peek through
2838 // token factors.
2839 std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2840 if (V.getValueType() != MVT::Other)
2841 return;
2842 if (V->getOpcode() == ISD::EntryToken)
2843 return;
2844 if (!Visited.insert(V.getNode()).second)
2845 return;
2846 if (V->getOpcode() == ISD::TokenFactor) {
2847 for (const SDValue &Op : V->op_values())
2848 AddChains(Op);
2849 } else
2850 InputChains.push_back(V);
2851 };
2852
2853 for (auto *N : ChainNodesMatched) {
2854 Worklist.push_back(N);
2855 Visited.insert(N);
2856 }
2857
2858 while (!Worklist.empty())
2859 AddChains(Worklist.pop_back_val()->getOperand(0));
2860
2861 // Skip the search if there are no chain dependencies.
2862 if (InputChains.size() == 0)
2863 return CurDAG->getEntryNode();
2864
2865 // If one of these chains is a successor of input, we must have a
2866 // node that is both the predecessor and successor of the
2867 // to-be-merged nodes. Fail.
2868 Visited.clear();
2869 for (SDValue V : InputChains) {
2870 // If we need to create a TokenFactor, and any of the input chain nodes will
2871 // also be glued to the output, we cannot merge the chains. The TokenFactor
2872 // would prevent the glue from being honored.
2873 if (InputChains.size() != 1 &&
2874 V->getValueType(V->getNumValues() - 1) == MVT::Glue &&
2875 InputGlue.getNode() == V.getNode())
2876 return SDValue();
2877 Worklist.push_back(V.getNode());
2878 }
2879
2880 for (auto *N : ChainNodesMatched)
2881 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2882 return SDValue();
2883
2884 // Return merged chain.
2885 if (InputChains.size() == 1)
2886 return InputChains[0];
2887 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2888 MVT::Other, InputChains);
2889}
2890
2891/// MorphNode - Handle morphing a node in place for the selector.
2892SDNode *SelectionDAGISel::
2893MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2894 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2895 // It is possible we're using MorphNodeTo to replace a node with no
2896 // normal results with one that has a normal result (or we could be
2897 // adding a chain) and the input could have glue and chains as well.
2898 // In this case we need to shift the operands down.
2899 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2900 // than the old isel though.
2901 int OldGlueResultNo = -1, OldChainResultNo = -1;
2902
2903 unsigned NTMNumResults = Node->getNumValues();
2904 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2905 OldGlueResultNo = NTMNumResults-1;
2906 if (NTMNumResults != 1 &&
2907 Node->getValueType(NTMNumResults-2) == MVT::Other)
2908 OldChainResultNo = NTMNumResults-2;
2909 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2910 OldChainResultNo = NTMNumResults-1;
2911
2912 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2913 // that this deletes operands of the old node that become dead.
2914 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2915
2916 // MorphNodeTo can operate in two ways: if an existing node with the
2917 // specified operands exists, it can just return it. Otherwise, it
2918 // updates the node in place to have the requested operands.
2919 if (Res == Node) {
2920 // If we updated the node in place, reset the node ID. To the isel,
2921 // this should be just like a newly allocated machine node.
2922 Res->setNodeId(-1);
2923 }
2924
2925 unsigned ResNumResults = Res->getNumValues();
2926 // Move the glue if needed.
2927 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2928 static_cast<unsigned>(OldGlueResultNo) != ResNumResults - 1)
2929 ReplaceUses(SDValue(Node, OldGlueResultNo),
2930 SDValue(Res, ResNumResults - 1));
2931
2932 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2933 --ResNumResults;
2934
2935 // Move the chain reference if needed.
2936 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2937 static_cast<unsigned>(OldChainResultNo) != ResNumResults - 1)
2938 ReplaceUses(SDValue(Node, OldChainResultNo),
2939 SDValue(Res, ResNumResults - 1));
2940
2941 // Otherwise, no replacement happened because the node already exists. Replace
2942 // Uses of the old node with the new one.
2943 if (Res != Node) {
2944 ReplaceNode(Node, Res);
2945 } else {
2947 }
2948
2949 return Res;
2950}
2951
2952/// CheckSame - Implements OP_CheckSame.
2954CheckSame(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
2955 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
2956 // Accept if it is exactly the same as a previously recorded node.
2957 unsigned RecNo = MatcherTable[MatcherIndex++];
2958 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2959 return N == RecordedNodes[RecNo].first;
2960}
2961
2962/// CheckChildSame - Implements OP_CheckChildXSame.
2964 const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
2965 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
2966 unsigned ChildNo) {
2967 if (ChildNo >= N.getNumOperands())
2968 return false; // Match fails if out of range child #.
2969 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2970 RecordedNodes);
2971}
2972
2973/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2975CheckPatternPredicate(unsigned Opcode, const uint8_t *MatcherTable,
2976 size_t &MatcherIndex, const SelectionDAGISel &SDISel) {
2977 bool TwoBytePredNo =
2979 unsigned PredNo =
2980 TwoBytePredNo || Opcode == SelectionDAGISel::OPC_CheckPatternPredicate
2981 ? MatcherTable[MatcherIndex++]
2983 if (TwoBytePredNo)
2984 PredNo |= MatcherTable[MatcherIndex++] << 8;
2985 return SDISel.CheckPatternPredicate(PredNo);
2986}
2987
2988/// CheckNodePredicate - Implements OP_CheckNodePredicate.
2990CheckNodePredicate(unsigned Opcode, const uint8_t *MatcherTable,
2991 size_t &MatcherIndex, const SelectionDAGISel &SDISel,
2992 SDValue Op) {
2993 unsigned PredNo = Opcode == SelectionDAGISel::OPC_CheckPredicate
2994 ? MatcherTable[MatcherIndex++]
2996 return SDISel.CheckNodePredicate(Op, PredNo);
2997}
2998
3000CheckOpcode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDNode *N) {
3001 uint16_t Opc = MatcherTable[MatcherIndex++];
3002 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
3003 return N->getOpcode() == Opc;
3004}
3005
3007 SDValue N,
3008 const TargetLowering *TLI,
3009 const DataLayout &DL) {
3010 if (N.getValueType() == VT)
3011 return true;
3012
3013 // Handle the case when VT is iPTR.
3014 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
3015}
3016
3019 const DataLayout &DL, unsigned ChildNo) {
3020 if (ChildNo >= N.getNumOperands())
3021 return false; // Match fails if out of range child #.
3022 return ::CheckType(VT, N.getOperand(ChildNo), TLI, DL);
3023}
3024
3026CheckCondCode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N) {
3027 return cast<CondCodeSDNode>(N)->get() ==
3028 static_cast<ISD::CondCode>(MatcherTable[MatcherIndex++]);
3029}
3030
3032CheckChild2CondCode(const uint8_t *MatcherTable, size_t &MatcherIndex,
3033 SDValue N) {
3034 if (2 >= N.getNumOperands())
3035 return false;
3036 return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
3037}
3038
3040CheckValueType(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3041 const TargetLowering *TLI, const DataLayout &DL) {
3042 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
3043 if (cast<VTSDNode>(N)->getVT() == VT)
3044 return true;
3045
3046 // Handle the case when VT is iPTR.
3047 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
3048}
3049
3051CheckInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N) {
3052 int64_t Val = GetSignedVBR(MatcherTable, MatcherIndex);
3053
3055 return C && C->getAPIntValue().trySExtValue() == Val;
3056}
3057
3059CheckChildInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3060 unsigned ChildNo) {
3061 if (ChildNo >= N.getNumOperands())
3062 return false; // Match fails if out of range child #.
3063 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
3064}
3065
3067CheckAndImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3068 const SelectionDAGISel &SDISel) {
3069 int64_t Val = MatcherTable[MatcherIndex++];
3070 if (Val & 128)
3071 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3072
3073 if (N->getOpcode() != ISD::AND) return false;
3074
3075 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3076 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
3077}
3078
3080CheckOrImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N,
3081 const SelectionDAGISel &SDISel) {
3082 int64_t Val = MatcherTable[MatcherIndex++];
3083 if (Val & 128)
3084 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3085
3086 if (N->getOpcode() != ISD::OR) return false;
3087
3088 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3089 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
3090}
3091
3092/// IsPredicateKnownToFail - If we know how and can do so without pushing a
3093/// scope, evaluate the current node. Returns true if the current predicate is
3094/// known to fail; Index is unspecified in that case. If the current predicate
3095/// is known to pass, returns false and advances Index past it. If the current
3096/// predicate is unknown, returns false and leaves Index at the predicate.
3098 const uint8_t *Table, size_t &Index, SDValue N,
3099 const SelectionDAGISel &SDISel,
3100 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
3101 size_t StartIndex = Index;
3102 unsigned Opcode = Table[Index++];
3103 switch (Opcode) {
3104 default:
3105 Index = StartIndex; // Could not evaluate this predicate.
3106 return false;
3108 return !::CheckSame(Table, Index, N, RecordedNodes);
3113 return !::CheckChildSame(Table, Index, N, RecordedNodes,
3125 return !::CheckPatternPredicate(Opcode, Table, Index, SDISel);
3135 return !::CheckNodePredicate(Opcode, Table, Index, SDISel, N);
3137 return !::CheckOpcode(Table, Index, N.getNode());
3143 MVT VT;
3144 switch (Opcode) {
3146 VT = MVT::i32;
3147 break;
3149 VT = MVT::i64;
3150 break;
3152 VT = getHwModeVT(Table, Index, SDISel);
3153 break;
3155 VT = SDISel.getValueTypeForHwMode(0);
3156 break;
3157 default:
3158 VT = getSimpleVT(Table, Index);
3159 break;
3160 }
3161 return !::CheckType(VT.SimpleTy, N, SDISel.TLI,
3162 SDISel.CurDAG->getDataLayout());
3163 }
3166 unsigned Res = Table[Index++];
3168 ? getHwModeVT(Table, Index, SDISel)
3169 : getSimpleVT(Table, Index);
3170 return !::CheckType(VT.SimpleTy, N.getValue(Res), SDISel.TLI,
3171 SDISel.CurDAG->getDataLayout());
3172 }
3213 MVT VT;
3214 unsigned ChildNo;
3217 VT = MVT::i32;
3219 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3221 VT = MVT::i64;
3223 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeByHwMode &&
3225 VT = getHwModeVT(Table, Index, SDISel);
3229 VT = SDISel.getValueTypeForHwMode(0);
3231 } else {
3232 VT = getSimpleVT(Table, Index);
3233 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3234 }
3235 return !::CheckChildType(VT.SimpleTy, N, SDISel.TLI,
3236 SDISel.CurDAG->getDataLayout(), ChildNo);
3237 }
3239 return !::CheckCondCode(Table, Index, N);
3241 return !::CheckChild2CondCode(Table, Index, N);
3243 return !::CheckValueType(Table, Index, N, SDISel.TLI,
3244 SDISel.CurDAG->getDataLayout());
3246 return !::CheckInteger(Table, Index, N);
3252 return !::CheckChildInteger(
3255 return !::CheckAndImm(Table, Index, N, SDISel);
3257 return !::CheckOrImm(Table, Index, N, SDISel);
3258 }
3259}
3260
3261namespace {
3262
3263struct MatchScope {
3264 /// FailIndex - If this match fails, this is the index to continue with.
3265 unsigned FailIndex;
3266
3267 /// NodeStack - The node stack when the scope was formed.
3268 SmallVector<SDValue, 4> NodeStack;
3269
3270 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
3271 unsigned NumRecordedNodes;
3272
3273 /// NumMatchedMemRefs - The number of matched memref entries.
3274 unsigned NumMatchedMemRefs;
3275
3276 /// InputChain/InputGlue - The current chain/glue
3277 SDValue InputChain, InputGlue;
3278
3279 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
3280 bool HasChainNodesMatched;
3281};
3282
3283/// \A DAG update listener to keep the matching state
3284/// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
3285/// change the DAG while matching. X86 addressing mode matcher is an example
3286/// for this.
3287class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
3288{
3289 SDNode **NodeToMatch;
3290 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
3291 SmallVectorImpl<MatchScope> &MatchScopes;
3292
3293public:
3294 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
3295 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
3296 SmallVectorImpl<MatchScope> &MS)
3297 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
3298 RecordedNodes(RN), MatchScopes(MS) {}
3299
3300 void NodeDeleted(SDNode *N, SDNode *E) override {
3301 // Some early-returns here to avoid the search if we deleted the node or
3302 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
3303 // do, so it's unnecessary to update matching state at that point).
3304 // Neither of these can occur currently because we only install this
3305 // update listener during matching a complex patterns.
3306 if (!E || E->isMachineOpcode())
3307 return;
3308 // Check if NodeToMatch was updated.
3309 if (N == *NodeToMatch)
3310 *NodeToMatch = E;
3311 // Performing linear search here does not matter because we almost never
3312 // run this code. You'd have to have a CSE during complex pattern
3313 // matching.
3314 for (auto &I : RecordedNodes)
3315 if (I.first.getNode() == N)
3316 I.first.setNode(E);
3317
3318 for (auto &I : MatchScopes)
3319 for (auto &J : I.NodeStack)
3320 if (J.getNode() == N)
3321 J.setNode(E);
3322 }
3323};
3324
3325} // end anonymous namespace
3326
3328 const uint8_t *MatcherTable,
3329 unsigned TableSize,
3330 const uint8_t *OperandLists) {
3331 // FIXME: Should these even be selected? Handle these cases in the caller?
3332 switch (NodeToMatch->getOpcode()) {
3333 default:
3334 break;
3335 case ISD::EntryToken: // These nodes remain the same.
3336 case ISD::BasicBlock:
3337 case ISD::Register:
3338 case ISD::RegisterMask:
3339 case ISD::HANDLENODE:
3340 case ISD::MDNODE_SDNODE:
3346 case ISD::MCSymbol:
3351 case ISD::TokenFactor:
3352 case ISD::CopyFromReg:
3353 case ISD::CopyToReg:
3354 case ISD::EH_LABEL:
3357 case ISD::LIFETIME_END:
3358 case ISD::PSEUDO_PROBE:
3360 NodeToMatch->setNodeId(-1); // Mark selected.
3361 return;
3362 case ISD::AssertSext:
3363 case ISD::AssertZext:
3365 case ISD::AssertAlign:
3366 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
3367 CurDAG->RemoveDeadNode(NodeToMatch);
3368 return;
3369 case ISD::INLINEASM:
3370 case ISD::INLINEASM_BR:
3371 Select_INLINEASM(NodeToMatch);
3372 return;
3373 case ISD::READ_REGISTER:
3374 Select_READ_REGISTER(NodeToMatch);
3375 return;
3377 Select_WRITE_REGISTER(NodeToMatch);
3378 return;
3379 case ISD::POISON:
3380 case ISD::UNDEF:
3381 Select_UNDEF(NodeToMatch);
3382 return;
3383 case ISD::FAKE_USE:
3384 Select_FAKE_USE(NodeToMatch);
3385 return;
3386 case ISD::RELOC_NONE:
3387 Select_RELOC_NONE(NodeToMatch);
3388 return;
3389 case ISD::FREEZE:
3390 Select_FREEZE(NodeToMatch);
3391 return;
3392 case ISD::ARITH_FENCE:
3393 Select_ARITH_FENCE(NodeToMatch);
3394 return;
3395 case ISD::MEMBARRIER:
3396 Select_MEMBARRIER(NodeToMatch);
3397 return;
3398 case ISD::STACKMAP:
3399 Select_STACKMAP(NodeToMatch);
3400 return;
3401 case ISD::PATCHPOINT:
3402 Select_PATCHPOINT(NodeToMatch);
3403 return;
3405 Select_JUMP_TABLE_DEBUG_INFO(NodeToMatch);
3406 return;
3408 Select_CONVERGENCECTRL_ANCHOR(NodeToMatch);
3409 return;
3411 Select_CONVERGENCECTRL_ENTRY(NodeToMatch);
3412 return;
3414 Select_CONVERGENCECTRL_LOOP(NodeToMatch);
3415 return;
3416 }
3417
3418 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
3419
3420 // Set up the node stack with NodeToMatch as the only node on the stack.
3421 SmallVector<SDValue, 8> NodeStack;
3422 SDValue N = SDValue(NodeToMatch, 0);
3423 NodeStack.push_back(N);
3424
3425 // MatchScopes - Scopes used when matching, if a match failure happens, this
3426 // indicates where to continue checking.
3427 SmallVector<MatchScope, 8> MatchScopes;
3428
3429 // RecordedNodes - This is the set of nodes that have been recorded by the
3430 // state machine. The second value is the parent of the node, or null if the
3431 // root is recorded.
3433
3434 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
3435 // pattern.
3437
3438 // These are the current input chain and glue for use when generating nodes.
3439 // Various Emit operations change these. For example, emitting a copytoreg
3440 // uses and updates these.
3441 SDValue InputChain, InputGlue, DeactivationSymbol;
3442
3443 // ChainNodesMatched - If a pattern matches nodes that have input/output
3444 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
3445 // which ones they are. The result is captured into this list so that we can
3446 // update the chain results when the pattern is complete.
3447 SmallVector<SDNode*, 3> ChainNodesMatched;
3448
3449 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
3450
3451 // Determine where to start the interpreter. Normally we start at opcode #0,
3452 // but if the state machine starts with an OPC_SwitchOpcode, then we
3453 // accelerate the first lookup (which is guaranteed to be hot) with the
3454 // OpcodeOffset table.
3455 size_t MatcherIndex = 0;
3456
3457 if (!OpcodeOffset.empty()) {
3458 // Already computed the OpcodeOffset table, just index into it.
3459 if (N.getOpcode() < OpcodeOffset.size())
3460 MatcherIndex = OpcodeOffset[N.getOpcode()];
3461 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
3462
3463 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
3464 // Otherwise, the table isn't computed, but the state machine does start
3465 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
3466 // is the first time we're selecting an instruction.
3467 size_t Idx = 1;
3468 while (true) {
3469 // Get the size of this case.
3470 unsigned CaseSize = MatcherTable[Idx++];
3471 if (CaseSize & 128)
3472 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
3473 if (CaseSize == 0) break;
3474
3475 // Get the opcode, add the index to the table.
3476 uint16_t Opc = MatcherTable[Idx++];
3477 Opc |= static_cast<uint16_t>(MatcherTable[Idx++]) << 8;
3478 if (Opc >= OpcodeOffset.size())
3479 OpcodeOffset.resize((Opc+1)*2);
3480 OpcodeOffset[Opc] = Idx;
3481 Idx += CaseSize;
3482 }
3483
3484 // Okay, do the lookup for the first opcode.
3485 if (N.getOpcode() < OpcodeOffset.size())
3486 MatcherIndex = OpcodeOffset[N.getOpcode()];
3487 }
3488
3489 while (true) {
3490 assert(MatcherIndex < TableSize && "Invalid index");
3491#ifndef NDEBUG
3492 size_t CurrentOpcodeIndex = MatcherIndex;
3493#endif
3494 BuiltinOpcodes Opcode =
3495 static_cast<BuiltinOpcodes>(MatcherTable[MatcherIndex++]);
3496 switch (Opcode) {
3497 case OPC_Scope: {
3498 // Okay, the semantics of this operation are that we should push a scope
3499 // then evaluate the first child. However, pushing a scope only to have
3500 // the first check fail (which then pops it) is inefficient. If we can
3501 // determine immediately that the first check (or first several) will
3502 // immediately fail, don't even bother pushing a scope for them.
3503 size_t FailIndex;
3504
3505 while (true) {
3506 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3507 if (NumToSkip & 128)
3508 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3509 // Found the end of the scope with no match.
3510 if (NumToSkip == 0) {
3511 FailIndex = 0;
3512 break;
3513 }
3514
3515 FailIndex = MatcherIndex+NumToSkip;
3516
3517 size_t MatcherIndexOfPredicate = MatcherIndex;
3518 (void)MatcherIndexOfPredicate; // silence warning.
3519
3520 // If we can't evaluate this predicate without pushing a scope (e.g. if
3521 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3522 // push the scope and evaluate the full predicate chain.
3523 if (!IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, *this,
3524 RecordedNodes))
3525 break;
3526
3527 LLVM_DEBUG(
3528 dbgs() << " Skipped scope entry (due to false predicate) at "
3529 << "index " << MatcherIndexOfPredicate << ", continuing at "
3530 << FailIndex << "\n");
3531 ++NumDAGIselRetries;
3532
3533 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3534 // move to the next case.
3535 MatcherIndex = FailIndex;
3536 }
3537
3538 // If the whole scope failed to match, bail.
3539 if (FailIndex == 0) break;
3540
3541 // Push a MatchScope which indicates where to go if the first child fails
3542 // to match.
3543 MatchScope &NewEntry = MatchScopes.emplace_back();
3544 NewEntry.FailIndex = FailIndex;
3545 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3546 NewEntry.NumRecordedNodes = RecordedNodes.size();
3547 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3548 NewEntry.InputChain = InputChain;
3549 NewEntry.InputGlue = InputGlue;
3550 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3551 continue;
3552 }
3553 case OPC_RecordNode: {
3554 // Remember this node, it may end up being an operand in the pattern.
3555 SDNode *Parent = nullptr;
3556 if (NodeStack.size() > 1)
3557 Parent = NodeStack[NodeStack.size()-2].getNode();
3558 RecordedNodes.emplace_back(N, Parent);
3559 continue;
3560 }
3561
3566 unsigned ChildNo = Opcode-OPC_RecordChild0;
3567 if (ChildNo >= N.getNumOperands())
3568 break; // Match fails if out of range child #.
3569
3570 RecordedNodes.emplace_back(N->getOperand(ChildNo), N.getNode());
3571 continue;
3572 }
3573 case OPC_RecordMemRef:
3574 if (auto *MN = dyn_cast<MemSDNode>(N))
3575 llvm::append_range(MatchedMemRefs, MN->memoperands());
3576 else {
3577 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
3578 dbgs() << '\n');
3579 }
3580
3581 continue;
3582
3584 // If the current node has an input glue, capture it in InputGlue.
3585 if (N->getNumOperands() != 0 &&
3586 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3587 InputGlue = N->getOperand(N->getNumOperands()-1);
3588 continue;
3589
3591 // If the current node has a deactivation symbol, capture it in
3592 // DeactivationSymbol.
3593 if (N->getNumOperands() != 0 &&
3594 N->getOperand(N->getNumOperands() - 1).getOpcode() ==
3596 DeactivationSymbol = N->getOperand(N->getNumOperands() - 1);
3597 continue;
3598
3599 case OPC_MoveChild: {
3600 unsigned ChildNo = MatcherTable[MatcherIndex++];
3601 if (ChildNo >= N.getNumOperands())
3602 break; // Match fails if out of range child #.
3603 N = N.getOperand(ChildNo);
3604 NodeStack.push_back(N);
3605 continue;
3606 }
3607
3608 case OPC_MoveChild0: case OPC_MoveChild1:
3609 case OPC_MoveChild2: case OPC_MoveChild3:
3610 case OPC_MoveChild4: case OPC_MoveChild5:
3611 case OPC_MoveChild6: case OPC_MoveChild7: {
3612 unsigned ChildNo = Opcode-OPC_MoveChild0;
3613 if (ChildNo >= N.getNumOperands())
3614 break; // Match fails if out of range child #.
3615 N = N.getOperand(ChildNo);
3616 NodeStack.push_back(N);
3617 continue;
3618 }
3619
3620 case OPC_MoveSibling:
3621 case OPC_MoveSibling0:
3622 case OPC_MoveSibling1:
3623 case OPC_MoveSibling2:
3624 case OPC_MoveSibling3:
3625 case OPC_MoveSibling4:
3626 case OPC_MoveSibling5:
3627 case OPC_MoveSibling6:
3628 case OPC_MoveSibling7: {
3629 // Pop the current node off the NodeStack.
3630 NodeStack.pop_back();
3631 assert(!NodeStack.empty() && "Node stack imbalance!");
3632 N = NodeStack.back();
3633
3634 unsigned SiblingNo = Opcode == OPC_MoveSibling
3635 ? MatcherTable[MatcherIndex++]
3636 : Opcode - OPC_MoveSibling0;
3637 if (SiblingNo >= N.getNumOperands())
3638 break; // Match fails if out of range sibling #.
3639 N = N.getOperand(SiblingNo);
3640 NodeStack.push_back(N);
3641 continue;
3642 }
3643 case OPC_MoveParent:
3644 // Pop the current node off the NodeStack.
3645 NodeStack.pop_back();
3646 assert(!NodeStack.empty() && "Node stack imbalance!");
3647 N = NodeStack.back();
3648 continue;
3649
3650 case OPC_CheckSame:
3651 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3652 continue;
3653
3656 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3657 Opcode-OPC_CheckChild0Same))
3658 break;
3659 continue;
3660
3671 if (!::CheckPatternPredicate(Opcode, MatcherTable, MatcherIndex, *this))
3672 break;
3673 continue;
3682 case OPC_CheckPredicate:
3683 if (!::CheckNodePredicate(Opcode, MatcherTable, MatcherIndex, *this, N))
3684 break;
3685 continue;
3687 unsigned OpNum = MatcherTable[MatcherIndex++];
3689
3690 for (unsigned i = 0; i < OpNum; ++i)
3691 Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3692
3693 unsigned PredNo = MatcherTable[MatcherIndex++];
3695 break;
3696 continue;
3697 }
3706 case OPC_CheckComplexPat7: {
3707 unsigned CPNum = Opcode == OPC_CheckComplexPat
3708 ? MatcherTable[MatcherIndex++]
3709 : Opcode - OPC_CheckComplexPat0;
3710 unsigned RecNo = MatcherTable[MatcherIndex++];
3711 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3712
3713 // If target can modify DAG during matching, keep the matching state
3714 // consistent.
3715 std::unique_ptr<MatchStateUpdater> MSU;
3717 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3718 MatchScopes));
3719
3720 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3721 RecordedNodes[RecNo].first, CPNum,
3722 RecordedNodes))
3723 break;
3724 continue;
3725 }
3726 case OPC_CheckOpcode:
3727 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3728 continue;
3729
3730 case OPC_CheckType:
3731 case OPC_CheckTypeI32:
3732 case OPC_CheckTypeI64:
3735 MVT VT;
3736 switch (Opcode) {
3737 case OPC_CheckTypeI32:
3738 VT = MVT::i32;
3739 break;
3740 case OPC_CheckTypeI64:
3741 VT = MVT::i64;
3742 break;
3744 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
3745 break;
3747 VT = getValueTypeForHwMode(0);
3748 break;
3749 default:
3750 VT = getSimpleVT(MatcherTable, MatcherIndex);
3751 break;
3752 }
3753 if (!::CheckType(VT.SimpleTy, N, TLI, CurDAG->getDataLayout()))
3754 break;
3755 continue;
3756 }
3757
3758 case OPC_CheckTypeRes:
3760 unsigned Res = MatcherTable[MatcherIndex++];
3761 MVT VT = Opcode == OPC_CheckTypeResByHwMode
3762 ? getHwModeVT(MatcherTable, MatcherIndex, *this)
3763 : getSimpleVT(MatcherTable, MatcherIndex);
3764 if (!::CheckType(VT.SimpleTy, N.getValue(Res), TLI,
3765 CurDAG->getDataLayout()))
3766 break;
3767 continue;
3768 }
3769
3770 case OPC_SwitchOpcode: {
3771 unsigned CurNodeOpcode = N.getOpcode();
3772 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3773 unsigned CaseSize;
3774 while (true) {
3775 // Get the size of this case.
3776 CaseSize = MatcherTable[MatcherIndex++];
3777 if (CaseSize & 128)
3778 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3779 if (CaseSize == 0) break;
3780
3781 uint16_t Opc = MatcherTable[MatcherIndex++];
3782 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
3783
3784 // If the opcode matches, then we will execute this case.
3785 if (CurNodeOpcode == Opc)
3786 break;
3787
3788 // Otherwise, skip over this case.
3789 MatcherIndex += CaseSize;
3790 }
3791
3792 // If no cases matched, bail out.
3793 if (CaseSize == 0) break;
3794
3795 // Otherwise, execute the case we found.
3796 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
3797 << MatcherIndex << "\n");
3798 continue;
3799 }
3800
3801 case OPC_SwitchType: {
3802 MVT CurNodeVT = N.getSimpleValueType();
3803 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3804 unsigned CaseSize;
3805 while (true) {
3806 // Get the size of this case.
3807 CaseSize = MatcherTable[MatcherIndex++];
3808 if (CaseSize & 128)
3809 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3810 if (CaseSize == 0) break;
3811
3812 MVT CaseVT = getSimpleVT(MatcherTable, MatcherIndex);
3813 if (CaseVT == MVT::iPTR)
3814 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3815
3816 // If the VT matches, then we will execute this case.
3817 if (CurNodeVT == CaseVT)
3818 break;
3819
3820 // Otherwise, skip over this case.
3821 MatcherIndex += CaseSize;
3822 }
3823
3824 // If no cases matched, bail out.
3825 if (CaseSize == 0) break;
3826
3827 // Otherwise, execute the case we found.
3828 LLVM_DEBUG(dbgs() << " TypeSwitch[" << CurNodeVT
3829 << "] from " << SwitchStart << " to " << MatcherIndex
3830 << '\n');
3831 continue;
3832 }
3834 unsigned ChildNo = MatcherTable[MatcherIndex++];
3835 [[maybe_unused]] unsigned SwitchStart = MatcherIndex - 2;
3836 // The match fails if the child is missing or not a constant.
3837 std::optional<int64_t> ChildVal;
3838 if (ChildNo < N.getNumOperands()) {
3839 if (auto *C = dyn_cast<ConstantSDNode>(N.getOperand(ChildNo)))
3840 ChildVal = C->getAPIntValue().trySExtValue();
3841 }
3842
3843 unsigned CaseSize;
3844 while (true) {
3845 // Get the size of this case.
3846 CaseSize = MatcherTable[MatcherIndex++];
3847 if (CaseSize & 128)
3848 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3849 if (CaseSize == 0)
3850 break;
3851
3852 int64_t CaseVal = GetSignedVBR(MatcherTable, MatcherIndex);
3853
3854 // If the value matches, then we will execute this case.
3855 if (ChildVal == CaseVal)
3856 break;
3857
3858 // Otherwise, skip over this case.
3859 MatcherIndex += CaseSize;
3860 }
3861
3862 // If no cases matched, bail out.
3863 if (CaseSize == 0)
3864 break;
3865
3866 LLVM_DEBUG(dbgs() << " ChildIntegerSwitch[" << ChildNo << "] from "
3867 << SwitchStart << " to " << MatcherIndex << '\n');
3868 continue;
3869 }
3895 unsigned ChildNo;
3898 VT = MVT::i32;
3900 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3902 VT = MVT::i64;
3904 } else {
3905 VT = getSimpleVT(MatcherTable, MatcherIndex);
3906 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3907 }
3908 if (!::CheckChildType(VT, N, TLI, CurDAG->getDataLayout(), ChildNo))
3909 break;
3910 continue;
3911 }
3928 MVT VT;
3929 unsigned ChildNo;
3930 if (Opcode >= OPC_CheckChild0TypeByHwMode0 &&
3931 Opcode <= OPC_CheckChild7TypeByHwMode0) {
3932 VT = getValueTypeForHwMode(0);
3933 ChildNo = Opcode - OPC_CheckChild0TypeByHwMode0;
3934 } else {
3935 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
3936 ChildNo = Opcode - OPC_CheckChild0TypeByHwMode;
3937 }
3938 if (!::CheckChildType(VT.SimpleTy, N, TLI, CurDAG->getDataLayout(),
3939 ChildNo))
3940 break;
3941 continue;
3942 }
3943 case OPC_CheckCondCode:
3944 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3945 continue;
3947 if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3948 continue;
3949 case OPC_CheckValueType:
3950 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3951 CurDAG->getDataLayout()))
3952 break;
3953 continue;
3954 case OPC_CheckInteger:
3955 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3956 continue;
3960 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3961 Opcode-OPC_CheckChild0Integer)) break;
3962 continue;
3963 case OPC_CheckAndImm:
3964 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3965 continue;
3966 case OPC_CheckOrImm:
3967 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3968 continue;
3971 break;
3972 continue;
3975 break;
3976 continue;
3977 case OPC_CheckUndef:
3978 if (!N.isUndef())
3979 break;
3980 continue;
3981
3983 assert(NodeStack.size() != 1 && "No parent node");
3984 // Verify that all intermediate nodes between the root and this one have
3985 // a single use (ignoring chains, which are handled in UpdateChains).
3986 bool HasMultipleUses = false;
3987 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3988 unsigned NNonChainUses = 0;
3989 SDNode *NS = NodeStack[i].getNode();
3990 for (const SDUse &U : NS->uses())
3991 if (U.getValueType() != MVT::Other)
3992 if (++NNonChainUses > 1) {
3993 HasMultipleUses = true;
3994 break;
3995 }
3996 if (HasMultipleUses) break;
3997 }
3998 if (HasMultipleUses) break;
3999
4000 // Check to see that the target thinks this is profitable to fold and that
4001 // we can fold it without inducing cycles in the graph.
4002 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
4003 NodeToMatch) ||
4004 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
4005 NodeToMatch, OptLevel,
4006 true/*We validate our own chains*/))
4007 break;
4008
4009 continue;
4010 }
4011 case OPC_EmitInteger:
4012 case OPC_EmitIntegerI8:
4013 case OPC_EmitIntegerI16:
4014 case OPC_EmitIntegerI32:
4015 case OPC_EmitIntegerI64:
4018 MVT VT;
4019 switch (Opcode) {
4020 case OPC_EmitIntegerI8:
4021 VT = MVT::i8;
4022 break;
4023 case OPC_EmitIntegerI16:
4024 VT = MVT::i16;
4025 break;
4026 case OPC_EmitIntegerI32:
4027 VT = MVT::i32;
4028 break;
4029 case OPC_EmitIntegerI64:
4030 VT = MVT::i64;
4031 break;
4033 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
4034 break;
4036 VT = getValueTypeForHwMode(0);
4037 break;
4038 default:
4039 VT = getSimpleVT(MatcherTable, MatcherIndex);
4040 break;
4041 }
4042 int64_t Val = GetSignedVBR(MatcherTable, MatcherIndex);
4043 Val = SignExtend64(Val, MVT(VT).getFixedSizeInBits());
4044 RecordedNodes.emplace_back(
4045 CurDAG->getSignedConstant(Val, SDLoc(NodeToMatch), VT.SimpleTy,
4046 /*isTarget=*/true),
4047 nullptr);
4048 continue;
4049 }
4050
4051 case OPC_EmitRegister:
4055 MVT VT;
4056 switch (Opcode) {
4058 VT = MVT::i32;
4059 break;
4061 VT = MVT::i64;
4062 break;
4064 VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
4065 break;
4066 default:
4067 VT = getSimpleVT(MatcherTable, MatcherIndex);
4068 break;
4069 }
4070 unsigned RegNo = MatcherTable[MatcherIndex++];
4071 RecordedNodes.emplace_back(CurDAG->getRegister(RegNo, VT), nullptr);
4072 continue;
4073 }
4074 case OPC_EmitRegister2:
4076 // For targets w/ more than 256 register names, the register enum
4077 // values are stored in two bytes in the matcher table (just like
4078 // opcodes).
4079 MVT VT = Opcode == OPC_EmitRegisterByHwMode2
4080 ? getHwModeVT(MatcherTable, MatcherIndex, *this)
4081 : getSimpleVT(MatcherTable, MatcherIndex);
4082 unsigned RegNo = MatcherTable[MatcherIndex++];
4083 RegNo |= MatcherTable[MatcherIndex++] << 8;
4084 RecordedNodes.emplace_back(CurDAG->getRegister(RegNo, VT), nullptr);
4085 continue;
4086 }
4087
4097 // Convert from IMM/FPIMM to target version.
4098 unsigned RecNo = Opcode == OPC_EmitConvertToTarget
4099 ? MatcherTable[MatcherIndex++]
4100 : Opcode - OPC_EmitConvertToTarget0;
4101 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
4102 SDValue Imm = RecordedNodes[RecNo].first;
4103
4104 if (Imm->getOpcode() == ISD::Constant) {
4105 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
4106 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
4107 Imm.getValueType());
4108 } else if (Imm->getOpcode() == ISD::ConstantFP) {
4109 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
4110 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
4111 Imm.getValueType());
4112 }
4113
4114 RecordedNodes.emplace_back(Imm, RecordedNodes[RecNo].second);
4115 continue;
4116 }
4117
4118 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
4119 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
4120 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
4121 // These are space-optimized forms of OPC_EmitMergeInputChains.
4122 assert(!InputChain.getNode() &&
4123 "EmitMergeInputChains should be the first chain producing node");
4124 assert(ChainNodesMatched.empty() &&
4125 "Should only have one EmitMergeInputChains per match");
4126
4127 // Read all of the chained nodes.
4128 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
4129 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
4130 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
4131
4132 // If the chained node is not the root, we can't fold it if it has
4133 // multiple uses.
4134 // FIXME: What if other value results of the node have uses not matched
4135 // by this pattern?
4136 if (ChainNodesMatched.back() != NodeToMatch &&
4137 !RecordedNodes[RecNo].first.hasOneUse()) {
4138 ChainNodesMatched.clear();
4139 break;
4140 }
4141
4142 // Merge the input chains if they are not intra-pattern references.
4143 InputChain = HandleMergeInputChains(ChainNodesMatched, InputGlue, CurDAG);
4144
4145 if (!InputChain.getNode())
4146 break; // Failed to merge.
4147 continue;
4148 }
4149
4151 assert(!InputChain.getNode() &&
4152 "EmitMergeInputChains should be the first chain producing node");
4153 // This node gets a list of nodes we matched in the input that have
4154 // chains. We want to token factor all of the input chains to these nodes
4155 // together. However, if any of the input chains is actually one of the
4156 // nodes matched in this pattern, then we have an intra-match reference.
4157 // Ignore these because the newly token factored chain should not refer to
4158 // the old nodes.
4159 unsigned NumChains = MatcherTable[MatcherIndex++];
4160 assert(NumChains != 0 && "Can't TF zero chains");
4161
4162 assert(ChainNodesMatched.empty() &&
4163 "Should only have one EmitMergeInputChains per match");
4164
4165 // Read all of the chained nodes.
4166 for (unsigned i = 0; i != NumChains; ++i) {
4167 unsigned RecNo = MatcherTable[MatcherIndex++];
4168 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
4169 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
4170
4171 // If the chained node is not the root, we can't fold it if it has
4172 // multiple uses.
4173 // FIXME: What if other value results of the node have uses not matched
4174 // by this pattern?
4175 if (ChainNodesMatched.back() != NodeToMatch &&
4176 !RecordedNodes[RecNo].first.hasOneUse()) {
4177 ChainNodesMatched.clear();
4178 break;
4179 }
4180 }
4181
4182 // If the inner loop broke out, the match fails.
4183 if (ChainNodesMatched.empty())
4184 break;
4185
4186 // Merge the input chains if they are not intra-pattern references.
4187 InputChain = HandleMergeInputChains(ChainNodesMatched, InputGlue, CurDAG);
4188
4189 if (!InputChain.getNode())
4190 break; // Failed to merge.
4191
4192 continue;
4193 }
4194
4195 case OPC_EmitCopyToReg:
4196 case OPC_EmitCopyToReg0:
4197 case OPC_EmitCopyToReg1:
4198 case OPC_EmitCopyToReg2:
4199 case OPC_EmitCopyToReg3:
4200 case OPC_EmitCopyToReg4:
4201 case OPC_EmitCopyToReg5:
4202 case OPC_EmitCopyToReg6:
4203 case OPC_EmitCopyToReg7:
4205 unsigned RecNo =
4206 Opcode >= OPC_EmitCopyToReg0 && Opcode <= OPC_EmitCopyToReg7
4207 ? Opcode - OPC_EmitCopyToReg0
4208 : MatcherTable[MatcherIndex++];
4209 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
4210 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
4211 if (Opcode == OPC_EmitCopyToRegTwoByte)
4212 DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
4213
4214 if (!InputChain.getNode())
4215 InputChain = CurDAG->getEntryNode();
4216
4217 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
4218 DestPhysReg, RecordedNodes[RecNo].first,
4219 InputGlue);
4220
4221 InputGlue = InputChain.getValue(1);
4222 continue;
4223 }
4224
4225 case OPC_EmitNodeXForm: {
4226 unsigned XFormNo = MatcherTable[MatcherIndex++];
4227 unsigned RecNo = MatcherTable[MatcherIndex++];
4228 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
4229 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
4230 RecordedNodes.emplace_back(Res, nullptr);
4231 continue;
4232 }
4233 case OPC_Coverage: {
4234 // This is emitted right before MorphNode/EmitNode.
4235 // So it should be safe to assume that this node has been selected
4236 unsigned index = MatcherTable[MatcherIndex++];
4237 index |= (MatcherTable[MatcherIndex++] << 8);
4238 index |= (MatcherTable[MatcherIndex++] << 16);
4239 index |= (MatcherTable[MatcherIndex++] << 24);
4240 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
4241 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
4242 continue;
4243 }
4244
4245 case OPC_EmitNode:
4247 case OPC_EmitNode0:
4248 case OPC_EmitNode1:
4249 case OPC_EmitNode2:
4250 case OPC_EmitNode1None:
4251 case OPC_EmitNode2None:
4252 case OPC_EmitNode0Chain:
4253 case OPC_EmitNode1Chain:
4254 case OPC_EmitNode2Chain:
4255 case OPC_MorphNodeTo:
4257 case OPC_MorphNodeTo0:
4258 case OPC_MorphNodeTo1:
4259 case OPC_MorphNodeTo2:
4269 uint32_t TargetOpc = MatcherTable[MatcherIndex++];
4270 TargetOpc |= (MatcherTable[MatcherIndex++] << 8);
4271 unsigned EmitNodeInfo;
4272 if (Opcode >= OPC_EmitNode1None && Opcode <= OPC_EmitNode2Chain) {
4273 if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4274 EmitNodeInfo = OPFL_Chain;
4275 else
4276 EmitNodeInfo = OPFL_None;
4277 } else if (Opcode >= OPC_MorphNodeTo1None &&
4278 Opcode <= OPC_MorphNodeTo2GlueOutput) {
4279 if (Opcode >= OPC_MorphNodeTo0Chain && Opcode <= OPC_MorphNodeTo2Chain)
4280 EmitNodeInfo = OPFL_Chain;
4281 else if (Opcode >= OPC_MorphNodeTo1GlueInput &&
4282 Opcode <= OPC_MorphNodeTo2GlueInput)
4283 EmitNodeInfo = OPFL_GlueInput;
4284 else if (Opcode >= OPC_MorphNodeTo1GlueOutput &&
4286 EmitNodeInfo = OPFL_GlueOutput;
4287 else
4288 EmitNodeInfo = OPFL_None;
4289 } else
4290 EmitNodeInfo = MatcherTable[MatcherIndex++];
4291 // Get the result VT list.
4292 unsigned NumVTs;
4293 // If this is one of the compressed forms, get the number of VTs based
4294 // on the Opcode. Otherwise read the next byte from the table.
4295 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
4296 NumVTs = Opcode - OPC_MorphNodeTo0;
4297 else if (Opcode >= OPC_MorphNodeTo1None && Opcode <= OPC_MorphNodeTo2None)
4298 NumVTs = Opcode - OPC_MorphNodeTo1None + 1;
4299 else if (Opcode >= OPC_MorphNodeTo0Chain &&
4300 Opcode <= OPC_MorphNodeTo2Chain)
4301 NumVTs = Opcode - OPC_MorphNodeTo0Chain;
4302 else if (Opcode >= OPC_MorphNodeTo1GlueInput &&
4303 Opcode <= OPC_MorphNodeTo2GlueInput)
4304 NumVTs = Opcode - OPC_MorphNodeTo1GlueInput + 1;
4305 else if (Opcode >= OPC_MorphNodeTo1GlueOutput &&
4307 NumVTs = Opcode - OPC_MorphNodeTo1GlueOutput + 1;
4308 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
4309 NumVTs = Opcode - OPC_EmitNode0;
4310 else if (Opcode >= OPC_EmitNode1None && Opcode <= OPC_EmitNode2None)
4311 NumVTs = Opcode - OPC_EmitNode1None + 1;
4312 else if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4313 NumVTs = Opcode - OPC_EmitNode0Chain;
4314 else
4315 NumVTs = MatcherTable[MatcherIndex++];
4317 if (Opcode == OPC_EmitNodeByHwMode || Opcode == OPC_MorphNodeToByHwMode) {
4318 for (unsigned i = 0; i != NumVTs; ++i) {
4319 MVT VT = getHwModeVT(MatcherTable, MatcherIndex, *this);
4320 if (VT == MVT::iPTR)
4321 VT = TLI->getPointerTy(CurDAG->getDataLayout());
4322 VTs.push_back(VT);
4323 }
4324 } else {
4325 for (unsigned i = 0; i != NumVTs; ++i) {
4326 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
4327 if (VT == MVT::iPTR)
4328 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
4329 VTs.push_back(VT);
4330 }
4331 }
4332
4333 if (EmitNodeInfo & OPFL_Chain)
4334 VTs.push_back(MVT::Other);
4335 if (EmitNodeInfo & OPFL_GlueOutput)
4336 VTs.push_back(MVT::Glue);
4337
4338 // This is hot code, so optimize the two most common cases of 1 and 2
4339 // results.
4340 SDVTList VTList;
4341 if (VTs.size() == 1)
4342 VTList = CurDAG->getVTList(VTs[0]);
4343 else if (VTs.size() == 2)
4344 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
4345 else
4346 VTList = CurDAG->getVTList(VTs);
4347
4348 // Get the operand list.
4349 unsigned NumOps = MatcherTable[MatcherIndex++];
4350
4352 if (NumOps != 0) {
4353 // Get the index into the OperandLists.
4354 size_t OperandIndex = MatcherTable[MatcherIndex++];
4355 if (OperandIndex & 128)
4356 OperandIndex = GetVBR(OperandIndex, MatcherTable, MatcherIndex);
4357
4358 for (unsigned i = 0; i != NumOps; ++i) {
4359 unsigned RecNo = OperandLists[OperandIndex++];
4360 if (RecNo & 128)
4361 RecNo = GetVBR(RecNo, OperandLists, OperandIndex);
4362
4363 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
4364 Ops.push_back(RecordedNodes[RecNo].first);
4365 }
4366 }
4367
4368 // If there are variadic operands to add, handle them now.
4369 if (EmitNodeInfo & OPFL_VariadicInfo) {
4370 // Determine the start index to copy from.
4371 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
4372 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
4373 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
4374 "Invalid variadic node");
4375 // Copy all of the variadic operands, not including a potential glue
4376 // input.
4377 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
4378 i != e; ++i) {
4379 SDValue V = NodeToMatch->getOperand(i);
4380 if (V.getValueType() == MVT::Glue) break;
4381 Ops.push_back(V);
4382 }
4383 }
4384
4385 // If this has chain/glue inputs, add them.
4386 if (EmitNodeInfo & OPFL_Chain)
4387 Ops.push_back(InputChain);
4388 if (DeactivationSymbol.getNode() != nullptr)
4389 Ops.push_back(DeactivationSymbol);
4390 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
4391 Ops.push_back(InputGlue);
4392
4393 // Check whether any matched node could raise an FP exception. Since all
4394 // such nodes must have a chain, it suffices to check ChainNodesMatched.
4395 // We need to perform this check before potentially modifying one of the
4396 // nodes via MorphNode.
4397 bool MayRaiseFPException =
4398 llvm::any_of(ChainNodesMatched, [this](SDNode *N) {
4399 return mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept();
4400 });
4401
4402 // Create the node.
4403 MachineSDNode *Res = nullptr;
4404 bool IsMorphNodeTo =
4405 Opcode == OPC_MorphNodeTo || Opcode == OPC_MorphNodeToByHwMode ||
4406 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2GlueOutput);
4407 if (!IsMorphNodeTo) {
4408 // If this is a normal EmitNode command, just create the new node and
4409 // add the results to the RecordedNodes list.
4410 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
4411 VTList, Ops);
4412
4413 // Add all the non-glue/non-chain results to the RecordedNodes list.
4414 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
4415 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
4416 RecordedNodes.emplace_back(SDValue(Res, i), nullptr);
4417 }
4418 } else {
4419 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
4420 "NodeToMatch was removed partway through selection");
4422 SDNode *E) {
4423 CurDAG->salvageDebugInfo(*N);
4424 auto &Chain = ChainNodesMatched;
4425 assert((!E || !is_contained(Chain, N)) &&
4426 "Chain node replaced during MorphNode");
4427 llvm::erase(Chain, N);
4428 });
4429 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
4430 Ops, EmitNodeInfo));
4431 }
4432
4433 // Set the NoFPExcept flag when no original matched node could
4434 // raise an FP exception, but the new node potentially might.
4435 if (!MayRaiseFPException && mayRaiseFPException(Res))
4436 Res->setFlags(Res->getFlags() | SDNodeFlags::NoFPExcept);
4437
4438 // If the node had chain/glue results, update our notion of the current
4439 // chain and glue.
4440 if (EmitNodeInfo & OPFL_GlueOutput) {
4441 InputGlue = SDValue(Res, VTs.size()-1);
4442 if (EmitNodeInfo & OPFL_Chain)
4443 InputChain = SDValue(Res, VTs.size()-2);
4444 } else if (EmitNodeInfo & OPFL_Chain)
4445 InputChain = SDValue(Res, VTs.size()-1);
4446
4447 // If the OPFL_MemRefs glue is set on this node, slap all of the
4448 // accumulated memrefs onto it.
4449 //
4450 // FIXME: This is vastly incorrect for patterns with multiple outputs
4451 // instructions that access memory and for ComplexPatterns that match
4452 // loads.
4453 if (EmitNodeInfo & OPFL_MemRefs) {
4454 // Only attach load or store memory operands if the generated
4455 // instruction may load or store.
4456 const MCInstrDesc &MCID = TII->get(TargetOpc);
4457 bool mayLoad = MCID.mayLoad();
4458 bool mayStore = MCID.mayStore();
4459
4460 // We expect to have relatively few of these so just filter them into a
4461 // temporary buffer so that we can easily add them to the instruction.
4463 for (MachineMemOperand *MMO : MatchedMemRefs) {
4464 if (MMO->isLoad()) {
4465 if (mayLoad)
4466 FilteredMemRefs.push_back(MMO);
4467 } else if (MMO->isStore()) {
4468 if (mayStore)
4469 FilteredMemRefs.push_back(MMO);
4470 } else {
4471 FilteredMemRefs.push_back(MMO);
4472 }
4473 }
4474
4475 CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
4476 }
4477
4478 LLVM_DEBUG({
4479 if (!MatchedMemRefs.empty() && Res->memoperands_empty())
4480 dbgs() << " Dropping mem operands\n";
4481 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") << " node: ";
4482 Res->dump(CurDAG);
4483 });
4484
4485 // If this was a MorphNodeTo then we're completely done!
4486 if (IsMorphNodeTo) {
4487 // Update chain uses.
4488 UpdateChains(Res, InputChain, ChainNodesMatched, true);
4489 return;
4490 }
4491 continue;
4492 }
4493
4494 case OPC_CompleteMatch: {
4495 // The match has been completed, and any new nodes (if any) have been
4496 // created. Patch up references to the matched dag to use the newly
4497 // created nodes.
4498 unsigned NumResults = MatcherTable[MatcherIndex++];
4499
4500 for (unsigned i = 0; i != NumResults; ++i) {
4501 unsigned ResSlot = MatcherTable[MatcherIndex++];
4502 if (ResSlot & 128)
4503 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
4504
4505 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
4506 SDValue Res = RecordedNodes[ResSlot].first;
4507
4508 assert(i < NodeToMatch->getNumValues() &&
4509 NodeToMatch->getValueType(i) != MVT::Other &&
4510 NodeToMatch->getValueType(i) != MVT::Glue &&
4511 "Invalid number of results to complete!");
4512 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
4513 NodeToMatch->getValueType(i) == MVT::iPTR ||
4514 Res.getValueType() == MVT::iPTR ||
4515 NodeToMatch->getValueType(i).getSizeInBits() ==
4516 Res.getValueSizeInBits()) &&
4517 "invalid replacement");
4518 ReplaceUses(SDValue(NodeToMatch, i), Res);
4519 }
4520
4521 // Update chain uses.
4522 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
4523
4524 // If the root node defines glue, we need to update it to the glue result.
4525 // TODO: This never happens in our tests and I think it can be removed /
4526 // replaced with an assert, but if we do it this the way the change is
4527 // NFC.
4528 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
4529 MVT::Glue &&
4530 InputGlue.getNode())
4531 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
4532 InputGlue);
4533
4534 assert(NodeToMatch->use_empty() &&
4535 "Didn't replace all uses of the node?");
4536 CurDAG->RemoveDeadNode(NodeToMatch);
4537
4538 return;
4539 }
4540 }
4541
4542 // If the code reached this point, then the match failed. See if there is
4543 // another child to try in the current 'Scope', otherwise pop it until we
4544 // find a case to check.
4545 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
4546 << "\n");
4547 ++NumDAGIselRetries;
4548 while (true) {
4549 if (MatchScopes.empty()) {
4550 CannotYetSelect(NodeToMatch);
4551 return;
4552 }
4553
4554 // Restore the interpreter state back to the point where the scope was
4555 // formed.
4556 MatchScope &LastScope = MatchScopes.back();
4557 RecordedNodes.resize(LastScope.NumRecordedNodes);
4558 NodeStack.assign(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
4559 N = NodeStack.back();
4560
4561 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
4562 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
4563 MatcherIndex = LastScope.FailIndex;
4564
4565 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
4566
4567 InputChain = LastScope.InputChain;
4568 InputGlue = LastScope.InputGlue;
4569 if (!LastScope.HasChainNodesMatched)
4570 ChainNodesMatched.clear();
4571
4572 // Check to see what the offset is at the new MatcherIndex. If it is zero
4573 // we have reached the end of this scope, otherwise we have another child
4574 // in the current scope to try.
4575 unsigned NumToSkip = MatcherTable[MatcherIndex++];
4576 if (NumToSkip & 128)
4577 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
4578
4579 // If we have another child in this scope to match, update FailIndex and
4580 // try it.
4581 if (NumToSkip != 0) {
4582 LastScope.FailIndex = MatcherIndex+NumToSkip;
4583 break;
4584 }
4585
4586 // End of this scope, pop it and try the next child in the containing
4587 // scope.
4588 MatchScopes.pop_back();
4589 }
4590 }
4591}
4592
4593/// Return whether the node may raise an FP exception.
4595 // For machine opcodes, consult the MCID flag.
4596 if (N->isMachineOpcode()) {
4597 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
4598 return MCID.mayRaiseFPException();
4599 }
4600
4601 // For ISD opcodes, only StrictFP opcodes may raise an FP
4602 // exception.
4603 if (N->isTargetOpcode()) {
4604 const SelectionDAGTargetInfo &TSI = CurDAG->getSelectionDAGInfo();
4605 return TSI.mayRaiseFPException(N->getOpcode());
4606 }
4607 return N->isStrictFPOpcode();
4608}
4609
4611 assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
4612 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
4613 if (!C)
4614 return false;
4615
4616 // Detect when "or" is used to add an offset to a stack object.
4617 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
4618 MachineFrameInfo &MFI = MF->getFrameInfo();
4619 Align A = MFI.getObjectAlign(FN->getIndex());
4620 int32_t Off = C->getSExtValue();
4621 // If the alleged offset fits in the zero bits guaranteed by
4622 // the alignment, then this or is really an add.
4623 return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
4624 }
4625 return false;
4626}
4627
4629 SDValue &ShAmt) const {
4630 assert(isPowerOf2_32(ShiftWidth) && "Unexpected max shift amount!");
4631 unsigned ShiftBits = Log2_32(ShiftWidth);
4632
4633 // A truncation that keeps the low ShiftBits bits doesn't change the bits the
4634 // shift reads.
4635 if (N.getOpcode() == ISD::TRUNCATE &&
4636 N.getScalarValueSizeInBits() >= ShiftBits)
4637 N = N.getOperand(0);
4638
4639 if (N.getOpcode() != ISD::AND || !isa<ConstantSDNode>(N.getOperand(1)))
4640 return false;
4641
4642 const APInt &AndMask = N.getConstantOperandAPInt(1);
4643 if (AndMask.getBitWidth() < ShiftBits)
4644 return false;
4645
4646 // Since the max shift amount is a power of 2 we can subtract 1 to make a
4647 // mask that covers the bits needed to represent all shift amounts.
4648 APInt ShMask(AndMask.getBitWidth(), ShiftWidth - 1);
4649 if (!ShMask.isSubsetOf(AndMask)) {
4650 // SimplifyDemandedBits may have optimized the mask so try restoring any
4651 // bits that are known zero.
4652 KnownBits Known = CurDAG->computeKnownBits(N.getOperand(0));
4653 if (!ShMask.isSubsetOf(AndMask | Known.Zero))
4654 return false;
4655 }
4656
4657 ShAmt = N.getOperand(0);
4658 return true;
4659}
4660
4661void SelectionDAGISel::CannotYetSelect(SDNode *N) {
4662 std::string msg;
4664 Msg << "Cannot select: ";
4665
4666 Msg.enable_colors(errs().has_colors());
4667
4668 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
4669 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
4670 N->getOpcode() != ISD::INTRINSIC_VOID) {
4671 N->printrFull(Msg, CurDAG);
4672 Msg << "\nIn function: " << MF->getName();
4673 } else {
4674 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
4675 unsigned iid = N->getConstantOperandVal(HasInputChain);
4676 if (iid < Intrinsic::num_intrinsics)
4677 Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
4678 else
4679 Msg << "unknown intrinsic #" << iid;
4680 }
4681 report_fatal_error(Twine(msg));
4682}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
return SDValue()
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Expand Atomic instructions
BitTracker BT
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ATTRIBUTE_ALWAYS_INLINE
LLVM_ATTRIBUTE_ALWAYS_INLINE - On compilers where we have a directive to do so, mark a method "always...
Definition Compiler.h:376
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the FastISel class.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
This header defines classes/functions to handle pass execution timing information with interfaces for...
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
MachineRegisterInfo & MRI
SI Fold Operands
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckNodePredicate(unsigned Opcode, const uint8_t *MatcherTable, size_t &MatcherIndex, const SelectionDAGISel &SDISel, SDValue Op)
CheckNodePredicate - Implements OP_CheckNodePredicate.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
CheckSame - Implements OP_CheckSame.
static cl::opt< bool > ViewSUnitDAGs("view-sunit-dags", cl::Hidden, cl::desc("Pop up a window to show SUnit dags after they are processed"))
static cl::opt< bool > ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the post " "legalize types dag combine pass"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOrImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckCondCode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, unsigned ChildNo)
static cl::opt< bool > ViewISelDAGs("view-isel-dags", cl::Hidden, cl::desc("Pop up a window to show isel dags as they are selected"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE uint64_t GetVBR(uint64_t Val, const uint8_t *MatcherTable, size_t &Idx)
GetVBR - decode a vbr encoding whose top bit is set.
static cl::opt< bool > DumpSortedDAG("dump-sorted-dags", cl::Hidden, cl::desc("Print DAGs with sorted nodes in debug dump"), cl::init(false))
static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort)
static bool IsPredicateKnownToFail(const uint8_t *Table, size_t &Index, SDValue N, const SelectionDAGISel &SDISel, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
IsPredicateKnownToFail - If we know how and can do so without pushing a scope, evaluate the current n...
static cl::opt< bool > ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the second " "dag combine pass"))
static RegisterScheduler defaultListDAGScheduler("default", "Best scheduler for the target", createDefaultScheduler)
static cl::opt< int > EnableFastISelAbort("fast-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \"fast\" instruction selection " "fails to lower an instruction: 0 disable the abort, 1 will " "abort but for args, calls and terminators, 2 will also " "abort for argument lowering, and 3 will never fallback " "to SelectionDAG."))
static void mapWasmLandingPadIndex(MachineBasicBlock *MBB, const CatchPadInst *CPI)
#define ISEL_DUMP(X)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildSame(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes, unsigned ChildNo)
CheckChildSame - Implements OP_CheckChildXSame.
static void processSingleLocVars(FunctionLoweringInfo &FuncInfo, FunctionVarLocs const *FnVarLocs)
Collect single location variable information generated with assignment tracking.
static cl::opt< bool > UseMBPI("use-mbpi", cl::desc("use Machine Branch Probability Info"), cl::init(true), cl::Hidden)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI, const DataLayout &DL, unsigned ChildNo)
static bool dontUseFastISelFor(const Function &Fn)
static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, bool IgnoreChains)
findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path beyond "ImmedUse".
static cl::opt< bool > ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the first " "dag combine pass"))
static bool processIfEntryValueDbgDeclare(FunctionLoweringInfo &FuncInfo, const Value *Arg, DIExpression *Expr, DILocalVariable *Var, DebugLoc DbgLoc)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckInteger(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckPatternPredicate(unsigned Opcode, const uint8_t *MatcherTable, size_t &MatcherIndex, const SelectionDAGISel &SDISel)
CheckPatternPredicate - Implements OP_CheckPatternPredicate.
static cl::opt< bool > ViewSchedDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed"))
static void processDbgDeclares(FunctionLoweringInfo &FuncInfo)
Collect llvm.dbg.declare information.
static void preserveFakeUses(BasicBlock::iterator Begin, BasicBlock::iterator End)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOpcode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDNode *N)
static SDValue HandleMergeInputChains(const SmallVectorImpl< SDNode * > &ChainNodesMatched, SDValue InputGlue, SelectionDAG *CurDAG)
HandleMergeInputChains - This implements the OPC_EmitMergeInputChains operation for when the pattern ...
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckAndImm(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckValueType(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static cl::opt< bool > ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize"))
static cl::opt< bool > ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize types"))
static cl::opt< RegisterScheduler::FunctionPassCtor, false, RegisterPassParser< RegisterScheduler > > ISHeuristic("pre-RA-sched", cl::init(&createDefaultScheduler), cl::Hidden, cl::desc("Instruction schedulers available (before register" " allocation):"))
ISHeuristic command line option for instruction schedulers.
static LLVM_ATTRIBUTE_ALWAYS_INLINE int64_t GetSignedVBR(const unsigned char *MatcherTable, size_t &Idx)
static bool maintainPGOProfile(const TargetMachine &TM, CodeGenOptLevel OptLevel)
static cl::opt< bool > EnableFastISelFallbackReport("fast-isel-report-on-fallback", cl::Hidden, cl::desc("Emit a diagnostic when \"fast\" instruction selection " "falls back to SelectionDAG."))
static bool processDbgDeclare(FunctionLoweringInfo &FuncInfo, const Value *Address, DIExpression *Expr, DILocalVariable *Var, DebugLoc DbgLoc)
static LLVM_ATTRIBUTE_ALWAYS_INLINE MVT::SimpleValueType getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex)
getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value, use GetVBR to decode it.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChild2CondCode(const uint8_t *MatcherTable, size_t &MatcherIndex, SDValue N)
static cl::opt< std::string > FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, cl::desc("Only display the basic block whose name " "matches this for all view-*-dags options"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE MVT getHwModeVT(const uint8_t *MatcherTable, size_t &MatcherIndex, const SelectionDAGISel &SDISel)
Decode a HwMode VT in MatcherTable by calling getValueTypeForHwMode.
static bool isFoldedOrDeadInstruction(const Instruction *I, const FunctionLoweringInfo &FuncInfo)
isFoldedOrDeadInstruction - Return true if the specified instruction is side-effect free and is eithe...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
unsigned getNumber() const
Definition BasicBlock.h:94
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:170
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:682
LLVM_ABI const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes BranchProbabilityInfo.
Legacy analysis pass which computes BranchProbabilityInfo.
This class represents a function call, abstracting a target machine's calling convention.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Diagnostic information for ISel fallback path.
void setLastLocalValue(MachineInstr *I)
Update the position of the last instruction emitted for materializing constants for use in the curren...
Definition FastISel.h:239
void handleDbgInfo(const Instruction *II)
Target-independent lowering of non-instruction debug info associated with this instruction.
bool tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst)
We're checking to see if we can fold LI into FoldInst.
void removeDeadCode(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E)
Remove all dead instructions between the I and E.
Definition FastISel.cpp:415
void startNewBlock()
Set the current block to which generated machine instructions will be appended.
Definition FastISel.cpp:123
bool selectInstruction(const Instruction *I)
Do "fast" instruction selection for the given LLVM IR instruction and append the generated machine in...
void finishBasicBlock()
Flush the local value map.
Definition FastISel.cpp:136
void recomputeInsertPt()
Reset InsertPt to prepare for inserting instructions into the current block.
Definition FastISel.cpp:406
bool lowerArguments()
Do "fast" instruction selection for function arguments and append the machine instructions to the cur...
Definition FastISel.cpp:138
unsigned arg_size() const
arg_size - Return the number of funcletpad arguments.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
SmallPtrSet< const DbgVariableRecord *, 8 > PreprocessedDVRDeclares
Collection of dbg_declare instructions handled after argument lowering and before ISel proper.
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
LLVM_ABI int getArgumentFrameIndex(const Argument *A)
getArgumentFrameIndex - Get frame index for the byval argument.
bool isExportedInst(const Value *V) const
isExportedInst - Return true if the specified value is an instruction exported from its block.
DenseMap< const Value *, Register > ValueMap
ValueMap - Since we emit code for the function a basic block at a time, we must remember which virtua...
MachineRegisterInfo * RegInfo
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:197
Data structure describing the variable locations in a function.
const VarLocInfo * single_locs_begin() const
DILocalVariable * getDILocalVariable(const VarLocInfo *Loc) const
Return the DILocalVariable for the location definition represented by ID.
const VarLocInfo * single_locs_end() const
One past the last single-location variable location definition.
const BasicBlock & getEntryBlock() const
Definition Function.h:803
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:822
iterator_range< arg_iterator > args()
Definition Function.h:886
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition Function.h:321
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
An analysis pass which caches information about the Function.
Definition GCMetadata.h:214
An analysis pass which caches information about the entire Module.
Definition GCMetadata.h:237
Module * getParent()
Get the module that this global value is contained inside of...
This class is used to form a handle around another node that is persistent and is updated across invo...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool isTerminator() const
iterator_range< user_iterator > users()
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
Describe properties that are true of each instruction in the target description file.
const MDNode * getMD() const
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
Machine Value Type.
SimpleValueType SimpleTy
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasCalls() const
Return true if the current function has any function calls.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index)
Map the landing pad to its index. Used for Wasm exception handling.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void setUseDebugInstrRef(bool UseInstrRef)
Set whether this function will use instruction referencing or not.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool shouldUseDebugInstrRef() const
Determine whether, in the current machine configuration, we should use instruction referencing or not...
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable in a stack slot.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
Representation of each machine instruction.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
Register getReg() const
getReg - Returns the register number.
MachinePassRegistry - Track the registration of machine passes.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
ArrayRef< std::pair< MCRegister, Register > > liveins() const
An SDNode that represents everything that will be needed to construct a MachineInstr.
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:377
This class is used by SelectionDAGISel to temporarily override the optimization level on a per-functi...
OptLevelChanger(SelectionDAGISel &ISel, CodeGenOptLevel NewOptLevel)
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
RegisterPassParser class - Handle the addition of new machine passes.
ScheduleDAGSDNodes *(*)(SelectionDAGISel *, CodeGenOptLevel) FunctionPassCtor
static LLVM_ABI MachinePassRegistry< FunctionPassCtor > Registry
RegisterScheduler class - Track the registration of instruction schedulers.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
SDNode * getGluedUser() const
If this node has a glue value with a user, return the user (there is at most one).
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
iterator_range< use_iterator > uses()
void setNodeId(int Id)
Set unique node id.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
SelectionDAGISelLegacy(char &ID, std::unique_ptr< SelectionDAGISel > S)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
std::optional< BatchAAResults > BatchAA
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, std::vector< SDValue > &OutOps)
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckOrMask - The isel is trying to match something like (or X, 255).
void initializeAnalysisResults(MachineFunctionAnalysisManager &MFAM)
const TargetTransformInfo * TTI
virtual bool CheckNodePredicate(SDValue Op, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
virtual bool CheckNodePredicateWithOperands(SDValue Op, unsigned PredNo, ArrayRef< SDValue > Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
std::unique_ptr< OptimizationRemarkEmitter > ORE
Current optimization remark emitter.
MachineRegisterInfo * RegInfo
unsigned DAGSize
DAGSize - Size of DAG being instruction selected.
bool isOrEquivalentToAdd(const SDNode *N) const
virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N, unsigned PatternNo, SmallVectorImpl< std::pair< SDValue, SDNode * > > &Result)
virtual bool CheckPatternPredicate(unsigned PredNo) const
CheckPatternPredicate - This function is generated by tblgen in the target.
static int getNumFixedFromVariadicInfo(unsigned Flags)
getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the number of fixed arity values ...
const TargetLibraryInfo * LibInfo
static int getUninvalidatedNodeId(SDNode *N)
const TargetInstrInfo * TII
std::unique_ptr< SwiftErrorValueTracking > SwiftError
static void EnforceNodeIdInvariant(SDNode *N)
void ReplaceUses(SDValue F, SDValue T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const
IsProfitableToFold - Returns true if it's profitable to fold the specific operand node N of U during ...
virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo)
virtual MVT getValueTypeForHwMode(unsigned Index) const
bool MatchFilterFuncName
True if the function currently processing is in the function printing list (i.e.
void SelectInlineAsmMemoryOperands(std::vector< SDValue > &Ops, const SDLoc &DL)
SelectInlineAsmMemoryOperands - Calls to this are automatically generated by tblgen.
static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOptLevel OptLevel, bool IgnoreChains=false)
IsLegalToFold - Returns true if the specific operand node N of U can be folded during instruction sel...
virtual bool ComplexPatternFuncMutatesDAG() const
Return true if complex patterns for this target can mutate the DAG.
virtual void PreprocessISelDAG()
PreprocessISelDAG - This hook allows targets to hack on the graph before instruction selection starts...
BatchAAResults * getBatchAA() const
Returns a (possibly null) pointer to the current BatchAAResults.
bool CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckAndMask - The isel is trying to match something like (and X, 255).
virtual StringRef getPatternForIndex(unsigned index)
getPatternForIndex - Patterns selected by tablegen during ISEL
bool mayRaiseFPException(SDNode *Node) const
Return whether the node may raise an FP exception.
std::unique_ptr< SelectionDAGBuilder > SDB
bool selectShiftAmountMask(SDValue N, unsigned ShiftWidth, SDValue &ShAmt) const
Look through a mask on the amount N of a shift that reads only the low Log2(ShiftWidth) bits of its a...
void ReplaceNode(SDNode *F, SDNode *T)
Replace all uses of F with T, then remove F from the DAG.
void SelectCodeCommon(SDNode *NodeToMatch, const uint8_t *MatcherTable, unsigned TableSize, const uint8_t *OperandLists)
const LibcallLoweringInfo * LibcallLowering
SelectionDAGISel(TargetMachine &tm, CodeGenOptLevel OL=CodeGenOptLevel::Default)
virtual bool runOnMachineFunction(MachineFunction &mf)
static void InvalidateNodeId(SDNode *N)
virtual StringRef getIncludePathForIndex(unsigned index)
getIncludePathForIndex - get the td source location of pattern instantiation
Targets can subclass this to parameterize the SelectionDAG lowering and instruction selection process...
virtual bool mayRaiseFPException(unsigned Opcode) const
Returns true if a node with the given target-specific opcode may raise a floating-point exception.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
allnodes_const_iterator allnodes_begin() const
const DataLayout & getDataLayout() const
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
ilist< SDNode >::iterator allnodes_iterator
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
virtual MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
Primary interface to the complete machine description for the target machine.
const std::optional< PGOOptions > & getPGOOption() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
Wrapper pass for TargetTransformInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
@ TargetConstantPool
Definition ISDOpcodes.h:191
@ CONVERGENCECTRL_ANCHOR
The llvm.experimental.convergence.* intrinsics.
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ TargetBlockAddress
Definition ISDOpcodes.h:193
@ DEACTIVATION_SYMBOL
Untyped node storing deactivation symbol reference (DeactivationSymbolSDNode).
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ FAKE_USE
FAKE_USE represents a use of the operand but does not do anything.
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ TargetExternalSymbol
Definition ISDOpcodes.h:192
@ CONVERGENCECTRL_ENTRY
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:71
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ TargetConstantFP
Definition ISDOpcodes.h:182
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ TargetFrameIndex
Definition ISDOpcodes.h:189
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ RELOC_NONE
Issue a no-op relocation against a given symbol at the current location.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
@ STACKMAP
The llvm.experimental.stackmap intrinsic.
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ CONVERGENCECTRL_LOOP
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:188
LLVM_ABI bool isConstantSplatVectorAllOnes(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
LLVM_ABI ScheduleDAGSDNodes * createDefaultScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createDefaultScheduler - This creates an instruction scheduler appropriate for the target.
@ Offset
Definition DWP.cpp:577
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI ScheduleDAGSDNodes * createBURRListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createBURRListDAGScheduler - This creates a bottom up register usage reduction list scheduler.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Known
Known to have no common set bits.
@ Kill
The last use of a register.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI ScheduleDAGSDNodes * createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createHybridListDAGScheduler - This creates a bottom up register pressure aware list scheduler that m...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI MachineBasicBlock::iterator findSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI ScheduleDAGSDNodes * createFastDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createFastDAGScheduler - This creates a "fast" scheduler.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI ScheduleDAGSDNodes * createDAGLinearizer(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createDAGLinearizer - This creates a "no-scheduling" scheduler which linearize the DAG using topologi...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool isFunctionInPrintList(StringRef FunctionName)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
@ AfterLegalizeDAG
Definition DAGCombine.h:19
@ AfterLegalizeVectorOps
Definition DAGCombine.h:18
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
@ AfterLegalizeTypes
Definition DAGCombine.h:17
LLVM_ABI ScheduleDAGSDNodes * createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createSourceListDAGScheduler - This creates a bottom up list scheduler that schedules nodes in source...
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
DWARFExpression::Operation Op
LLVM_ABI void initializeAAResultsWrapperPassPass(PassRegistry &)
LLVM_ABI void initializeTargetLibraryInfoWrapperPassPass(PassRegistry &)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI ScheduleDAGSDNodes * createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createILPListDAGScheduler - This creates a bottom up register pressure aware list scheduler that trie...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI void initializeBranchProbabilityInfoWrapperPassPass(PassRegistry &)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
LLVM_ABI ScheduleDAGSDNodes * createVLIWDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createVLIWDAGScheduler - Scheduler for VLIW targets.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
A struct capturing PGO tunables.
Definition PGOOptions.h:22
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Clients of various APIs that cause global effects on the DAG can optionally implement this interface.
LLVM_ABI void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)
DenseMap< const BasicBlock *, int > BlockToStateMap