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