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