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