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