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 
13 #include "llvm/CodeGen/SelectionDAGISel.h"
14 #include "ScheduleDAGSDNodes.h"
15 #include "SelectionDAGBuilder.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
31 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
32 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/CodeGen/FastISel.h"
37 #include "llvm/CodeGen/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GCMetadata.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineFunctionPass.h"
44 #include "llvm/CodeGen/MachineInstr.h"
45 #include "llvm/CodeGen/MachineInstrBuilder.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachinePassRegistry.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/CodeGen/SchedulerRegistry.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/StackProtector.h"
55 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetLowering.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/ValueTypes.h"
61 #include "llvm/IR/BasicBlock.h"
62 #include "llvm/IR/Constants.h"
63 #include "llvm/IR/DataLayout.h"
64 #include "llvm/IR/DebugInfoMetadata.h"
65 #include "llvm/IR/DebugLoc.h"
66 #include "llvm/IR/DiagnosticInfo.h"
67 #include "llvm/IR/Dominators.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/InlineAsm.h"
70 #include "llvm/IR/InstIterator.h"
71 #include "llvm/IR/InstrTypes.h"
72 #include "llvm/IR/Instruction.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/Intrinsics.h"
76 #include "llvm/IR/IntrinsicsWebAssembly.h"
77 #include "llvm/IR/Metadata.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/User.h"
80 #include "llvm/IR/Value.h"
81 #include "llvm/InitializePasses.h"
82 #include "llvm/MC/MCInstrDesc.h"
83 #include "llvm/MC/MCRegisterInfo.h"
84 #include "llvm/Pass.h"
85 #include "llvm/Support/BranchProbability.h"
86 #include "llvm/Support/Casting.h"
87 #include "llvm/Support/CodeGen.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Compiler.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/KnownBits.h"
93 #include "llvm/Support/MachineValueType.h"
94 #include "llvm/Support/Timer.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetIntrinsicInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
100 #include <algorithm>
101 #include <cassert>
102 #include <cstdint>
103 #include <iterator>
104 #include <limits>
105 #include <memory>
106 #include <string>
107 #include <utility>
108 #include <vector>
109 
110 using namespace llvm;
111 
112 #define DEBUG_TYPE "isel"
113 
114 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
115 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
116 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
117 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
118 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
119 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
120 STATISTIC(NumFastIselFailLowerArguments,
121           "Number of entry blocks where fast isel failed to lower arguments");
122 
123 static cl::opt<int> EnableFastISelAbort(
124     "fast-isel-abort", cl::Hidden,
125     cl::desc("Enable abort calls when \"fast\" instruction selection "
126              "fails to lower an instruction: 0 disable the abort, 1 will "
127              "abort but for args, calls and terminators, 2 will also "
128              "abort for argument lowering, and 3 will never fallback "
129              "to SelectionDAG."));
130 
131 static cl::opt<bool> EnableFastISelFallbackReport(
132     "fast-isel-report-on-fallback", cl::Hidden,
133     cl::desc("Emit a diagnostic when \"fast\" instruction selection "
134              "falls back to SelectionDAG."));
135 
136 static cl::opt<bool>
137 UseMBPI("use-mbpi",
138         cl::desc("use Machine Branch Probability Info"),
139         cl::init(true), cl::Hidden);
140 
141 #ifndef NDEBUG
142 static cl::opt<std::string>
143 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
144                         cl::desc("Only display the basic block whose name "
145                                  "matches this for all view-*-dags options"));
146 static cl::opt<bool>
147 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
148           cl::desc("Pop up a window to show dags before the first "
149                    "dag combine pass"));
150 static cl::opt<bool>
151 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
152           cl::desc("Pop up a window to show dags before legalize types"));
153 static cl::opt<bool>
154     ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
155                      cl::desc("Pop up a window to show dags before the post "
156                               "legalize types dag combine pass"));
157 static cl::opt<bool>
158     ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
159                      cl::desc("Pop up a window to show dags before legalize"));
160 static cl::opt<bool>
161 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
162           cl::desc("Pop up a window to show dags before the second "
163                    "dag combine pass"));
164 static cl::opt<bool>
165 ViewISelDAGs("view-isel-dags", cl::Hidden,
166           cl::desc("Pop up a window to show isel dags as they are selected"));
167 static cl::opt<bool>
168 ViewSchedDAGs("view-sched-dags", cl::Hidden,
169           cl::desc("Pop up a window to show sched dags as they are processed"));
170 static cl::opt<bool>
171 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
172       cl::desc("Pop up a window to show SUnit dags after they are processed"));
173 #else
174 static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
175                   ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
176                   ViewDAGCombine2 = false, ViewISelDAGs = false,
177                   ViewSchedDAGs = false, ViewSUnitDAGs = false;
178 #endif
179 
180 //===---------------------------------------------------------------------===//
181 ///
182 /// RegisterScheduler class - Track the registration of instruction schedulers.
183 ///
184 //===---------------------------------------------------------------------===//
185 MachinePassRegistry<RegisterScheduler::FunctionPassCtor>
186     RegisterScheduler::Registry;
187 
188 //===---------------------------------------------------------------------===//
189 ///
190 /// ISHeuristic command line option for instruction schedulers.
191 ///
192 //===---------------------------------------------------------------------===//
193 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
194                RegisterPassParser<RegisterScheduler>>
195 ISHeuristic("pre-RA-sched",
196             cl::init(&createDefaultScheduler), cl::Hidden,
197             cl::desc("Instruction schedulers available (before register"
198                      " allocation):"));
199 
200 static RegisterScheduler
201 defaultListDAGScheduler("default", "Best scheduler for the target",
202                         createDefaultScheduler);
203 
204 namespace llvm {
205 
206   //===--------------------------------------------------------------------===//
207   /// This class is used by SelectionDAGISel to temporarily override
208   /// the optimization level on a per-function basis.
209   class OptLevelChanger {
210     SelectionDAGISel &IS;
211     CodeGenOpt::Level SavedOptLevel;
212     bool SavedFastISel;
213 
214   public:
215     OptLevelChanger(SelectionDAGISel &ISel,
216                     CodeGenOpt::Level NewOptLevel) : IS(ISel) {
217       SavedOptLevel = IS.OptLevel;
218       SavedFastISel = IS.TM.Options.EnableFastISel;
219       if (NewOptLevel == SavedOptLevel)
220         return;
221       IS.OptLevel = NewOptLevel;
222       IS.TM.setOptLevel(NewOptLevel);
223       LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
224                         << IS.MF->getFunction().getName() << "\n");
225       LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O"
226                         << NewOptLevel << "\n");
227       if (NewOptLevel == CodeGenOpt::None) {
228         IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
229         LLVM_DEBUG(
230             dbgs() << "\tFastISel is "
231                    << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
232                    << "\n");
233       }
234     }
235 
236     ~OptLevelChanger() {
237       if (IS.OptLevel == SavedOptLevel)
238         return;
239       LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
240                         << IS.MF->getFunction().getName() << "\n");
241       LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O"
242                         << SavedOptLevel << "\n");
243       IS.OptLevel = SavedOptLevel;
244       IS.TM.setOptLevel(SavedOptLevel);
245       IS.TM.setFastISel(SavedFastISel);
246     }
247   };
248 
249   //===--------------------------------------------------------------------===//
250   /// createDefaultScheduler - This creates an instruction scheduler appropriate
251   /// for the target.
252   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
253                                              CodeGenOpt::Level OptLevel) {
254     const TargetLowering *TLI = IS->TLI;
255     const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
256 
257     // Try first to see if the Target has its own way of selecting a scheduler
258     if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
259       return SchedulerCtor(IS, OptLevel);
260     }
261 
262     if (OptLevel == CodeGenOpt::None ||
263         (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
264         TLI->getSchedulingPreference() == Sched::Source)
265       return createSourceListDAGScheduler(IS, OptLevel);
266     if (TLI->getSchedulingPreference() == Sched::RegPressure)
267       return createBURRListDAGScheduler(IS, OptLevel);
268     if (TLI->getSchedulingPreference() == Sched::Hybrid)
269       return createHybridListDAGScheduler(IS, OptLevel);
270     if (TLI->getSchedulingPreference() == Sched::VLIW)
271       return createVLIWDAGScheduler(IS, OptLevel);
272     assert(TLI->getSchedulingPreference() == Sched::ILP &&
273            "Unknown sched type!");
274     return createILPListDAGScheduler(IS, OptLevel);
275   }
276 
277 } // end namespace llvm
278 
279 // EmitInstrWithCustomInserter - This method should be implemented by targets
280 // that mark instructions with the 'usesCustomInserter' flag.  These
281 // instructions are special in various ways, which require special support to
282 // insert.  The specified MachineInstr is created but not inserted into any
283 // basic blocks, and this method is called to expand it into a sequence of
284 // instructions, potentially also creating new basic blocks and control flow.
285 // When new basic blocks are inserted and the edges from MBB to its successors
286 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
287 // DenseMap.
288 MachineBasicBlock *
289 TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
290                                             MachineBasicBlock *MBB) const {
291 #ifndef NDEBUG
292   dbgs() << "If a target marks an instruction with "
293           "'usesCustomInserter', it must implement "
294           "TargetLowering::EmitInstrWithCustomInserter!";
295 #endif
296   llvm_unreachable(nullptr);
297 }
298 
299 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
300                                                    SDNode *Node) const {
301   assert(!MI.hasPostISelHook() &&
302          "If a target marks an instruction with 'hasPostISelHook', "
303          "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
304 }
305 
306 //===----------------------------------------------------------------------===//
307 // SelectionDAGISel code
308 //===----------------------------------------------------------------------===//
309 
310 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL)
311     : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()),
312       SwiftError(new SwiftErrorValueTracking()),
313       CurDAG(new SelectionDAG(tm, OL)),
314       SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
315                                                 OL)),
316       AA(), GFI(), OptLevel(OL), DAGSize(0) {
317   initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
318   initializeBranchProbabilityInfoWrapperPassPass(
319       *PassRegistry::getPassRegistry());
320   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
321   initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
322 }
323 
324 SelectionDAGISel::~SelectionDAGISel() {
325   delete CurDAG;
326   delete SwiftError;
327 }
328 
329 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
330   if (OptLevel != CodeGenOpt::None)
331     AU.addRequired<AAResultsWrapperPass>();
332   AU.addRequired<GCModuleInfo>();
333   AU.addRequired<StackProtector>();
334   AU.addPreserved<GCModuleInfo>();
335   AU.addRequired<TargetLibraryInfoWrapperPass>();
336   AU.addRequired<TargetTransformInfoWrapperPass>();
337   if (UseMBPI && OptLevel != CodeGenOpt::None)
338     AU.addRequired<BranchProbabilityInfoWrapperPass>();
339   AU.addRequired<ProfileSummaryInfoWrapperPass>();
340   if (OptLevel != CodeGenOpt::None)
341     LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
342   MachineFunctionPass::getAnalysisUsage(AU);
343 }
344 
345 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
346 /// may trap on it.  In this case we have to split the edge so that the path
347 /// through the predecessor block that doesn't go to the phi block doesn't
348 /// execute the possibly trapping instruction. If available, we pass domtree
349 /// and loop info to be updated when we split critical edges. This is because
350 /// SelectionDAGISel preserves these analyses.
351 /// This is required for correctness, so it must be done at -O0.
352 ///
353 static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT,
354                                          LoopInfo *LI) {
355   // Loop for blocks with phi nodes.
356   for (BasicBlock &BB : Fn) {
357     PHINode *PN = dyn_cast<PHINode>(BB.begin());
358     if (!PN) continue;
359 
360   ReprocessBlock:
361     // For each block with a PHI node, check to see if any of the input values
362     // are potentially trapping constant expressions.  Constant expressions are
363     // the only potentially trapping value that can occur as the argument to a
364     // PHI.
365     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
366       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
367         ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
368         if (!CE || !CE->canTrap()) continue;
369 
370         // The only case we have to worry about is when the edge is critical.
371         // Since this block has a PHI Node, we assume it has multiple input
372         // edges: check to see if the pred has multiple successors.
373         BasicBlock *Pred = PN->getIncomingBlock(i);
374         if (Pred->getTerminator()->getNumSuccessors() == 1)
375           continue;
376 
377         // Okay, we have to split this edge.
378         SplitCriticalEdge(
379             Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
380             CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges());
381         goto ReprocessBlock;
382       }
383   }
384 }
385 
386 static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
387                                          MachineModuleInfo &MMI) {
388   // Only needed for MSVC
389   if (!TT.isWindowsMSVCEnvironment())
390     return;
391 
392   // If it's already set, nothing to do.
393   if (MMI.usesMSVCFloatingPoint())
394     return;
395 
396   for (const Instruction &I : instructions(F)) {
397     if (I.getType()->isFPOrFPVectorTy()) {
398       MMI.setUsesMSVCFloatingPoint(true);
399       return;
400     }
401     for (const auto &Op : I.operands()) {
402       if (Op->getType()->isFPOrFPVectorTy()) {
403         MMI.setUsesMSVCFloatingPoint(true);
404         return;
405       }
406     }
407   }
408 }
409 
410 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
411   // If we already selected that function, we do not need to run SDISel.
412   if (mf.getProperties().hasProperty(
413           MachineFunctionProperties::Property::Selected))
414     return false;
415   // Do some sanity-checking on the command-line options.
416   assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
417          "-fast-isel-abort > 0 requires -fast-isel");
418 
419   const Function &Fn = mf.getFunction();
420   MF = &mf;
421 
422   // Reset the target options before resetting the optimization
423   // level below.
424   // FIXME: This is a horrible hack and should be processed via
425   // codegen looking at the optimization level explicitly when
426   // it wants to look at it.
427   TM.resetTargetOptions(Fn);
428   // Reset OptLevel to None for optnone functions.
429   CodeGenOpt::Level NewOptLevel = OptLevel;
430   if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
431     NewOptLevel = CodeGenOpt::None;
432   OptLevelChanger OLC(*this, NewOptLevel);
433 
434   TII = MF->getSubtarget().getInstrInfo();
435   TLI = MF->getSubtarget().getTargetLowering();
436   RegInfo = &MF->getRegInfo();
437   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn);
438   GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
439   ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
440   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
441   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
442   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
443   LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
444   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
445   BlockFrequencyInfo *BFI = nullptr;
446   if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOpt::None)
447     BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
448 
449   LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
450 
451   SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI);
452 
453   CurDAG->init(*MF, *ORE, this, LibInfo,
454                getAnalysisIfAvailable<LegacyDivergenceAnalysis>(), PSI, BFI);
455   FuncInfo->set(Fn, *MF, CurDAG);
456   SwiftError->setFunction(*MF);
457 
458   // Now get the optional analyzes if we want to.
459   // This is based on the possibly changed OptLevel (after optnone is taken
460   // into account).  That's unfortunate but OK because it just means we won't
461   // ask for passes that have been required anyway.
462 
463   if (UseMBPI && OptLevel != CodeGenOpt::None)
464     FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
465   else
466     FuncInfo->BPI = nullptr;
467 
468   if (OptLevel != CodeGenOpt::None)
469     AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
470   else
471     AA = nullptr;
472 
473   SDB->init(GFI, AA, LibInfo);
474 
475   MF->setHasInlineAsm(false);
476 
477   FuncInfo->SplitCSR = false;
478 
479   // We split CSR if the target supports it for the given function
480   // and the function has only return exits.
481   if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
482     FuncInfo->SplitCSR = true;
483 
484     // Collect all the return blocks.
485     for (const BasicBlock &BB : Fn) {
486       if (!succ_empty(&BB))
487         continue;
488 
489       const Instruction *Term = BB.getTerminator();
490       if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
491         continue;
492 
493       // Bail out if the exit block is not Return nor Unreachable.
494       FuncInfo->SplitCSR = false;
495       break;
496     }
497   }
498 
499   MachineBasicBlock *EntryMBB = &MF->front();
500   if (FuncInfo->SplitCSR)
501     // This performs initialization so lowering for SplitCSR will be correct.
502     TLI->initializeSplitCSR(EntryMBB);
503 
504   SelectAllBasicBlocks(Fn);
505   if (FastISelFailed && EnableFastISelFallbackReport) {
506     DiagnosticInfoISelFallback DiagFallback(Fn);
507     Fn.getContext().diagnose(DiagFallback);
508   }
509 
510   // Replace forward-declared registers with the registers containing
511   // the desired value.
512   // Note: it is important that this happens **before** the call to
513   // EmitLiveInCopies, since implementations can skip copies of unused
514   // registers. If we don't apply the reg fixups before, some registers may
515   // appear as unused and will be skipped, resulting in bad MI.
516   MachineRegisterInfo &MRI = MF->getRegInfo();
517   for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
518                                               E = FuncInfo->RegFixups.end();
519        I != E; ++I) {
520     Register From = I->first;
521     Register To = I->second;
522     // If To is also scheduled to be replaced, find what its ultimate
523     // replacement is.
524     while (true) {
525       DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
526       if (J == E)
527         break;
528       To = J->second;
529     }
530     // Make sure the new register has a sufficiently constrained register class.
531     if (Register::isVirtualRegister(From) && Register::isVirtualRegister(To))
532       MRI.constrainRegClass(To, MRI.getRegClass(From));
533     // Replace it.
534 
535     // Replacing one register with another won't touch the kill flags.
536     // We need to conservatively clear the kill flags as a kill on the old
537     // register might dominate existing uses of the new register.
538     if (!MRI.use_empty(To))
539       MRI.clearKillFlags(From);
540     MRI.replaceRegWith(From, To);
541   }
542 
543   // If the first basic block in the function has live ins that need to be
544   // copied into vregs, emit the copies into the top of the block before
545   // emitting the code for the block.
546   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
547   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
548 
549   // Insert copies in the entry block and the return blocks.
550   if (FuncInfo->SplitCSR) {
551     SmallVector<MachineBasicBlock*, 4> Returns;
552     // Collect all the return blocks.
553     for (MachineBasicBlock &MBB : mf) {
554       if (!MBB.succ_empty())
555         continue;
556 
557       MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
558       if (Term != MBB.end() && Term->isReturn()) {
559         Returns.push_back(&MBB);
560         continue;
561       }
562     }
563     TLI->insertCopiesSplitCSR(EntryMBB, Returns);
564   }
565 
566   DenseMap<unsigned, unsigned> LiveInMap;
567   if (!FuncInfo->ArgDbgValues.empty())
568     for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
569       if (LI.second)
570         LiveInMap.insert(LI);
571 
572   // Insert DBG_VALUE instructions for function arguments to the entry block.
573   for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
574     MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
575     bool hasFI = MI->getOperand(0).isFI();
576     Register Reg =
577         hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
578     if (Register::isPhysicalRegister(Reg))
579       EntryMBB->insert(EntryMBB->begin(), MI);
580     else {
581       MachineInstr *Def = RegInfo->getVRegDef(Reg);
582       if (Def) {
583         MachineBasicBlock::iterator InsertPos = Def;
584         // FIXME: VR def may not be in entry block.
585         Def->getParent()->insert(std::next(InsertPos), MI);
586       } else
587         LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
588                           << Register::virtReg2Index(Reg) << "\n");
589     }
590 
591     // If Reg is live-in then update debug info to track its copy in a vreg.
592     DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
593     if (LDI != LiveInMap.end()) {
594       assert(!hasFI && "There's no handling of frame pointer updating here yet "
595                        "- add if needed");
596       MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
597       MachineBasicBlock::iterator InsertPos = Def;
598       const MDNode *Variable = MI->getDebugVariable();
599       const MDNode *Expr = MI->getDebugExpression();
600       DebugLoc DL = MI->getDebugLoc();
601       bool IsIndirect = MI->isIndirectDebugValue();
602       if (IsIndirect)
603         assert(MI->getOperand(1).getImm() == 0 &&
604                "DBG_VALUE with nonzero offset");
605       assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
606              "Expected inlined-at fields to agree");
607       // Def is never a terminator here, so it is ok to increment InsertPos.
608       BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
609               IsIndirect, LDI->second, Variable, Expr);
610 
611       // If this vreg is directly copied into an exported register then
612       // that COPY instructions also need DBG_VALUE, if it is the only
613       // user of LDI->second.
614       MachineInstr *CopyUseMI = nullptr;
615       for (MachineRegisterInfo::use_instr_iterator
616            UI = RegInfo->use_instr_begin(LDI->second),
617            E = RegInfo->use_instr_end(); UI != E; ) {
618         MachineInstr *UseMI = &*(UI++);
619         if (UseMI->isDebugValue()) continue;
620         if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
621           CopyUseMI = UseMI; continue;
622         }
623         // Otherwise this is another use or second copy use.
624         CopyUseMI = nullptr; break;
625       }
626       if (CopyUseMI &&
627           TRI.getRegSizeInBits(LDI->second, MRI) ==
628               TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
629         // Use MI's debug location, which describes where Variable was
630         // declared, rather than whatever is attached to CopyUseMI.
631         MachineInstr *NewMI =
632             BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
633                     CopyUseMI->getOperand(0).getReg(), Variable, Expr);
634         MachineBasicBlock::iterator Pos = CopyUseMI;
635         EntryMBB->insertAfter(Pos, NewMI);
636       }
637     }
638   }
639 
640   // Determine if there are any calls in this machine function.
641   MachineFrameInfo &MFI = MF->getFrameInfo();
642   for (const auto &MBB : *MF) {
643     if (MFI.hasCalls() && MF->hasInlineAsm())
644       break;
645 
646     for (const auto &MI : MBB) {
647       const MCInstrDesc &MCID = TII->get(MI.getOpcode());
648       if ((MCID.isCall() && !MCID.isReturn()) ||
649           MI.isStackAligningInlineAsm()) {
650         MFI.setHasCalls(true);
651       }
652       if (MI.isInlineAsm()) {
653         MF->setHasInlineAsm(true);
654       }
655     }
656   }
657 
658   // Determine if there is a call to setjmp in the machine function.
659   MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
660 
661   // Determine if floating point is used for msvc
662   computeUsesMSVCFloatingPoint(TM.getTargetTriple(), Fn, MF->getMMI());
663 
664   // Release function-specific state. SDB and CurDAG are already cleared
665   // at this point.
666   FuncInfo->clear();
667 
668   LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
669   LLVM_DEBUG(MF->print(dbgs()));
670 
671   return true;
672 }
673 
674 static void reportFastISelFailure(MachineFunction &MF,
675                                   OptimizationRemarkEmitter &ORE,
676                                   OptimizationRemarkMissed &R,
677                                   bool ShouldAbort) {
678   // Print the function name explicitly if we don't have a debug location (which
679   // makes the diagnostic less useful) or if we're going to emit a raw error.
680   if (!R.getLocation().isValid() || ShouldAbort)
681     R << (" (in function: " + MF.getName() + ")").str();
682 
683   if (ShouldAbort)
684     report_fatal_error(R.getMsg());
685 
686   ORE.emit(R);
687 }
688 
689 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
690                                         BasicBlock::const_iterator End,
691                                         bool &HadTailCall) {
692   // Allow creating illegal types during DAG building for the basic block.
693   CurDAG->NewNodesMustHaveLegalTypes = false;
694 
695   // Lower the instructions. If a call is emitted as a tail call, cease emitting
696   // nodes for this block.
697   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
698     if (!ElidedArgCopyInstrs.count(&*I))
699       SDB->visit(*I);
700   }
701 
702   // Make sure the root of the DAG is up-to-date.
703   CurDAG->setRoot(SDB->getControlRoot());
704   HadTailCall = SDB->HasTailCall;
705   SDB->resolveOrClearDbgInfo();
706   SDB->clear();
707 
708   // Final step, emit the lowered DAG as machine code.
709   CodeGenAndEmitDAG();
710 }
711 
712 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
713   SmallPtrSet<SDNode *, 16> Added;
714   SmallVector<SDNode*, 128> Worklist;
715 
716   Worklist.push_back(CurDAG->getRoot().getNode());
717   Added.insert(CurDAG->getRoot().getNode());
718 
719   KnownBits Known;
720 
721   do {
722     SDNode *N = Worklist.pop_back_val();
723 
724     // Otherwise, add all chain operands to the worklist.
725     for (const SDValue &Op : N->op_values())
726       if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
727         Worklist.push_back(Op.getNode());
728 
729     // If this is a CopyToReg with a vreg dest, process it.
730     if (N->getOpcode() != ISD::CopyToReg)
731       continue;
732 
733     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
734     if (!Register::isVirtualRegister(DestReg))
735       continue;
736 
737     // Ignore non-integer values.
738     SDValue Src = N->getOperand(2);
739     EVT SrcVT = Src.getValueType();
740     if (!SrcVT.isInteger())
741       continue;
742 
743     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
744     Known = CurDAG->computeKnownBits(Src);
745     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
746   } while (!Worklist.empty());
747 }
748 
749 void SelectionDAGISel::CodeGenAndEmitDAG() {
750   StringRef GroupName = "sdag";
751   StringRef GroupDescription = "Instruction Selection and Scheduling";
752   std::string BlockName;
753   bool MatchFilterBB = false; (void)MatchFilterBB;
754 #ifndef NDEBUG
755   TargetTransformInfo &TTI =
756       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn);
757 #endif
758 
759   // Pre-type legalization allow creation of any node types.
760   CurDAG->NewNodesMustHaveLegalTypes = false;
761 
762 #ifndef NDEBUG
763   MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
764                    FilterDAGBasicBlockName ==
765                        FuncInfo->MBB->getBasicBlock()->getName());
766 #endif
767 #ifdef NDEBUG
768   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewDAGCombineLT ||
769       ViewLegalizeDAGs || ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs ||
770       ViewSUnitDAGs)
771 #endif
772   {
773     BlockName =
774         (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
775   }
776   LLVM_DEBUG(dbgs() << "Initial selection DAG: "
777                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
778                     << "'\n";
779              CurDAG->dump());
780 
781   if (ViewDAGCombine1 && MatchFilterBB)
782     CurDAG->viewGraph("dag-combine1 input for " + BlockName);
783 
784   // Run the DAG combiner in pre-legalize mode.
785   {
786     NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
787                        GroupDescription, TimePassesIsEnabled);
788     CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel);
789   }
790 
791 #ifndef NDEBUG
792   if (TTI.hasBranchDivergence())
793     CurDAG->VerifyDAGDiverence();
794 #endif
795 
796   LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: "
797                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
798                     << "'\n";
799              CurDAG->dump());
800 
801   // Second step, hack on the DAG until it only uses operations and types that
802   // the target supports.
803   if (ViewLegalizeTypesDAGs && MatchFilterBB)
804     CurDAG->viewGraph("legalize-types input for " + BlockName);
805 
806   bool Changed;
807   {
808     NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
809                        GroupDescription, TimePassesIsEnabled);
810     Changed = CurDAG->LegalizeTypes();
811   }
812 
813 #ifndef NDEBUG
814   if (TTI.hasBranchDivergence())
815     CurDAG->VerifyDAGDiverence();
816 #endif
817 
818   LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: "
819                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
820                     << "'\n";
821              CurDAG->dump());
822 
823   // Only allow creation of legal node types.
824   CurDAG->NewNodesMustHaveLegalTypes = true;
825 
826   if (Changed) {
827     if (ViewDAGCombineLT && MatchFilterBB)
828       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
829 
830     // Run the DAG combiner in post-type-legalize mode.
831     {
832       NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
833                          GroupName, GroupDescription, TimePassesIsEnabled);
834       CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel);
835     }
836 
837 #ifndef NDEBUG
838     if (TTI.hasBranchDivergence())
839       CurDAG->VerifyDAGDiverence();
840 #endif
841 
842     LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: "
843                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
844                       << "'\n";
845                CurDAG->dump());
846   }
847 
848   {
849     NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
850                        GroupDescription, TimePassesIsEnabled);
851     Changed = CurDAG->LegalizeVectors();
852   }
853 
854   if (Changed) {
855     LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: "
856                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
857                       << "'\n";
858                CurDAG->dump());
859 
860     {
861       NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
862                          GroupDescription, TimePassesIsEnabled);
863       CurDAG->LegalizeTypes();
864     }
865 
866     LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: "
867                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
868                       << "'\n";
869                CurDAG->dump());
870 
871     if (ViewDAGCombineLT && MatchFilterBB)
872       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
873 
874     // Run the DAG combiner in post-type-legalize mode.
875     {
876       NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
877                          GroupName, GroupDescription, TimePassesIsEnabled);
878       CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel);
879     }
880 
881     LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: "
882                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
883                       << "'\n";
884                CurDAG->dump());
885 
886 #ifndef NDEBUG
887     if (TTI.hasBranchDivergence())
888       CurDAG->VerifyDAGDiverence();
889 #endif
890   }
891 
892   if (ViewLegalizeDAGs && MatchFilterBB)
893     CurDAG->viewGraph("legalize input for " + BlockName);
894 
895   {
896     NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
897                        GroupDescription, TimePassesIsEnabled);
898     CurDAG->Legalize();
899   }
900 
901 #ifndef NDEBUG
902   if (TTI.hasBranchDivergence())
903     CurDAG->VerifyDAGDiverence();
904 #endif
905 
906   LLVM_DEBUG(dbgs() << "Legalized selection DAG: "
907                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
908                     << "'\n";
909              CurDAG->dump());
910 
911   if (ViewDAGCombine2 && MatchFilterBB)
912     CurDAG->viewGraph("dag-combine2 input for " + BlockName);
913 
914   // Run the DAG combiner in post-legalize mode.
915   {
916     NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
917                        GroupDescription, TimePassesIsEnabled);
918     CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel);
919   }
920 
921 #ifndef NDEBUG
922   if (TTI.hasBranchDivergence())
923     CurDAG->VerifyDAGDiverence();
924 #endif
925 
926   LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: "
927                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
928                     << "'\n";
929              CurDAG->dump());
930 
931   if (OptLevel != CodeGenOpt::None)
932     ComputeLiveOutVRegInfo();
933 
934   if (ViewISelDAGs && MatchFilterBB)
935     CurDAG->viewGraph("isel input for " + BlockName);
936 
937   // Third, instruction select all of the operations to machine code, adding the
938   // code to the MachineBasicBlock.
939   {
940     NamedRegionTimer T("isel", "Instruction Selection", GroupName,
941                        GroupDescription, TimePassesIsEnabled);
942     DoInstructionSelection();
943   }
944 
945   LLVM_DEBUG(dbgs() << "Selected selection DAG: "
946                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
947                     << "'\n";
948              CurDAG->dump());
949 
950   if (ViewSchedDAGs && MatchFilterBB)
951     CurDAG->viewGraph("scheduler input for " + BlockName);
952 
953   // Schedule machine code.
954   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
955   {
956     NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
957                        GroupDescription, TimePassesIsEnabled);
958     Scheduler->Run(CurDAG, FuncInfo->MBB);
959   }
960 
961   if (ViewSUnitDAGs && MatchFilterBB)
962     Scheduler->viewGraph();
963 
964   // Emit machine code to BB.  This can change 'BB' to the last block being
965   // inserted into.
966   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
967   {
968     NamedRegionTimer T("emit", "Instruction Creation", GroupName,
969                        GroupDescription, TimePassesIsEnabled);
970 
971     // FuncInfo->InsertPt is passed by reference and set to the end of the
972     // scheduled instructions.
973     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
974   }
975 
976   // If the block was split, make sure we update any references that are used to
977   // update PHI nodes later on.
978   if (FirstMBB != LastMBB)
979     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
980 
981   // Free the scheduler state.
982   {
983     NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
984                        GroupDescription, TimePassesIsEnabled);
985     delete Scheduler;
986   }
987 
988   // Free the SelectionDAG state, now that we're finished with it.
989   CurDAG->clear();
990 }
991 
992 namespace {
993 
994 /// ISelUpdater - helper class to handle updates of the instruction selection
995 /// graph.
996 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
997   SelectionDAG::allnodes_iterator &ISelPosition;
998 
999 public:
1000   ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1001     : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1002 
1003   /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1004   /// deleted is the current ISelPosition node, update ISelPosition.
1005   ///
1006   void NodeDeleted(SDNode *N, SDNode *E) override {
1007     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1008       ++ISelPosition;
1009   }
1010 };
1011 
1012 } // end anonymous namespace
1013 
1014 // This function is used to enforce the topological node id property
1015 // property leveraged during Instruction selection. Before selection all
1016 // nodes are given a non-negative id such that all nodes have a larger id than
1017 // their operands. As this holds transitively we can prune checks that a node N
1018 // is a predecessor of M another by not recursively checking through M's
1019 // operands if N's ID is larger than M's ID. This is significantly improves
1020 // performance of for various legality checks (e.g. IsLegalToFold /
1021 // UpdateChains).
1022 
1023 // However, when we fuse multiple nodes into a single node
1024 // during selection we may induce a predecessor relationship between inputs and
1025 // outputs of distinct nodes being merged violating the topological property.
1026 // Should a fused node have a successor which has yet to be selected, our
1027 // legality checks would be incorrect. To avoid this we mark all unselected
1028 // sucessor nodes, i.e. id != -1 as invalid for pruning by bit-negating (x =>
1029 // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1030 // We use bit-negation to more clearly enforce that node id -1 can only be
1031 // achieved by selected nodes). As the conversion is reversable the original Id,
1032 // topological pruning can still be leveraged when looking for unselected nodes.
1033 // This method is call internally in all ISel replacement calls.
1034 void SelectionDAGISel::EnforceNodeIdInvariant(SDNode *Node) {
1035   SmallVector<SDNode *, 4> Nodes;
1036   Nodes.push_back(Node);
1037 
1038   while (!Nodes.empty()) {
1039     SDNode *N = Nodes.pop_back_val();
1040     for (auto *U : N->uses()) {
1041       auto UId = U->getNodeId();
1042       if (UId > 0) {
1043         InvalidateNodeId(U);
1044         Nodes.push_back(U);
1045       }
1046     }
1047   }
1048 }
1049 
1050 // InvalidateNodeId - As discusses in EnforceNodeIdInvariant, mark a
1051 // NodeId with the equivalent node id which is invalid for topological
1052 // pruning.
1053 void SelectionDAGISel::InvalidateNodeId(SDNode *N) {
1054   int InvalidId = -(N->getNodeId() + 1);
1055   N->setNodeId(InvalidId);
1056 }
1057 
1058 // getUninvalidatedNodeId - get original uninvalidated node id.
1059 int SelectionDAGISel::getUninvalidatedNodeId(SDNode *N) {
1060   int Id = N->getNodeId();
1061   if (Id < -1)
1062     return -(Id + 1);
1063   return Id;
1064 }
1065 
1066 void SelectionDAGISel::DoInstructionSelection() {
1067   LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1068                     << printMBBReference(*FuncInfo->MBB) << " '"
1069                     << FuncInfo->MBB->getName() << "'\n");
1070 
1071   PreprocessISelDAG();
1072 
1073   // Select target instructions for the DAG.
1074   {
1075     // Number all nodes with a topological order and set DAGSize.
1076     DAGSize = CurDAG->AssignTopologicalOrder();
1077 
1078     // Create a dummy node (which is not added to allnodes), that adds
1079     // a reference to the root node, preventing it from being deleted,
1080     // and tracking any changes of the root.
1081     HandleSDNode Dummy(CurDAG->getRoot());
1082     SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
1083     ++ISelPosition;
1084 
1085     // Make sure that ISelPosition gets properly updated when nodes are deleted
1086     // in calls made from this function.
1087     ISelUpdater ISU(*CurDAG, ISelPosition);
1088 
1089     // The AllNodes list is now topological-sorted. Visit the
1090     // nodes by starting at the end of the list (the root of the
1091     // graph) and preceding back toward the beginning (the entry
1092     // node).
1093     while (ISelPosition != CurDAG->allnodes_begin()) {
1094       SDNode *Node = &*--ISelPosition;
1095       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1096       // but there are currently some corner cases that it misses. Also, this
1097       // makes it theoretically possible to disable the DAGCombiner.
1098       if (Node->use_empty())
1099         continue;
1100 
1101 #ifndef NDEBUG
1102       SmallVector<SDNode *, 4> Nodes;
1103       Nodes.push_back(Node);
1104 
1105       while (!Nodes.empty()) {
1106         auto N = Nodes.pop_back_val();
1107         if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1108           continue;
1109         for (const SDValue &Op : N->op_values()) {
1110           if (Op->getOpcode() == ISD::TokenFactor)
1111             Nodes.push_back(Op.getNode());
1112           else {
1113             // We rely on topological ordering of node ids for checking for
1114             // cycles when fusing nodes during selection. All unselected nodes
1115             // successors of an already selected node should have a negative id.
1116             // This assertion will catch such cases. If this assertion triggers
1117             // it is likely you using DAG-level Value/Node replacement functions
1118             // (versus equivalent ISEL replacement) in backend-specific
1119             // selections. See comment in EnforceNodeIdInvariant for more
1120             // details.
1121             assert(Op->getNodeId() != -1 &&
1122                    "Node has already selected predecessor node");
1123           }
1124         }
1125       }
1126 #endif
1127 
1128       // When we are using non-default rounding modes or FP exception behavior
1129       // FP operations are represented by StrictFP pseudo-operations.  For
1130       // targets that do not (yet) understand strict FP operations directly,
1131       // we convert them to normal FP opcodes instead at this point.  This
1132       // will allow them to be handled by existing target-specific instruction
1133       // selectors.
1134       if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1135         // For some opcodes, we need to call TLI->getOperationAction using
1136         // the first operand type instead of the result type.  Note that this
1137         // must match what SelectionDAGLegalize::LegalizeOp is doing.
1138         EVT ActionVT;
1139         switch (Node->getOpcode()) {
1140         case ISD::STRICT_SINT_TO_FP:
1141         case ISD::STRICT_UINT_TO_FP:
1142         case ISD::STRICT_LRINT:
1143         case ISD::STRICT_LLRINT:
1144         case ISD::STRICT_LROUND:
1145         case ISD::STRICT_LLROUND:
1146         case ISD::STRICT_FSETCC:
1147         case ISD::STRICT_FSETCCS:
1148           ActionVT = Node->getOperand(1).getValueType();
1149           break;
1150         default:
1151           ActionVT = Node->getValueType(0);
1152           break;
1153         }
1154         if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1155             == TargetLowering::Expand)
1156           Node = CurDAG->mutateStrictFPToFP(Node);
1157       }
1158 
1159       LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1160                  Node->dump(CurDAG));
1161 
1162       Select(Node);
1163     }
1164 
1165     CurDAG->setRoot(Dummy.getValue());
1166   }
1167 
1168   LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1169 
1170   PostprocessISelDAG();
1171 }
1172 
1173 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
1174   for (const User *U : CPI->users()) {
1175     if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1176       Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1177       if (IID == Intrinsic::eh_exceptionpointer ||
1178           IID == Intrinsic::eh_exceptioncode)
1179         return true;
1180     }
1181   }
1182   return false;
1183 }
1184 
1185 // wasm.landingpad.index intrinsic is for associating a landing pad index number
1186 // with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1187 // and store the mapping in the function.
1188 static void mapWasmLandingPadIndex(MachineBasicBlock *MBB,
1189                                    const CatchPadInst *CPI) {
1190   MachineFunction *MF = MBB->getParent();
1191   // In case of single catch (...), we don't emit LSDA, so we don't need
1192   // this information.
1193   bool IsSingleCatchAllClause =
1194       CPI->getNumArgOperands() == 1 &&
1195       cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1196   if (!IsSingleCatchAllClause) {
1197     // Create a mapping from landing pad label to landing pad index.
1198     bool IntrFound = false;
1199     for (const User *U : CPI->users()) {
1200       if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1201         Intrinsic::ID IID = Call->getIntrinsicID();
1202         if (IID == Intrinsic::wasm_landingpad_index) {
1203           Value *IndexArg = Call->getArgOperand(1);
1204           int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1205           MF->setWasmLandingPadIndex(MBB, Index);
1206           IntrFound = true;
1207           break;
1208         }
1209       }
1210     }
1211     assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1212     (void)IntrFound;
1213   }
1214 }
1215 
1216 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1217 /// do other setup for EH landing-pad blocks.
1218 bool SelectionDAGISel::PrepareEHLandingPad() {
1219   MachineBasicBlock *MBB = FuncInfo->MBB;
1220   const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1221   const BasicBlock *LLVMBB = MBB->getBasicBlock();
1222   const TargetRegisterClass *PtrRC =
1223       TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
1224 
1225   auto Pers = classifyEHPersonality(PersonalityFn);
1226 
1227   // Catchpads have one live-in register, which typically holds the exception
1228   // pointer or code.
1229   if (isFuncletEHPersonality(Pers)) {
1230     if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1231       if (hasExceptionPointerOrCodeUser(CPI)) {
1232         // Get or create the virtual register to hold the pointer or code.  Mark
1233         // the live in physreg and copy into the vreg.
1234         MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1235         assert(EHPhysReg && "target lacks exception pointer register");
1236         MBB->addLiveIn(EHPhysReg);
1237         unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1238         BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1239                 TII->get(TargetOpcode::COPY), VReg)
1240             .addReg(EHPhysReg, RegState::Kill);
1241       }
1242     }
1243     return true;
1244   }
1245 
1246   // Add a label to mark the beginning of the landing pad.  Deletion of the
1247   // landing pad can thus be detected via the MachineModuleInfo.
1248   MCSymbol *Label = MF->addLandingPad(MBB);
1249 
1250   const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1251   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1252     .addSym(Label);
1253 
1254   // If the unwinder does not preserve all registers, ensure that the
1255   // function marks the clobbered registers as used.
1256   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
1257   if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1258     MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
1259 
1260   if (Pers == EHPersonality::Wasm_CXX) {
1261     if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
1262       mapWasmLandingPadIndex(MBB, CPI);
1263   } else {
1264     // Assign the call site to the landing pad's begin label.
1265     MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1266     // Mark exception register as live in.
1267     if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1268       FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1269     // Mark exception selector register as live in.
1270     if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1271       FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1272   }
1273 
1274   return true;
1275 }
1276 
1277 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1278 /// side-effect free and is either dead or folded into a generated instruction.
1279 /// Return false if it needs to be emitted.
1280 static bool isFoldedOrDeadInstruction(const Instruction *I,
1281                                       const FunctionLoweringInfo &FuncInfo) {
1282   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1283          !I->isTerminator() &&     // Terminators aren't folded.
1284          !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1285          !I->isEHPad() &&             // EH pad instructions aren't folded.
1286          !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1287 }
1288 
1289 /// Collect llvm.dbg.declare information. This is done after argument lowering
1290 /// in case the declarations refer to arguments.
1291 static void processDbgDeclares(FunctionLoweringInfo &FuncInfo) {
1292   MachineFunction *MF = FuncInfo.MF;
1293   const DataLayout &DL = MF->getDataLayout();
1294   for (const BasicBlock &BB : *FuncInfo.Fn) {
1295     for (const Instruction &I : BB) {
1296       const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I);
1297       if (!DI)
1298         continue;
1299 
1300       assert(DI->getVariable() && "Missing variable");
1301       assert(DI->getDebugLoc() && "Missing location");
1302       const Value *Address = DI->getAddress();
1303       if (!Address) {
1304         LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *DI
1305                           << " (bad address)\n");
1306         continue;
1307       }
1308 
1309       // Look through casts and constant offset GEPs. These mostly come from
1310       // inalloca.
1311       APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
1312       Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1313 
1314       // Check if the variable is a static alloca or a byval or inalloca
1315       // argument passed in memory. If it is not, then we will ignore this
1316       // intrinsic and handle this during isel like dbg.value.
1317       int FI = std::numeric_limits<int>::max();
1318       if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1319         auto SI = FuncInfo.StaticAllocaMap.find(AI);
1320         if (SI != FuncInfo.StaticAllocaMap.end())
1321           FI = SI->second;
1322       } else if (const auto *Arg = dyn_cast<Argument>(Address))
1323         FI = FuncInfo.getArgumentFrameIndex(Arg);
1324 
1325       if (FI == std::numeric_limits<int>::max())
1326         continue;
1327 
1328       DIExpression *Expr = DI->getExpression();
1329       if (Offset.getBoolValue())
1330         Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset,
1331                                      Offset.getZExtValue());
1332       LLVM_DEBUG(dbgs() << "processDbgDeclares: setVariableDbgInfo FI=" << FI
1333                         << ", " << *DI << "\n");
1334       MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc());
1335     }
1336   }
1337 }
1338 
1339 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1340   FastISelFailed = false;
1341   // Initialize the Fast-ISel state, if needed.
1342   FastISel *FastIS = nullptr;
1343   if (TM.Options.EnableFastISel) {
1344     LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1345     FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1346   }
1347 
1348   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1349 
1350   // Lower arguments up front. An RPO iteration always visits the entry block
1351   // first.
1352   assert(*RPOT.begin() == &Fn.getEntryBlock());
1353   ++NumEntryBlocks;
1354 
1355   // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1356   FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1357   FuncInfo->InsertPt = FuncInfo->MBB->begin();
1358 
1359   CurDAG->setFunctionLoweringInfo(FuncInfo.get());
1360 
1361   if (!FastIS) {
1362     LowerArguments(Fn);
1363   } else {
1364     // See if fast isel can lower the arguments.
1365     FastIS->startNewBlock();
1366     if (!FastIS->lowerArguments()) {
1367       FastISelFailed = true;
1368       // Fast isel failed to lower these arguments
1369       ++NumFastIselFailLowerArguments;
1370 
1371       OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1372                                  Fn.getSubprogram(),
1373                                  &Fn.getEntryBlock());
1374       R << "FastISel didn't lower all arguments: "
1375         << ore::NV("Prototype", Fn.getType());
1376       reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
1377 
1378       // Use SelectionDAG argument lowering
1379       LowerArguments(Fn);
1380       CurDAG->setRoot(SDB->getControlRoot());
1381       SDB->clear();
1382       CodeGenAndEmitDAG();
1383     }
1384 
1385     // If we inserted any instructions at the beginning, make a note of
1386     // where they are, so we can be sure to emit subsequent instructions
1387     // after them.
1388     if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1389       FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1390     else
1391       FastIS->setLastLocalValue(nullptr);
1392   }
1393 
1394   bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1395 
1396   if (FastIS && Inserted)
1397     FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1398 
1399   processDbgDeclares(*FuncInfo);
1400 
1401   // Iterate over all basic blocks in the function.
1402   StackProtector &SP = getAnalysis<StackProtector>();
1403   for (const BasicBlock *LLVMBB : RPOT) {
1404     if (OptLevel != CodeGenOpt::None) {
1405       bool AllPredsVisited = true;
1406       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1407            PI != PE; ++PI) {
1408         if (!FuncInfo->VisitedBBs.count(*PI)) {
1409           AllPredsVisited = false;
1410           break;
1411         }
1412       }
1413 
1414       if (AllPredsVisited) {
1415         for (const PHINode &PN : LLVMBB->phis())
1416           FuncInfo->ComputePHILiveOutRegInfo(&PN);
1417       } else {
1418         for (const PHINode &PN : LLVMBB->phis())
1419           FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1420       }
1421 
1422       FuncInfo->VisitedBBs.insert(LLVMBB);
1423     }
1424 
1425     BasicBlock::const_iterator const Begin =
1426         LLVMBB->getFirstNonPHI()->getIterator();
1427     BasicBlock::const_iterator const End = LLVMBB->end();
1428     BasicBlock::const_iterator BI = End;
1429 
1430     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1431     if (!FuncInfo->MBB)
1432       continue; // Some blocks like catchpads have no code or MBB.
1433 
1434     // Insert new instructions after any phi or argument setup code.
1435     FuncInfo->InsertPt = FuncInfo->MBB->end();
1436 
1437     // Setup an EH landing-pad block.
1438     FuncInfo->ExceptionPointerVirtReg = 0;
1439     FuncInfo->ExceptionSelectorVirtReg = 0;
1440     if (LLVMBB->isEHPad())
1441       if (!PrepareEHLandingPad())
1442         continue;
1443 
1444     // Before doing SelectionDAG ISel, see if FastISel has been requested.
1445     if (FastIS) {
1446       if (LLVMBB != &Fn.getEntryBlock())
1447         FastIS->startNewBlock();
1448 
1449       unsigned NumFastIselRemaining = std::distance(Begin, End);
1450 
1451       // Pre-assign swifterror vregs.
1452       SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1453 
1454       // Do FastISel on as many instructions as possible.
1455       for (; BI != Begin; --BI) {
1456         const Instruction *Inst = &*std::prev(BI);
1457 
1458         // If we no longer require this instruction, skip it.
1459         if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1460             ElidedArgCopyInstrs.count(Inst)) {
1461           --NumFastIselRemaining;
1462           continue;
1463         }
1464 
1465         // Bottom-up: reset the insert pos at the top, after any local-value
1466         // instructions.
1467         FastIS->recomputeInsertPt();
1468 
1469         // Try to select the instruction with FastISel.
1470         if (FastIS->selectInstruction(Inst)) {
1471           --NumFastIselRemaining;
1472           ++NumFastIselSuccess;
1473           // If fast isel succeeded, skip over all the folded instructions, and
1474           // then see if there is a load right before the selected instructions.
1475           // Try to fold the load if so.
1476           const Instruction *BeforeInst = Inst;
1477           while (BeforeInst != &*Begin) {
1478             BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1479             if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1480               break;
1481           }
1482           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1483               BeforeInst->hasOneUse() &&
1484               FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1485             // If we succeeded, don't re-select the load.
1486             BI = std::next(BasicBlock::const_iterator(BeforeInst));
1487             --NumFastIselRemaining;
1488             ++NumFastIselSuccess;
1489           }
1490           continue;
1491         }
1492 
1493         FastISelFailed = true;
1494 
1495         // Then handle certain instructions as single-LLVM-Instruction blocks.
1496         // We cannot separate out GCrelocates to their own blocks since we need
1497         // to keep track of gc-relocates for a particular gc-statepoint. This is
1498         // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1499         // visitGCRelocate.
1500         if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1501             !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1502           OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1503                                      Inst->getDebugLoc(), LLVMBB);
1504 
1505           R << "FastISel missed call";
1506 
1507           if (R.isEnabled() || EnableFastISelAbort) {
1508             std::string InstStrStorage;
1509             raw_string_ostream InstStr(InstStrStorage);
1510             InstStr << *Inst;
1511 
1512             R << ": " << InstStr.str();
1513           }
1514 
1515           reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
1516 
1517           if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1518               !Inst->use_empty()) {
1519             Register &R = FuncInfo->ValueMap[Inst];
1520             if (!R)
1521               R = FuncInfo->CreateRegs(Inst);
1522           }
1523 
1524           bool HadTailCall = false;
1525           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1526           SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1527 
1528           // If the call was emitted as a tail call, we're done with the block.
1529           // We also need to delete any previously emitted instructions.
1530           if (HadTailCall) {
1531             FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1532             --BI;
1533             break;
1534           }
1535 
1536           // Recompute NumFastIselRemaining as Selection DAG instruction
1537           // selection may have handled the call, input args, etc.
1538           unsigned RemainingNow = std::distance(Begin, BI);
1539           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1540           NumFastIselRemaining = RemainingNow;
1541           continue;
1542         }
1543 
1544         OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1545                                    Inst->getDebugLoc(), LLVMBB);
1546 
1547         bool ShouldAbort = EnableFastISelAbort;
1548         if (Inst->isTerminator()) {
1549           // Use a different message for terminator misses.
1550           R << "FastISel missed terminator";
1551           // Don't abort for terminator unless the level is really high
1552           ShouldAbort = (EnableFastISelAbort > 2);
1553         } else {
1554           R << "FastISel missed";
1555         }
1556 
1557         if (R.isEnabled() || EnableFastISelAbort) {
1558           std::string InstStrStorage;
1559           raw_string_ostream InstStr(InstStrStorage);
1560           InstStr << *Inst;
1561           R << ": " << InstStr.str();
1562         }
1563 
1564         reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1565 
1566         NumFastIselFailures += NumFastIselRemaining;
1567         break;
1568       }
1569 
1570       FastIS->recomputeInsertPt();
1571     }
1572 
1573     if (SP.shouldEmitSDCheck(*LLVMBB)) {
1574       bool FunctionBasedInstrumentation =
1575           TLI->getSSPStackGuardCheck(*Fn.getParent());
1576       SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1577                                    FunctionBasedInstrumentation);
1578     }
1579 
1580     if (Begin != BI)
1581       ++NumDAGBlocks;
1582     else
1583       ++NumFastIselBlocks;
1584 
1585     if (Begin != BI) {
1586       // Run SelectionDAG instruction selection on the remainder of the block
1587       // not handled by FastISel. If FastISel is not run, this is the entire
1588       // block.
1589       bool HadTailCall;
1590       SelectBasicBlock(Begin, BI, HadTailCall);
1591 
1592       // But if FastISel was run, we already selected some of the block.
1593       // If we emitted a tail-call, we need to delete any previously emitted
1594       // instruction that follows it.
1595       if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1596         FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1597     }
1598 
1599     if (FastIS)
1600       FastIS->finishBasicBlock();
1601     FinishBasicBlock();
1602     FuncInfo->PHINodesToUpdate.clear();
1603     ElidedArgCopyInstrs.clear();
1604   }
1605 
1606   SP.copyToMachineFrameInfo(MF->getFrameInfo());
1607 
1608   SwiftError->propagateVRegs();
1609 
1610   delete FastIS;
1611   SDB->clearDanglingDebugInfo();
1612   SDB->SPDescriptor.resetPerFunctionState();
1613 }
1614 
1615 /// Given that the input MI is before a partial terminator sequence TSeq, return
1616 /// true if M + TSeq also a partial terminator sequence.
1617 ///
1618 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1619 /// lowering copy vregs into physical registers, which are then passed into
1620 /// terminator instructors so we can satisfy ABI constraints. A partial
1621 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1622 /// may be the whole terminator sequence).
1623 static bool MIIsInTerminatorSequence(const MachineInstr &MI) {
1624   // If we do not have a copy or an implicit def, we return true if and only if
1625   // MI is a debug value.
1626   if (!MI.isCopy() && !MI.isImplicitDef())
1627     // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1628     // physical registers if there is debug info associated with the terminator
1629     // of our mbb. We want to include said debug info in our terminator
1630     // sequence, so we return true in that case.
1631     return MI.isDebugValue();
1632 
1633   // We have left the terminator sequence if we are not doing one of the
1634   // following:
1635   //
1636   // 1. Copying a vreg into a physical register.
1637   // 2. Copying a vreg into a vreg.
1638   // 3. Defining a register via an implicit def.
1639 
1640   // OPI should always be a register definition...
1641   MachineInstr::const_mop_iterator OPI = MI.operands_begin();
1642   if (!OPI->isReg() || !OPI->isDef())
1643     return false;
1644 
1645   // Defining any register via an implicit def is always ok.
1646   if (MI.isImplicitDef())
1647     return true;
1648 
1649   // Grab the copy source...
1650   MachineInstr::const_mop_iterator OPI2 = OPI;
1651   ++OPI2;
1652   assert(OPI2 != MI.operands_end()
1653          && "Should have a copy implying we should have 2 arguments.");
1654 
1655   // Make sure that the copy dest is not a vreg when the copy source is a
1656   // physical register.
1657   if (!OPI2->isReg() || (!Register::isPhysicalRegister(OPI->getReg()) &&
1658                          Register::isPhysicalRegister(OPI2->getReg())))
1659     return false;
1660 
1661   return true;
1662 }
1663 
1664 /// Find the split point at which to splice the end of BB into its success stack
1665 /// protector check machine basic block.
1666 ///
1667 /// On many platforms, due to ABI constraints, terminators, even before register
1668 /// allocation, use physical registers. This creates an issue for us since
1669 /// physical registers at this point can not travel across basic
1670 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1671 /// when they enter functions and moves them through a sequence of copies back
1672 /// into the physical registers right before the terminator creating a
1673 /// ``Terminator Sequence''. This function is searching for the beginning of the
1674 /// terminator sequence so that we can ensure that we splice off not just the
1675 /// terminator, but additionally the copies that move the vregs into the
1676 /// physical registers.
1677 static MachineBasicBlock::iterator
1678 FindSplitPointForStackProtector(MachineBasicBlock *BB) {
1679   MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1680   //
1681   if (SplitPoint == BB->begin())
1682     return SplitPoint;
1683 
1684   MachineBasicBlock::iterator Start = BB->begin();
1685   MachineBasicBlock::iterator Previous = SplitPoint;
1686   --Previous;
1687 
1688   while (MIIsInTerminatorSequence(*Previous)) {
1689     SplitPoint = Previous;
1690     if (Previous == Start)
1691       break;
1692     --Previous;
1693   }
1694 
1695   return SplitPoint;
1696 }
1697 
1698 void
1699 SelectionDAGISel::FinishBasicBlock() {
1700   LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1701                     << FuncInfo->PHINodesToUpdate.size() << "\n";
1702              for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1703                   ++i) dbgs()
1704              << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1705              << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1706 
1707   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1708   // PHI nodes in successors.
1709   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1710     MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1711     assert(PHI->isPHI() &&
1712            "This is not a machine PHI node that we are updating!");
1713     if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1714       continue;
1715     PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1716   }
1717 
1718   // Handle stack protector.
1719   if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1720     // The target provides a guard check function. There is no need to
1721     // generate error handling code or to split current basic block.
1722     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1723 
1724     // Add load and check to the basicblock.
1725     FuncInfo->MBB = ParentMBB;
1726     FuncInfo->InsertPt =
1727         FindSplitPointForStackProtector(ParentMBB);
1728     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1729     CurDAG->setRoot(SDB->getRoot());
1730     SDB->clear();
1731     CodeGenAndEmitDAG();
1732 
1733     // Clear the Per-BB State.
1734     SDB->SPDescriptor.resetPerBBState();
1735   } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1736     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1737     MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1738 
1739     // Find the split point to split the parent mbb. At the same time copy all
1740     // physical registers used in the tail of parent mbb into virtual registers
1741     // before the split point and back into physical registers after the split
1742     // point. This prevents us needing to deal with Live-ins and many other
1743     // register allocation issues caused by us splitting the parent mbb. The
1744     // register allocator will clean up said virtual copies later on.
1745     MachineBasicBlock::iterator SplitPoint =
1746         FindSplitPointForStackProtector(ParentMBB);
1747 
1748     // Splice the terminator of ParentMBB into SuccessMBB.
1749     SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1750                        SplitPoint,
1751                        ParentMBB->end());
1752 
1753     // Add compare/jump on neq/jump to the parent BB.
1754     FuncInfo->MBB = ParentMBB;
1755     FuncInfo->InsertPt = ParentMBB->end();
1756     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1757     CurDAG->setRoot(SDB->getRoot());
1758     SDB->clear();
1759     CodeGenAndEmitDAG();
1760 
1761     // CodeGen Failure MBB if we have not codegened it yet.
1762     MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1763     if (FailureMBB->empty()) {
1764       FuncInfo->MBB = FailureMBB;
1765       FuncInfo->InsertPt = FailureMBB->end();
1766       SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1767       CurDAG->setRoot(SDB->getRoot());
1768       SDB->clear();
1769       CodeGenAndEmitDAG();
1770     }
1771 
1772     // Clear the Per-BB State.
1773     SDB->SPDescriptor.resetPerBBState();
1774   }
1775 
1776   // Lower each BitTestBlock.
1777   for (auto &BTB : SDB->SL->BitTestCases) {
1778     // Lower header first, if it wasn't already lowered
1779     if (!BTB.Emitted) {
1780       // Set the current basic block to the mbb we wish to insert the code into
1781       FuncInfo->MBB = BTB.Parent;
1782       FuncInfo->InsertPt = FuncInfo->MBB->end();
1783       // Emit the code
1784       SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1785       CurDAG->setRoot(SDB->getRoot());
1786       SDB->clear();
1787       CodeGenAndEmitDAG();
1788     }
1789 
1790     BranchProbability UnhandledProb = BTB.Prob;
1791     for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1792       UnhandledProb -= BTB.Cases[j].ExtraProb;
1793       // Set the current basic block to the mbb we wish to insert the code into
1794       FuncInfo->MBB = BTB.Cases[j].ThisBB;
1795       FuncInfo->InsertPt = FuncInfo->MBB->end();
1796       // Emit the code
1797 
1798       // If all cases cover a contiguous range, it is not necessary to jump to
1799       // the default block after the last bit test fails. This is because the
1800       // range check during bit test header creation has guaranteed that every
1801       // case here doesn't go outside the range. In this case, there is no need
1802       // to perform the last bit test, as it will always be true. Instead, make
1803       // the second-to-last bit-test fall through to the target of the last bit
1804       // test, and delete the last bit test.
1805 
1806       MachineBasicBlock *NextMBB;
1807       if (BTB.ContiguousRange && j + 2 == ej) {
1808         // Second-to-last bit-test with contiguous range: fall through to the
1809         // target of the final bit test.
1810         NextMBB = BTB.Cases[j + 1].TargetBB;
1811       } else if (j + 1 == ej) {
1812         // For the last bit test, fall through to Default.
1813         NextMBB = BTB.Default;
1814       } else {
1815         // Otherwise, fall through to the next bit test.
1816         NextMBB = BTB.Cases[j + 1].ThisBB;
1817       }
1818 
1819       SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1820                             FuncInfo->MBB);
1821 
1822       CurDAG->setRoot(SDB->getRoot());
1823       SDB->clear();
1824       CodeGenAndEmitDAG();
1825 
1826       if (BTB.ContiguousRange && j + 2 == ej) {
1827         // Since we're not going to use the final bit test, remove it.
1828         BTB.Cases.pop_back();
1829         break;
1830       }
1831     }
1832 
1833     // Update PHI Nodes
1834     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1835          pi != pe; ++pi) {
1836       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1837       MachineBasicBlock *PHIBB = PHI->getParent();
1838       assert(PHI->isPHI() &&
1839              "This is not a machine PHI node that we are updating!");
1840       // This is "default" BB. We have two jumps to it. From "header" BB and
1841       // from last "case" BB, unless the latter was skipped.
1842       if (PHIBB == BTB.Default) {
1843         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
1844         if (!BTB.ContiguousRange) {
1845           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1846               .addMBB(BTB.Cases.back().ThisBB);
1847          }
1848       }
1849       // One of "cases" BB.
1850       for (unsigned j = 0, ej = BTB.Cases.size();
1851            j != ej; ++j) {
1852         MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
1853         if (cBB->isSuccessor(PHIBB))
1854           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1855       }
1856     }
1857   }
1858   SDB->SL->BitTestCases.clear();
1859 
1860   // If the JumpTable record is filled in, then we need to emit a jump table.
1861   // Updating the PHI nodes is tricky in this case, since we need to determine
1862   // whether the PHI is a successor of the range check MBB or the jump table MBB
1863   for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
1864     // Lower header first, if it wasn't already lowered
1865     if (!SDB->SL->JTCases[i].first.Emitted) {
1866       // Set the current basic block to the mbb we wish to insert the code into
1867       FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
1868       FuncInfo->InsertPt = FuncInfo->MBB->end();
1869       // Emit the code
1870       SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
1871                                 SDB->SL->JTCases[i].first, FuncInfo->MBB);
1872       CurDAG->setRoot(SDB->getRoot());
1873       SDB->clear();
1874       CodeGenAndEmitDAG();
1875     }
1876 
1877     // Set the current basic block to the mbb we wish to insert the code into
1878     FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
1879     FuncInfo->InsertPt = FuncInfo->MBB->end();
1880     // Emit the code
1881     SDB->visitJumpTable(SDB->SL->JTCases[i].second);
1882     CurDAG->setRoot(SDB->getRoot());
1883     SDB->clear();
1884     CodeGenAndEmitDAG();
1885 
1886     // Update PHI Nodes
1887     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1888          pi != pe; ++pi) {
1889       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1890       MachineBasicBlock *PHIBB = PHI->getParent();
1891       assert(PHI->isPHI() &&
1892              "This is not a machine PHI node that we are updating!");
1893       // "default" BB. We can go there only from header BB.
1894       if (PHIBB == SDB->SL->JTCases[i].second.Default)
1895         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1896            .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
1897       // JT BB. Just iterate over successors here
1898       if (FuncInfo->MBB->isSuccessor(PHIBB))
1899         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1900     }
1901   }
1902   SDB->SL->JTCases.clear();
1903 
1904   // If we generated any switch lowering information, build and codegen any
1905   // additional DAGs necessary.
1906   for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
1907     // Set the current basic block to the mbb we wish to insert the code into
1908     FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
1909     FuncInfo->InsertPt = FuncInfo->MBB->end();
1910 
1911     // Determine the unique successors.
1912     SmallVector<MachineBasicBlock *, 2> Succs;
1913     Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
1914     if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
1915       Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
1916 
1917     // Emit the code. Note that this could result in FuncInfo->MBB being split.
1918     SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
1919     CurDAG->setRoot(SDB->getRoot());
1920     SDB->clear();
1921     CodeGenAndEmitDAG();
1922 
1923     // Remember the last block, now that any splitting is done, for use in
1924     // populating PHI nodes in successors.
1925     MachineBasicBlock *ThisBB = FuncInfo->MBB;
1926 
1927     // Handle any PHI nodes in successors of this chunk, as if we were coming
1928     // from the original BB before switch expansion.  Note that PHI nodes can
1929     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1930     // handle them the right number of times.
1931     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1932       FuncInfo->MBB = Succs[i];
1933       FuncInfo->InsertPt = FuncInfo->MBB->end();
1934       // FuncInfo->MBB may have been removed from the CFG if a branch was
1935       // constant folded.
1936       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1937         for (MachineBasicBlock::iterator
1938              MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1939              MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1940           MachineInstrBuilder PHI(*MF, MBBI);
1941           // This value for this PHI node is recorded in PHINodesToUpdate.
1942           for (unsigned pn = 0; ; ++pn) {
1943             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1944                    "Didn't find PHI entry!");
1945             if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1946               PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1947               break;
1948             }
1949           }
1950         }
1951       }
1952     }
1953   }
1954   SDB->SL->SwitchCases.clear();
1955 }
1956 
1957 /// Create the scheduler. If a specific scheduler was specified
1958 /// via the SchedulerRegistry, use it, otherwise select the
1959 /// one preferred by the target.
1960 ///
1961 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1962   return ISHeuristic(this, OptLevel);
1963 }
1964 
1965 //===----------------------------------------------------------------------===//
1966 // Helper functions used by the generated instruction selector.
1967 //===----------------------------------------------------------------------===//
1968 // Calls to these methods are generated by tblgen.
1969 
1970 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1971 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1972 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1973 /// specified in the .td file (e.g. 255).
1974 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1975                                     int64_t DesiredMaskS) const {
1976   const APInt &ActualMask = RHS->getAPIntValue();
1977   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1978 
1979   // If the actual mask exactly matches, success!
1980   if (ActualMask == DesiredMask)
1981     return true;
1982 
1983   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1984   if (!ActualMask.isSubsetOf(DesiredMask))
1985     return false;
1986 
1987   // Otherwise, the DAG Combiner may have proven that the value coming in is
1988   // either already zero or is not demanded.  Check for known zero input bits.
1989   APInt NeededMask = DesiredMask & ~ActualMask;
1990   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1991     return true;
1992 
1993   // TODO: check to see if missing bits are just not demanded.
1994 
1995   // Otherwise, this pattern doesn't match.
1996   return false;
1997 }
1998 
1999 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
2000 /// the dag combiner simplified the 255, we still want to match.  RHS is the
2001 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2002 /// specified in the .td file (e.g. 255).
2003 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
2004                                    int64_t DesiredMaskS) const {
2005   const APInt &ActualMask = RHS->getAPIntValue();
2006   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2007 
2008   // If the actual mask exactly matches, success!
2009   if (ActualMask == DesiredMask)
2010     return true;
2011 
2012   // If the actual AND mask is allowing unallowed bits, this doesn't match.
2013   if (!ActualMask.isSubsetOf(DesiredMask))
2014     return false;
2015 
2016   // Otherwise, the DAG Combiner may have proven that the value coming in is
2017   // either already zero or is not demanded.  Check for known zero input bits.
2018   APInt NeededMask = DesiredMask & ~ActualMask;
2019   KnownBits Known = CurDAG->computeKnownBits(LHS);
2020 
2021   // If all the missing bits in the or are already known to be set, match!
2022   if (NeededMask.isSubsetOf(Known.One))
2023     return true;
2024 
2025   // TODO: check to see if missing bits are just not demanded.
2026 
2027   // Otherwise, this pattern doesn't match.
2028   return false;
2029 }
2030 
2031 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2032 /// by tblgen.  Others should not call it.
2033 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
2034                                                      const SDLoc &DL) {
2035   std::vector<SDValue> InOps;
2036   std::swap(InOps, Ops);
2037 
2038   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
2039   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
2040   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
2041   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
2042 
2043   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
2044   if (InOps[e-1].getValueType() == MVT::Glue)
2045     --e;  // Don't process a glue operand if it is here.
2046 
2047   while (i != e) {
2048     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
2049     if (!InlineAsm::isMemKind(Flags)) {
2050       // Just skip over this operand, copying the operands verbatim.
2051       Ops.insert(Ops.end(), InOps.begin()+i,
2052                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
2053       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
2054     } else {
2055       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
2056              "Memory operand with multiple values?");
2057 
2058       unsigned TiedToOperand;
2059       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
2060         // We need the constraint ID from the operand this is tied to.
2061         unsigned CurOp = InlineAsm::Op_FirstOperand;
2062         Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
2063         for (; TiedToOperand; --TiedToOperand) {
2064           CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
2065           Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
2066         }
2067       }
2068 
2069       // Otherwise, this is a memory operand.  Ask the target to select it.
2070       std::vector<SDValue> SelOps;
2071       unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
2072       if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
2073         report_fatal_error("Could not match memory address.  Inline asm"
2074                            " failure!");
2075 
2076       // Add this to the output node.
2077       unsigned NewFlags =
2078         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
2079       NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
2080       Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
2081       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2082       i += 2;
2083     }
2084   }
2085 
2086   // Add the glue input back if present.
2087   if (e != InOps.size())
2088     Ops.push_back(InOps.back());
2089 }
2090 
2091 /// findGlueUse - Return use of MVT::Glue value produced by the specified
2092 /// SDNode.
2093 ///
2094 static SDNode *findGlueUse(SDNode *N) {
2095   unsigned FlagResNo = N->getNumValues()-1;
2096   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2097     SDUse &Use = I.getUse();
2098     if (Use.getResNo() == FlagResNo)
2099       return Use.getUser();
2100   }
2101   return nullptr;
2102 }
2103 
2104 /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2105 /// beyond "ImmedUse".  We may ignore chains as they are checked separately.
2106 static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2107                           bool IgnoreChains) {
2108   SmallPtrSet<const SDNode *, 16> Visited;
2109   SmallVector<const SDNode *, 16> WorkList;
2110   // Only check if we have non-immediate uses of Def.
2111   if (ImmedUse->isOnlyUserOf(Def))
2112     return false;
2113 
2114   // We don't care about paths to Def that go through ImmedUse so mark it
2115   // visited and mark non-def operands as used.
2116   Visited.insert(ImmedUse);
2117   for (const SDValue &Op : ImmedUse->op_values()) {
2118     SDNode *N = Op.getNode();
2119     // Ignore chain deps (they are validated by
2120     // HandleMergeInputChains) and immediate uses
2121     if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2122       continue;
2123     if (!Visited.insert(N).second)
2124       continue;
2125     WorkList.push_back(N);
2126   }
2127 
2128   // Initialize worklist to operands of Root.
2129   if (Root != ImmedUse) {
2130     for (const SDValue &Op : Root->op_values()) {
2131       SDNode *N = Op.getNode();
2132       // Ignore chains (they are validated by HandleMergeInputChains)
2133       if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2134         continue;
2135       if (!Visited.insert(N).second)
2136         continue;
2137       WorkList.push_back(N);
2138     }
2139   }
2140 
2141   return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2142 }
2143 
2144 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2145 /// operand node N of U during instruction selection that starts at Root.
2146 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
2147                                           SDNode *Root) const {
2148   if (OptLevel == CodeGenOpt::None) return false;
2149   return N.hasOneUse();
2150 }
2151 
2152 /// IsLegalToFold - Returns true if the specific operand node N of
2153 /// U can be folded during instruction selection that starts at Root.
2154 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
2155                                      CodeGenOpt::Level OptLevel,
2156                                      bool IgnoreChains) {
2157   if (OptLevel == CodeGenOpt::None) return false;
2158 
2159   // If Root use can somehow reach N through a path that that doesn't contain
2160   // U then folding N would create a cycle. e.g. In the following
2161   // diagram, Root can reach N through X. If N is folded into Root, then
2162   // X is both a predecessor and a successor of U.
2163   //
2164   //          [N*]           //
2165   //         ^   ^           //
2166   //        /     \          //
2167   //      [U*]    [X]?       //
2168   //        ^     ^          //
2169   //         \   /           //
2170   //          \ /            //
2171   //         [Root*]         //
2172   //
2173   // * indicates nodes to be folded together.
2174   //
2175   // If Root produces glue, then it gets (even more) interesting. Since it
2176   // will be "glued" together with its glue use in the scheduler, we need to
2177   // check if it might reach N.
2178   //
2179   //          [N*]           //
2180   //         ^   ^           //
2181   //        /     \          //
2182   //      [U*]    [X]?       //
2183   //        ^       ^        //
2184   //         \       \       //
2185   //          \      |       //
2186   //         [Root*] |       //
2187   //          ^      |       //
2188   //          f      |       //
2189   //          |      /       //
2190   //         [Y]    /        //
2191   //           ^   /         //
2192   //           f  /          //
2193   //           | /           //
2194   //          [GU]           //
2195   //
2196   // If GU (glue use) indirectly reaches N (the load), and Root folds N
2197   // (call it Fold), then X is a predecessor of GU and a successor of
2198   // Fold. But since Fold and GU are glued together, this will create
2199   // a cycle in the scheduling graph.
2200 
2201   // If the node has glue, walk down the graph to the "lowest" node in the
2202   // glueged set.
2203   EVT VT = Root->getValueType(Root->getNumValues()-1);
2204   while (VT == MVT::Glue) {
2205     SDNode *GU = findGlueUse(Root);
2206     if (!GU)
2207       break;
2208     Root = GU;
2209     VT = Root->getValueType(Root->getNumValues()-1);
2210 
2211     // If our query node has a glue result with a use, we've walked up it.  If
2212     // the user (which has already been selected) has a chain or indirectly uses
2213     // the chain, HandleMergeInputChains will not consider it.  Because of
2214     // this, we cannot ignore chains in this predicate.
2215     IgnoreChains = false;
2216   }
2217 
2218   return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2219 }
2220 
2221 void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2222   SDLoc DL(N);
2223 
2224   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2225   SelectInlineAsmMemoryOperands(Ops, DL);
2226 
2227   const EVT VTs[] = {MVT::Other, MVT::Glue};
2228   SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2229   New->setNodeId(-1);
2230   ReplaceUses(N, New.getNode());
2231   CurDAG->RemoveDeadNode(N);
2232 }
2233 
2234 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2235   SDLoc dl(Op);
2236   MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2237   const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2238 
2239   EVT VT = Op->getValueType(0);
2240   LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2241   Register Reg =
2242       TLI->getRegisterByName(RegStr->getString().data(), Ty,
2243                              CurDAG->getMachineFunction());
2244   SDValue New = CurDAG->getCopyFromReg(
2245                         Op->getOperand(0), dl, Reg, Op->getValueType(0));
2246   New->setNodeId(-1);
2247   ReplaceUses(Op, New.getNode());
2248   CurDAG->RemoveDeadNode(Op);
2249 }
2250 
2251 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2252   SDLoc dl(Op);
2253   MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2254   const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2255 
2256   EVT VT = Op->getOperand(2).getValueType();
2257   LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2258 
2259   Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
2260                                         CurDAG->getMachineFunction());
2261   SDValue New = CurDAG->getCopyToReg(
2262                         Op->getOperand(0), dl, Reg, Op->getOperand(2));
2263   New->setNodeId(-1);
2264   ReplaceUses(Op, New.getNode());
2265   CurDAG->RemoveDeadNode(Op);
2266 }
2267 
2268 void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2269   CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2270 }
2271 
2272 void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2273   // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2274   // If FREEZE instruction is added later, the code below must be changed as
2275   // well.
2276   CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2277                        N->getOperand(0));
2278 }
2279 
2280 /// GetVBR - decode a vbr encoding whose top bit is set.
2281 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t
2282 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2283   assert(Val >= 128 && "Not a VBR");
2284   Val &= 127;  // Remove first vbr bit.
2285 
2286   unsigned Shift = 7;
2287   uint64_t NextBits;
2288   do {
2289     NextBits = MatcherTable[Idx++];
2290     Val |= (NextBits&127) << Shift;
2291     Shift += 7;
2292   } while (NextBits & 128);
2293 
2294   return Val;
2295 }
2296 
2297 /// When a match is complete, this method updates uses of interior chain results
2298 /// to use the new results.
2299 void SelectionDAGISel::UpdateChains(
2300     SDNode *NodeToMatch, SDValue InputChain,
2301     SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2302   SmallVector<SDNode*, 4> NowDeadNodes;
2303 
2304   // Now that all the normal results are replaced, we replace the chain and
2305   // glue results if present.
2306   if (!ChainNodesMatched.empty()) {
2307     assert(InputChain.getNode() &&
2308            "Matched input chains but didn't produce a chain");
2309     // Loop over all of the nodes we matched that produced a chain result.
2310     // Replace all the chain results with the final chain we ended up with.
2311     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2312       SDNode *ChainNode = ChainNodesMatched[i];
2313       // If ChainNode is null, it's because we replaced it on a previous
2314       // iteration and we cleared it out of the map. Just skip it.
2315       if (!ChainNode)
2316         continue;
2317 
2318       assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2319              "Deleted node left in chain");
2320 
2321       // Don't replace the results of the root node if we're doing a
2322       // MorphNodeTo.
2323       if (ChainNode == NodeToMatch && isMorphNodeTo)
2324         continue;
2325 
2326       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2327       if (ChainVal.getValueType() == MVT::Glue)
2328         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2329       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2330       SelectionDAG::DAGNodeDeletedListener NDL(
2331           *CurDAG, [&](SDNode *N, SDNode *E) {
2332             std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2333                          static_cast<SDNode *>(nullptr));
2334           });
2335       if (ChainNode->getOpcode() != ISD::TokenFactor)
2336         ReplaceUses(ChainVal, InputChain);
2337 
2338       // If the node became dead and we haven't already seen it, delete it.
2339       if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2340           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
2341         NowDeadNodes.push_back(ChainNode);
2342     }
2343   }
2344 
2345   if (!NowDeadNodes.empty())
2346     CurDAG->RemoveDeadNodes(NowDeadNodes);
2347 
2348   LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2349 }
2350 
2351 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2352 /// operation for when the pattern matched at least one node with a chains.  The
2353 /// input vector contains a list of all of the chained nodes that we match.  We
2354 /// must determine if this is a valid thing to cover (i.e. matching it won't
2355 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2356 /// be used as the input node chain for the generated nodes.
2357 static SDValue
2358 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2359                        SelectionDAG *CurDAG) {
2360 
2361   SmallPtrSet<const SDNode *, 16> Visited;
2362   SmallVector<const SDNode *, 8> Worklist;
2363   SmallVector<SDValue, 3> InputChains;
2364   unsigned int Max = 8192;
2365 
2366   // Quick exit on trivial merge.
2367   if (ChainNodesMatched.size() == 1)
2368     return ChainNodesMatched[0]->getOperand(0);
2369 
2370   // Add chains that aren't already added (internal). Peek through
2371   // token factors.
2372   std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2373     if (V.getValueType() != MVT::Other)
2374       return;
2375     if (V->getOpcode() == ISD::EntryToken)
2376       return;
2377     if (!Visited.insert(V.getNode()).second)
2378       return;
2379     if (V->getOpcode() == ISD::TokenFactor) {
2380       for (const SDValue &Op : V->op_values())
2381         AddChains(Op);
2382     } else
2383       InputChains.push_back(V);
2384   };
2385 
2386   for (auto *N : ChainNodesMatched) {
2387     Worklist.push_back(N);
2388     Visited.insert(N);
2389   }
2390 
2391   while (!Worklist.empty())
2392     AddChains(Worklist.pop_back_val()->getOperand(0));
2393 
2394   // Skip the search if there are no chain dependencies.
2395   if (InputChains.size() == 0)
2396     return CurDAG->getEntryNode();
2397 
2398   // If one of these chains is a successor of input, we must have a
2399   // node that is both the predecessor and successor of the
2400   // to-be-merged nodes. Fail.
2401   Visited.clear();
2402   for (SDValue V : InputChains)
2403     Worklist.push_back(V.getNode());
2404 
2405   for (auto *N : ChainNodesMatched)
2406     if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2407       return SDValue();
2408 
2409   // Return merged chain.
2410   if (InputChains.size() == 1)
2411     return InputChains[0];
2412   return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2413                          MVT::Other, InputChains);
2414 }
2415 
2416 /// MorphNode - Handle morphing a node in place for the selector.
2417 SDNode *SelectionDAGISel::
2418 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2419           ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2420   // It is possible we're using MorphNodeTo to replace a node with no
2421   // normal results with one that has a normal result (or we could be
2422   // adding a chain) and the input could have glue and chains as well.
2423   // In this case we need to shift the operands down.
2424   // FIXME: This is a horrible hack and broken in obscure cases, no worse
2425   // than the old isel though.
2426   int OldGlueResultNo = -1, OldChainResultNo = -1;
2427 
2428   unsigned NTMNumResults = Node->getNumValues();
2429   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2430     OldGlueResultNo = NTMNumResults-1;
2431     if (NTMNumResults != 1 &&
2432         Node->getValueType(NTMNumResults-2) == MVT::Other)
2433       OldChainResultNo = NTMNumResults-2;
2434   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2435     OldChainResultNo = NTMNumResults-1;
2436 
2437   // Call the underlying SelectionDAG routine to do the transmogrification. Note
2438   // that this deletes operands of the old node that become dead.
2439   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2440 
2441   // MorphNodeTo can operate in two ways: if an existing node with the
2442   // specified operands exists, it can just return it.  Otherwise, it
2443   // updates the node in place to have the requested operands.
2444   if (Res == Node) {
2445     // If we updated the node in place, reset the node ID.  To the isel,
2446     // this should be just like a newly allocated machine node.
2447     Res->setNodeId(-1);
2448   }
2449 
2450   unsigned ResNumResults = Res->getNumValues();
2451   // Move the glue if needed.
2452   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2453       (unsigned)OldGlueResultNo != ResNumResults-1)
2454     ReplaceUses(SDValue(Node, OldGlueResultNo),
2455                 SDValue(Res, ResNumResults - 1));
2456 
2457   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2458     --ResNumResults;
2459 
2460   // Move the chain reference if needed.
2461   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2462       (unsigned)OldChainResultNo != ResNumResults-1)
2463     ReplaceUses(SDValue(Node, OldChainResultNo),
2464                 SDValue(Res, ResNumResults - 1));
2465 
2466   // Otherwise, no replacement happened because the node already exists. Replace
2467   // Uses of the old node with the new one.
2468   if (Res != Node) {
2469     ReplaceNode(Node, Res);
2470   } else {
2471     EnforceNodeIdInvariant(Res);
2472   }
2473 
2474   return Res;
2475 }
2476 
2477 /// CheckSame - Implements OP_CheckSame.
2478 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2479 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2480           SDValue N,
2481           const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2482   // Accept if it is exactly the same as a previously recorded node.
2483   unsigned RecNo = MatcherTable[MatcherIndex++];
2484   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2485   return N == RecordedNodes[RecNo].first;
2486 }
2487 
2488 /// CheckChildSame - Implements OP_CheckChildXSame.
2489 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2490 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2491               SDValue N,
2492               const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes,
2493               unsigned ChildNo) {
2494   if (ChildNo >= N.getNumOperands())
2495     return false;  // Match fails if out of range child #.
2496   return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2497                      RecordedNodes);
2498 }
2499 
2500 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2501 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2502 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2503                       const SelectionDAGISel &SDISel) {
2504   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2505 }
2506 
2507 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2508 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2509 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2510                    const SelectionDAGISel &SDISel, SDNode *N) {
2511   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2512 }
2513 
2514 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2515 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2516             SDNode *N) {
2517   uint16_t Opc = MatcherTable[MatcherIndex++];
2518   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2519   return N->getOpcode() == Opc;
2520 }
2521 
2522 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2523 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2524           const TargetLowering *TLI, const DataLayout &DL) {
2525   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2526   if (N.getValueType() == VT) return true;
2527 
2528   // Handle the case when VT is iPTR.
2529   return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2530 }
2531 
2532 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2533 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2534                SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2535                unsigned ChildNo) {
2536   if (ChildNo >= N.getNumOperands())
2537     return false;  // Match fails if out of range child #.
2538   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2539                      DL);
2540 }
2541 
2542 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2543 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2544               SDValue N) {
2545   return cast<CondCodeSDNode>(N)->get() ==
2546       (ISD::CondCode)MatcherTable[MatcherIndex++];
2547 }
2548 
2549 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2550 CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2551                     SDValue N) {
2552   if (2 >= N.getNumOperands())
2553     return false;
2554   return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
2555 }
2556 
2557 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2558 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2559                SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2560   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2561   if (cast<VTSDNode>(N)->getVT() == VT)
2562     return true;
2563 
2564   // Handle the case when VT is iPTR.
2565   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2566 }
2567 
2568 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2569 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2570              SDValue N) {
2571   int64_t Val = MatcherTable[MatcherIndex++];
2572   if (Val & 128)
2573     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2574 
2575   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2576   return C && C->getSExtValue() == Val;
2577 }
2578 
2579 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2580 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2581                   SDValue N, unsigned ChildNo) {
2582   if (ChildNo >= N.getNumOperands())
2583     return false;  // Match fails if out of range child #.
2584   return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2585 }
2586 
2587 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2588 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2589             SDValue N, const SelectionDAGISel &SDISel) {
2590   int64_t Val = MatcherTable[MatcherIndex++];
2591   if (Val & 128)
2592     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2593 
2594   if (N->getOpcode() != ISD::AND) return false;
2595 
2596   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2597   return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2598 }
2599 
2600 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2601 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2602            SDValue N, const SelectionDAGISel &SDISel) {
2603   int64_t Val = MatcherTable[MatcherIndex++];
2604   if (Val & 128)
2605     Val = GetVBR(Val, MatcherTable, MatcherIndex);
2606 
2607   if (N->getOpcode() != ISD::OR) return false;
2608 
2609   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2610   return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2611 }
2612 
2613 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2614 /// scope, evaluate the current node.  If the current predicate is known to
2615 /// fail, set Result=true and return anything.  If the current predicate is
2616 /// known to pass, set Result=false and return the MatcherIndex to continue
2617 /// with.  If the current predicate is unknown, set Result=false and return the
2618 /// MatcherIndex to continue with.
2619 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2620                                        unsigned Index, SDValue N,
2621                                        bool &Result,
2622                                        const SelectionDAGISel &SDISel,
2623                   SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2624   switch (Table[Index++]) {
2625   default:
2626     Result = false;
2627     return Index-1;  // Could not evaluate this predicate.
2628   case SelectionDAGISel::OPC_CheckSame:
2629     Result = !::CheckSame(Table, Index, N, RecordedNodes);
2630     return Index;
2631   case SelectionDAGISel::OPC_CheckChild0Same:
2632   case SelectionDAGISel::OPC_CheckChild1Same:
2633   case SelectionDAGISel::OPC_CheckChild2Same:
2634   case SelectionDAGISel::OPC_CheckChild3Same:
2635     Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2636                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2637     return Index;
2638   case SelectionDAGISel::OPC_CheckPatternPredicate:
2639     Result = !::CheckPatternPredicate(Table, Index, SDISel);
2640     return Index;
2641   case SelectionDAGISel::OPC_CheckPredicate:
2642     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2643     return Index;
2644   case SelectionDAGISel::OPC_CheckOpcode:
2645     Result = !::CheckOpcode(Table, Index, N.getNode());
2646     return Index;
2647   case SelectionDAGISel::OPC_CheckType:
2648     Result = !::CheckType(Table, Index, N, SDISel.TLI,
2649                           SDISel.CurDAG->getDataLayout());
2650     return Index;
2651   case SelectionDAGISel::OPC_CheckTypeRes: {
2652     unsigned Res = Table[Index++];
2653     Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI,
2654                           SDISel.CurDAG->getDataLayout());
2655     return Index;
2656   }
2657   case SelectionDAGISel::OPC_CheckChild0Type:
2658   case SelectionDAGISel::OPC_CheckChild1Type:
2659   case SelectionDAGISel::OPC_CheckChild2Type:
2660   case SelectionDAGISel::OPC_CheckChild3Type:
2661   case SelectionDAGISel::OPC_CheckChild4Type:
2662   case SelectionDAGISel::OPC_CheckChild5Type:
2663   case SelectionDAGISel::OPC_CheckChild6Type:
2664   case SelectionDAGISel::OPC_CheckChild7Type:
2665     Result = !::CheckChildType(
2666                  Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2667                  Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
2668     return Index;
2669   case SelectionDAGISel::OPC_CheckCondCode:
2670     Result = !::CheckCondCode(Table, Index, N);
2671     return Index;
2672   case SelectionDAGISel::OPC_CheckChild2CondCode:
2673     Result = !::CheckChild2CondCode(Table, Index, N);
2674     return Index;
2675   case SelectionDAGISel::OPC_CheckValueType:
2676     Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2677                                SDISel.CurDAG->getDataLayout());
2678     return Index;
2679   case SelectionDAGISel::OPC_CheckInteger:
2680     Result = !::CheckInteger(Table, Index, N);
2681     return Index;
2682   case SelectionDAGISel::OPC_CheckChild0Integer:
2683   case SelectionDAGISel::OPC_CheckChild1Integer:
2684   case SelectionDAGISel::OPC_CheckChild2Integer:
2685   case SelectionDAGISel::OPC_CheckChild3Integer:
2686   case SelectionDAGISel::OPC_CheckChild4Integer:
2687     Result = !::CheckChildInteger(Table, Index, N,
2688                      Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2689     return Index;
2690   case SelectionDAGISel::OPC_CheckAndImm:
2691     Result = !::CheckAndImm(Table, Index, N, SDISel);
2692     return Index;
2693   case SelectionDAGISel::OPC_CheckOrImm:
2694     Result = !::CheckOrImm(Table, Index, N, SDISel);
2695     return Index;
2696   }
2697 }
2698 
2699 namespace {
2700 
2701 struct MatchScope {
2702   /// FailIndex - If this match fails, this is the index to continue with.
2703   unsigned FailIndex;
2704 
2705   /// NodeStack - The node stack when the scope was formed.
2706   SmallVector<SDValue, 4> NodeStack;
2707 
2708   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2709   unsigned NumRecordedNodes;
2710 
2711   /// NumMatchedMemRefs - The number of matched memref entries.
2712   unsigned NumMatchedMemRefs;
2713 
2714   /// InputChain/InputGlue - The current chain/glue
2715   SDValue InputChain, InputGlue;
2716 
2717   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2718   bool HasChainNodesMatched;
2719 };
2720 
2721 /// \A DAG update listener to keep the matching state
2722 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2723 /// change the DAG while matching.  X86 addressing mode matcher is an example
2724 /// for this.
2725 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2726 {
2727   SDNode **NodeToMatch;
2728   SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
2729   SmallVectorImpl<MatchScope> &MatchScopes;
2730 
2731 public:
2732   MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
2733                     SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
2734                     SmallVectorImpl<MatchScope> &MS)
2735       : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
2736         RecordedNodes(RN), MatchScopes(MS) {}
2737 
2738   void NodeDeleted(SDNode *N, SDNode *E) override {
2739     // Some early-returns here to avoid the search if we deleted the node or
2740     // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2741     // do, so it's unnecessary to update matching state at that point).
2742     // Neither of these can occur currently because we only install this
2743     // update listener during matching a complex patterns.
2744     if (!E || E->isMachineOpcode())
2745       return;
2746     // Check if NodeToMatch was updated.
2747     if (N == *NodeToMatch)
2748       *NodeToMatch = E;
2749     // Performing linear search here does not matter because we almost never
2750     // run this code.  You'd have to have a CSE during complex pattern
2751     // matching.
2752     for (auto &I : RecordedNodes)
2753       if (I.first.getNode() == N)
2754         I.first.setNode(E);
2755 
2756     for (auto &I : MatchScopes)
2757       for (auto &J : I.NodeStack)
2758         if (J.getNode() == N)
2759           J.setNode(E);
2760   }
2761 };
2762 
2763 } // end anonymous namespace
2764 
2765 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
2766                                         const unsigned char *MatcherTable,
2767                                         unsigned TableSize) {
2768   // FIXME: Should these even be selected?  Handle these cases in the caller?
2769   switch (NodeToMatch->getOpcode()) {
2770   default:
2771     break;
2772   case ISD::EntryToken:       // These nodes remain the same.
2773   case ISD::BasicBlock:
2774   case ISD::Register:
2775   case ISD::RegisterMask:
2776   case ISD::HANDLENODE:
2777   case ISD::MDNODE_SDNODE:
2778   case ISD::TargetConstant:
2779   case ISD::TargetConstantFP:
2780   case ISD::TargetConstantPool:
2781   case ISD::TargetFrameIndex:
2782   case ISD::TargetExternalSymbol:
2783   case ISD::MCSymbol:
2784   case ISD::TargetBlockAddress:
2785   case ISD::TargetJumpTable:
2786   case ISD::TargetGlobalTLSAddress:
2787   case ISD::TargetGlobalAddress:
2788   case ISD::TokenFactor:
2789   case ISD::CopyFromReg:
2790   case ISD::CopyToReg:
2791   case ISD::EH_LABEL:
2792   case ISD::ANNOTATION_LABEL:
2793   case ISD::LIFETIME_START:
2794   case ISD::LIFETIME_END:
2795     NodeToMatch->setNodeId(-1); // Mark selected.
2796     return;
2797   case ISD::AssertSext:
2798   case ISD::AssertZext:
2799   case ISD::AssertAlign:
2800     ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
2801     CurDAG->RemoveDeadNode(NodeToMatch);
2802     return;
2803   case ISD::INLINEASM:
2804   case ISD::INLINEASM_BR:
2805     Select_INLINEASM(NodeToMatch);
2806     return;
2807   case ISD::READ_REGISTER:
2808     Select_READ_REGISTER(NodeToMatch);
2809     return;
2810   case ISD::WRITE_REGISTER:
2811     Select_WRITE_REGISTER(NodeToMatch);
2812     return;
2813   case ISD::UNDEF:
2814     Select_UNDEF(NodeToMatch);
2815     return;
2816   case ISD::FREEZE:
2817     Select_FREEZE(NodeToMatch);
2818     return;
2819   }
2820 
2821   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2822 
2823   // Set up the node stack with NodeToMatch as the only node on the stack.
2824   SmallVector<SDValue, 8> NodeStack;
2825   SDValue N = SDValue(NodeToMatch, 0);
2826   NodeStack.push_back(N);
2827 
2828   // MatchScopes - Scopes used when matching, if a match failure happens, this
2829   // indicates where to continue checking.
2830   SmallVector<MatchScope, 8> MatchScopes;
2831 
2832   // RecordedNodes - This is the set of nodes that have been recorded by the
2833   // state machine.  The second value is the parent of the node, or null if the
2834   // root is recorded.
2835   SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2836 
2837   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2838   // pattern.
2839   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2840 
2841   // These are the current input chain and glue for use when generating nodes.
2842   // Various Emit operations change these.  For example, emitting a copytoreg
2843   // uses and updates these.
2844   SDValue InputChain, InputGlue;
2845 
2846   // ChainNodesMatched - If a pattern matches nodes that have input/output
2847   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2848   // which ones they are.  The result is captured into this list so that we can
2849   // update the chain results when the pattern is complete.
2850   SmallVector<SDNode*, 3> ChainNodesMatched;
2851 
2852   LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
2853 
2854   // Determine where to start the interpreter.  Normally we start at opcode #0,
2855   // but if the state machine starts with an OPC_SwitchOpcode, then we
2856   // accelerate the first lookup (which is guaranteed to be hot) with the
2857   // OpcodeOffset table.
2858   unsigned MatcherIndex = 0;
2859 
2860   if (!OpcodeOffset.empty()) {
2861     // Already computed the OpcodeOffset table, just index into it.
2862     if (N.getOpcode() < OpcodeOffset.size())
2863       MatcherIndex = OpcodeOffset[N.getOpcode()];
2864     LLVM_DEBUG(dbgs() << "  Initial Opcode index to " << MatcherIndex << "\n");
2865 
2866   } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2867     // Otherwise, the table isn't computed, but the state machine does start
2868     // with an OPC_SwitchOpcode instruction.  Populate the table now, since this
2869     // is the first time we're selecting an instruction.
2870     unsigned Idx = 1;
2871     while (true) {
2872       // Get the size of this case.
2873       unsigned CaseSize = MatcherTable[Idx++];
2874       if (CaseSize & 128)
2875         CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2876       if (CaseSize == 0) break;
2877 
2878       // Get the opcode, add the index to the table.
2879       uint16_t Opc = MatcherTable[Idx++];
2880       Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2881       if (Opc >= OpcodeOffset.size())
2882         OpcodeOffset.resize((Opc+1)*2);
2883       OpcodeOffset[Opc] = Idx;
2884       Idx += CaseSize;
2885     }
2886 
2887     // Okay, do the lookup for the first opcode.
2888     if (N.getOpcode() < OpcodeOffset.size())
2889       MatcherIndex = OpcodeOffset[N.getOpcode()];
2890   }
2891 
2892   while (true) {
2893     assert(MatcherIndex < TableSize && "Invalid index");
2894 #ifndef NDEBUG
2895     unsigned CurrentOpcodeIndex = MatcherIndex;
2896 #endif
2897     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2898     switch (Opcode) {
2899     case OPC_Scope: {
2900       // Okay, the semantics of this operation are that we should push a scope
2901       // then evaluate the first child.  However, pushing a scope only to have
2902       // the first check fail (which then pops it) is inefficient.  If we can
2903       // determine immediately that the first check (or first several) will
2904       // immediately fail, don't even bother pushing a scope for them.
2905       unsigned FailIndex;
2906 
2907       while (true) {
2908         unsigned NumToSkip = MatcherTable[MatcherIndex++];
2909         if (NumToSkip & 128)
2910           NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2911         // Found the end of the scope with no match.
2912         if (NumToSkip == 0) {
2913           FailIndex = 0;
2914           break;
2915         }
2916 
2917         FailIndex = MatcherIndex+NumToSkip;
2918 
2919         unsigned MatcherIndexOfPredicate = MatcherIndex;
2920         (void)MatcherIndexOfPredicate; // silence warning.
2921 
2922         // If we can't evaluate this predicate without pushing a scope (e.g. if
2923         // it is a 'MoveParent') or if the predicate succeeds on this node, we
2924         // push the scope and evaluate the full predicate chain.
2925         bool Result;
2926         MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2927                                               Result, *this, RecordedNodes);
2928         if (!Result)
2929           break;
2930 
2931         LLVM_DEBUG(
2932             dbgs() << "  Skipped scope entry (due to false predicate) at "
2933                    << "index " << MatcherIndexOfPredicate << ", continuing at "
2934                    << FailIndex << "\n");
2935         ++NumDAGIselRetries;
2936 
2937         // Otherwise, we know that this case of the Scope is guaranteed to fail,
2938         // move to the next case.
2939         MatcherIndex = FailIndex;
2940       }
2941 
2942       // If the whole scope failed to match, bail.
2943       if (FailIndex == 0) break;
2944 
2945       // Push a MatchScope which indicates where to go if the first child fails
2946       // to match.
2947       MatchScope NewEntry;
2948       NewEntry.FailIndex = FailIndex;
2949       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2950       NewEntry.NumRecordedNodes = RecordedNodes.size();
2951       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2952       NewEntry.InputChain = InputChain;
2953       NewEntry.InputGlue = InputGlue;
2954       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2955       MatchScopes.push_back(NewEntry);
2956       continue;
2957     }
2958     case OPC_RecordNode: {
2959       // Remember this node, it may end up being an operand in the pattern.
2960       SDNode *Parent = nullptr;
2961       if (NodeStack.size() > 1)
2962         Parent = NodeStack[NodeStack.size()-2].getNode();
2963       RecordedNodes.push_back(std::make_pair(N, Parent));
2964       continue;
2965     }
2966 
2967     case OPC_RecordChild0: case OPC_RecordChild1:
2968     case OPC_RecordChild2: case OPC_RecordChild3:
2969     case OPC_RecordChild4: case OPC_RecordChild5:
2970     case OPC_RecordChild6: case OPC_RecordChild7: {
2971       unsigned ChildNo = Opcode-OPC_RecordChild0;
2972       if (ChildNo >= N.getNumOperands())
2973         break;  // Match fails if out of range child #.
2974 
2975       RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2976                                              N.getNode()));
2977       continue;
2978     }
2979     case OPC_RecordMemRef:
2980       if (auto *MN = dyn_cast<MemSDNode>(N))
2981         MatchedMemRefs.push_back(MN->getMemOperand());
2982       else {
2983         LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
2984                    dbgs() << '\n');
2985       }
2986 
2987       continue;
2988 
2989     case OPC_CaptureGlueInput:
2990       // If the current node has an input glue, capture it in InputGlue.
2991       if (N->getNumOperands() != 0 &&
2992           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2993         InputGlue = N->getOperand(N->getNumOperands()-1);
2994       continue;
2995 
2996     case OPC_MoveChild: {
2997       unsigned ChildNo = MatcherTable[MatcherIndex++];
2998       if (ChildNo >= N.getNumOperands())
2999         break;  // Match fails if out of range child #.
3000       N = N.getOperand(ChildNo);
3001       NodeStack.push_back(N);
3002       continue;
3003     }
3004 
3005     case OPC_MoveChild0: case OPC_MoveChild1:
3006     case OPC_MoveChild2: case OPC_MoveChild3:
3007     case OPC_MoveChild4: case OPC_MoveChild5:
3008     case OPC_MoveChild6: case OPC_MoveChild7: {
3009       unsigned ChildNo = Opcode-OPC_MoveChild0;
3010       if (ChildNo >= N.getNumOperands())
3011         break;  // Match fails if out of range child #.
3012       N = N.getOperand(ChildNo);
3013       NodeStack.push_back(N);
3014       continue;
3015     }
3016 
3017     case OPC_MoveParent:
3018       // Pop the current node off the NodeStack.
3019       NodeStack.pop_back();
3020       assert(!NodeStack.empty() && "Node stack imbalance!");
3021       N = NodeStack.back();
3022       continue;
3023 
3024     case OPC_CheckSame:
3025       if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3026       continue;
3027 
3028     case OPC_CheckChild0Same: case OPC_CheckChild1Same:
3029     case OPC_CheckChild2Same: case OPC_CheckChild3Same:
3030       if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3031                             Opcode-OPC_CheckChild0Same))
3032         break;
3033       continue;
3034 
3035     case OPC_CheckPatternPredicate:
3036       if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
3037       continue;
3038     case OPC_CheckPredicate:
3039       if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
3040                                 N.getNode()))
3041         break;
3042       continue;
3043     case OPC_CheckPredicateWithOperands: {
3044       unsigned OpNum = MatcherTable[MatcherIndex++];
3045       SmallVector<SDValue, 8> Operands;
3046 
3047       for (unsigned i = 0; i < OpNum; ++i)
3048         Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3049 
3050       unsigned PredNo = MatcherTable[MatcherIndex++];
3051       if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
3052         break;
3053       continue;
3054     }
3055     case OPC_CheckComplexPat: {
3056       unsigned CPNum = MatcherTable[MatcherIndex++];
3057       unsigned RecNo = MatcherTable[MatcherIndex++];
3058       assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3059 
3060       // If target can modify DAG during matching, keep the matching state
3061       // consistent.
3062       std::unique_ptr<MatchStateUpdater> MSU;
3063       if (ComplexPatternFuncMutatesDAG())
3064         MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3065                                         MatchScopes));
3066 
3067       if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3068                                RecordedNodes[RecNo].first, CPNum,
3069                                RecordedNodes))
3070         break;
3071       continue;
3072     }
3073     case OPC_CheckOpcode:
3074       if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3075       continue;
3076 
3077     case OPC_CheckType:
3078       if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3079                        CurDAG->getDataLayout()))
3080         break;
3081       continue;
3082 
3083     case OPC_CheckTypeRes: {
3084       unsigned Res = MatcherTable[MatcherIndex++];
3085       if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI,
3086                        CurDAG->getDataLayout()))
3087         break;
3088       continue;
3089     }
3090 
3091     case OPC_SwitchOpcode: {
3092       unsigned CurNodeOpcode = N.getOpcode();
3093       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3094       unsigned CaseSize;
3095       while (true) {
3096         // Get the size of this case.
3097         CaseSize = MatcherTable[MatcherIndex++];
3098         if (CaseSize & 128)
3099           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3100         if (CaseSize == 0) break;
3101 
3102         uint16_t Opc = MatcherTable[MatcherIndex++];
3103         Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3104 
3105         // If the opcode matches, then we will execute this case.
3106         if (CurNodeOpcode == Opc)
3107           break;
3108 
3109         // Otherwise, skip over this case.
3110         MatcherIndex += CaseSize;
3111       }
3112 
3113       // If no cases matched, bail out.
3114       if (CaseSize == 0) break;
3115 
3116       // Otherwise, execute the case we found.
3117       LLVM_DEBUG(dbgs() << "  OpcodeSwitch from " << SwitchStart << " to "
3118                         << MatcherIndex << "\n");
3119       continue;
3120     }
3121 
3122     case OPC_SwitchType: {
3123       MVT CurNodeVT = N.getSimpleValueType();
3124       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3125       unsigned CaseSize;
3126       while (true) {
3127         // Get the size of this case.
3128         CaseSize = MatcherTable[MatcherIndex++];
3129         if (CaseSize & 128)
3130           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3131         if (CaseSize == 0) break;
3132 
3133         MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3134         if (CaseVT == MVT::iPTR)
3135           CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3136 
3137         // If the VT matches, then we will execute this case.
3138         if (CurNodeVT == CaseVT)
3139           break;
3140 
3141         // Otherwise, skip over this case.
3142         MatcherIndex += CaseSize;
3143       }
3144 
3145       // If no cases matched, bail out.
3146       if (CaseSize == 0) break;
3147 
3148       // Otherwise, execute the case we found.
3149       LLVM_DEBUG(dbgs() << "  TypeSwitch[" << EVT(CurNodeVT).getEVTString()
3150                         << "] from " << SwitchStart << " to " << MatcherIndex
3151                         << '\n');
3152       continue;
3153     }
3154     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
3155     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
3156     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
3157     case OPC_CheckChild6Type: case OPC_CheckChild7Type:
3158       if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3159                             CurDAG->getDataLayout(),
3160                             Opcode - OPC_CheckChild0Type))
3161         break;
3162       continue;
3163     case OPC_CheckCondCode:
3164       if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3165       continue;
3166     case OPC_CheckChild2CondCode:
3167       if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3168       continue;
3169     case OPC_CheckValueType:
3170       if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3171                             CurDAG->getDataLayout()))
3172         break;
3173       continue;
3174     case OPC_CheckInteger:
3175       if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3176       continue;
3177     case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
3178     case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
3179     case OPC_CheckChild4Integer:
3180       if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3181                                Opcode-OPC_CheckChild0Integer)) break;
3182       continue;
3183     case OPC_CheckAndImm:
3184       if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3185       continue;
3186     case OPC_CheckOrImm:
3187       if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3188       continue;
3189     case OPC_CheckImmAllOnesV:
3190       if (!ISD::isBuildVectorAllOnes(N.getNode())) break;
3191       continue;
3192     case OPC_CheckImmAllZerosV:
3193       if (!ISD::isBuildVectorAllZeros(N.getNode())) break;
3194       continue;
3195 
3196     case OPC_CheckFoldableChainNode: {
3197       assert(NodeStack.size() != 1 && "No parent node");
3198       // Verify that all intermediate nodes between the root and this one have
3199       // a single use (ignoring chains, which are handled in UpdateChains).
3200       bool HasMultipleUses = false;
3201       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3202         unsigned NNonChainUses = 0;
3203         SDNode *NS = NodeStack[i].getNode();
3204         for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
3205           if (UI.getUse().getValueType() != MVT::Other)
3206             if (++NNonChainUses > 1) {
3207               HasMultipleUses = true;
3208               break;
3209             }
3210         if (HasMultipleUses) break;
3211       }
3212       if (HasMultipleUses) break;
3213 
3214       // Check to see that the target thinks this is profitable to fold and that
3215       // we can fold it without inducing cycles in the graph.
3216       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3217                               NodeToMatch) ||
3218           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3219                          NodeToMatch, OptLevel,
3220                          true/*We validate our own chains*/))
3221         break;
3222 
3223       continue;
3224     }
3225     case OPC_EmitInteger: {
3226       MVT::SimpleValueType VT =
3227         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3228       int64_t Val = MatcherTable[MatcherIndex++];
3229       if (Val & 128)
3230         Val = GetVBR(Val, MatcherTable, MatcherIndex);
3231       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3232                               CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3233                                                         VT), nullptr));
3234       continue;
3235     }
3236     case OPC_EmitRegister: {
3237       MVT::SimpleValueType VT =
3238         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3239       unsigned RegNo = MatcherTable[MatcherIndex++];
3240       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3241                               CurDAG->getRegister(RegNo, VT), nullptr));
3242       continue;
3243     }
3244     case OPC_EmitRegister2: {
3245       // For targets w/ more than 256 register names, the register enum
3246       // values are stored in two bytes in the matcher table (just like
3247       // opcodes).
3248       MVT::SimpleValueType VT =
3249         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3250       unsigned RegNo = MatcherTable[MatcherIndex++];
3251       RegNo |= MatcherTable[MatcherIndex++] << 8;
3252       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3253                               CurDAG->getRegister(RegNo, VT), nullptr));
3254       continue;
3255     }
3256 
3257     case OPC_EmitConvertToTarget:  {
3258       // Convert from IMM/FPIMM to target version.
3259       unsigned RecNo = MatcherTable[MatcherIndex++];
3260       assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3261       SDValue Imm = RecordedNodes[RecNo].first;
3262 
3263       if (Imm->getOpcode() == ISD::Constant) {
3264         const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3265         Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3266                                         Imm.getValueType());
3267       } else if (Imm->getOpcode() == ISD::ConstantFP) {
3268         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3269         Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3270                                           Imm.getValueType());
3271       }
3272 
3273       RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3274       continue;
3275     }
3276 
3277     case OPC_EmitMergeInputChains1_0:    // OPC_EmitMergeInputChains, 1, 0
3278     case OPC_EmitMergeInputChains1_1:    // OPC_EmitMergeInputChains, 1, 1
3279     case OPC_EmitMergeInputChains1_2: {  // OPC_EmitMergeInputChains, 1, 2
3280       // These are space-optimized forms of OPC_EmitMergeInputChains.
3281       assert(!InputChain.getNode() &&
3282              "EmitMergeInputChains should be the first chain producing node");
3283       assert(ChainNodesMatched.empty() &&
3284              "Should only have one EmitMergeInputChains per match");
3285 
3286       // Read all of the chained nodes.
3287       unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3288       assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3289       ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3290 
3291       // FIXME: What if other value results of the node have uses not matched
3292       // by this pattern?
3293       if (ChainNodesMatched.back() != NodeToMatch &&
3294           !RecordedNodes[RecNo].first.hasOneUse()) {
3295         ChainNodesMatched.clear();
3296         break;
3297       }
3298 
3299       // Merge the input chains if they are not intra-pattern references.
3300       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3301 
3302       if (!InputChain.getNode())
3303         break;  // Failed to merge.
3304       continue;
3305     }
3306 
3307     case OPC_EmitMergeInputChains: {
3308       assert(!InputChain.getNode() &&
3309              "EmitMergeInputChains should be the first chain producing node");
3310       // This node gets a list of nodes we matched in the input that have
3311       // chains.  We want to token factor all of the input chains to these nodes
3312       // together.  However, if any of the input chains is actually one of the
3313       // nodes matched in this pattern, then we have an intra-match reference.
3314       // Ignore these because the newly token factored chain should not refer to
3315       // the old nodes.
3316       unsigned NumChains = MatcherTable[MatcherIndex++];
3317       assert(NumChains != 0 && "Can't TF zero chains");
3318 
3319       assert(ChainNodesMatched.empty() &&
3320              "Should only have one EmitMergeInputChains per match");
3321 
3322       // Read all of the chained nodes.
3323       for (unsigned i = 0; i != NumChains; ++i) {
3324         unsigned RecNo = MatcherTable[MatcherIndex++];
3325         assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3326         ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3327 
3328         // FIXME: What if other value results of the node have uses not matched
3329         // by this pattern?
3330         if (ChainNodesMatched.back() != NodeToMatch &&
3331             !RecordedNodes[RecNo].first.hasOneUse()) {
3332           ChainNodesMatched.clear();
3333           break;
3334         }
3335       }
3336 
3337       // If the inner loop broke out, the match fails.
3338       if (ChainNodesMatched.empty())
3339         break;
3340 
3341       // Merge the input chains if they are not intra-pattern references.
3342       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3343 
3344       if (!InputChain.getNode())
3345         break;  // Failed to merge.
3346 
3347       continue;
3348     }
3349 
3350     case OPC_EmitCopyToReg:
3351     case OPC_EmitCopyToReg2: {
3352       unsigned RecNo = MatcherTable[MatcherIndex++];
3353       assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3354       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3355       if (Opcode == OPC_EmitCopyToReg2)
3356         DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
3357 
3358       if (!InputChain.getNode())
3359         InputChain = CurDAG->getEntryNode();
3360 
3361       InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3362                                         DestPhysReg, RecordedNodes[RecNo].first,
3363                                         InputGlue);
3364 
3365       InputGlue = InputChain.getValue(1);
3366       continue;
3367     }
3368 
3369     case OPC_EmitNodeXForm: {
3370       unsigned XFormNo = MatcherTable[MatcherIndex++];
3371       unsigned RecNo = MatcherTable[MatcherIndex++];
3372       assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3373       SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3374       RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3375       continue;
3376     }
3377     case OPC_Coverage: {
3378       // This is emitted right before MorphNode/EmitNode.
3379       // So it should be safe to assume that this node has been selected
3380       unsigned index = MatcherTable[MatcherIndex++];
3381       index |= (MatcherTable[MatcherIndex++] << 8);
3382       dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3383       dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3384       continue;
3385     }
3386 
3387     case OPC_EmitNode:     case OPC_MorphNodeTo:
3388     case OPC_EmitNode0:    case OPC_EmitNode1:    case OPC_EmitNode2:
3389     case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: {
3390       uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3391       TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3392       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3393       // Get the result VT list.
3394       unsigned NumVTs;
3395       // If this is one of the compressed forms, get the number of VTs based
3396       // on the Opcode. Otherwise read the next byte from the table.
3397       if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
3398         NumVTs = Opcode - OPC_MorphNodeTo0;
3399       else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
3400         NumVTs = Opcode - OPC_EmitNode0;
3401       else
3402         NumVTs = MatcherTable[MatcherIndex++];
3403       SmallVector<EVT, 4> VTs;
3404       for (unsigned i = 0; i != NumVTs; ++i) {
3405         MVT::SimpleValueType VT =
3406           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3407         if (VT == MVT::iPTR)
3408           VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3409         VTs.push_back(VT);
3410       }
3411 
3412       if (EmitNodeInfo & OPFL_Chain)
3413         VTs.push_back(MVT::Other);
3414       if (EmitNodeInfo & OPFL_GlueOutput)
3415         VTs.push_back(MVT::Glue);
3416 
3417       // This is hot code, so optimize the two most common cases of 1 and 2
3418       // results.
3419       SDVTList VTList;
3420       if (VTs.size() == 1)
3421         VTList = CurDAG->getVTList(VTs[0]);
3422       else if (VTs.size() == 2)
3423         VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3424       else
3425         VTList = CurDAG->getVTList(VTs);
3426 
3427       // Get the operand list.
3428       unsigned NumOps = MatcherTable[MatcherIndex++];
3429       SmallVector<SDValue, 8> Ops;
3430       for (unsigned i = 0; i != NumOps; ++i) {
3431         unsigned RecNo = MatcherTable[MatcherIndex++];
3432         if (RecNo & 128)
3433           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3434 
3435         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3436         Ops.push_back(RecordedNodes[RecNo].first);
3437       }
3438 
3439       // If there are variadic operands to add, handle them now.
3440       if (EmitNodeInfo & OPFL_VariadicInfo) {
3441         // Determine the start index to copy from.
3442         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3443         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3444         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3445                "Invalid variadic node");
3446         // Copy all of the variadic operands, not including a potential glue
3447         // input.
3448         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3449              i != e; ++i) {
3450           SDValue V = NodeToMatch->getOperand(i);
3451           if (V.getValueType() == MVT::Glue) break;
3452           Ops.push_back(V);
3453         }
3454       }
3455 
3456       // If this has chain/glue inputs, add them.
3457       if (EmitNodeInfo & OPFL_Chain)
3458         Ops.push_back(InputChain);
3459       if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3460         Ops.push_back(InputGlue);
3461 
3462       // Check whether any matched node could raise an FP exception.  Since all
3463       // such nodes must have a chain, it suffices to check ChainNodesMatched.
3464       // We need to perform this check before potentially modifying one of the
3465       // nodes via MorphNode.
3466       bool MayRaiseFPException = false;
3467       for (auto *N : ChainNodesMatched)
3468         if (mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept()) {
3469           MayRaiseFPException = true;
3470           break;
3471         }
3472 
3473       // Create the node.
3474       MachineSDNode *Res = nullptr;
3475       bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
3476                      (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
3477       if (!IsMorphNodeTo) {
3478         // If this is a normal EmitNode command, just create the new node and
3479         // add the results to the RecordedNodes list.
3480         Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3481                                      VTList, Ops);
3482 
3483         // Add all the non-glue/non-chain results to the RecordedNodes list.
3484         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3485           if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3486           RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3487                                                              nullptr));
3488         }
3489       } else {
3490         assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
3491                "NodeToMatch was removed partway through selection");
3492         SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
3493                                                               SDNode *E) {
3494           CurDAG->salvageDebugInfo(*N);
3495           auto &Chain = ChainNodesMatched;
3496           assert((!E || !is_contained(Chain, N)) &&
3497                  "Chain node replaced during MorphNode");
3498           Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end());
3499         });
3500         Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
3501                                             Ops, EmitNodeInfo));
3502       }
3503 
3504       // Set the NoFPExcept flag when no original matched node could
3505       // raise an FP exception, but the new node potentially might.
3506       if (!MayRaiseFPException && mayRaiseFPException(Res)) {
3507         SDNodeFlags Flags = Res->getFlags();
3508         Flags.setNoFPExcept(true);
3509         Res->setFlags(Flags);
3510       }
3511 
3512       // If the node had chain/glue results, update our notion of the current
3513       // chain and glue.
3514       if (EmitNodeInfo & OPFL_GlueOutput) {
3515         InputGlue = SDValue(Res, VTs.size()-1);
3516         if (EmitNodeInfo & OPFL_Chain)
3517           InputChain = SDValue(Res, VTs.size()-2);
3518       } else if (EmitNodeInfo & OPFL_Chain)
3519         InputChain = SDValue(Res, VTs.size()-1);
3520 
3521       // If the OPFL_MemRefs glue is set on this node, slap all of the
3522       // accumulated memrefs onto it.
3523       //
3524       // FIXME: This is vastly incorrect for patterns with multiple outputs
3525       // instructions that access memory and for ComplexPatterns that match
3526       // loads.
3527       if (EmitNodeInfo & OPFL_MemRefs) {
3528         // Only attach load or store memory operands if the generated
3529         // instruction may load or store.
3530         const MCInstrDesc &MCID = TII->get(TargetOpc);
3531         bool mayLoad = MCID.mayLoad();
3532         bool mayStore = MCID.mayStore();
3533 
3534         // We expect to have relatively few of these so just filter them into a
3535         // temporary buffer so that we can easily add them to the instruction.
3536         SmallVector<MachineMemOperand *, 4> FilteredMemRefs;
3537         for (MachineMemOperand *MMO : MatchedMemRefs) {
3538           if (MMO->isLoad()) {
3539             if (mayLoad)
3540               FilteredMemRefs.push_back(MMO);
3541           } else if (MMO->isStore()) {
3542             if (mayStore)
3543               FilteredMemRefs.push_back(MMO);
3544           } else {
3545             FilteredMemRefs.push_back(MMO);
3546           }
3547         }
3548 
3549         CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
3550       }
3551 
3552       LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
3553                      << "  Dropping mem operands\n";
3554                  dbgs() << "  " << (IsMorphNodeTo ? "Morphed" : "Created")
3555                         << " node: ";
3556                  Res->dump(CurDAG););
3557 
3558       // If this was a MorphNodeTo then we're completely done!
3559       if (IsMorphNodeTo) {
3560         // Update chain uses.
3561         UpdateChains(Res, InputChain, ChainNodesMatched, true);
3562         return;
3563       }
3564       continue;
3565     }
3566 
3567     case OPC_CompleteMatch: {
3568       // The match has been completed, and any new nodes (if any) have been
3569       // created.  Patch up references to the matched dag to use the newly
3570       // created nodes.
3571       unsigned NumResults = MatcherTable[MatcherIndex++];
3572 
3573       for (unsigned i = 0; i != NumResults; ++i) {
3574         unsigned ResSlot = MatcherTable[MatcherIndex++];
3575         if (ResSlot & 128)
3576           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3577 
3578         assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3579         SDValue Res = RecordedNodes[ResSlot].first;
3580 
3581         assert(i < NodeToMatch->getNumValues() &&
3582                NodeToMatch->getValueType(i) != MVT::Other &&
3583                NodeToMatch->getValueType(i) != MVT::Glue &&
3584                "Invalid number of results to complete!");
3585         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3586                 NodeToMatch->getValueType(i) == MVT::iPTR ||
3587                 Res.getValueType() == MVT::iPTR ||
3588                 NodeToMatch->getValueType(i).getSizeInBits() ==
3589                     Res.getValueSizeInBits()) &&
3590                "invalid replacement");
3591         ReplaceUses(SDValue(NodeToMatch, i), Res);
3592       }
3593 
3594       // Update chain uses.
3595       UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
3596 
3597       // If the root node defines glue, we need to update it to the glue result.
3598       // TODO: This never happens in our tests and I think it can be removed /
3599       // replaced with an assert, but if we do it this the way the change is
3600       // NFC.
3601       if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
3602               MVT::Glue &&
3603           InputGlue.getNode())
3604         ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
3605                     InputGlue);
3606 
3607       assert(NodeToMatch->use_empty() &&
3608              "Didn't replace all uses of the node?");
3609       CurDAG->RemoveDeadNode(NodeToMatch);
3610 
3611       return;
3612     }
3613     }
3614 
3615     // If the code reached this point, then the match failed.  See if there is
3616     // another child to try in the current 'Scope', otherwise pop it until we
3617     // find a case to check.
3618     LLVM_DEBUG(dbgs() << "  Match failed at index " << CurrentOpcodeIndex
3619                       << "\n");
3620     ++NumDAGIselRetries;
3621     while (true) {
3622       if (MatchScopes.empty()) {
3623         CannotYetSelect(NodeToMatch);
3624         return;
3625       }
3626 
3627       // Restore the interpreter state back to the point where the scope was
3628       // formed.
3629       MatchScope &LastScope = MatchScopes.back();
3630       RecordedNodes.resize(LastScope.NumRecordedNodes);
3631       NodeStack.clear();
3632       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3633       N = NodeStack.back();
3634 
3635       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3636         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3637       MatcherIndex = LastScope.FailIndex;
3638 
3639       LLVM_DEBUG(dbgs() << "  Continuing at " << MatcherIndex << "\n");
3640 
3641       InputChain = LastScope.InputChain;
3642       InputGlue = LastScope.InputGlue;
3643       if (!LastScope.HasChainNodesMatched)
3644         ChainNodesMatched.clear();
3645 
3646       // Check to see what the offset is at the new MatcherIndex.  If it is zero
3647       // we have reached the end of this scope, otherwise we have another child
3648       // in the current scope to try.
3649       unsigned NumToSkip = MatcherTable[MatcherIndex++];
3650       if (NumToSkip & 128)
3651         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3652 
3653       // If we have another child in this scope to match, update FailIndex and
3654       // try it.
3655       if (NumToSkip != 0) {
3656         LastScope.FailIndex = MatcherIndex+NumToSkip;
3657         break;
3658       }
3659 
3660       // End of this scope, pop it and try the next child in the containing
3661       // scope.
3662       MatchScopes.pop_back();
3663     }
3664   }
3665 }
3666 
3667 /// Return whether the node may raise an FP exception.
3668 bool SelectionDAGISel::mayRaiseFPException(SDNode *N) const {
3669   // For machine opcodes, consult the MCID flag.
3670   if (N->isMachineOpcode()) {
3671     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
3672     return MCID.mayRaiseFPException();
3673   }
3674 
3675   // For ISD opcodes, only StrictFP opcodes may raise an FP
3676   // exception.
3677   if (N->isTargetOpcode())
3678     return N->isTargetStrictFPOpcode();
3679   return N->isStrictFPOpcode();
3680 }
3681 
3682 bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
3683   assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
3684   auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3685   if (!C)
3686     return false;
3687 
3688   // Detect when "or" is used to add an offset to a stack object.
3689   if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
3690     MachineFrameInfo &MFI = MF->getFrameInfo();
3691     Align A = MFI.getObjectAlign(FN->getIndex());
3692     int32_t Off = C->getSExtValue();
3693     // If the alleged offset fits in the zero bits guaranteed by
3694     // the alignment, then this or is really an add.
3695     return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
3696   }
3697   return false;
3698 }
3699 
3700 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3701   std::string msg;
3702   raw_string_ostream Msg(msg);
3703   Msg << "Cannot select: ";
3704 
3705   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3706       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3707       N->getOpcode() != ISD::INTRINSIC_VOID) {
3708     N->printrFull(Msg, CurDAG);
3709     Msg << "\nIn function: " << MF->getName();
3710   } else {
3711     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3712     unsigned iid =
3713       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3714     if (iid < Intrinsic::num_intrinsics)
3715       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None);
3716     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3717       Msg << "target intrinsic %" << TII->getName(iid);
3718     else
3719       Msg << "unknown intrinsic #" << iid;
3720   }
3721   report_fatal_error(Msg.str());
3722 }
3723 
3724 char SelectionDAGISel::ID = 0;
3725