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