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