LLVM 20.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"
83#include "llvm/IR/PrintPasses.h"
84#include "llvm/IR/Statepoint.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/User.h"
87#include "llvm/IR/Value.h"
89#include "llvm/MC/MCInstrDesc.h"
90#include "llvm/Pass.h"
96#include "llvm/Support/Debug.h"
99#include "llvm/Support/Timer.h"
105#include <algorithm>
106#include <cassert>
107#include <cstdint>
108#include <iterator>
109#include <limits>
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
151 cl::desc("Only display the basic block whose name "
152 "matches this for all view-*-dags options"));
153static cl::opt<bool>
154ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
155 cl::desc("Pop up a window to show dags before the first "
156 "dag combine pass"));
157static cl::opt<bool>
158ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
159 cl::desc("Pop up a window to show dags before legalize types"));
160static cl::opt<bool>
161 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
162 cl::desc("Pop up a window to show dags before the post "
163 "legalize types dag combine pass"));
164static cl::opt<bool>
165 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
166 cl::desc("Pop up a window to show dags before legalize"));
167static cl::opt<bool>
168ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
169 cl::desc("Pop up a window to show dags before the second "
170 "dag combine pass"));
171static cl::opt<bool>
172ViewISelDAGs("view-isel-dags", cl::Hidden,
173 cl::desc("Pop up a window to show isel dags as they are selected"));
174static cl::opt<bool>
175ViewSchedDAGs("view-sched-dags", cl::Hidden,
176 cl::desc("Pop up a window to show sched dags as they are processed"));
177static cl::opt<bool>
178ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
179 cl::desc("Pop up a window to show SUnit dags after they are processed"));
180#else
181static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
182 ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
183 ViewDAGCombine2 = false, ViewISelDAGs = false,
184 ViewSchedDAGs = false, ViewSUnitDAGs = false;
185#endif
186
187#ifndef NDEBUG
188#define ISEL_DUMP(X) \
189 do { \
190 if (llvm::DebugFlag && \
191 (isCurrentDebugType(DEBUG_TYPE) || \
192 (isCurrentDebugType(ISEL_DUMP_DEBUG_TYPE) && MatchFilterFuncName))) { \
193 X; \
194 } \
195 } while (false)
196#else
197#define ISEL_DUMP(X) do { } while (false)
198#endif
199
200//===---------------------------------------------------------------------===//
201///
202/// RegisterScheduler class - Track the registration of instruction schedulers.
203///
204//===---------------------------------------------------------------------===//
207
208//===---------------------------------------------------------------------===//
209///
210/// ISHeuristic command line option for instruction schedulers.
211///
212//===---------------------------------------------------------------------===//
215ISHeuristic("pre-RA-sched",
217 cl::desc("Instruction schedulers available (before register"
218 " allocation):"));
219
221defaultListDAGScheduler("default", "Best scheduler for the target",
223
224static bool dontUseFastISelFor(const Function &Fn) {
225 // Don't enable FastISel for functions with swiftasync Arguments.
226 // Debug info on those is reliant on good Argument lowering, and FastISel is
227 // not capable of lowering the entire function. Mixing the two selectors tend
228 // to result in poor lowering of Arguments.
229 return any_of(Fn.args(), [](const Argument &Arg) {
230 return Arg.hasAttribute(Attribute::AttrKind::SwiftAsync);
231 });
232}
233
234namespace llvm {
235
236 //===--------------------------------------------------------------------===//
237 /// This class is used by SelectionDAGISel to temporarily override
238 /// the optimization level on a per-function basis.
241 CodeGenOptLevel SavedOptLevel;
242 bool SavedFastISel;
243
244 public:
246 : IS(ISel) {
247 SavedOptLevel = IS.OptLevel;
248 SavedFastISel = IS.TM.Options.EnableFastISel;
249 if (NewOptLevel != SavedOptLevel) {
250 IS.OptLevel = NewOptLevel;
251 IS.TM.setOptLevel(NewOptLevel);
252 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
253 << IS.MF->getFunction().getName() << "\n");
254 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(SavedOptLevel)
255 << " ; After: -O" << static_cast<int>(NewOptLevel)
256 << "\n");
257 if (NewOptLevel == CodeGenOptLevel::None)
259 }
261 IS.TM.setFastISel(false);
263 dbgs() << "\tFastISel is "
264 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
265 << "\n");
266 }
267
269 if (IS.OptLevel == SavedOptLevel)
270 return;
271 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
272 << IS.MF->getFunction().getName() << "\n");
273 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(IS.OptLevel)
274 << " ; After: -O" << static_cast<int>(SavedOptLevel) << "\n");
275 IS.OptLevel = SavedOptLevel;
276 IS.TM.setOptLevel(SavedOptLevel);
277 IS.TM.setFastISel(SavedFastISel);
278 }
279 };
280
281 //===--------------------------------------------------------------------===//
282 /// createDefaultScheduler - This creates an instruction scheduler appropriate
283 /// for the target.
285 CodeGenOptLevel OptLevel) {
286 const TargetLowering *TLI = IS->TLI;
287 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
288
289 // Try first to see if the Target has its own way of selecting a scheduler
290 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
291 return SchedulerCtor(IS, OptLevel);
292 }
293
294 if (OptLevel == CodeGenOptLevel::None ||
295 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
297 return createSourceListDAGScheduler(IS, OptLevel);
299 return createBURRListDAGScheduler(IS, OptLevel);
301 return createHybridListDAGScheduler(IS, OptLevel);
303 return createVLIWDAGScheduler(IS, OptLevel);
305 return createFastDAGScheduler(IS, OptLevel);
307 return createDAGLinearizer(IS, OptLevel);
309 "Unknown sched type!");
310 return createILPListDAGScheduler(IS, OptLevel);
311 }
312
313} // end namespace llvm
314
317 MachineBasicBlock *MBB) const {
318#ifndef NDEBUG
319 dbgs() << "If a target marks an instruction with "
320 "'usesCustomInserter', it must implement "
321 "TargetLowering::EmitInstrWithCustomInserter!\n";
322#endif
323 llvm_unreachable(nullptr);
324}
325
327 SDNode *Node) const {
328 assert(!MI.hasPostISelHook() &&
329 "If a target marks an instruction with 'hasPostISelHook', "
330 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
331}
332
333//===----------------------------------------------------------------------===//
334// SelectionDAGISel code
335//===----------------------------------------------------------------------===//
336
338 char &ID, std::unique_ptr<SelectionDAGISel> S)
339 : MachineFunctionPass(ID), Selector(std::move(S)) {
345}
346
348 // If we already selected that function, we do not need to run SDISel.
349 if (MF.getProperties().hasProperty(
351 return false;
352
353 // Do some sanity-checking on the command-line options.
354 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
355 report_fatal_error("-fast-isel-abort > 0 requires -fast-isel");
356
357 // Decide what flavour of variable location debug-info will be used, before
358 // we change the optimisation level.
360
361 // Reset the target options before resetting the optimization
362 // level below.
363 // FIXME: This is a horrible hack and should be processed via
364 // codegen looking at the optimization level explicitly when
365 // it wants to look at it.
366 Selector->TM.resetTargetOptions(MF.getFunction());
367 // Reset OptLevel to None for optnone functions.
368 CodeGenOptLevel NewOptLevel = skipFunction(MF.getFunction())
370 : Selector->OptLevel;
371
372 Selector->MF = &MF;
373 OptLevelChanger OLC(*Selector, NewOptLevel);
374 Selector->initializeAnalysisResults(*this);
375 return Selector->runOnMachineFunction(MF);
376}
377
379 : TM(tm), FuncInfo(new FunctionLoweringInfo()),
380 SwiftError(new SwiftErrorValueTracking()),
381 CurDAG(new SelectionDAG(tm, OL)),
382 SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
383 OL)),
384 OptLevel(OL) {
390}
391
393 delete CurDAG;
394 delete SwiftError;
395}
396
398 CodeGenOptLevel OptLevel = Selector->OptLevel;
399 if (OptLevel != CodeGenOptLevel::None)
405#ifndef NDEBUG
407#endif
409 if (UseMBPI && OptLevel != CodeGenOptLevel::None)
412 // AssignmentTrackingAnalysis only runs if assignment tracking is enabled for
413 // the module.
416 if (OptLevel != CodeGenOptLevel::None)
419}
420
424 // If we already selected that function, we do not need to run SDISel.
425 if (MF.getProperties().hasProperty(
427 return PreservedAnalyses::all();
428
429 // Do some sanity-checking on the command-line options.
430 if (EnableFastISelAbort && !Selector->TM.Options.EnableFastISel)
431 report_fatal_error("-fast-isel-abort > 0 requires -fast-isel");
432
433 // Decide what flavour of variable location debug-info will be used, before
434 // we change the optimisation level.
436
437 // Reset the target options before resetting the optimization
438 // level below.
439 // FIXME: This is a horrible hack and should be processed via
440 // codegen looking at the optimization level explicitly when
441 // it wants to look at it.
442 Selector->TM.resetTargetOptions(MF.getFunction());
443 // Reset OptLevel to None for optnone functions.
444 // TODO: Add a function analysis to handle this.
445 Selector->MF = &MF;
446 // Reset OptLevel to None for optnone functions.
447 CodeGenOptLevel NewOptLevel = MF.getFunction().hasOptNone()
449 : Selector->OptLevel;
450
451 OptLevelChanger OLC(*Selector, NewOptLevel);
452 Selector->initializeAnalysisResults(MFAM);
453 Selector->runOnMachineFunction(MF);
454
456}
457
461 .getManager();
463 Function &Fn = MF->getFunction();
464#ifndef NDEBUG
465 FuncName = Fn.getName();
467#else
469#endif
470
473 RegInfo = &MF->getRegInfo();
475 GFI = Fn.hasGC() ? &FAM.getResult<GCFunctionAnalysis>(Fn) : nullptr;
476 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
478 auto *PSI = MAMP.getCachedResult<ProfileSummaryAnalysis>(*Fn.getParent());
479 BlockFrequencyInfo *BFI = nullptr;
481 if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
483
484 FunctionVarLocs const *FnVarLocs = nullptr;
487
490 MAMP.getCachedResult<MachineModuleAnalysis>(*Fn.getParent())->getMMI();
491
492 CurDAG->init(*MF, *ORE, MFAM, LibInfo, UA, PSI, BFI, MMI, FnVarLocs);
493
494 // Now get the optional analyzes if we want to.
495 // This is based on the possibly changed OptLevel (after optnone is taken
496 // into account). That's unfortunate but OK because it just means we won't
497 // ask for passes that have been required anyway.
498
501 else
502 FuncInfo->BPI = nullptr;
503
505 AA = &FAM.getResult<AAManager>(Fn);
506 else
507 AA = nullptr;
508
510
511#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
513#endif
514}
515
517 Function &Fn = MF->getFunction();
518#ifndef NDEBUG
519 FuncName = Fn.getName();
521#else
523#endif
524
527 RegInfo = &MF->getRegInfo();
529 GFI = Fn.hasGC() ? &MFP.getAnalysis<GCModuleInfo>().getFunctionInfo(Fn)
530 : nullptr;
531 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
532 AC = &MFP.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(Fn);
533 auto *PSI = &MFP.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
534 BlockFrequencyInfo *BFI = nullptr;
535 if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
536 BFI = &MFP.getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
537
538 FunctionVarLocs const *FnVarLocs = nullptr;
540 FnVarLocs = MFP.getAnalysis<AssignmentTrackingAnalysis>().getResults();
541
542 UniformityInfo *UA = nullptr;
543 if (auto *UAPass = MFP.getAnalysisIfAvailable<UniformityInfoWrapperPass>())
544 UA = &UAPass->getUniformityInfo();
545
548
549 CurDAG->init(*MF, *ORE, &MFP, LibInfo, UA, PSI, BFI, MMI, FnVarLocs);
550
551 // Now get the optional analyzes if we want to.
552 // This is based on the possibly changed OptLevel (after optnone is taken
553 // into account). That's unfortunate but OK because it just means we won't
554 // ask for passes that have been required anyway.
555
557 FuncInfo->BPI =
559 else
560 FuncInfo->BPI = nullptr;
561
563 AA = &MFP.getAnalysis<AAResultsWrapperPass>().getAAResults();
564 else
565 AA = nullptr;
566
567 SP = &MFP.getAnalysis<StackProtector>().getLayoutInfo();
568
569#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
571#endif
572}
573
576 const Function &Fn = mf.getFunction();
577
578 bool InstrRef = mf.shouldUseDebugInstrRef();
579
580 FuncInfo->set(MF->getFunction(), *MF, CurDAG);
581
582 ISEL_DUMP(dbgs() << "\n\n\n=== " << FuncName << '\n');
583
584 SDB->init(GFI, AA, AC, LibInfo);
585
586 MF->setHasInlineAsm(false);
587
588 FuncInfo->SplitCSR = false;
589
590 // We split CSR if the target supports it for the given function
591 // and the function has only return exits.
593 FuncInfo->SplitCSR = true;
594
595 // Collect all the return blocks.
596 for (const BasicBlock &BB : Fn) {
597 if (!succ_empty(&BB))
598 continue;
599
600 const Instruction *Term = BB.getTerminator();
601 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
602 continue;
603
604 // Bail out if the exit block is not Return nor Unreachable.
605 FuncInfo->SplitCSR = false;
606 break;
607 }
608 }
609
610 MachineBasicBlock *EntryMBB = &MF->front();
611 if (FuncInfo->SplitCSR)
612 // This performs initialization so lowering for SplitCSR will be correct.
613 TLI->initializeSplitCSR(EntryMBB);
614
615 SelectAllBasicBlocks(Fn);
617 DiagnosticInfoISelFallback DiagFallback(Fn);
618 Fn.getContext().diagnose(DiagFallback);
619 }
620
621 // Replace forward-declared registers with the registers containing
622 // the desired value.
623 // Note: it is important that this happens **before** the call to
624 // EmitLiveInCopies, since implementations can skip copies of unused
625 // registers. If we don't apply the reg fixups before, some registers may
626 // appear as unused and will be skipped, resulting in bad MI.
628 for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
629 E = FuncInfo->RegFixups.end();
630 I != E; ++I) {
631 Register From = I->first;
632 Register To = I->second;
633 // If To is also scheduled to be replaced, find what its ultimate
634 // replacement is.
635 while (true) {
636 DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
637 if (J == E)
638 break;
639 To = J->second;
640 }
641 // Make sure the new register has a sufficiently constrained register class.
642 if (From.isVirtual() && To.isVirtual())
643 MRI.constrainRegClass(To, MRI.getRegClass(From));
644 // Replace it.
645
646 // Replacing one register with another won't touch the kill flags.
647 // We need to conservatively clear the kill flags as a kill on the old
648 // register might dominate existing uses of the new register.
649 if (!MRI.use_empty(To))
650 MRI.clearKillFlags(From);
651 MRI.replaceRegWith(From, To);
652 }
653
654 // If the first basic block in the function has live ins that need to be
655 // copied into vregs, emit the copies into the top of the block before
656 // emitting the code for the block.
658 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
659
660 // Insert copies in the entry block and the return blocks.
661 if (FuncInfo->SplitCSR) {
663 // Collect all the return blocks.
664 for (MachineBasicBlock &MBB : mf) {
665 if (!MBB.succ_empty())
666 continue;
667
669 if (Term != MBB.end() && Term->isReturn()) {
670 Returns.push_back(&MBB);
671 continue;
672 }
673 }
674 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
675 }
676
678 if (!FuncInfo->ArgDbgValues.empty())
679 for (std::pair<MCRegister, Register> LI : RegInfo->liveins())
680 if (LI.second)
681 LiveInMap.insert(LI);
682
683 // Insert DBG_VALUE instructions for function arguments to the entry block.
684 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
685 MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
686 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
687 "Function parameters should not be described by DBG_VALUE_LIST.");
688 bool hasFI = MI->getDebugOperand(0).isFI();
689 Register Reg =
690 hasFI ? TRI.getFrameRegister(*MF) : MI->getDebugOperand(0).getReg();
691 if (Reg.isPhysical())
692 EntryMBB->insert(EntryMBB->begin(), MI);
693 else {
694 MachineInstr *Def = RegInfo->getVRegDef(Reg);
695 if (Def) {
696 MachineBasicBlock::iterator InsertPos = Def;
697 // FIXME: VR def may not be in entry block.
698 Def->getParent()->insert(std::next(InsertPos), MI);
699 } else
700 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
701 << Register::virtReg2Index(Reg) << "\n");
702 }
703
704 // Don't try and extend through copies in instruction referencing mode.
705 if (InstrRef)
706 continue;
707
708 // If Reg is live-in then update debug info to track its copy in a vreg.
710 if (LDI != LiveInMap.end()) {
711 assert(!hasFI && "There's no handling of frame pointer updating here yet "
712 "- add if needed");
713 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
714 MachineBasicBlock::iterator InsertPos = Def;
715 const MDNode *Variable = MI->getDebugVariable();
716 const MDNode *Expr = MI->getDebugExpression();
717 DebugLoc DL = MI->getDebugLoc();
718 bool IsIndirect = MI->isIndirectDebugValue();
719 if (IsIndirect)
720 assert(MI->getDebugOffset().getImm() == 0 &&
721 "DBG_VALUE with nonzero offset");
722 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
723 "Expected inlined-at fields to agree");
724 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
725 "Didn't expect to see a DBG_VALUE_LIST here");
726 // Def is never a terminator here, so it is ok to increment InsertPos.
727 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
728 IsIndirect, LDI->second, Variable, Expr);
729
730 // If this vreg is directly copied into an exported register then
731 // that COPY instructions also need DBG_VALUE, if it is the only
732 // user of LDI->second.
733 MachineInstr *CopyUseMI = nullptr;
734 for (MachineInstr &UseMI : RegInfo->use_instructions(LDI->second)) {
735 if (UseMI.isDebugValue())
736 continue;
737 if (UseMI.isCopy() && !CopyUseMI && UseMI.getParent() == EntryMBB) {
738 CopyUseMI = &UseMI;
739 continue;
740 }
741 // Otherwise this is another use or second copy use.
742 CopyUseMI = nullptr;
743 break;
744 }
745 if (CopyUseMI &&
746 TRI.getRegSizeInBits(LDI->second, MRI) ==
747 TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
748 // Use MI's debug location, which describes where Variable was
749 // declared, rather than whatever is attached to CopyUseMI.
750 MachineInstr *NewMI =
751 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
752 CopyUseMI->getOperand(0).getReg(), Variable, Expr);
753 MachineBasicBlock::iterator Pos = CopyUseMI;
754 EntryMBB->insertAfter(Pos, NewMI);
755 }
756 }
757 }
758
759 // For debug-info, in instruction referencing mode, we need to perform some
760 // post-isel maintenence.
761 if (MF->useDebugInstrRef())
763
764 // Determine if there are any calls in this machine function.
766 for (const auto &MBB : *MF) {
767 if (MFI.hasCalls() && MF->hasInlineAsm())
768 break;
769
770 for (const auto &MI : MBB) {
771 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
772 if ((MCID.isCall() && !MCID.isReturn()) ||
773 MI.isStackAligningInlineAsm()) {
774 MFI.setHasCalls(true);
775 }
776 if (MI.isInlineAsm()) {
777 MF->setHasInlineAsm(true);
778 }
779 }
780 }
781
782 // Release function-specific state. SDB and CurDAG are already cleared
783 // at this point.
784 FuncInfo->clear();
785
786 ISEL_DUMP(dbgs() << "*** MachineFunction at end of ISel ***\n");
787 ISEL_DUMP(MF->print(dbgs()));
788
789 return true;
790}
791
795 bool ShouldAbort) {
796 // Print the function name explicitly if we don't have a debug location (which
797 // makes the diagnostic less useful) or if we're going to emit a raw error.
798 if (!R.getLocation().isValid() || ShouldAbort)
799 R << (" (in function: " + MF.getName() + ")").str();
800
801 if (ShouldAbort)
802 report_fatal_error(Twine(R.getMsg()));
803
804 ORE.emit(R);
805 LLVM_DEBUG(dbgs() << R.getMsg() << "\n");
806}
807
808// Detect any fake uses that follow a tail call and move them before the tail
809// call. Ignore fake uses that use values that are def'd by or after the tail
810// call.
814 if (--I == Begin || !isa<ReturnInst>(*I))
815 return;
816 // Detect whether there are any fake uses trailing a (potential) tail call.
817 bool HaveFakeUse = false;
818 bool HaveTailCall = false;
819 do {
820 if (const CallInst *CI = dyn_cast<CallInst>(--I))
821 if (CI->isTailCall()) {
822 HaveTailCall = true;
823 break;
824 }
825 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
826 if (II->getIntrinsicID() == Intrinsic::fake_use)
827 HaveFakeUse = true;
828 } while (I != Begin);
829
830 // If we didn't find any tail calls followed by fake uses, we are done.
831 if (!HaveTailCall || !HaveFakeUse)
832 return;
833
835 // Record the fake uses we found so we can move them to the front of the
836 // tail call. Ignore them if they use a value that is def'd by or after
837 // the tail call.
838 for (BasicBlock::iterator Inst = I; Inst != End; Inst++) {
839 if (IntrinsicInst *FakeUse = dyn_cast<IntrinsicInst>(Inst);
840 FakeUse && FakeUse->getIntrinsicID() == Intrinsic::fake_use) {
841 if (auto UsedDef = dyn_cast<Instruction>(FakeUse->getOperand(0));
842 !UsedDef || UsedDef->getParent() != I->getParent() ||
843 UsedDef->comesBefore(&*I))
844 FakeUses.push_back(FakeUse);
845 }
846 }
847
848 for (auto *Inst : FakeUses)
849 Inst->moveBefore(*Inst->getParent(), I);
850}
851
852void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
854 bool &HadTailCall) {
855 // Allow creating illegal types during DAG building for the basic block.
857
858 // Lower the instructions. If a call is emitted as a tail call, cease emitting
859 // nodes for this block. If an instruction is elided, don't emit it, but do
860 // handle any debug-info attached to it.
861 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
862 if (!ElidedArgCopyInstrs.count(&*I))
863 SDB->visit(*I);
864 else
865 SDB->visitDbgInfo(*I);
866 }
867
868 // Make sure the root of the DAG is up-to-date.
869 CurDAG->setRoot(SDB->getControlRoot());
870 HadTailCall = SDB->HasTailCall;
871 SDB->resolveOrClearDbgInfo();
872 SDB->clear();
873
874 // Final step, emit the lowered DAG as machine code.
875 CodeGenAndEmitDAG();
876}
877
878void SelectionDAGISel::ComputeLiveOutVRegInfo() {
881
882 Worklist.push_back(CurDAG->getRoot().getNode());
883 Added.insert(CurDAG->getRoot().getNode());
884
885 KnownBits Known;
886
887 do {
888 SDNode *N = Worklist.pop_back_val();
889
890 // Otherwise, add all chain operands to the worklist.
891 for (const SDValue &Op : N->op_values())
892 if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
893 Worklist.push_back(Op.getNode());
894
895 // If this is a CopyToReg with a vreg dest, process it.
896 if (N->getOpcode() != ISD::CopyToReg)
897 continue;
898
899 Register DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
900 if (!DestReg.isVirtual())
901 continue;
902
903 // Ignore non-integer values.
904 SDValue Src = N->getOperand(2);
905 EVT SrcVT = Src.getValueType();
906 if (!SrcVT.isInteger())
907 continue;
908
909 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
910 Known = CurDAG->computeKnownBits(Src);
911 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
912 } while (!Worklist.empty());
913}
914
915void SelectionDAGISel::CodeGenAndEmitDAG() {
916 StringRef GroupName = "sdag";
917 StringRef GroupDescription = "Instruction Selection and Scheduling";
918 std::string BlockName;
919 bool MatchFilterBB = false;
920 (void)MatchFilterBB;
921
922 // Pre-type legalization allow creation of any node types.
924
925#ifndef NDEBUG
926 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
928 FuncInfo->MBB->getBasicBlock()->getName());
929#endif
930#ifdef NDEBUG
934#endif
935 {
936 BlockName =
937 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
938 }
939 ISEL_DUMP(dbgs() << "\nInitial selection DAG: "
940 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
941 << "'\n";
942 CurDAG->dump());
943
944#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
946 CurDAG->VerifyDAGDivergence();
947#endif
948
949 if (ViewDAGCombine1 && MatchFilterBB)
950 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
951
952 // Run the DAG combiner in pre-legalize mode.
953 {
954 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
955 GroupDescription, TimePassesIsEnabled);
957 }
958
959 ISEL_DUMP(dbgs() << "\nOptimized lowered selection DAG: "
960 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
961 << "'\n";
962 CurDAG->dump());
963
964#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
966 CurDAG->VerifyDAGDivergence();
967#endif
968
969 // Second step, hack on the DAG until it only uses operations and types that
970 // the target supports.
971 if (ViewLegalizeTypesDAGs && MatchFilterBB)
972 CurDAG->viewGraph("legalize-types input for " + BlockName);
973
974 bool Changed;
975 {
976 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
977 GroupDescription, TimePassesIsEnabled);
978 Changed = CurDAG->LegalizeTypes();
979 }
980
981 ISEL_DUMP(dbgs() << "\nType-legalized selection DAG: "
982 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
983 << "'\n";
984 CurDAG->dump());
985
986#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
988 CurDAG->VerifyDAGDivergence();
989#endif
990
991 // Only allow creation of legal node types.
993
994 if (Changed) {
995 if (ViewDAGCombineLT && MatchFilterBB)
996 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
997
998 // Run the DAG combiner in post-type-legalize mode.
999 {
1000 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
1001 GroupName, GroupDescription, TimePassesIsEnabled);
1003 }
1004
1005 ISEL_DUMP(dbgs() << "\nOptimized type-legalized selection DAG: "
1006 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1007 << "'\n";
1008 CurDAG->dump());
1009
1010#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1011 if (TTI->hasBranchDivergence())
1012 CurDAG->VerifyDAGDivergence();
1013#endif
1014 }
1015
1016 {
1017 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
1018 GroupDescription, TimePassesIsEnabled);
1019 Changed = CurDAG->LegalizeVectors();
1020 }
1021
1022 if (Changed) {
1023 ISEL_DUMP(dbgs() << "\nVector-legalized selection DAG: "
1024 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1025 << "'\n";
1026 CurDAG->dump());
1027
1028#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1029 if (TTI->hasBranchDivergence())
1030 CurDAG->VerifyDAGDivergence();
1031#endif
1032
1033 {
1034 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
1035 GroupDescription, TimePassesIsEnabled);
1037 }
1038
1039 ISEL_DUMP(dbgs() << "\nVector/type-legalized selection DAG: "
1040 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1041 << "'\n";
1042 CurDAG->dump());
1043
1044#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1045 if (TTI->hasBranchDivergence())
1046 CurDAG->VerifyDAGDivergence();
1047#endif
1048
1049 if (ViewDAGCombineLT && MatchFilterBB)
1050 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
1051
1052 // Run the DAG combiner in post-type-legalize mode.
1053 {
1054 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
1055 GroupName, GroupDescription, TimePassesIsEnabled);
1057 }
1058
1059 ISEL_DUMP(dbgs() << "\nOptimized vector-legalized selection DAG: "
1060 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1061 << "'\n";
1062 CurDAG->dump());
1063
1064#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1065 if (TTI->hasBranchDivergence())
1066 CurDAG->VerifyDAGDivergence();
1067#endif
1068 }
1069
1070 if (ViewLegalizeDAGs && MatchFilterBB)
1071 CurDAG->viewGraph("legalize input for " + BlockName);
1072
1073 {
1074 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
1075 GroupDescription, TimePassesIsEnabled);
1076 CurDAG->Legalize();
1077 }
1078
1079 ISEL_DUMP(dbgs() << "\nLegalized selection DAG: "
1080 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1081 << "'\n";
1082 CurDAG->dump());
1083
1084#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1085 if (TTI->hasBranchDivergence())
1086 CurDAG->VerifyDAGDivergence();
1087#endif
1088
1089 if (ViewDAGCombine2 && MatchFilterBB)
1090 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
1091
1092 // Run the DAG combiner in post-legalize mode.
1093 {
1094 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
1095 GroupDescription, TimePassesIsEnabled);
1097 }
1098
1099 ISEL_DUMP(dbgs() << "\nOptimized legalized selection DAG: "
1100 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1101 << "'\n";
1102 CurDAG->dump());
1103
1104#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
1105 if (TTI->hasBranchDivergence())
1106 CurDAG->VerifyDAGDivergence();
1107#endif
1108
1110 ComputeLiveOutVRegInfo();
1111
1112 if (ViewISelDAGs && MatchFilterBB)
1113 CurDAG->viewGraph("isel input for " + BlockName);
1114
1115 // Third, instruction select all of the operations to machine code, adding the
1116 // code to the MachineBasicBlock.
1117 {
1118 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
1119 GroupDescription, TimePassesIsEnabled);
1120 DoInstructionSelection();
1121 }
1122
1123 ISEL_DUMP(dbgs() << "\nSelected selection DAG: "
1124 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
1125 << "'\n";
1126 CurDAG->dump());
1127
1128 if (ViewSchedDAGs && MatchFilterBB)
1129 CurDAG->viewGraph("scheduler input for " + BlockName);
1130
1131 // Schedule machine code.
1132 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
1133 {
1134 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
1135 GroupDescription, TimePassesIsEnabled);
1136 Scheduler->Run(CurDAG, FuncInfo->MBB);
1137 }
1138
1139 if (ViewSUnitDAGs && MatchFilterBB)
1140 Scheduler->viewGraph();
1141
1142 // Emit machine code to BB. This can change 'BB' to the last block being
1143 // inserted into.
1144 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
1145 {
1146 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
1147 GroupDescription, TimePassesIsEnabled);
1148
1149 // FuncInfo->InsertPt is passed by reference and set to the end of the
1150 // scheduled instructions.
1151 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
1152 }
1153
1154 // If the block was split, make sure we update any references that are used to
1155 // update PHI nodes later on.
1156 if (FirstMBB != LastMBB)
1157 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
1158
1159 // Free the scheduler state.
1160 {
1161 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
1162 GroupDescription, TimePassesIsEnabled);
1163 delete Scheduler;
1164 }
1165
1166 // Free the SelectionDAG state, now that we're finished with it.
1167 CurDAG->clear();
1168}
1169
1170namespace {
1171
1172/// ISelUpdater - helper class to handle updates of the instruction selection
1173/// graph.
1174class ISelUpdater : public SelectionDAG::DAGUpdateListener {
1175 SelectionDAG::allnodes_iterator &ISelPosition;
1176
1177public:
1178 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1179 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1180
1181 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1182 /// deleted is the current ISelPosition node, update ISelPosition.
1183 ///
1184 void NodeDeleted(SDNode *N, SDNode *E) override {
1185 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1186 ++ISelPosition;
1187 }
1188
1189 /// NodeInserted - Handle new nodes inserted into the graph: propagate
1190 /// metadata from root nodes that also applies to new nodes, in case the root
1191 /// is later deleted.
1192 void NodeInserted(SDNode *N) override {
1193 SDNode *CurNode = &*ISelPosition;
1194 if (MDNode *MD = DAG.getPCSections(CurNode))
1195 DAG.addPCSections(N, MD);
1196 if (MDNode *MMRA = DAG.getMMRAMetadata(CurNode))
1197 DAG.addMMRAMetadata(N, MMRA);
1198 }
1199};
1200
1201} // end anonymous namespace
1202
1203// This function is used to enforce the topological node id property
1204// leveraged during instruction selection. Before the selection process all
1205// nodes are given a non-negative id such that all nodes have a greater id than
1206// their operands. As this holds transitively we can prune checks that a node N
1207// is a predecessor of M another by not recursively checking through M's
1208// operands if N's ID is larger than M's ID. This significantly improves
1209// performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
1210
1211// However, when we fuse multiple nodes into a single node during the
1212// selection we may induce a predecessor relationship between inputs and
1213// outputs of distinct nodes being merged, violating the topological property.
1214// Should a fused node have a successor which has yet to be selected,
1215// our legality checks would be incorrect. To avoid this we mark all unselected
1216// successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
1217// (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1218// We use bit-negation to more clearly enforce that node id -1 can only be
1219// achieved by selected nodes. As the conversion is reversable to the original
1220// Id, topological pruning can still be leveraged when looking for unselected
1221// nodes. This method is called internally in all ISel replacement related
1222// functions.
1225 Nodes.push_back(Node);
1226
1227 while (!Nodes.empty()) {
1228 SDNode *N = Nodes.pop_back_val();
1229 for (auto *U : N->users()) {
1230 auto UId = U->getNodeId();
1231 if (UId > 0) {
1233 Nodes.push_back(U);
1234 }
1235 }
1236 }
1237}
1238
1239// InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
1240// NodeId with the equivalent node id which is invalid for topological
1241// pruning.
1243 int InvalidId = -(N->getNodeId() + 1);
1244 N->setNodeId(InvalidId);
1245}
1246
1247// getUninvalidatedNodeId - get original uninvalidated node id.
1249 int Id = N->getNodeId();
1250 if (Id < -1)
1251 return -(Id + 1);
1252 return Id;
1253}
1254
1255void SelectionDAGISel::DoInstructionSelection() {
1256 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1257 << printMBBReference(*FuncInfo->MBB) << " '"
1258 << FuncInfo->MBB->getName() << "'\n");
1259
1261
1262 // Select target instructions for the DAG.
1263 {
1264 // Number all nodes with a topological order and set DAGSize.
1266
1267 // Create a dummy node (which is not added to allnodes), that adds
1268 // a reference to the root node, preventing it from being deleted,
1269 // and tracking any changes of the root.
1270 HandleSDNode Dummy(CurDAG->getRoot());
1272 ++ISelPosition;
1273
1274 // Make sure that ISelPosition gets properly updated when nodes are deleted
1275 // in calls made from this function. New nodes inherit relevant metadata.
1276 ISelUpdater ISU(*CurDAG, ISelPosition);
1277
1278 // The AllNodes list is now topological-sorted. Visit the
1279 // nodes by starting at the end of the list (the root of the
1280 // graph) and preceding back toward the beginning (the entry
1281 // node).
1282 while (ISelPosition != CurDAG->allnodes_begin()) {
1283 SDNode *Node = &*--ISelPosition;
1284 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1285 // but there are currently some corner cases that it misses. Also, this
1286 // makes it theoretically possible to disable the DAGCombiner.
1287 if (Node->use_empty())
1288 continue;
1289
1290#ifndef NDEBUG
1292 Nodes.push_back(Node);
1293
1294 while (!Nodes.empty()) {
1295 auto N = Nodes.pop_back_val();
1296 if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1297 continue;
1298 for (const SDValue &Op : N->op_values()) {
1299 if (Op->getOpcode() == ISD::TokenFactor)
1300 Nodes.push_back(Op.getNode());
1301 else {
1302 // We rely on topological ordering of node ids for checking for
1303 // cycles when fusing nodes during selection. All unselected nodes
1304 // successors of an already selected node should have a negative id.
1305 // This assertion will catch such cases. If this assertion triggers
1306 // it is likely you using DAG-level Value/Node replacement functions
1307 // (versus equivalent ISEL replacement) in backend-specific
1308 // selections. See comment in EnforceNodeIdInvariant for more
1309 // details.
1310 assert(Op->getNodeId() != -1 &&
1311 "Node has already selected predecessor node");
1312 }
1313 }
1314 }
1315#endif
1316
1317 // When we are using non-default rounding modes or FP exception behavior
1318 // FP operations are represented by StrictFP pseudo-operations. For
1319 // targets that do not (yet) understand strict FP operations directly,
1320 // we convert them to normal FP opcodes instead at this point. This
1321 // will allow them to be handled by existing target-specific instruction
1322 // selectors.
1323 if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1324 // For some opcodes, we need to call TLI->getOperationAction using
1325 // the first operand type instead of the result type. Note that this
1326 // must match what SelectionDAGLegalize::LegalizeOp is doing.
1327 EVT ActionVT;
1328 switch (Node->getOpcode()) {
1331 case ISD::STRICT_LRINT:
1332 case ISD::STRICT_LLRINT:
1333 case ISD::STRICT_LROUND:
1335 case ISD::STRICT_FSETCC:
1337 ActionVT = Node->getOperand(1).getValueType();
1338 break;
1339 default:
1340 ActionVT = Node->getValueType(0);
1341 break;
1342 }
1343 if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1346 }
1347
1348 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1349 Node->dump(CurDAG));
1350
1351 Select(Node);
1352 }
1353
1354 CurDAG->setRoot(Dummy.getValue());
1355 }
1356
1357 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1358
1360}
1361
1363 for (const User *U : CPI->users()) {
1364 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1365 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1366 if (IID == Intrinsic::eh_exceptionpointer ||
1367 IID == Intrinsic::eh_exceptioncode)
1368 return true;
1369 }
1370 }
1371 return false;
1372}
1373
1374// wasm.landingpad.index intrinsic is for associating a landing pad index number
1375// with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1376// and store the mapping in the function.
1378 const CatchPadInst *CPI) {
1379 MachineFunction *MF = MBB->getParent();
1380 // In case of single catch (...), we don't emit LSDA, so we don't need
1381 // this information.
1382 bool IsSingleCatchAllClause =
1383 CPI->arg_size() == 1 &&
1384 cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1385 // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
1386 // and they don't need LSDA info
1387 bool IsCatchLongjmp = CPI->arg_size() == 0;
1388 if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
1389 // Create a mapping from landing pad label to landing pad index.
1390 bool IntrFound = false;
1391 for (const User *U : CPI->users()) {
1392 if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1393 Intrinsic::ID IID = Call->getIntrinsicID();
1394 if (IID == Intrinsic::wasm_landingpad_index) {
1395 Value *IndexArg = Call->getArgOperand(1);
1396 int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1397 MF->setWasmLandingPadIndex(MBB, Index);
1398 IntrFound = true;
1399 break;
1400 }
1401 }
1402 }
1403 assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1404 (void)IntrFound;
1405 }
1406}
1407
1408/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1409/// do other setup for EH landing-pad blocks.
1410bool SelectionDAGISel::PrepareEHLandingPad() {
1412 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1413 const BasicBlock *LLVMBB = MBB->getBasicBlock();
1414 const TargetRegisterClass *PtrRC =
1416
1417 auto Pers = classifyEHPersonality(PersonalityFn);
1418
1419 // Catchpads have one live-in register, which typically holds the exception
1420 // pointer or code.
1421 if (isFuncletEHPersonality(Pers)) {
1422 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1424 // Get or create the virtual register to hold the pointer or code. Mark
1425 // the live in physreg and copy into the vreg.
1426 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1427 assert(EHPhysReg && "target lacks exception pointer register");
1428 MBB->addLiveIn(EHPhysReg);
1429 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1430 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1431 TII->get(TargetOpcode::COPY), VReg)
1432 .addReg(EHPhysReg, RegState::Kill);
1433 }
1434 }
1435 return true;
1436 }
1437
1438 // Add a label to mark the beginning of the landing pad. Deletion of the
1439 // landing pad can thus be detected via the MachineModuleInfo.
1441
1442 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1443 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1444 .addSym(Label);
1445
1446 // If the unwinder does not preserve all registers, ensure that the
1447 // function marks the clobbered registers as used.
1449 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1451
1452 if (Pers == EHPersonality::Wasm_CXX) {
1453 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
1455 } else {
1456 // Assign the call site to the landing pad's begin label.
1457 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1458 // Mark exception register as live in.
1459 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1460 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1461 // Mark exception selector register as live in.
1462 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1463 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1464 }
1465
1466 return true;
1467}
1468
1469// Mark and Report IPToState for each Block under IsEHa
1470void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
1472 if (!EHInfo)
1473 return;
1474 for (MachineBasicBlock &MBB : *MF) {
1475 const BasicBlock *BB = MBB.getBasicBlock();
1476 int State = EHInfo->BlockToStateMap[BB];
1477 if (BB->getFirstMayFaultInst()) {
1478 // Report IP range only for blocks with Faulty inst
1479 auto MBBb = MBB.getFirstNonPHI();
1480
1481 if (MBBb == MBB.end())
1482 continue;
1483
1484 MachineInstr *MIb = &*MBBb;
1485 if (MIb->isTerminator())
1486 continue;
1487
1488 // Insert EH Labels
1489 MCSymbol *BeginLabel = MF->getContext().createTempSymbol();
1490 MCSymbol *EndLabel = MF->getContext().createTempSymbol();
1491 EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
1492 BuildMI(MBB, MBBb, SDB->getCurDebugLoc(),
1493 TII->get(TargetOpcode::EH_LABEL))
1494 .addSym(BeginLabel);
1495 auto MBBe = MBB.instr_end();
1496 MachineInstr *MIe = &*(--MBBe);
1497 // insert before (possible multiple) terminators
1498 while (MIe->isTerminator())
1499 MIe = &*(--MBBe);
1500 ++MBBe;
1501 BuildMI(MBB, MBBe, SDB->getCurDebugLoc(),
1502 TII->get(TargetOpcode::EH_LABEL))
1503 .addSym(EndLabel);
1504 }
1505 }
1506}
1507
1508/// isFoldedOrDeadInstruction - Return true if the specified instruction is
1509/// side-effect free and is either dead or folded into a generated instruction.
1510/// Return false if it needs to be emitted.
1512 const FunctionLoweringInfo &FuncInfo) {
1513 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1514 !I->isTerminator() && // Terminators aren't folded.
1515 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1516 !I->isEHPad() && // EH pad instructions aren't folded.
1517 !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1518}
1519
1521 const Value *Arg, DIExpression *Expr,
1522 DILocalVariable *Var,
1523 DebugLoc DbgLoc) {
1524 if (!Expr->isEntryValue() || !isa<Argument>(Arg))
1525 return false;
1526
1527 auto ArgIt = FuncInfo.ValueMap.find(Arg);
1528 if (ArgIt == FuncInfo.ValueMap.end())
1529 return false;
1530 Register ArgVReg = ArgIt->getSecond();
1531
1532 // Find the corresponding livein physical register to this argument.
1533 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
1534 if (VirtReg == ArgVReg) {
1535 // Append an op deref to account for the fact that this is a dbg_declare.
1536 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
1537 FuncInfo.MF->setVariableDbgInfo(Var, Expr, PhysReg, DbgLoc);
1538 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1539 << ", Expr=" << *Expr << ", MCRegister=" << PhysReg
1540 << ", DbgLoc=" << DbgLoc << "\n");
1541 return true;
1542 }
1543 return false;
1544}
1545
1547 const Value *Address, DIExpression *Expr,
1548 DILocalVariable *Var, DebugLoc DbgLoc) {
1549 if (!Address) {
1550 LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *Var
1551 << " (bad address)\n");
1552 return false;
1553 }
1554
1555 if (processIfEntryValueDbgDeclare(FuncInfo, Address, Expr, Var, DbgLoc))
1556 return true;
1557
1558 MachineFunction *MF = FuncInfo.MF;
1559 const DataLayout &DL = MF->getDataLayout();
1560
1561 assert(Var && "Missing variable");
1562 assert(DbgLoc && "Missing location");
1563
1564 // Look through casts and constant offset GEPs. These mostly come from
1565 // inalloca.
1566 APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
1567 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1568
1569 // Check if the variable is a static alloca or a byval or inalloca
1570 // argument passed in memory. If it is not, then we will ignore this
1571 // intrinsic and handle this during isel like dbg.value.
1572 int FI = std::numeric_limits<int>::max();
1573 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1574 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1575 if (SI != FuncInfo.StaticAllocaMap.end())
1576 FI = SI->second;
1577 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1578 FI = FuncInfo.getArgumentFrameIndex(Arg);
1579
1580 if (FI == std::numeric_limits<int>::max())
1581 return false;
1582
1583 if (Offset.getBoolValue())
1585 Offset.getZExtValue());
1586
1587 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1588 << ", Expr=" << *Expr << ", FI=" << FI
1589 << ", DbgLoc=" << DbgLoc << "\n");
1590 MF->setVariableDbgInfo(Var, Expr, FI, DbgLoc);
1591 return true;
1592}
1593
1594/// Collect llvm.dbg.declare information. This is done after argument lowering
1595/// in case the declarations refer to arguments.
1597 for (const auto &I : instructions(*FuncInfo.Fn)) {
1598 const auto *DI = dyn_cast<DbgDeclareInst>(&I);
1599 if (DI && processDbgDeclare(FuncInfo, DI->getAddress(), DI->getExpression(),
1600 DI->getVariable(), DI->getDebugLoc()))
1601 FuncInfo.PreprocessedDbgDeclares.insert(DI);
1602 for (const DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1604 processDbgDeclare(FuncInfo, DVR.getVariableLocationOp(0),
1605 DVR.getExpression(), DVR.getVariable(),
1606 DVR.getDebugLoc()))
1607 FuncInfo.PreprocessedDVRDeclares.insert(&DVR);
1608 }
1609 }
1610}
1611
1612/// Collect single location variable information generated with assignment
1613/// tracking. This is done after argument lowering in case the declarations
1614/// refer to arguments.
1616 FunctionVarLocs const *FnVarLocs) {
1617 for (auto It = FnVarLocs->single_locs_begin(),
1618 End = FnVarLocs->single_locs_end();
1619 It != End; ++It) {
1620 assert(!It->Values.hasArgList() && "Single loc variadic ops not supported");
1621 processDbgDeclare(FuncInfo, It->Values.getVariableLocationOp(0), It->Expr,
1622 FnVarLocs->getDILocalVariable(It->VariableID), It->DL);
1623 }
1624}
1625
1626void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1627 FastISelFailed = false;
1628 // Initialize the Fast-ISel state, if needed.
1629 FastISel *FastIS = nullptr;
1631 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1632 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1633 }
1634
1636
1637 // Lower arguments up front. An RPO iteration always visits the entry block
1638 // first.
1639 assert(*RPOT.begin() == &Fn.getEntryBlock());
1640 ++NumEntryBlocks;
1641
1642 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1643 FuncInfo->MBB = FuncInfo->getMBB(&Fn.getEntryBlock());
1644 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1645
1647
1648 if (!FastIS) {
1649 LowerArguments(Fn);
1650 } else {
1651 // See if fast isel can lower the arguments.
1652 FastIS->startNewBlock();
1653 if (!FastIS->lowerArguments()) {
1654 FastISelFailed = true;
1655 // Fast isel failed to lower these arguments
1656 ++NumFastIselFailLowerArguments;
1657
1658 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1659 Fn.getSubprogram(),
1660 &Fn.getEntryBlock());
1661 R << "FastISel didn't lower all arguments: "
1662 << ore::NV("Prototype", Fn.getFunctionType());
1664
1665 // Use SelectionDAG argument lowering
1666 LowerArguments(Fn);
1667 CurDAG->setRoot(SDB->getControlRoot());
1668 SDB->clear();
1669 CodeGenAndEmitDAG();
1670 }
1671
1672 // If we inserted any instructions at the beginning, make a note of
1673 // where they are, so we can be sure to emit subsequent instructions
1674 // after them.
1675 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1676 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1677 else
1678 FastIS->setLastLocalValue(nullptr);
1679 }
1680
1681 bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1682
1683 if (FastIS && Inserted)
1684 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1685
1688 "expected AssignmentTrackingAnalysis pass results");
1690 } else {
1692 }
1693
1694 // Iterate over all basic blocks in the function.
1695 FuncInfo->VisitedBBs.assign(Fn.getMaxBlockNumber(), false);
1696 for (const BasicBlock *LLVMBB : RPOT) {
1698 bool AllPredsVisited = true;
1699 for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1700 if (!FuncInfo->VisitedBBs[Pred->getNumber()]) {
1701 AllPredsVisited = false;
1702 break;
1703 }
1704 }
1705
1706 if (AllPredsVisited) {
1707 for (const PHINode &PN : LLVMBB->phis())
1708 FuncInfo->ComputePHILiveOutRegInfo(&PN);
1709 } else {
1710 for (const PHINode &PN : LLVMBB->phis())
1711 FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1712 }
1713
1714 FuncInfo->VisitedBBs[LLVMBB->getNumber()] = true;
1715 }
1716
1717 // Fake uses that follow tail calls are dropped. To avoid this, move
1718 // such fake uses in front of the tail call, provided they don't
1719 // use anything def'd by or after the tail call.
1720 {
1721 BasicBlock::iterator BBStart =
1722 const_cast<BasicBlock *>(LLVMBB)->getFirstNonPHI()->getIterator();
1723 BasicBlock::iterator BBEnd = const_cast<BasicBlock *>(LLVMBB)->end();
1724 preserveFakeUses(BBStart, BBEnd);
1725 }
1726
1727 BasicBlock::const_iterator const Begin =
1728 LLVMBB->getFirstNonPHI()->getIterator();
1729 BasicBlock::const_iterator const End = LLVMBB->end();
1731
1732 FuncInfo->MBB = FuncInfo->getMBB(LLVMBB);
1733 if (!FuncInfo->MBB)
1734 continue; // Some blocks like catchpads have no code or MBB.
1735
1736 // Insert new instructions after any phi or argument setup code.
1737 FuncInfo->InsertPt = FuncInfo->MBB->end();
1738
1739 // Setup an EH landing-pad block.
1740 FuncInfo->ExceptionPointerVirtReg = 0;
1741 FuncInfo->ExceptionSelectorVirtReg = 0;
1742 if (LLVMBB->isEHPad())
1743 if (!PrepareEHLandingPad())
1744 continue;
1745
1746 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1747 if (FastIS) {
1748 if (LLVMBB != &Fn.getEntryBlock())
1749 FastIS->startNewBlock();
1750
1751 unsigned NumFastIselRemaining = std::distance(Begin, End);
1752
1753 // Pre-assign swifterror vregs.
1754 SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1755
1756 // Do FastISel on as many instructions as possible.
1757 for (; BI != Begin; --BI) {
1758 const Instruction *Inst = &*std::prev(BI);
1759
1760 // If we no longer require this instruction, skip it.
1761 if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1762 ElidedArgCopyInstrs.count(Inst)) {
1763 --NumFastIselRemaining;
1764 FastIS->handleDbgInfo(Inst);
1765 continue;
1766 }
1767
1768 // Bottom-up: reset the insert pos at the top, after any local-value
1769 // instructions.
1770 FastIS->recomputeInsertPt();
1771
1772 // Try to select the instruction with FastISel.
1773 if (FastIS->selectInstruction(Inst)) {
1774 --NumFastIselRemaining;
1775 ++NumFastIselSuccess;
1776
1777 FastIS->handleDbgInfo(Inst);
1778 // If fast isel succeeded, skip over all the folded instructions, and
1779 // then see if there is a load right before the selected instructions.
1780 // Try to fold the load if so.
1781 const Instruction *BeforeInst = Inst;
1782 while (BeforeInst != &*Begin) {
1783 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1784 if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1785 break;
1786 }
1787 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1788 BeforeInst->hasOneUse() &&
1789 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1790 // If we succeeded, don't re-select the load.
1792 << "FastISel folded load: " << *BeforeInst << "\n");
1793 FastIS->handleDbgInfo(BeforeInst);
1794 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1795 --NumFastIselRemaining;
1796 ++NumFastIselSuccess;
1797 }
1798 continue;
1799 }
1800
1801 FastISelFailed = true;
1802
1803 // Then handle certain instructions as single-LLVM-Instruction blocks.
1804 // We cannot separate out GCrelocates to their own blocks since we need
1805 // to keep track of gc-relocates for a particular gc-statepoint. This is
1806 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1807 // visitGCRelocate.
1808 if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1809 !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1810 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1811 Inst->getDebugLoc(), LLVMBB);
1812
1813 R << "FastISel missed call";
1814
1815 if (R.isEnabled() || EnableFastISelAbort) {
1816 std::string InstStrStorage;
1817 raw_string_ostream InstStr(InstStrStorage);
1818 InstStr << *Inst;
1819
1820 R << ": " << InstStrStorage;
1821 }
1822
1824
1825 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1826 !Inst->use_empty()) {
1827 Register &R = FuncInfo->ValueMap[Inst];
1828 if (!R)
1829 R = FuncInfo->CreateRegs(Inst);
1830 }
1831
1832 bool HadTailCall = false;
1833 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1834 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1835
1836 // If the call was emitted as a tail call, we're done with the block.
1837 // We also need to delete any previously emitted instructions.
1838 if (HadTailCall) {
1839 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1840 --BI;
1841 break;
1842 }
1843
1844 // Recompute NumFastIselRemaining as Selection DAG instruction
1845 // selection may have handled the call, input args, etc.
1846 unsigned RemainingNow = std::distance(Begin, BI);
1847 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1848 NumFastIselRemaining = RemainingNow;
1849 continue;
1850 }
1851
1852 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1853 Inst->getDebugLoc(), LLVMBB);
1854
1855 bool ShouldAbort = EnableFastISelAbort;
1856 if (Inst->isTerminator()) {
1857 // Use a different message for terminator misses.
1858 R << "FastISel missed terminator";
1859 // Don't abort for terminator unless the level is really high
1860 ShouldAbort = (EnableFastISelAbort > 2);
1861 } else {
1862 R << "FastISel missed";
1863 }
1864
1865 if (R.isEnabled() || EnableFastISelAbort) {
1866 std::string InstStrStorage;
1867 raw_string_ostream InstStr(InstStrStorage);
1868 InstStr << *Inst;
1869 R << ": " << InstStrStorage;
1870 }
1871
1872 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1873
1874 NumFastIselFailures += NumFastIselRemaining;
1875 break;
1876 }
1877
1878 FastIS->recomputeInsertPt();
1879 }
1880
1881 if (SP->shouldEmitSDCheck(*LLVMBB)) {
1882 bool FunctionBasedInstrumentation =
1884 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->getMBB(LLVMBB),
1885 FunctionBasedInstrumentation);
1886 }
1887
1888 if (Begin != BI)
1889 ++NumDAGBlocks;
1890 else
1891 ++NumFastIselBlocks;
1892
1893 if (Begin != BI) {
1894 // Run SelectionDAG instruction selection on the remainder of the block
1895 // not handled by FastISel. If FastISel is not run, this is the entire
1896 // block.
1897 bool HadTailCall;
1898 SelectBasicBlock(Begin, BI, HadTailCall);
1899
1900 // But if FastISel was run, we already selected some of the block.
1901 // If we emitted a tail-call, we need to delete any previously emitted
1902 // instruction that follows it.
1903 if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1904 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1905 }
1906
1907 if (FastIS)
1908 FastIS->finishBasicBlock();
1909 FinishBasicBlock();
1910 FuncInfo->PHINodesToUpdate.clear();
1911 ElidedArgCopyInstrs.clear();
1912 }
1913
1914 // AsynchEH: Report Block State under -AsynchEH
1915 if (Fn.getParent()->getModuleFlag("eh-asynch"))
1916 reportIPToStateForBlocks(MF);
1917
1919
1921
1922 delete FastIS;
1923 SDB->clearDanglingDebugInfo();
1924 SDB->SPDescriptor.resetPerFunctionState();
1925}
1926
1927void
1928SelectionDAGISel::FinishBasicBlock() {
1929 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1930 << FuncInfo->PHINodesToUpdate.size() << "\n";
1931 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1932 ++i) dbgs()
1933 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1934 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1935
1936 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1937 // PHI nodes in successors.
1938 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1939 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1940 assert(PHI->isPHI() &&
1941 "This is not a machine PHI node that we are updating!");
1942 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1943 continue;
1944 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1945 }
1946
1947 // Handle stack protector.
1948 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1949 // The target provides a guard check function. There is no need to
1950 // generate error handling code or to split current basic block.
1951 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1952
1953 // Add load and check to the basicblock.
1954 FuncInfo->MBB = ParentMBB;
1955 FuncInfo->InsertPt =
1957 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1958 CurDAG->setRoot(SDB->getRoot());
1959 SDB->clear();
1960 CodeGenAndEmitDAG();
1961
1962 // Clear the Per-BB State.
1963 SDB->SPDescriptor.resetPerBBState();
1964 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1965 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1966 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1967
1968 // Find the split point to split the parent mbb. At the same time copy all
1969 // physical registers used in the tail of parent mbb into virtual registers
1970 // before the split point and back into physical registers after the split
1971 // point. This prevents us needing to deal with Live-ins and many other
1972 // register allocation issues caused by us splitting the parent mbb. The
1973 // register allocator will clean up said virtual copies later on.
1974 MachineBasicBlock::iterator SplitPoint =
1976
1977 // Splice the terminator of ParentMBB into SuccessMBB.
1978 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1979 SplitPoint,
1980 ParentMBB->end());
1981
1982 // Add compare/jump on neq/jump to the parent BB.
1983 FuncInfo->MBB = ParentMBB;
1984 FuncInfo->InsertPt = ParentMBB->end();
1985 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1986 CurDAG->setRoot(SDB->getRoot());
1987 SDB->clear();
1988 CodeGenAndEmitDAG();
1989
1990 // CodeGen Failure MBB if we have not codegened it yet.
1991 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1992 if (FailureMBB->empty()) {
1993 FuncInfo->MBB = FailureMBB;
1994 FuncInfo->InsertPt = FailureMBB->end();
1995 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1996 CurDAG->setRoot(SDB->getRoot());
1997 SDB->clear();
1998 CodeGenAndEmitDAG();
1999 }
2000
2001 // Clear the Per-BB State.
2002 SDB->SPDescriptor.resetPerBBState();
2003 }
2004
2005 // Lower each BitTestBlock.
2006 for (auto &BTB : SDB->SL->BitTestCases) {
2007 // Lower header first, if it wasn't already lowered
2008 if (!BTB.Emitted) {
2009 // Set the current basic block to the mbb we wish to insert the code into
2010 FuncInfo->MBB = BTB.Parent;
2011 FuncInfo->InsertPt = FuncInfo->MBB->end();
2012 // Emit the code
2013 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
2014 CurDAG->setRoot(SDB->getRoot());
2015 SDB->clear();
2016 CodeGenAndEmitDAG();
2017 }
2018
2019 BranchProbability UnhandledProb = BTB.Prob;
2020 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
2021 UnhandledProb -= BTB.Cases[j].ExtraProb;
2022 // Set the current basic block to the mbb we wish to insert the code into
2023 FuncInfo->MBB = BTB.Cases[j].ThisBB;
2024 FuncInfo->InsertPt = FuncInfo->MBB->end();
2025 // Emit the code
2026
2027 // If all cases cover a contiguous range, it is not necessary to jump to
2028 // the default block after the last bit test fails. This is because the
2029 // range check during bit test header creation has guaranteed that every
2030 // case here doesn't go outside the range. In this case, there is no need
2031 // to perform the last bit test, as it will always be true. Instead, make
2032 // the second-to-last bit-test fall through to the target of the last bit
2033 // test, and delete the last bit test.
2034
2035 MachineBasicBlock *NextMBB;
2036 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2037 // Second-to-last bit-test with contiguous range or omitted range
2038 // check: fall through to the target of the final bit test.
2039 NextMBB = BTB.Cases[j + 1].TargetBB;
2040 } else if (j + 1 == ej) {
2041 // For the last bit test, fall through to Default.
2042 NextMBB = BTB.Default;
2043 } else {
2044 // Otherwise, fall through to the next bit test.
2045 NextMBB = BTB.Cases[j + 1].ThisBB;
2046 }
2047
2048 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
2049 FuncInfo->MBB);
2050
2051 CurDAG->setRoot(SDB->getRoot());
2052 SDB->clear();
2053 CodeGenAndEmitDAG();
2054
2055 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
2056 // Since we're not going to use the final bit test, remove it.
2057 BTB.Cases.pop_back();
2058 break;
2059 }
2060 }
2061
2062 // Update PHI Nodes
2063 for (const std::pair<MachineInstr *, unsigned> &P :
2064 FuncInfo->PHINodesToUpdate) {
2065 MachineInstrBuilder PHI(*MF, P.first);
2066 MachineBasicBlock *PHIBB = PHI->getParent();
2067 assert(PHI->isPHI() &&
2068 "This is not a machine PHI node that we are updating!");
2069 // This is "default" BB. We have two jumps to it. From "header" BB and
2070 // from last "case" BB, unless the latter was skipped.
2071 if (PHIBB == BTB.Default) {
2072 PHI.addReg(P.second).addMBB(BTB.Parent);
2073 if (!BTB.ContiguousRange) {
2074 PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
2075 }
2076 }
2077 // One of "cases" BB.
2078 for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
2079 MachineBasicBlock* cBB = BT.ThisBB;
2080 if (cBB->isSuccessor(PHIBB))
2081 PHI.addReg(P.second).addMBB(cBB);
2082 }
2083 }
2084 }
2085 SDB->SL->BitTestCases.clear();
2086
2087 // If the JumpTable record is filled in, then we need to emit a jump table.
2088 // Updating the PHI nodes is tricky in this case, since we need to determine
2089 // whether the PHI is a successor of the range check MBB or the jump table MBB
2090 for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
2091 // Lower header first, if it wasn't already lowered
2092 if (!SDB->SL->JTCases[i].first.Emitted) {
2093 // Set the current basic block to the mbb we wish to insert the code into
2094 FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
2095 FuncInfo->InsertPt = FuncInfo->MBB->end();
2096 // Emit the code
2097 SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
2098 SDB->SL->JTCases[i].first, FuncInfo->MBB);
2099 CurDAG->setRoot(SDB->getRoot());
2100 SDB->clear();
2101 CodeGenAndEmitDAG();
2102 }
2103
2104 // Set the current basic block to the mbb we wish to insert the code into
2105 FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
2106 FuncInfo->InsertPt = FuncInfo->MBB->end();
2107 // Emit the code
2108 SDB->visitJumpTable(SDB->SL->JTCases[i].second);
2109 CurDAG->setRoot(SDB->getRoot());
2110 SDB->clear();
2111 CodeGenAndEmitDAG();
2112
2113 // Update PHI Nodes
2114 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
2115 pi != pe; ++pi) {
2116 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
2117 MachineBasicBlock *PHIBB = PHI->getParent();
2118 assert(PHI->isPHI() &&
2119 "This is not a machine PHI node that we are updating!");
2120 // "default" BB. We can go there only from header BB.
2121 if (PHIBB == SDB->SL->JTCases[i].second.Default)
2122 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
2123 .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
2124 // JT BB. Just iterate over successors here
2125 if (FuncInfo->MBB->isSuccessor(PHIBB))
2126 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
2127 }
2128 }
2129 SDB->SL->JTCases.clear();
2130
2131 // If we generated any switch lowering information, build and codegen any
2132 // additional DAGs necessary.
2133 for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
2134 // Set the current basic block to the mbb we wish to insert the code into
2135 FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
2136 FuncInfo->InsertPt = FuncInfo->MBB->end();
2137
2138 // Determine the unique successors.
2140 Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
2141 if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
2142 Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
2143
2144 // Emit the code. Note that this could result in FuncInfo->MBB being split.
2145 SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
2146 CurDAG->setRoot(SDB->getRoot());
2147 SDB->clear();
2148 CodeGenAndEmitDAG();
2149
2150 // Remember the last block, now that any splitting is done, for use in
2151 // populating PHI nodes in successors.
2152 MachineBasicBlock *ThisBB = FuncInfo->MBB;
2153
2154 // Handle any PHI nodes in successors of this chunk, as if we were coming
2155 // from the original BB before switch expansion. Note that PHI nodes can
2156 // occur multiple times in PHINodesToUpdate. We have to be very careful to
2157 // handle them the right number of times.
2158 for (MachineBasicBlock *Succ : Succs) {
2159 FuncInfo->MBB = Succ;
2160 FuncInfo->InsertPt = FuncInfo->MBB->end();
2161 // FuncInfo->MBB may have been removed from the CFG if a branch was
2162 // constant folded.
2163 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
2165 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
2166 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
2168 // This value for this PHI node is recorded in PHINodesToUpdate.
2169 for (unsigned pn = 0; ; ++pn) {
2170 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
2171 "Didn't find PHI entry!");
2172 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
2173 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
2174 break;
2175 }
2176 }
2177 }
2178 }
2179 }
2180 }
2181 SDB->SL->SwitchCases.clear();
2182}
2183
2184/// Create the scheduler. If a specific scheduler was specified
2185/// via the SchedulerRegistry, use it, otherwise select the
2186/// one preferred by the target.
2187///
2188ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
2189 return ISHeuristic(this, OptLevel);
2190}
2191
2192//===----------------------------------------------------------------------===//
2193// Helper functions used by the generated instruction selector.
2194//===----------------------------------------------------------------------===//
2195// Calls to these methods are generated by tblgen.
2196
2197/// CheckAndMask - The isel is trying to match something like (and X, 255). If
2198/// the dag combiner simplified the 255, we still want to match. RHS is the
2199/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2200/// specified in the .td file (e.g. 255).
2202 int64_t DesiredMaskS) const {
2203 const APInt &ActualMask = RHS->getAPIntValue();
2204 // TODO: Avoid implicit trunc?
2205 // See https://github.com/llvm/llvm-project/issues/112510.
2206 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS,
2207 /*isSigned=*/false, /*implicitTrunc=*/true);
2208
2209 // If the actual mask exactly matches, success!
2210 if (ActualMask == DesiredMask)
2211 return true;
2212
2213 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2214 if (!ActualMask.isSubsetOf(DesiredMask))
2215 return false;
2216
2217 // Otherwise, the DAG Combiner may have proven that the value coming in is
2218 // either already zero or is not demanded. Check for known zero input bits.
2219 APInt NeededMask = DesiredMask & ~ActualMask;
2220 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2221 return true;
2222
2223 // TODO: check to see if missing bits are just not demanded.
2224
2225 // Otherwise, this pattern doesn't match.
2226 return false;
2227}
2228
2229/// CheckOrMask - The isel is trying to match something like (or X, 255). If
2230/// the dag combiner simplified the 255, we still want to match. RHS is the
2231/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2232/// specified in the .td file (e.g. 255).
2234 int64_t DesiredMaskS) const {
2235 const APInt &ActualMask = RHS->getAPIntValue();
2236 // TODO: Avoid implicit trunc?
2237 // See https://github.com/llvm/llvm-project/issues/112510.
2238 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS,
2239 /*isSigned=*/false, /*implicitTrunc=*/true);
2240
2241 // If the actual mask exactly matches, success!
2242 if (ActualMask == DesiredMask)
2243 return true;
2244
2245 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2246 if (!ActualMask.isSubsetOf(DesiredMask))
2247 return false;
2248
2249 // Otherwise, the DAG Combiner may have proven that the value coming in is
2250 // either already zero or is not demanded. Check for known zero input bits.
2251 APInt NeededMask = DesiredMask & ~ActualMask;
2253
2254 // If all the missing bits in the or are already known to be set, match!
2255 if (NeededMask.isSubsetOf(Known.One))
2256 return true;
2257
2258 // TODO: check to see if missing bits are just not demanded.
2259
2260 // Otherwise, this pattern doesn't match.
2261 return false;
2262}
2263
2264/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2265/// by tblgen. Others should not call it.
2267 const SDLoc &DL) {
2268 // Change the vector of SDValue into a list of SDNodeHandle for x86 might call
2269 // replaceAllUses when matching address.
2270
2271 std::list<HandleSDNode> Handles;
2272
2273 Handles.emplace_back(Ops[InlineAsm::Op_InputChain]); // 0
2274 Handles.emplace_back(Ops[InlineAsm::Op_AsmString]); // 1
2275 Handles.emplace_back(Ops[InlineAsm::Op_MDNode]); // 2, !srcloc
2276 Handles.emplace_back(
2277 Ops[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2278
2279 unsigned i = InlineAsm::Op_FirstOperand, e = Ops.size();
2280 if (Ops[e - 1].getValueType() == MVT::Glue)
2281 --e; // Don't process a glue operand if it is here.
2282
2283 while (i != e) {
2284 InlineAsm::Flag Flags(Ops[i]->getAsZExtVal());
2285 if (!Flags.isMemKind() && !Flags.isFuncKind()) {
2286 // Just skip over this operand, copying the operands verbatim.
2287 Handles.insert(Handles.end(), Ops.begin() + i,
2288 Ops.begin() + i + Flags.getNumOperandRegisters() + 1);
2289 i += Flags.getNumOperandRegisters() + 1;
2290 } else {
2291 assert(Flags.getNumOperandRegisters() == 1 &&
2292 "Memory operand with multiple values?");
2293
2294 unsigned TiedToOperand;
2295 if (Flags.isUseOperandTiedToDef(TiedToOperand)) {
2296 // We need the constraint ID from the operand this is tied to.
2297 unsigned CurOp = InlineAsm::Op_FirstOperand;
2298 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2299 for (; TiedToOperand; --TiedToOperand) {
2300 CurOp += Flags.getNumOperandRegisters() + 1;
2301 Flags = InlineAsm::Flag(Ops[CurOp]->getAsZExtVal());
2302 }
2303 }
2304
2305 // Otherwise, this is a memory operand. Ask the target to select it.
2306 std::vector<SDValue> SelOps;
2307 const InlineAsm::ConstraintCode ConstraintID =
2308 Flags.getMemoryConstraintID();
2309 if (SelectInlineAsmMemoryOperand(Ops[i + 1], ConstraintID, SelOps))
2310 report_fatal_error("Could not match memory address. Inline asm"
2311 " failure!");
2312
2313 // Add this to the output node.
2314 Flags = InlineAsm::Flag(Flags.isMemKind() ? InlineAsm::Kind::Mem
2316 SelOps.size());
2317 Flags.setMemConstraint(ConstraintID);
2318 Handles.emplace_back(CurDAG->getTargetConstant(Flags, DL, MVT::i32));
2319 Handles.insert(Handles.end(), SelOps.begin(), SelOps.end());
2320 i += 2;
2321 }
2322 }
2323
2324 // Add the glue input back if present.
2325 if (e != Ops.size())
2326 Handles.emplace_back(Ops.back());
2327
2328 Ops.clear();
2329 for (auto &handle : Handles)
2330 Ops.push_back(handle.getValue());
2331}
2332
2333/// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2334/// beyond "ImmedUse". We may ignore chains as they are checked separately.
2335static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2336 bool IgnoreChains) {
2339 // Only check if we have non-immediate uses of Def.
2340 if (ImmedUse->isOnlyUserOf(Def))
2341 return false;
2342
2343 // We don't care about paths to Def that go through ImmedUse so mark it
2344 // visited and mark non-def operands as used.
2345 Visited.insert(ImmedUse);
2346 for (const SDValue &Op : ImmedUse->op_values()) {
2347 SDNode *N = Op.getNode();
2348 // Ignore chain deps (they are validated by
2349 // HandleMergeInputChains) and immediate uses
2350 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2351 continue;
2352 if (!Visited.insert(N).second)
2353 continue;
2354 WorkList.push_back(N);
2355 }
2356
2357 // Initialize worklist to operands of Root.
2358 if (Root != ImmedUse) {
2359 for (const SDValue &Op : Root->op_values()) {
2360 SDNode *N = Op.getNode();
2361 // Ignore chains (they are validated by HandleMergeInputChains)
2362 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2363 continue;
2364 if (!Visited.insert(N).second)
2365 continue;
2366 WorkList.push_back(N);
2367 }
2368 }
2369
2370 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2371}
2372
2373/// IsProfitableToFold - Returns true if it's profitable to fold the specific
2374/// operand node N of U during instruction selection that starts at Root.
2376 SDNode *Root) const {
2378 return false;
2379 return N.hasOneUse();
2380}
2381
2382/// IsLegalToFold - Returns true if the specific operand node N of
2383/// U can be folded during instruction selection that starts at Root.
2385 CodeGenOptLevel OptLevel,
2386 bool IgnoreChains) {
2388 return false;
2389
2390 // If Root use can somehow reach N through a path that doesn't contain
2391 // U then folding N would create a cycle. e.g. In the following
2392 // diagram, Root can reach N through X. If N is folded into Root, then
2393 // X is both a predecessor and a successor of U.
2394 //
2395 // [N*] //
2396 // ^ ^ //
2397 // / \ //
2398 // [U*] [X]? //
2399 // ^ ^ //
2400 // \ / //
2401 // \ / //
2402 // [Root*] //
2403 //
2404 // * indicates nodes to be folded together.
2405 //
2406 // If Root produces glue, then it gets (even more) interesting. Since it
2407 // will be "glued" together with its glue use in the scheduler, we need to
2408 // check if it might reach N.
2409 //
2410 // [N*] //
2411 // ^ ^ //
2412 // / \ //
2413 // [U*] [X]? //
2414 // ^ ^ //
2415 // \ \ //
2416 // \ | //
2417 // [Root*] | //
2418 // ^ | //
2419 // f | //
2420 // | / //
2421 // [Y] / //
2422 // ^ / //
2423 // f / //
2424 // | / //
2425 // [GU] //
2426 //
2427 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2428 // (call it Fold), then X is a predecessor of GU and a successor of
2429 // Fold. But since Fold and GU are glued together, this will create
2430 // a cycle in the scheduling graph.
2431
2432 // If the node has glue, walk down the graph to the "lowest" node in the
2433 // glueged set.
2434 EVT VT = Root->getValueType(Root->getNumValues()-1);
2435 while (VT == MVT::Glue) {
2436 SDNode *GU = Root->getGluedUser();
2437 if (!GU)
2438 break;
2439 Root = GU;
2440 VT = Root->getValueType(Root->getNumValues()-1);
2441
2442 // If our query node has a glue result with a use, we've walked up it. If
2443 // the user (which has already been selected) has a chain or indirectly uses
2444 // the chain, HandleMergeInputChains will not consider it. Because of
2445 // this, we cannot ignore chains in this predicate.
2446 IgnoreChains = false;
2447 }
2448
2449 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2450}
2451
2452void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2453 SDLoc DL(N);
2454
2455 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2457
2458 const EVT VTs[] = {MVT::Other, MVT::Glue};
2459 SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2460 New->setNodeId(-1);
2461 ReplaceUses(N, New.getNode());
2463}
2464
2465void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2466 SDLoc dl(Op);
2467 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2468 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2469
2470 EVT VT = Op->getValueType(0);
2471 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2472 Register Reg =
2473 TLI->getRegisterByName(RegStr->getString().data(), Ty,
2476 Op->getOperand(0), dl, Reg, Op->getValueType(0));
2477 New->setNodeId(-1);
2478 ReplaceUses(Op, New.getNode());
2480}
2481
2482void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2483 SDLoc dl(Op);
2484 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2485 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2486
2487 EVT VT = Op->getOperand(2).getValueType();
2488 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2489
2490 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
2493 Op->getOperand(0), dl, Reg, Op->getOperand(2));
2494 New->setNodeId(-1);
2495 ReplaceUses(Op, New.getNode());
2497}
2498
2499void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2500 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2501}
2502
2503// Use the generic target FAKE_USE target opcode. The chain operand
2504// must come last, because InstrEmitter::AddOperand() requires it.
2505void SelectionDAGISel::Select_FAKE_USE(SDNode *N) {
2506 CurDAG->SelectNodeTo(N, TargetOpcode::FAKE_USE, N->getValueType(0),
2507 N->getOperand(1), N->getOperand(0));
2508}
2509
2510void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2511 // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2512 // If FREEZE instruction is added later, the code below must be changed as
2513 // well.
2514 CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2515 N->getOperand(0));
2516}
2517
2518void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2519 CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2520 N->getOperand(0));
2521}
2522
2523void SelectionDAGISel::Select_MEMBARRIER(SDNode *N) {
2524 CurDAG->SelectNodeTo(N, TargetOpcode::MEMBARRIER, N->getValueType(0),
2525 N->getOperand(0));
2526}
2527
2528void SelectionDAGISel::Select_CONVERGENCECTRL_ANCHOR(SDNode *N) {
2529 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ANCHOR,
2530 N->getValueType(0));
2531}
2532
2533void SelectionDAGISel::Select_CONVERGENCECTRL_ENTRY(SDNode *N) {
2534 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_ENTRY,
2535 N->getValueType(0));
2536}
2537
2538void SelectionDAGISel::Select_CONVERGENCECTRL_LOOP(SDNode *N) {
2539 CurDAG->SelectNodeTo(N, TargetOpcode::CONVERGENCECTRL_LOOP,
2540 N->getValueType(0), N->getOperand(0));
2541}
2542
2543void SelectionDAGISel::pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops,
2544 SDValue OpVal, SDLoc DL) {
2545 SDNode *OpNode = OpVal.getNode();
2546
2547 // FrameIndex nodes should have been directly emitted to TargetFrameIndex
2548 // nodes at DAG-construction time.
2549 assert(OpNode->getOpcode() != ISD::FrameIndex);
2550
2551 if (OpNode->getOpcode() == ISD::Constant) {
2552 Ops.push_back(
2553 CurDAG->getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
2555 OpVal.getValueType()));
2556 } else {
2557 Ops.push_back(OpVal);
2558 }
2559}
2560
2561void SelectionDAGISel::Select_STACKMAP(SDNode *N) {
2563 auto *It = N->op_begin();
2564 SDLoc DL(N);
2565
2566 // Stash the chain and glue operands so we can move them to the end.
2567 SDValue Chain = *It++;
2568 SDValue InGlue = *It++;
2569
2570 // <id> operand.
2571 SDValue ID = *It++;
2572 assert(ID.getValueType() == MVT::i64);
2573 Ops.push_back(ID);
2574
2575 // <numShadowBytes> operand.
2576 SDValue Shad = *It++;
2577 assert(Shad.getValueType() == MVT::i32);
2578 Ops.push_back(Shad);
2579
2580 // Live variable operands.
2581 for (; It != N->op_end(); It++)
2582 pushStackMapLiveVariable(Ops, *It, DL);
2583
2584 Ops.push_back(Chain);
2585 Ops.push_back(InGlue);
2586
2587 SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
2588 CurDAG->SelectNodeTo(N, TargetOpcode::STACKMAP, NodeTys, Ops);
2589}
2590
2591void SelectionDAGISel::Select_PATCHPOINT(SDNode *N) {
2593 auto *It = N->op_begin();
2594 SDLoc DL(N);
2595
2596 // Cache arguments that will be moved to the end in the target node.
2597 SDValue Chain = *It++;
2598 std::optional<SDValue> Glue;
2599 if (It->getValueType() == MVT::Glue)
2600 Glue = *It++;
2601 SDValue RegMask = *It++;
2602
2603 // <id> operand.
2604 SDValue ID = *It++;
2605 assert(ID.getValueType() == MVT::i64);
2606 Ops.push_back(ID);
2607
2608 // <numShadowBytes> operand.
2609 SDValue Shad = *It++;
2610 assert(Shad.getValueType() == MVT::i32);
2611 Ops.push_back(Shad);
2612
2613 // Add the callee.
2614 Ops.push_back(*It++);
2615
2616 // Add <numArgs>.
2617 SDValue NumArgs = *It++;
2618 assert(NumArgs.getValueType() == MVT::i32);
2619 Ops.push_back(NumArgs);
2620
2621 // Calling convention.
2622 Ops.push_back(*It++);
2623
2624 // Push the args for the call.
2625 for (uint64_t I = NumArgs->getAsZExtVal(); I != 0; I--)
2626 Ops.push_back(*It++);
2627
2628 // Now push the live variables.
2629 for (; It != N->op_end(); It++)
2630 pushStackMapLiveVariable(Ops, *It, DL);
2631
2632 // Finally, the regmask, chain and (if present) glue are moved to the end.
2633 Ops.push_back(RegMask);
2634 Ops.push_back(Chain);
2635 if (Glue.has_value())
2636 Ops.push_back(*Glue);
2637
2638 SDVTList NodeTys = N->getVTList();
2639 CurDAG->SelectNodeTo(N, TargetOpcode::PATCHPOINT, NodeTys, Ops);
2640}
2641
2642/// GetVBR - decode a vbr encoding whose top bit is set.
2644GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2645 assert(Val >= 128 && "Not a VBR");
2646 Val &= 127; // Remove first vbr bit.
2647
2648 unsigned Shift = 7;
2649 uint64_t NextBits;
2650 do {
2651 NextBits = MatcherTable[Idx++];
2652 Val |= (NextBits&127) << Shift;
2653 Shift += 7;
2654 } while (NextBits & 128);
2655
2656 return Val;
2657}
2658
2659/// getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value,
2660/// use GetVBR to decode it.
2662getSimpleVT(const unsigned char *MatcherTable, unsigned &MatcherIndex) {
2663 unsigned SimpleVT = MatcherTable[MatcherIndex++];
2664 if (SimpleVT & 128)
2665 SimpleVT = GetVBR(SimpleVT, MatcherTable, MatcherIndex);
2666
2667 return static_cast<MVT::SimpleValueType>(SimpleVT);
2668}
2669
2670void SelectionDAGISel::Select_JUMP_TABLE_DEBUG_INFO(SDNode *N) {
2671 SDLoc dl(N);
2672 CurDAG->SelectNodeTo(N, TargetOpcode::JUMP_TABLE_DEBUG_INFO, MVT::Glue,
2673 CurDAG->getTargetConstant(N->getConstantOperandVal(1),
2674 dl, MVT::i64, true));
2675}
2676
2677/// When a match is complete, this method updates uses of interior chain results
2678/// to use the new results.
2679void SelectionDAGISel::UpdateChains(
2680 SDNode *NodeToMatch, SDValue InputChain,
2681 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2682 SmallVector<SDNode*, 4> NowDeadNodes;
2683
2684 // Now that all the normal results are replaced, we replace the chain and
2685 // glue results if present.
2686 if (!ChainNodesMatched.empty()) {
2687 assert(InputChain.getNode() &&
2688 "Matched input chains but didn't produce a chain");
2689 // Loop over all of the nodes we matched that produced a chain result.
2690 // Replace all the chain results with the final chain we ended up with.
2691 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2692 SDNode *ChainNode = ChainNodesMatched[i];
2693 // If ChainNode is null, it's because we replaced it on a previous
2694 // iteration and we cleared it out of the map. Just skip it.
2695 if (!ChainNode)
2696 continue;
2697
2698 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2699 "Deleted node left in chain");
2700
2701 // Don't replace the results of the root node if we're doing a
2702 // MorphNodeTo.
2703 if (ChainNode == NodeToMatch && isMorphNodeTo)
2704 continue;
2705
2706 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2707 if (ChainVal.getValueType() == MVT::Glue)
2708 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2709 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2711 *CurDAG, [&](SDNode *N, SDNode *E) {
2712 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2713 static_cast<SDNode *>(nullptr));
2714 });
2715 if (ChainNode->getOpcode() != ISD::TokenFactor)
2716 ReplaceUses(ChainVal, InputChain);
2717
2718 // If the node became dead and we haven't already seen it, delete it.
2719 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2720 !llvm::is_contained(NowDeadNodes, ChainNode))
2721 NowDeadNodes.push_back(ChainNode);
2722 }
2723 }
2724
2725 if (!NowDeadNodes.empty())
2726 CurDAG->RemoveDeadNodes(NowDeadNodes);
2727
2728 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2729}
2730
2731/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2732/// operation for when the pattern matched at least one node with a chains. The
2733/// input vector contains a list of all of the chained nodes that we match. We
2734/// must determine if this is a valid thing to cover (i.e. matching it won't
2735/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2736/// be used as the input node chain for the generated nodes.
2737static SDValue
2739 SelectionDAG *CurDAG) {
2740
2743 SmallVector<SDValue, 3> InputChains;
2744 unsigned int Max = 8192;
2745
2746 // Quick exit on trivial merge.
2747 if (ChainNodesMatched.size() == 1)
2748 return ChainNodesMatched[0]->getOperand(0);
2749
2750 // Add chains that aren't already added (internal). Peek through
2751 // token factors.
2752 std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2753 if (V.getValueType() != MVT::Other)
2754 return;
2755 if (V->getOpcode() == ISD::EntryToken)
2756 return;
2757 if (!Visited.insert(V.getNode()).second)
2758 return;
2759 if (V->getOpcode() == ISD::TokenFactor) {
2760 for (const SDValue &Op : V->op_values())
2761 AddChains(Op);
2762 } else
2763 InputChains.push_back(V);
2764 };
2765
2766 for (auto *N : ChainNodesMatched) {
2767 Worklist.push_back(N);
2768 Visited.insert(N);
2769 }
2770
2771 while (!Worklist.empty())
2772 AddChains(Worklist.pop_back_val()->getOperand(0));
2773
2774 // Skip the search if there are no chain dependencies.
2775 if (InputChains.size() == 0)
2776 return CurDAG->getEntryNode();
2777
2778 // If one of these chains is a successor of input, we must have a
2779 // node that is both the predecessor and successor of the
2780 // to-be-merged nodes. Fail.
2781 Visited.clear();
2782 for (SDValue V : InputChains)
2783 Worklist.push_back(V.getNode());
2784
2785 for (auto *N : ChainNodesMatched)
2786 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2787 return SDValue();
2788
2789 // Return merged chain.
2790 if (InputChains.size() == 1)
2791 return InputChains[0];
2792 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2793 MVT::Other, InputChains);
2794}
2795
2796/// MorphNode - Handle morphing a node in place for the selector.
2797SDNode *SelectionDAGISel::
2798MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2799 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2800 // It is possible we're using MorphNodeTo to replace a node with no
2801 // normal results with one that has a normal result (or we could be
2802 // adding a chain) and the input could have glue and chains as well.
2803 // In this case we need to shift the operands down.
2804 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2805 // than the old isel though.
2806 int OldGlueResultNo = -1, OldChainResultNo = -1;
2807
2808 unsigned NTMNumResults = Node->getNumValues();
2809 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2810 OldGlueResultNo = NTMNumResults-1;
2811 if (NTMNumResults != 1 &&
2812 Node->getValueType(NTMNumResults-2) == MVT::Other)
2813 OldChainResultNo = NTMNumResults-2;
2814 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2815 OldChainResultNo = NTMNumResults-1;
2816
2817 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2818 // that this deletes operands of the old node that become dead.
2819 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2820
2821 // MorphNodeTo can operate in two ways: if an existing node with the
2822 // specified operands exists, it can just return it. Otherwise, it
2823 // updates the node in place to have the requested operands.
2824 if (Res == Node) {
2825 // If we updated the node in place, reset the node ID. To the isel,
2826 // this should be just like a newly allocated machine node.
2827 Res->setNodeId(-1);
2828 }
2829
2830 unsigned ResNumResults = Res->getNumValues();
2831 // Move the glue if needed.
2832 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2833 static_cast<unsigned>(OldGlueResultNo) != ResNumResults - 1)
2834 ReplaceUses(SDValue(Node, OldGlueResultNo),
2835 SDValue(Res, ResNumResults - 1));
2836
2837 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2838 --ResNumResults;
2839
2840 // Move the chain reference if needed.
2841 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2842 static_cast<unsigned>(OldChainResultNo) != ResNumResults - 1)
2843 ReplaceUses(SDValue(Node, OldChainResultNo),
2844 SDValue(Res, ResNumResults - 1));
2845
2846 // Otherwise, no replacement happened because the node already exists. Replace
2847 // Uses of the old node with the new one.
2848 if (Res != Node) {
2849 ReplaceNode(Node, Res);
2850 } else {
2852 }
2853
2854 return Res;
2855}
2856
2857/// CheckSame - Implements OP_CheckSame.
2859CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2860 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
2861 // Accept if it is exactly the same as a previously recorded node.
2862 unsigned RecNo = MatcherTable[MatcherIndex++];
2863 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2864 return N == RecordedNodes[RecNo].first;
2865}
2866
2867/// CheckChildSame - Implements OP_CheckChildXSame.
2869 const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2870 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
2871 unsigned ChildNo) {
2872 if (ChildNo >= N.getNumOperands())
2873 return false; // Match fails if out of range child #.
2874 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2875 RecordedNodes);
2876}
2877
2878/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2880CheckPatternPredicate(unsigned Opcode, const unsigned char *MatcherTable,
2881 unsigned &MatcherIndex, const SelectionDAGISel &SDISel) {
2882 bool TwoBytePredNo =
2884 unsigned PredNo =
2885 TwoBytePredNo || Opcode == SelectionDAGISel::OPC_CheckPatternPredicate
2886 ? MatcherTable[MatcherIndex++]
2888 if (TwoBytePredNo)
2889 PredNo |= MatcherTable[MatcherIndex++] << 8;
2890 return SDISel.CheckPatternPredicate(PredNo);
2891}
2892
2893/// CheckNodePredicate - Implements OP_CheckNodePredicate.
2895CheckNodePredicate(unsigned Opcode, const unsigned char *MatcherTable,
2896 unsigned &MatcherIndex, const SelectionDAGISel &SDISel,
2897 SDNode *N) {
2898 unsigned PredNo = Opcode == SelectionDAGISel::OPC_CheckPredicate
2899 ? MatcherTable[MatcherIndex++]
2901 return SDISel.CheckNodePredicate(N, PredNo);
2902}
2903
2905CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2906 SDNode *N) {
2907 uint16_t Opc = MatcherTable[MatcherIndex++];
2908 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
2909 return N->getOpcode() == Opc;
2910}
2911
2913 SDValue N,
2914 const TargetLowering *TLI,
2915 const DataLayout &DL) {
2916 if (N.getValueType() == VT)
2917 return true;
2918
2919 // Handle the case when VT is iPTR.
2920 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2921}
2922
2925 const DataLayout &DL, unsigned ChildNo) {
2926 if (ChildNo >= N.getNumOperands())
2927 return false; // Match fails if out of range child #.
2928 return ::CheckType(VT, N.getOperand(ChildNo), TLI, DL);
2929}
2930
2932CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2933 SDValue N) {
2934 return cast<CondCodeSDNode>(N)->get() ==
2935 static_cast<ISD::CondCode>(MatcherTable[MatcherIndex++]);
2936}
2937
2939CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2940 SDValue N) {
2941 if (2 >= N.getNumOperands())
2942 return false;
2943 return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
2944}
2945
2947CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2948 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2949 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
2950 if (cast<VTSDNode>(N)->getVT() == VT)
2951 return true;
2952
2953 // Handle the case when VT is iPTR.
2954 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2955}
2956
2957// Bit 0 stores the sign of the immediate. The upper bits contain the magnitude
2958// shifted left by 1.
2960 if ((V & 1) == 0)
2961 return V >> 1;
2962 if (V != 1)
2963 return -(V >> 1);
2964 // There is no such thing as -0 with integers. "-0" really means MININT.
2965 return 1ULL << 63;
2966}
2967
2969CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2970 SDValue N) {
2971 int64_t Val = MatcherTable[MatcherIndex++];
2972 if (Val & 128)
2973 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2974
2975 Val = decodeSignRotatedValue(Val);
2976
2977 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2978 return C && C->getAPIntValue().trySExtValue() == Val;
2979}
2980
2982CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2983 SDValue N, unsigned ChildNo) {
2984 if (ChildNo >= N.getNumOperands())
2985 return false; // Match fails if out of range child #.
2986 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2987}
2988
2990CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2991 SDValue N, const SelectionDAGISel &SDISel) {
2992 int64_t Val = MatcherTable[MatcherIndex++];
2993 if (Val & 128)
2994 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2995
2996 if (N->getOpcode() != ISD::AND) return false;
2997
2998 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2999 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
3000}
3001
3003CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
3004 const SelectionDAGISel &SDISel) {
3005 int64_t Val = MatcherTable[MatcherIndex++];
3006 if (Val & 128)
3007 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3008
3009 if (N->getOpcode() != ISD::OR) return false;
3010
3011 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3012 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
3013}
3014
3015/// IsPredicateKnownToFail - If we know how and can do so without pushing a
3016/// scope, evaluate the current node. If the current predicate is known to
3017/// fail, set Result=true and return anything. If the current predicate is
3018/// known to pass, set Result=false and return the MatcherIndex to continue
3019/// with. If the current predicate is unknown, set Result=false and return the
3020/// MatcherIndex to continue with.
3021static unsigned IsPredicateKnownToFail(const unsigned char *Table,
3022 unsigned Index, SDValue N,
3023 bool &Result,
3024 const SelectionDAGISel &SDISel,
3025 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
3026 unsigned Opcode = Table[Index++];
3027 switch (Opcode) {
3028 default:
3029 Result = false;
3030 return Index-1; // Could not evaluate this predicate.
3032 Result = !::CheckSame(Table, Index, N, RecordedNodes);
3033 return Index;
3038 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
3039 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
3040 return Index;
3051 Result = !::CheckPatternPredicate(Opcode, Table, Index, SDISel);
3052 return Index;
3062 Result = !::CheckNodePredicate(Opcode, Table, Index, SDISel, N.getNode());
3063 return Index;
3065 Result = !::CheckOpcode(Table, Index, N.getNode());
3066 return Index;
3071 switch (Opcode) {
3073 VT = MVT::i32;
3074 break;
3076 VT = MVT::i64;
3077 break;
3078 default:
3079 VT = getSimpleVT(Table, Index);
3080 break;
3081 }
3082 Result = !::CheckType(VT, N, SDISel.TLI, SDISel.CurDAG->getDataLayout());
3083 return Index;
3084 }
3086 unsigned Res = Table[Index++];
3087 Result = !::CheckType(getSimpleVT(Table, Index), N.getValue(Res),
3088 SDISel.TLI, SDISel.CurDAG->getDataLayout());
3089 return Index;
3090 }
3116 unsigned ChildNo;
3119 VT = MVT::i32;
3121 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3123 VT = MVT::i64;
3125 } else {
3126 VT = getSimpleVT(Table, Index);
3127 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3128 }
3129 Result = !::CheckChildType(VT, N, SDISel.TLI,
3130 SDISel.CurDAG->getDataLayout(), ChildNo);
3131 return Index;
3132 }
3134 Result = !::CheckCondCode(Table, Index, N);
3135 return Index;
3137 Result = !::CheckChild2CondCode(Table, Index, N);
3138 return Index;
3140 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
3141 SDISel.CurDAG->getDataLayout());
3142 return Index;
3144 Result = !::CheckInteger(Table, Index, N);
3145 return Index;
3151 Result = !::CheckChildInteger(Table, Index, N,
3153 return Index;
3155 Result = !::CheckAndImm(Table, Index, N, SDISel);
3156 return Index;
3158 Result = !::CheckOrImm(Table, Index, N, SDISel);
3159 return Index;
3160 }
3161}
3162
3163namespace {
3164
3165struct MatchScope {
3166 /// FailIndex - If this match fails, this is the index to continue with.
3167 unsigned FailIndex;
3168
3169 /// NodeStack - The node stack when the scope was formed.
3170 SmallVector<SDValue, 4> NodeStack;
3171
3172 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
3173 unsigned NumRecordedNodes;
3174
3175 /// NumMatchedMemRefs - The number of matched memref entries.
3176 unsigned NumMatchedMemRefs;
3177
3178 /// InputChain/InputGlue - The current chain/glue
3179 SDValue InputChain, InputGlue;
3180
3181 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
3182 bool HasChainNodesMatched;
3183};
3184
3185/// \A DAG update listener to keep the matching state
3186/// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
3187/// change the DAG while matching. X86 addressing mode matcher is an example
3188/// for this.
3189class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
3190{
3191 SDNode **NodeToMatch;
3193 SmallVectorImpl<MatchScope> &MatchScopes;
3194
3195public:
3196 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
3197 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
3199 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
3200 RecordedNodes(RN), MatchScopes(MS) {}
3201
3202 void NodeDeleted(SDNode *N, SDNode *E) override {
3203 // Some early-returns here to avoid the search if we deleted the node or
3204 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
3205 // do, so it's unnecessary to update matching state at that point).
3206 // Neither of these can occur currently because we only install this
3207 // update listener during matching a complex patterns.
3208 if (!E || E->isMachineOpcode())
3209 return;
3210 // Check if NodeToMatch was updated.
3211 if (N == *NodeToMatch)
3212 *NodeToMatch = E;
3213 // Performing linear search here does not matter because we almost never
3214 // run this code. You'd have to have a CSE during complex pattern
3215 // matching.
3216 for (auto &I : RecordedNodes)
3217 if (I.first.getNode() == N)
3218 I.first.setNode(E);
3219
3220 for (auto &I : MatchScopes)
3221 for (auto &J : I.NodeStack)
3222 if (J.getNode() == N)
3223 J.setNode(E);
3224 }
3225};
3226
3227} // end anonymous namespace
3228
3230 const unsigned char *MatcherTable,
3231 unsigned TableSize) {
3232 // FIXME: Should these even be selected? Handle these cases in the caller?
3233 switch (NodeToMatch->getOpcode()) {
3234 default:
3235 break;
3236 case ISD::EntryToken: // These nodes remain the same.
3237 case ISD::BasicBlock:
3238 case ISD::Register:
3239 case ISD::RegisterMask:
3240 case ISD::HANDLENODE:
3241 case ISD::MDNODE_SDNODE:
3247 case ISD::MCSymbol:
3252 case ISD::TokenFactor:
3253 case ISD::CopyFromReg:
3254 case ISD::CopyToReg:
3255 case ISD::EH_LABEL:
3258 case ISD::LIFETIME_END:
3259 case ISD::PSEUDO_PROBE:
3260 NodeToMatch->setNodeId(-1); // Mark selected.
3261 return;
3262 case ISD::AssertSext:
3263 case ISD::AssertZext:
3264 case ISD::AssertAlign:
3265 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
3266 CurDAG->RemoveDeadNode(NodeToMatch);
3267 return;
3268 case ISD::INLINEASM:
3269 case ISD::INLINEASM_BR:
3270 Select_INLINEASM(NodeToMatch);
3271 return;
3272 case ISD::READ_REGISTER:
3273 Select_READ_REGISTER(NodeToMatch);
3274 return;
3276 Select_WRITE_REGISTER(NodeToMatch);
3277 return;
3278 case ISD::UNDEF:
3279 Select_UNDEF(NodeToMatch);
3280 return;
3281 case ISD::FAKE_USE:
3282 Select_FAKE_USE(NodeToMatch);
3283 return;
3284 case ISD::FREEZE:
3285 Select_FREEZE(NodeToMatch);
3286 return;
3287 case ISD::ARITH_FENCE:
3288 Select_ARITH_FENCE(NodeToMatch);
3289 return;
3290 case ISD::MEMBARRIER:
3291 Select_MEMBARRIER(NodeToMatch);
3292 return;
3293 case ISD::STACKMAP:
3294 Select_STACKMAP(NodeToMatch);
3295 return;
3296 case ISD::PATCHPOINT:
3297 Select_PATCHPOINT(NodeToMatch);
3298 return;
3300 Select_JUMP_TABLE_DEBUG_INFO(NodeToMatch);
3301 return;
3303 Select_CONVERGENCECTRL_ANCHOR(NodeToMatch);
3304 return;
3306 Select_CONVERGENCECTRL_ENTRY(NodeToMatch);
3307 return;
3309 Select_CONVERGENCECTRL_LOOP(NodeToMatch);
3310 return;
3311 }
3312
3313 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
3314
3315 // Set up the node stack with NodeToMatch as the only node on the stack.
3316 SmallVector<SDValue, 8> NodeStack;
3317 SDValue N = SDValue(NodeToMatch, 0);
3318 NodeStack.push_back(N);
3319
3320 // MatchScopes - Scopes used when matching, if a match failure happens, this
3321 // indicates where to continue checking.
3322 SmallVector<MatchScope, 8> MatchScopes;
3323
3324 // RecordedNodes - This is the set of nodes that have been recorded by the
3325 // state machine. The second value is the parent of the node, or null if the
3326 // root is recorded.
3328
3329 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
3330 // pattern.
3332
3333 // These are the current input chain and glue for use when generating nodes.
3334 // Various Emit operations change these. For example, emitting a copytoreg
3335 // uses and updates these.
3336 SDValue InputChain, InputGlue;
3337
3338 // ChainNodesMatched - If a pattern matches nodes that have input/output
3339 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
3340 // which ones they are. The result is captured into this list so that we can
3341 // update the chain results when the pattern is complete.
3342 SmallVector<SDNode*, 3> ChainNodesMatched;
3343
3344 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
3345
3346 // Determine where to start the interpreter. Normally we start at opcode #0,
3347 // but if the state machine starts with an OPC_SwitchOpcode, then we
3348 // accelerate the first lookup (which is guaranteed to be hot) with the
3349 // OpcodeOffset table.
3350 unsigned MatcherIndex = 0;
3351
3352 if (!OpcodeOffset.empty()) {
3353 // Already computed the OpcodeOffset table, just index into it.
3354 if (N.getOpcode() < OpcodeOffset.size())
3355 MatcherIndex = OpcodeOffset[N.getOpcode()];
3356 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
3357
3358 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
3359 // Otherwise, the table isn't computed, but the state machine does start
3360 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
3361 // is the first time we're selecting an instruction.
3362 unsigned Idx = 1;
3363 while (true) {
3364 // Get the size of this case.
3365 unsigned CaseSize = MatcherTable[Idx++];
3366 if (CaseSize & 128)
3367 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
3368 if (CaseSize == 0) break;
3369
3370 // Get the opcode, add the index to the table.
3371 uint16_t Opc = MatcherTable[Idx++];
3372 Opc |= static_cast<uint16_t>(MatcherTable[Idx++]) << 8;
3373 if (Opc >= OpcodeOffset.size())
3374 OpcodeOffset.resize((Opc+1)*2);
3375 OpcodeOffset[Opc] = Idx;
3376 Idx += CaseSize;
3377 }
3378
3379 // Okay, do the lookup for the first opcode.
3380 if (N.getOpcode() < OpcodeOffset.size())
3381 MatcherIndex = OpcodeOffset[N.getOpcode()];
3382 }
3383
3384 while (true) {
3385 assert(MatcherIndex < TableSize && "Invalid index");
3386#ifndef NDEBUG
3387 unsigned CurrentOpcodeIndex = MatcherIndex;
3388#endif
3389 BuiltinOpcodes Opcode =
3390 static_cast<BuiltinOpcodes>(MatcherTable[MatcherIndex++]);
3391 switch (Opcode) {
3392 case OPC_Scope: {
3393 // Okay, the semantics of this operation are that we should push a scope
3394 // then evaluate the first child. However, pushing a scope only to have
3395 // the first check fail (which then pops it) is inefficient. If we can
3396 // determine immediately that the first check (or first several) will
3397 // immediately fail, don't even bother pushing a scope for them.
3398 unsigned FailIndex;
3399
3400 while (true) {
3401 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3402 if (NumToSkip & 128)
3403 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3404 // Found the end of the scope with no match.
3405 if (NumToSkip == 0) {
3406 FailIndex = 0;
3407 break;
3408 }
3409
3410 FailIndex = MatcherIndex+NumToSkip;
3411
3412 unsigned MatcherIndexOfPredicate = MatcherIndex;
3413 (void)MatcherIndexOfPredicate; // silence warning.
3414
3415 // If we can't evaluate this predicate without pushing a scope (e.g. if
3416 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3417 // push the scope and evaluate the full predicate chain.
3418 bool Result;
3419 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
3420 Result, *this, RecordedNodes);
3421 if (!Result)
3422 break;
3423
3424 LLVM_DEBUG(
3425 dbgs() << " Skipped scope entry (due to false predicate) at "
3426 << "index " << MatcherIndexOfPredicate << ", continuing at "
3427 << FailIndex << "\n");
3428 ++NumDAGIselRetries;
3429
3430 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3431 // move to the next case.
3432 MatcherIndex = FailIndex;
3433 }
3434
3435 // If the whole scope failed to match, bail.
3436 if (FailIndex == 0) break;
3437
3438 // Push a MatchScope which indicates where to go if the first child fails
3439 // to match.
3440 MatchScope NewEntry;
3441 NewEntry.FailIndex = FailIndex;
3442 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3443 NewEntry.NumRecordedNodes = RecordedNodes.size();
3444 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3445 NewEntry.InputChain = InputChain;
3446 NewEntry.InputGlue = InputGlue;
3447 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3448 MatchScopes.push_back(NewEntry);
3449 continue;
3450 }
3451 case OPC_RecordNode: {
3452 // Remember this node, it may end up being an operand in the pattern.
3453 SDNode *Parent = nullptr;
3454 if (NodeStack.size() > 1)
3455 Parent = NodeStack[NodeStack.size()-2].getNode();
3456 RecordedNodes.push_back(std::make_pair(N, Parent));
3457 continue;
3458 }
3459
3464 unsigned ChildNo = Opcode-OPC_RecordChild0;
3465 if (ChildNo >= N.getNumOperands())
3466 break; // Match fails if out of range child #.
3467
3468 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
3469 N.getNode()));
3470 continue;
3471 }
3472 case OPC_RecordMemRef:
3473 if (auto *MN = dyn_cast<MemSDNode>(N))
3474 MatchedMemRefs.push_back(MN->getMemOperand());
3475 else {
3476 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
3477 dbgs() << '\n');
3478 }
3479
3480 continue;
3481
3483 // If the current node has an input glue, capture it in InputGlue.
3484 if (N->getNumOperands() != 0 &&
3485 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3486 InputGlue = N->getOperand(N->getNumOperands()-1);
3487 continue;
3488
3489 case OPC_MoveChild: {
3490 unsigned ChildNo = MatcherTable[MatcherIndex++];
3491 if (ChildNo >= N.getNumOperands())
3492 break; // Match fails if out of range child #.
3493 N = N.getOperand(ChildNo);
3494 NodeStack.push_back(N);
3495 continue;
3496 }
3497
3498 case OPC_MoveChild0: case OPC_MoveChild1:
3499 case OPC_MoveChild2: case OPC_MoveChild3:
3500 case OPC_MoveChild4: case OPC_MoveChild5:
3501 case OPC_MoveChild6: case OPC_MoveChild7: {
3502 unsigned ChildNo = Opcode-OPC_MoveChild0;
3503 if (ChildNo >= N.getNumOperands())
3504 break; // Match fails if out of range child #.
3505 N = N.getOperand(ChildNo);
3506 NodeStack.push_back(N);
3507 continue;
3508 }
3509
3510 case OPC_MoveSibling:
3511 case OPC_MoveSibling0:
3512 case OPC_MoveSibling1:
3513 case OPC_MoveSibling2:
3514 case OPC_MoveSibling3:
3515 case OPC_MoveSibling4:
3516 case OPC_MoveSibling5:
3517 case OPC_MoveSibling6:
3518 case OPC_MoveSibling7: {
3519 // Pop the current node off the NodeStack.
3520 NodeStack.pop_back();
3521 assert(!NodeStack.empty() && "Node stack imbalance!");
3522 N = NodeStack.back();
3523
3524 unsigned SiblingNo = Opcode == OPC_MoveSibling
3525 ? MatcherTable[MatcherIndex++]
3526 : Opcode - OPC_MoveSibling0;
3527 if (SiblingNo >= N.getNumOperands())
3528 break; // Match fails if out of range sibling #.
3529 N = N.getOperand(SiblingNo);
3530 NodeStack.push_back(N);
3531 continue;
3532 }
3533 case OPC_MoveParent:
3534 // Pop the current node off the NodeStack.
3535 NodeStack.pop_back();
3536 assert(!NodeStack.empty() && "Node stack imbalance!");
3537 N = NodeStack.back();
3538 continue;
3539
3540 case OPC_CheckSame:
3541 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3542 continue;
3543
3546 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3547 Opcode-OPC_CheckChild0Same))
3548 break;
3549 continue;
3550
3561 if (!::CheckPatternPredicate(Opcode, MatcherTable, MatcherIndex, *this))
3562 break;
3563 continue;
3572 case OPC_CheckPredicate:
3573 if (!::CheckNodePredicate(Opcode, MatcherTable, MatcherIndex, *this,
3574 N.getNode()))
3575 break;
3576 continue;
3578 unsigned OpNum = MatcherTable[MatcherIndex++];
3580
3581 for (unsigned i = 0; i < OpNum; ++i)
3582 Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3583
3584 unsigned PredNo = MatcherTable[MatcherIndex++];
3585 if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
3586 break;
3587 continue;
3588 }
3597 case OPC_CheckComplexPat7: {
3598 unsigned CPNum = Opcode == OPC_CheckComplexPat
3599 ? MatcherTable[MatcherIndex++]
3600 : Opcode - OPC_CheckComplexPat0;
3601 unsigned RecNo = MatcherTable[MatcherIndex++];
3602 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3603
3604 // If target can modify DAG during matching, keep the matching state
3605 // consistent.
3606 std::unique_ptr<MatchStateUpdater> MSU;
3608 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3609 MatchScopes));
3610
3611 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3612 RecordedNodes[RecNo].first, CPNum,
3613 RecordedNodes))
3614 break;
3615 continue;
3616 }
3617 case OPC_CheckOpcode:
3618 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3619 continue;
3620
3621 case OPC_CheckType:
3622 case OPC_CheckTypeI32:
3623 case OPC_CheckTypeI64:
3625 switch (Opcode) {
3626 case OPC_CheckTypeI32:
3627 VT = MVT::i32;
3628 break;
3629 case OPC_CheckTypeI64:
3630 VT = MVT::i64;
3631 break;
3632 default:
3633 VT = getSimpleVT(MatcherTable, MatcherIndex);
3634 break;
3635 }
3636 if (!::CheckType(VT, N, TLI, CurDAG->getDataLayout()))
3637 break;
3638 continue;
3639
3640 case OPC_CheckTypeRes: {
3641 unsigned Res = MatcherTable[MatcherIndex++];
3642 if (!::CheckType(getSimpleVT(MatcherTable, MatcherIndex), N.getValue(Res),
3644 break;
3645 continue;
3646 }
3647
3648 case OPC_SwitchOpcode: {
3649 unsigned CurNodeOpcode = N.getOpcode();
3650 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3651 unsigned CaseSize;
3652 while (true) {
3653 // Get the size of this case.
3654 CaseSize = MatcherTable[MatcherIndex++];
3655 if (CaseSize & 128)
3656 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3657 if (CaseSize == 0) break;
3658
3659 uint16_t Opc = MatcherTable[MatcherIndex++];
3660 Opc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
3661
3662 // If the opcode matches, then we will execute this case.
3663 if (CurNodeOpcode == Opc)
3664 break;
3665
3666 // Otherwise, skip over this case.
3667 MatcherIndex += CaseSize;
3668 }
3669
3670 // If no cases matched, bail out.
3671 if (CaseSize == 0) break;
3672
3673 // Otherwise, execute the case we found.
3674 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
3675 << MatcherIndex << "\n");
3676 continue;
3677 }
3678
3679 case OPC_SwitchType: {
3680 MVT CurNodeVT = N.getSimpleValueType();
3681 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3682 unsigned CaseSize;
3683 while (true) {
3684 // Get the size of this case.
3685 CaseSize = MatcherTable[MatcherIndex++];
3686 if (CaseSize & 128)
3687 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3688 if (CaseSize == 0) break;
3689
3690 MVT CaseVT = getSimpleVT(MatcherTable, MatcherIndex);
3691 if (CaseVT == MVT::iPTR)
3692 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3693
3694 // If the VT matches, then we will execute this case.
3695 if (CurNodeVT == CaseVT)
3696 break;
3697
3698 // Otherwise, skip over this case.
3699 MatcherIndex += CaseSize;
3700 }
3701
3702 // If no cases matched, bail out.
3703 if (CaseSize == 0) break;
3704
3705 // Otherwise, execute the case we found.
3706 LLVM_DEBUG(dbgs() << " TypeSwitch[" << CurNodeVT
3707 << "] from " << SwitchStart << " to " << MatcherIndex
3708 << '\n');
3709 continue;
3710 }
3736 unsigned ChildNo;
3739 VT = MVT::i32;
3741 } else if (Opcode >= SelectionDAGISel::OPC_CheckChild0TypeI64 &&
3743 VT = MVT::i64;
3745 } else {
3746 VT = getSimpleVT(MatcherTable, MatcherIndex);
3747 ChildNo = Opcode - SelectionDAGISel::OPC_CheckChild0Type;
3748 }
3749 if (!::CheckChildType(VT, N, TLI, CurDAG->getDataLayout(), ChildNo))
3750 break;
3751 continue;
3752 }
3753 case OPC_CheckCondCode:
3754 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3755 continue;
3757 if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3758 continue;
3759 case OPC_CheckValueType:
3760 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3762 break;
3763 continue;
3764 case OPC_CheckInteger:
3765 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3766 continue;
3770 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3771 Opcode-OPC_CheckChild0Integer)) break;
3772 continue;
3773 case OPC_CheckAndImm:
3774 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3775 continue;
3776 case OPC_CheckOrImm:
3777 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3778 continue;
3780 if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3781 break;
3782 continue;
3784 if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3785 break;
3786 continue;
3787
3789 assert(NodeStack.size() != 1 && "No parent node");
3790 // Verify that all intermediate nodes between the root and this one have
3791 // a single use (ignoring chains, which are handled in UpdateChains).
3792 bool HasMultipleUses = false;
3793 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3794 unsigned NNonChainUses = 0;
3795 SDNode *NS = NodeStack[i].getNode();
3796 for (const SDUse &U : NS->uses())
3797 if (U.getValueType() != MVT::Other)
3798 if (++NNonChainUses > 1) {
3799 HasMultipleUses = true;
3800 break;
3801 }
3802 if (HasMultipleUses) break;
3803 }
3804 if (HasMultipleUses) break;
3805
3806 // Check to see that the target thinks this is profitable to fold and that
3807 // we can fold it without inducing cycles in the graph.
3808 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3809 NodeToMatch) ||
3810 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3811 NodeToMatch, OptLevel,
3812 true/*We validate our own chains*/))
3813 break;
3814
3815 continue;
3816 }
3817 case OPC_EmitInteger:
3818 case OPC_EmitInteger8:
3819 case OPC_EmitInteger16:
3820 case OPC_EmitInteger32:
3821 case OPC_EmitInteger64:
3825 switch (Opcode) {
3826 case OPC_EmitInteger8:
3827 VT = MVT::i8;
3828 break;
3829 case OPC_EmitInteger16:
3830 VT = MVT::i16;
3831 break;
3832 case OPC_EmitInteger32:
3834 VT = MVT::i32;
3835 break;
3836 case OPC_EmitInteger64:
3837 VT = MVT::i64;
3838 break;
3839 default:
3840 VT = getSimpleVT(MatcherTable, MatcherIndex);
3841 break;
3842 }
3843 int64_t Val = MatcherTable[MatcherIndex++];
3844 if (Val & 128)
3845 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3846 if (Opcode >= OPC_EmitInteger && Opcode <= OPC_EmitInteger64)
3847 Val = decodeSignRotatedValue(Val);
3848 RecordedNodes.push_back(std::pair<SDValue, SDNode *>(
3849 CurDAG->getSignedConstant(Val, SDLoc(NodeToMatch), VT,
3850 /*isTarget=*/true),
3851 nullptr));
3852 continue;
3853 }
3854 case OPC_EmitRegister:
3856 case OPC_EmitRegisterI64: {
3858 switch (Opcode) {
3860 VT = MVT::i32;
3861 break;
3863 VT = MVT::i64;
3864 break;
3865 default:
3866 VT = getSimpleVT(MatcherTable, MatcherIndex);
3867 break;
3868 }
3869 unsigned RegNo = MatcherTable[MatcherIndex++];
3870 RecordedNodes.push_back(std::pair<SDValue, SDNode *>(
3871 CurDAG->getRegister(RegNo, VT), nullptr));
3872 continue;
3873 }
3874 case OPC_EmitRegister2: {
3875 // For targets w/ more than 256 register names, the register enum
3876 // values are stored in two bytes in the matcher table (just like
3877 // opcodes).
3878 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
3879 unsigned RegNo = MatcherTable[MatcherIndex++];
3880 RegNo |= MatcherTable[MatcherIndex++] << 8;
3881 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3882 CurDAG->getRegister(RegNo, VT), nullptr));
3883 continue;
3884 }
3885
3895 // Convert from IMM/FPIMM to target version.
3896 unsigned RecNo = Opcode == OPC_EmitConvertToTarget
3897 ? MatcherTable[MatcherIndex++]
3898 : Opcode - OPC_EmitConvertToTarget0;
3899 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3900 SDValue Imm = RecordedNodes[RecNo].first;
3901
3902 if (Imm->getOpcode() == ISD::Constant) {
3903 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3904 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3905 Imm.getValueType());
3906 } else if (Imm->getOpcode() == ISD::ConstantFP) {
3907 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3908 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3909 Imm.getValueType());
3910 }
3911
3912 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3913 continue;
3914 }
3915
3916 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3917 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3918 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3919 // These are space-optimized forms of OPC_EmitMergeInputChains.
3920 assert(!InputChain.getNode() &&
3921 "EmitMergeInputChains should be the first chain producing node");
3922 assert(ChainNodesMatched.empty() &&
3923 "Should only have one EmitMergeInputChains per match");
3924
3925 // Read all of the chained nodes.
3926 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3927 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3928 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3929
3930 // If the chained node is not the root, we can't fold it if it has
3931 // multiple uses.
3932 // FIXME: What if other value results of the node have uses not matched
3933 // by this pattern?
3934 if (ChainNodesMatched.back() != NodeToMatch &&
3935 !RecordedNodes[RecNo].first.hasOneUse()) {
3936 ChainNodesMatched.clear();
3937 break;
3938 }
3939
3940 // Merge the input chains if they are not intra-pattern references.
3941 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3942
3943 if (!InputChain.getNode())
3944 break; // Failed to merge.
3945 continue;
3946 }
3947
3949 assert(!InputChain.getNode() &&
3950 "EmitMergeInputChains should be the first chain producing node");
3951 // This node gets a list of nodes we matched in the input that have
3952 // chains. We want to token factor all of the input chains to these nodes
3953 // together. However, if any of the input chains is actually one of the
3954 // nodes matched in this pattern, then we have an intra-match reference.
3955 // Ignore these because the newly token factored chain should not refer to
3956 // the old nodes.
3957 unsigned NumChains = MatcherTable[MatcherIndex++];
3958 assert(NumChains != 0 && "Can't TF zero chains");
3959
3960 assert(ChainNodesMatched.empty() &&
3961 "Should only have one EmitMergeInputChains per match");
3962
3963 // Read all of the chained nodes.
3964 for (unsigned i = 0; i != NumChains; ++i) {
3965 unsigned RecNo = MatcherTable[MatcherIndex++];
3966 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3967 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3968
3969 // If the chained node is not the root, we can't fold it if it has
3970 // multiple uses.
3971 // FIXME: What if other value results of the node have uses not matched
3972 // by this pattern?
3973 if (ChainNodesMatched.back() != NodeToMatch &&
3974 !RecordedNodes[RecNo].first.hasOneUse()) {
3975 ChainNodesMatched.clear();
3976 break;
3977 }
3978 }
3979
3980 // If the inner loop broke out, the match fails.
3981 if (ChainNodesMatched.empty())
3982 break;
3983
3984 // Merge the input chains if they are not intra-pattern references.
3985 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3986
3987 if (!InputChain.getNode())
3988 break; // Failed to merge.
3989
3990 continue;
3991 }
3992
3993 case OPC_EmitCopyToReg:
3994 case OPC_EmitCopyToReg0:
3995 case OPC_EmitCopyToReg1:
3996 case OPC_EmitCopyToReg2:
3997 case OPC_EmitCopyToReg3:
3998 case OPC_EmitCopyToReg4:
3999 case OPC_EmitCopyToReg5:
4000 case OPC_EmitCopyToReg6:
4001 case OPC_EmitCopyToReg7:
4003 unsigned RecNo =
4004 Opcode >= OPC_EmitCopyToReg0 && Opcode <= OPC_EmitCopyToReg7
4005 ? Opcode - OPC_EmitCopyToReg0
4006 : MatcherTable[MatcherIndex++];
4007 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
4008 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
4009 if (Opcode == OPC_EmitCopyToRegTwoByte)
4010 DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
4011
4012 if (!InputChain.getNode())
4013 InputChain = CurDAG->getEntryNode();
4014
4015 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
4016 DestPhysReg, RecordedNodes[RecNo].first,
4017 InputGlue);
4018
4019 InputGlue = InputChain.getValue(1);
4020 continue;
4021 }
4022
4023 case OPC_EmitNodeXForm: {
4024 unsigned XFormNo = MatcherTable[MatcherIndex++];
4025 unsigned RecNo = MatcherTable[MatcherIndex++];
4026 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
4027 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
4028 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
4029 continue;
4030 }
4031 case OPC_Coverage: {
4032 // This is emitted right before MorphNode/EmitNode.
4033 // So it should be safe to assume that this node has been selected
4034 unsigned index = MatcherTable[MatcherIndex++];
4035 index |= (MatcherTable[MatcherIndex++] << 8);
4036 index |= (MatcherTable[MatcherIndex++] << 16);
4037 index |= (MatcherTable[MatcherIndex++] << 24);
4038 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
4039 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
4040 continue;
4041 }
4042
4043 case OPC_EmitNode:
4044 case OPC_EmitNode0:
4045 case OPC_EmitNode1:
4046 case OPC_EmitNode2:
4047 case OPC_EmitNode0None:
4048 case OPC_EmitNode1None:
4049 case OPC_EmitNode2None:
4050 case OPC_EmitNode0Chain:
4051 case OPC_EmitNode1Chain:
4052 case OPC_EmitNode2Chain:
4053 case OPC_MorphNodeTo:
4054 case OPC_MorphNodeTo0:
4055 case OPC_MorphNodeTo1:
4056 case OPC_MorphNodeTo2:
4069 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
4070 TargetOpc |= static_cast<uint16_t>(MatcherTable[MatcherIndex++]) << 8;
4071 unsigned EmitNodeInfo;
4072 if (Opcode >= OPC_EmitNode0None && Opcode <= OPC_EmitNode2Chain) {
4073 if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4074 EmitNodeInfo = OPFL_Chain;
4075 else
4076 EmitNodeInfo = OPFL_None;
4077 } else if (Opcode >= OPC_MorphNodeTo0None &&
4078 Opcode <= OPC_MorphNodeTo2GlueOutput) {
4079 if (Opcode >= OPC_MorphNodeTo0Chain && Opcode <= OPC_MorphNodeTo2Chain)
4080 EmitNodeInfo = OPFL_Chain;
4081 else if (Opcode >= OPC_MorphNodeTo0GlueInput &&
4082 Opcode <= OPC_MorphNodeTo2GlueInput)
4083 EmitNodeInfo = OPFL_GlueInput;
4084 else if (Opcode >= OPC_MorphNodeTo0GlueOutput &&
4086 EmitNodeInfo = OPFL_GlueOutput;
4087 else
4088 EmitNodeInfo = OPFL_None;
4089 } else
4090 EmitNodeInfo = MatcherTable[MatcherIndex++];
4091 // Get the result VT list.
4092 unsigned NumVTs;
4093 // If this is one of the compressed forms, get the number of VTs based
4094 // on the Opcode. Otherwise read the next byte from the table.
4095 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
4096 NumVTs = Opcode - OPC_MorphNodeTo0;
4097 else if (Opcode >= OPC_MorphNodeTo0None && Opcode <= OPC_MorphNodeTo2None)
4098 NumVTs = Opcode - OPC_MorphNodeTo0None;
4099 else if (Opcode >= OPC_MorphNodeTo0Chain &&
4100 Opcode <= OPC_MorphNodeTo2Chain)
4101 NumVTs = Opcode - OPC_MorphNodeTo0Chain;
4102 else if (Opcode >= OPC_MorphNodeTo0GlueInput &&
4103 Opcode <= OPC_MorphNodeTo2GlueInput)
4104 NumVTs = Opcode - OPC_MorphNodeTo0GlueInput;
4105 else if (Opcode >= OPC_MorphNodeTo0GlueOutput &&
4107 NumVTs = Opcode - OPC_MorphNodeTo0GlueOutput;
4108 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
4109 NumVTs = Opcode - OPC_EmitNode0;
4110 else if (Opcode >= OPC_EmitNode0None && Opcode <= OPC_EmitNode2None)
4111 NumVTs = Opcode - OPC_EmitNode0None;
4112 else if (Opcode >= OPC_EmitNode0Chain && Opcode <= OPC_EmitNode2Chain)
4113 NumVTs = Opcode - OPC_EmitNode0Chain;
4114 else
4115 NumVTs = MatcherTable[MatcherIndex++];
4117 for (unsigned i = 0; i != NumVTs; ++i) {
4118 MVT::SimpleValueType VT = getSimpleVT(MatcherTable, MatcherIndex);
4119 if (VT == MVT::iPTR)
4121 VTs.push_back(VT);
4122 }
4123
4124 if (EmitNodeInfo & OPFL_Chain)
4125 VTs.push_back(MVT::Other);
4126 if (EmitNodeInfo & OPFL_GlueOutput)
4127 VTs.push_back(MVT::Glue);
4128
4129 // This is hot code, so optimize the two most common cases of 1 and 2
4130 // results.
4131 SDVTList VTList;
4132 if (VTs.size() == 1)
4133 VTList = CurDAG->getVTList(VTs[0]);
4134 else if (VTs.size() == 2)
4135 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
4136 else
4137 VTList = CurDAG->getVTList(VTs);
4138
4139 // Get the operand list.
4140 unsigned NumOps = MatcherTable[MatcherIndex++];
4142 for (unsigned i = 0; i != NumOps; ++i) {
4143 unsigned RecNo = MatcherTable[MatcherIndex++];
4144 if (RecNo & 128)
4145 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
4146
4147 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
4148 Ops.push_back(RecordedNodes[RecNo].first);
4149 }
4150
4151 // If there are variadic operands to add, handle them now.
4152 if (EmitNodeInfo & OPFL_VariadicInfo) {
4153 // Determine the start index to copy from.
4154 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
4155 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
4156 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
4157 "Invalid variadic node");
4158 // Copy all of the variadic operands, not including a potential glue
4159 // input.
4160 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
4161 i != e; ++i) {
4162 SDValue V = NodeToMatch->getOperand(i);
4163 if (V.getValueType() == MVT::Glue) break;
4164 Ops.push_back(V);
4165 }
4166 }
4167
4168 // If this has chain/glue inputs, add them.
4169 if (EmitNodeInfo & OPFL_Chain)
4170 Ops.push_back(InputChain);
4171 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
4172 Ops.push_back(InputGlue);
4173
4174 // Check whether any matched node could raise an FP exception. Since all
4175 // such nodes must have a chain, it suffices to check ChainNodesMatched.
4176 // We need to perform this check before potentially modifying one of the
4177 // nodes via MorphNode.
4178 bool MayRaiseFPException =
4179 llvm::any_of(ChainNodesMatched, [this](SDNode *N) {
4180 return mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept();
4181 });
4182
4183 // Create the node.
4184 MachineSDNode *Res = nullptr;
4185 bool IsMorphNodeTo =
4186 Opcode == OPC_MorphNodeTo ||
4187 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2GlueOutput);
4188 if (!IsMorphNodeTo) {
4189 // If this is a normal EmitNode command, just create the new node and
4190 // add the results to the RecordedNodes list.
4191 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
4192 VTList, Ops);
4193
4194 // Add all the non-glue/non-chain results to the RecordedNodes list.
4195 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
4196 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
4197 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
4198 nullptr));
4199 }
4200 } else {
4201 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
4202 "NodeToMatch was removed partway through selection");
4204 SDNode *E) {
4206 auto &Chain = ChainNodesMatched;
4207 assert((!E || !is_contained(Chain, N)) &&
4208 "Chain node replaced during MorphNode");
4209 llvm::erase(Chain, N);
4210 });
4211 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
4212 Ops, EmitNodeInfo));
4213 }
4214
4215 // Set the NoFPExcept flag when no original matched node could
4216 // raise an FP exception, but the new node potentially might.
4217 if (!MayRaiseFPException && mayRaiseFPException(Res))
4218 Res->setFlags(Res->getFlags() | SDNodeFlags::NoFPExcept);
4219
4220 // If the node had chain/glue results, update our notion of the current
4221 // chain and glue.
4222 if (EmitNodeInfo & OPFL_GlueOutput) {
4223 InputGlue = SDValue(Res, VTs.size()-1);
4224 if (EmitNodeInfo & OPFL_Chain)
4225 InputChain = SDValue(Res, VTs.size()-2);
4226 } else if (EmitNodeInfo & OPFL_Chain)
4227 InputChain = SDValue(Res, VTs.size()-1);
4228
4229 // If the OPFL_MemRefs glue is set on this node, slap all of the
4230 // accumulated memrefs onto it.
4231 //
4232 // FIXME: This is vastly incorrect for patterns with multiple outputs
4233 // instructions that access memory and for ComplexPatterns that match
4234 // loads.
4235 if (EmitNodeInfo & OPFL_MemRefs) {
4236 // Only attach load or store memory operands if the generated
4237 // instruction may load or store.
4238 const MCInstrDesc &MCID = TII->get(TargetOpc);
4239 bool mayLoad = MCID.mayLoad();
4240 bool mayStore = MCID.mayStore();
4241
4242 // We expect to have relatively few of these so just filter them into a
4243 // temporary buffer so that we can easily add them to the instruction.
4245 for (MachineMemOperand *MMO : MatchedMemRefs) {
4246 if (MMO->isLoad()) {
4247 if (mayLoad)
4248 FilteredMemRefs.push_back(MMO);
4249 } else if (MMO->isStore()) {
4250 if (mayStore)
4251 FilteredMemRefs.push_back(MMO);
4252 } else {
4253 FilteredMemRefs.push_back(MMO);
4254 }
4255 }
4256
4257 CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
4258 }
4259
4260 LLVM_DEBUG({
4261 if (!MatchedMemRefs.empty() && Res->memoperands_empty())
4262 dbgs() << " Dropping mem operands\n";
4263 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") << " node: ";
4264 Res->dump(CurDAG);
4265 });
4266
4267 // If this was a MorphNodeTo then we're completely done!
4268 if (IsMorphNodeTo) {
4269 // Update chain uses.
4270 UpdateChains(Res, InputChain, ChainNodesMatched, true);
4271 return;
4272 }
4273 continue;
4274 }
4275
4276 case OPC_CompleteMatch: {
4277 // The match has been completed, and any new nodes (if any) have been
4278 // created. Patch up references to the matched dag to use the newly
4279 // created nodes.
4280 unsigned NumResults = MatcherTable[MatcherIndex++];
4281
4282 for (unsigned i = 0; i != NumResults; ++i) {
4283 unsigned ResSlot = MatcherTable[MatcherIndex++];
4284 if (ResSlot & 128)
4285 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
4286
4287 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
4288 SDValue Res = RecordedNodes[ResSlot].first;
4289
4290 assert(i < NodeToMatch->getNumValues() &&
4291 NodeToMatch->getValueType(i) != MVT::Other &&
4292 NodeToMatch->getValueType(i) != MVT::Glue &&
4293 "Invalid number of results to complete!");
4294 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
4295 NodeToMatch->getValueType(i) == MVT::iPTR ||
4296 Res.getValueType() == MVT::iPTR ||
4297 NodeToMatch->getValueType(i).getSizeInBits() ==
4298 Res.getValueSizeInBits()) &&
4299 "invalid replacement");
4300 ReplaceUses(SDValue(NodeToMatch, i), Res);
4301 }
4302
4303 // Update chain uses.
4304 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
4305
4306 // If the root node defines glue, we need to update it to the glue result.
4307 // TODO: This never happens in our tests and I think it can be removed /
4308 // replaced with an assert, but if we do it this the way the change is
4309 // NFC.
4310 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
4311 MVT::Glue &&
4312 InputGlue.getNode())
4313 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
4314 InputGlue);
4315
4316 assert(NodeToMatch->use_empty() &&
4317 "Didn't replace all uses of the node?");
4318 CurDAG->RemoveDeadNode(NodeToMatch);
4319
4320 return;
4321 }
4322 }
4323
4324 // If the code reached this point, then the match failed. See if there is
4325 // another child to try in the current 'Scope', otherwise pop it until we
4326 // find a case to check.
4327 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
4328 << "\n");
4329 ++NumDAGIselRetries;
4330 while (true) {
4331 if (MatchScopes.empty()) {
4332 CannotYetSelect(NodeToMatch);
4333 return;
4334 }
4335
4336 // Restore the interpreter state back to the point where the scope was
4337 // formed.
4338 MatchScope &LastScope = MatchScopes.back();
4339 RecordedNodes.resize(LastScope.NumRecordedNodes);
4340 NodeStack.clear();
4341 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
4342 N = NodeStack.back();
4343
4344 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
4345 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
4346 MatcherIndex = LastScope.FailIndex;
4347
4348 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
4349
4350 InputChain = LastScope.InputChain;
4351 InputGlue = LastScope.InputGlue;
4352 if (!LastScope.HasChainNodesMatched)
4353 ChainNodesMatched.clear();
4354
4355 // Check to see what the offset is at the new MatcherIndex. If it is zero
4356 // we have reached the end of this scope, otherwise we have another child
4357 // in the current scope to try.
4358 unsigned NumToSkip = MatcherTable[MatcherIndex++];
4359 if (NumToSkip & 128)
4360 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
4361
4362 // If we have another child in this scope to match, update FailIndex and
4363 // try it.
4364 if (NumToSkip != 0) {
4365 LastScope.FailIndex = MatcherIndex+NumToSkip;
4366 break;
4367 }
4368
4369 // End of this scope, pop it and try the next child in the containing
4370 // scope.
4371 MatchScopes.pop_back();
4372 }
4373 }
4374}
4375
4376/// Return whether the node may raise an FP exception.
4378 // For machine opcodes, consult the MCID flag.
4379 if (N->isMachineOpcode()) {
4380 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
4381 return MCID.mayRaiseFPException();
4382 }
4383
4384 // For ISD opcodes, only StrictFP opcodes may raise an FP
4385 // exception.
4386 if (N->isTargetOpcode()) {
4388 return TSI.mayRaiseFPException(N->getOpcode());
4389 }
4390 return N->isStrictFPOpcode();
4391}
4392
4394 assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
4395 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
4396 if (!C)
4397 return false;
4398
4399 // Detect when "or" is used to add an offset to a stack object.
4400 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
4402 Align A = MFI.getObjectAlign(FN->getIndex());
4403 int32_t Off = C->getSExtValue();
4404 // If the alleged offset fits in the zero bits guaranteed by
4405 // the alignment, then this or is really an add.
4406 return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
4407 }
4408 return false;
4409}
4410
4411void SelectionDAGISel::CannotYetSelect(SDNode *N) {
4412 std::string msg;
4413 raw_string_ostream Msg(msg);
4414 Msg << "Cannot select: ";
4415
4416 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
4417 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
4418 N->getOpcode() != ISD::INTRINSIC_VOID) {
4419 N->printrFull(Msg, CurDAG);
4420 Msg << "\nIn function: " << MF->getName();
4421 } else {
4422 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
4423 unsigned iid = N->getConstantOperandVal(HasInputChain);
4424 if (iid < Intrinsic::num_intrinsics)
4425 Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
4426 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
4427 Msg << "target intrinsic %" << TII->getName(iid);
4428 else
4429 Msg << "unknown intrinsic #" << iid;
4430 }
4432}
unsigned const MachineRegisterInfo * MRI
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
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
BlockVerifier::State From
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:340
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file defines the DenseMap class.
bool End
Definition: ELF_riscv.cpp:480
This file defines the FastISel class.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
Machine Instruction Scheduler
unsigned const TargetRegisterInfo * TRI
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static Type * getValueType(Value *V)
Returns the type of the given value/instruction V.
This file contains some templates that are useful if you are working with the STL at all.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
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 CheckPatternPredicate(unsigned Opcode, const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel)
CheckPatternPredicate - Implements OP_CheckPatternPredicate.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes, unsigned ChildNo)
CheckChildSame - Implements OP_CheckChildXSame.
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
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 unsigned char *MatcherTable, unsigned &Idx)
GetVBR - decode a vbr encoding whose top bit is set.
static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort)
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 unsigned IsPredicateKnownToFail(const unsigned char *Table, unsigned Index, SDValue N, bool &Result, const SelectionDAGISel &SDISel, 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< 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 void processSingleLocVars(FunctionLoweringInfo &FuncInfo, FunctionVarLocs const *FnVarLocs)
Collect single location variable information generated with assignment tracking.
static LLVM_ATTRIBUTE_ALWAYS_INLINE MVT::SimpleValueType getSimpleVT(const unsigned char *MatcherTable, unsigned &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 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
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 LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
CheckSame - Implements OP_CheckSame.
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"))