1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuilder.h"
17 #include "FunctionLoweringInfo.h"
18 #include "llvm/CodeGen/SelectionDAGISel.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/DebugInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetIntrinsicInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ADT/Statistic.h"
53 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
54 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
57 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
58 cl::desc("Enable verbose messages in the \"fast\" "
59 "instruction selector"));
61 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
62 cl::desc("Enable abort calls when \"fast\" instruction fails"));
66 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
67 cl::desc("Pop up a window to show dags before the first "
70 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
71 cl::desc("Pop up a window to show dags before legalize types"));
73 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
74 cl::desc("Pop up a window to show dags before legalize"));
76 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before the second "
80 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
81 cl::desc("Pop up a window to show dags before the post legalize types"
82 " dag combine pass"));
84 ViewISelDAGs("view-isel-dags", cl::Hidden,
85 cl::desc("Pop up a window to show isel dags as they are selected"));
87 ViewSchedDAGs("view-sched-dags", cl::Hidden,
88 cl::desc("Pop up a window to show sched dags as they are processed"));
90 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
91 cl::desc("Pop up a window to show SUnit dags after they are processed"));
93 static const bool ViewDAGCombine1 = false,
94 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
95 ViewDAGCombine2 = false,
96 ViewDAGCombineLT = false,
97 ViewISelDAGs = false, ViewSchedDAGs = false,
98 ViewSUnitDAGs = false;
101 //===---------------------------------------------------------------------===//
103 /// RegisterScheduler class - Track the registration of instruction schedulers.
105 //===---------------------------------------------------------------------===//
106 MachinePassRegistry RegisterScheduler::Registry;
108 //===---------------------------------------------------------------------===//
110 /// ISHeuristic command line option for instruction schedulers.
112 //===---------------------------------------------------------------------===//
113 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
114 RegisterPassParser<RegisterScheduler> >
115 ISHeuristic("pre-RA-sched",
116 cl::init(&createDefaultScheduler),
117 cl::desc("Instruction schedulers available (before register"
120 static RegisterScheduler
121 defaultListDAGScheduler("default", "Best scheduler for the target",
122 createDefaultScheduler);
125 //===--------------------------------------------------------------------===//
126 /// createDefaultScheduler - This creates an instruction scheduler appropriate
128 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
129 CodeGenOpt::Level OptLevel) {
130 const TargetLowering &TLI = IS->getTargetLowering();
132 if (OptLevel == CodeGenOpt::None)
133 return createFastDAGScheduler(IS, OptLevel);
134 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
135 return createTDListDAGScheduler(IS, OptLevel);
136 assert(TLI.getSchedulingPreference() ==
137 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
138 return createBURRListDAGScheduler(IS, OptLevel);
142 // EmitInstrWithCustomInserter - This method should be implemented by targets
143 // that mark instructions with the 'usesCustomInserter' flag. These
144 // instructions are special in various ways, which require special support to
145 // insert. The specified MachineInstr is created but not inserted into any
146 // basic blocks, and this method is called to expand it into a sequence of
147 // instructions, potentially also creating new basic blocks and control flow.
148 // When new basic blocks are inserted and the edges from MBB to its successors
149 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
151 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
152 MachineBasicBlock *MBB,
153 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
155 dbgs() << "If a target marks an instruction with "
156 "'usesCustomInserter', it must implement "
157 "TargetLowering::EmitInstrWithCustomInserter!";
163 //===----------------------------------------------------------------------===//
164 // SelectionDAGISel code
165 //===----------------------------------------------------------------------===//
167 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
168 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
169 FuncInfo(new FunctionLoweringInfo(TLI)),
170 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
171 SDB(new SelectionDAGBuilder(*CurDAG, TLI, *FuncInfo, OL)),
177 SelectionDAGISel::~SelectionDAGISel() {
183 unsigned SelectionDAGISel::MakeReg(EVT VT) {
184 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
187 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
188 AU.addRequired<AliasAnalysis>();
189 AU.addPreserved<AliasAnalysis>();
190 AU.addRequired<GCModuleInfo>();
191 AU.addPreserved<GCModuleInfo>();
192 MachineFunctionPass::getAnalysisUsage(AU);
195 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
196 // Do some sanity-checking on the command-line options.
197 assert((!EnableFastISelVerbose || EnableFastISel) &&
198 "-fast-isel-verbose requires -fast-isel");
199 assert((!EnableFastISelAbort || EnableFastISel) &&
200 "-fast-isel-abort requires -fast-isel");
202 Function &Fn = *mf.getFunction();
203 const TargetInstrInfo &TII = *TM.getInstrInfo();
204 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
207 RegInfo = &MF->getRegInfo();
208 AA = &getAnalysis<AliasAnalysis>();
209 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
211 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
214 FuncInfo->set(Fn, *MF, EnableFastISel);
217 SelectAllBasicBlocks(Fn, *MF, TII);
219 // If the first basic block in the function has live ins that need to be
220 // copied into vregs, emit the copies into the top of the block before
221 // emitting the code for the block.
222 RegInfo->EmitLiveInCopies(MF->begin(), TRI, TII);
225 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
226 "Not all catch info was assigned to a landing pad!");
229 // Release function-specific state. SDB and CurDAG are already cleared
236 /// SetDebugLoc - Update MF's and SDB's DebugLocs if debug information is
237 /// attached with this instruction.
238 static void SetDebugLoc(Instruction *I, SelectionDAGBuilder *SDB,
239 FastISel *FastIS, MachineFunction *MF) {
240 DebugLoc DL = I->getDebugLoc();
241 if (DL.isUnknown()) return;
243 SDB->setCurDebugLoc(DL);
246 FastIS->setCurDebugLoc(DL);
248 // If the function doesn't have a default debug location yet, set
249 // it. This is kind of a hack.
250 if (MF->getDefaultDebugLoc().isUnknown())
251 MF->setDefaultDebugLoc(DL);
254 /// ResetDebugLoc - Set MF's and SDB's DebugLocs to Unknown.
255 static void ResetDebugLoc(SelectionDAGBuilder *SDB, FastISel *FastIS) {
256 SDB->setCurDebugLoc(DebugLoc());
258 FastIS->setCurDebugLoc(DebugLoc());
261 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
262 BasicBlock::iterator Begin,
263 BasicBlock::iterator End,
265 SDB->setCurrentBasicBlock(BB);
267 // Lower all of the non-terminator instructions. If a call is emitted
268 // as a tail call, cease emitting nodes for this block.
269 for (BasicBlock::iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
270 SetDebugLoc(I, SDB, 0, MF);
272 if (!isa<TerminatorInst>(I)) {
275 // Set the current debug location back to "unknown" so that it doesn't
276 // spuriously apply to subsequent instructions.
277 ResetDebugLoc(SDB, 0);
281 if (!SDB->HasTailCall) {
282 // Ensure that all instructions which are used outside of their defining
283 // blocks are available as virtual registers. Invoke is handled elsewhere.
284 for (BasicBlock::iterator I = Begin; I != End; ++I)
285 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
286 SDB->CopyToExportRegsIfNeeded(I);
288 // Handle PHI nodes in successor blocks.
289 if (End == LLVMBB->end()) {
290 HandlePHINodesInSuccessorBlocks(LLVMBB);
292 // Lower the terminator after the copies are emitted.
293 SetDebugLoc(LLVMBB->getTerminator(), SDB, 0, MF);
294 SDB->visit(*LLVMBB->getTerminator());
295 ResetDebugLoc(SDB, 0);
299 // Make sure the root of the DAG is up-to-date.
300 CurDAG->setRoot(SDB->getControlRoot());
302 // Final step, emit the lowered DAG as machine code.
304 HadTailCall = SDB->HasTailCall;
309 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
310 /// nodes from the worklist.
311 class SDOPsWorkListRemover : public SelectionDAG::DAGUpdateListener {
312 SmallVector<SDNode*, 128> &Worklist;
313 SmallPtrSet<SDNode*, 128> &InWorklist;
315 SDOPsWorkListRemover(SmallVector<SDNode*, 128> &wl,
316 SmallPtrSet<SDNode*, 128> &inwl)
317 : Worklist(wl), InWorklist(inwl) {}
319 void RemoveFromWorklist(SDNode *N) {
320 if (!InWorklist.erase(N)) return;
322 SmallVector<SDNode*, 128>::iterator I =
323 std::find(Worklist.begin(), Worklist.end(), N);
324 assert(I != Worklist.end() && "Not in worklist");
326 *I = Worklist.back();
330 virtual void NodeDeleted(SDNode *N, SDNode *E) {
331 RemoveFromWorklist(N);
334 virtual void NodeUpdated(SDNode *N) {
340 /// TrivialTruncElim - Eliminate some trivial nops that can result from
341 /// ShrinkDemandedOps: (trunc (ext n)) -> n.
342 static bool TrivialTruncElim(SDValue Op,
343 TargetLowering::TargetLoweringOpt &TLO) {
344 SDValue N0 = Op.getOperand(0);
345 EVT VT = Op.getValueType();
346 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
347 N0.getOpcode() == ISD::SIGN_EXTEND ||
348 N0.getOpcode() == ISD::ANY_EXTEND) &&
349 N0.getOperand(0).getValueType() == VT) {
350 return TLO.CombineTo(Op, N0.getOperand(0));
355 /// ShrinkDemandedOps - A late transformation pass that shrink expressions
356 /// using TargetLowering::TargetLoweringOpt::ShrinkDemandedOp. It converts
357 /// x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
358 void SelectionDAGISel::ShrinkDemandedOps() {
359 SmallVector<SDNode*, 128> Worklist;
360 SmallPtrSet<SDNode*, 128> InWorklist;
362 // Add all the dag nodes to the worklist.
363 Worklist.reserve(CurDAG->allnodes_size());
364 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
365 E = CurDAG->allnodes_end(); I != E; ++I) {
366 Worklist.push_back(I);
367 InWorklist.insert(I);
370 TargetLowering::TargetLoweringOpt TLO(*CurDAG, true);
371 while (!Worklist.empty()) {
372 SDNode *N = Worklist.pop_back_val();
375 if (N->use_empty() && N != CurDAG->getRoot().getNode()) {
376 // Deleting this node may make its operands dead, add them to the worklist
377 // if they aren't already there.
378 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
379 if (InWorklist.insert(N->getOperand(i).getNode()))
380 Worklist.push_back(N->getOperand(i).getNode());
382 CurDAG->DeleteNode(N);
386 // Run ShrinkDemandedOp on scalar binary operations.
387 if (N->getNumValues() != 1 ||
388 !N->getValueType(0).isSimple() || !N->getValueType(0).isInteger())
391 unsigned BitWidth = N->getValueType(0).getScalarType().getSizeInBits();
392 APInt Demanded = APInt::getAllOnesValue(BitWidth);
393 APInt KnownZero, KnownOne;
394 if (!TLI.SimplifyDemandedBits(SDValue(N, 0), Demanded,
395 KnownZero, KnownOne, TLO) &&
396 (N->getOpcode() != ISD::TRUNCATE ||
397 !TrivialTruncElim(SDValue(N, 0), TLO)))
401 assert(!InWorklist.count(N) && "Already in worklist");
402 Worklist.push_back(N);
403 InWorklist.insert(N);
405 // Replace the old value with the new one.
406 DEBUG(errs() << "\nShrinkDemandedOps replacing ";
407 TLO.Old.getNode()->dump(CurDAG);
408 errs() << "\nWith: ";
409 TLO.New.getNode()->dump(CurDAG);
412 if (InWorklist.insert(TLO.New.getNode()))
413 Worklist.push_back(TLO.New.getNode());
415 SDOPsWorkListRemover DeadNodes(Worklist, InWorklist);
416 CurDAG->ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
418 if (!TLO.Old.getNode()->use_empty()) continue;
420 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands();
422 SDNode *OpNode = TLO.Old.getNode()->getOperand(i).getNode();
423 if (OpNode->hasOneUse()) {
424 // Add OpNode to the end of the list to revisit.
425 DeadNodes.RemoveFromWorklist(OpNode);
426 Worklist.push_back(OpNode);
427 InWorklist.insert(OpNode);
431 DeadNodes.RemoveFromWorklist(TLO.Old.getNode());
432 CurDAG->DeleteNode(TLO.Old.getNode());
436 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
437 SmallPtrSet<SDNode*, 128> VisitedNodes;
438 SmallVector<SDNode*, 128> Worklist;
440 Worklist.push_back(CurDAG->getRoot().getNode());
447 SDNode *N = Worklist.pop_back_val();
449 // If we've already seen this node, ignore it.
450 if (!VisitedNodes.insert(N))
453 // Otherwise, add all chain operands to the worklist.
454 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
455 if (N->getOperand(i).getValueType() == MVT::Other)
456 Worklist.push_back(N->getOperand(i).getNode());
458 // If this is a CopyToReg with a vreg dest, process it.
459 if (N->getOpcode() != ISD::CopyToReg)
462 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
463 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
466 // Ignore non-scalar or non-integer values.
467 SDValue Src = N->getOperand(2);
468 EVT SrcVT = Src.getValueType();
469 if (!SrcVT.isInteger() || SrcVT.isVector())
472 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
473 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
474 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
476 // Only install this information if it tells us something.
477 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
478 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
479 if (DestReg >= FuncInfo->LiveOutRegInfo.size())
480 FuncInfo->LiveOutRegInfo.resize(DestReg+1);
481 FunctionLoweringInfo::LiveOutInfo &LOI =
482 FuncInfo->LiveOutRegInfo[DestReg];
483 LOI.NumSignBits = NumSignBits;
484 LOI.KnownOne = KnownOne;
485 LOI.KnownZero = KnownZero;
487 } while (!Worklist.empty());
490 void SelectionDAGISel::CodeGenAndEmitDAG() {
491 std::string GroupName;
492 if (TimePassesIsEnabled)
493 GroupName = "Instruction Selection and Scheduling";
494 std::string BlockName;
495 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
496 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
498 BlockName = MF->getFunction()->getNameStr() + ":" +
499 BB->getBasicBlock()->getNameStr();
501 DEBUG(dbgs() << "Initial selection DAG:\n");
502 DEBUG(CurDAG->dump());
504 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
506 // Run the DAG combiner in pre-legalize mode.
507 if (TimePassesIsEnabled) {
508 NamedRegionTimer T("DAG Combining 1", GroupName);
509 CurDAG->Combine(Unrestricted, *AA, OptLevel);
511 CurDAG->Combine(Unrestricted, *AA, OptLevel);
514 DEBUG(dbgs() << "Optimized lowered selection DAG:\n");
515 DEBUG(CurDAG->dump());
517 // Second step, hack on the DAG until it only uses operations and types that
518 // the target supports.
519 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
523 if (TimePassesIsEnabled) {
524 NamedRegionTimer T("Type Legalization", GroupName);
525 Changed = CurDAG->LegalizeTypes();
527 Changed = CurDAG->LegalizeTypes();
530 DEBUG(dbgs() << "Type-legalized selection DAG:\n");
531 DEBUG(CurDAG->dump());
534 if (ViewDAGCombineLT)
535 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
537 // Run the DAG combiner in post-type-legalize mode.
538 if (TimePassesIsEnabled) {
539 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
540 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
542 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
545 DEBUG(dbgs() << "Optimized type-legalized selection DAG:\n");
546 DEBUG(CurDAG->dump());
549 if (TimePassesIsEnabled) {
550 NamedRegionTimer T("Vector Legalization", GroupName);
551 Changed = CurDAG->LegalizeVectors();
553 Changed = CurDAG->LegalizeVectors();
557 if (TimePassesIsEnabled) {
558 NamedRegionTimer T("Type Legalization 2", GroupName);
559 CurDAG->LegalizeTypes();
561 CurDAG->LegalizeTypes();
564 if (ViewDAGCombineLT)
565 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
567 // Run the DAG combiner in post-type-legalize mode.
568 if (TimePassesIsEnabled) {
569 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
570 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
572 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
575 DEBUG(dbgs() << "Optimized vector-legalized selection DAG:\n");
576 DEBUG(CurDAG->dump());
579 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
581 if (TimePassesIsEnabled) {
582 NamedRegionTimer T("DAG Legalization", GroupName);
583 CurDAG->Legalize(OptLevel);
585 CurDAG->Legalize(OptLevel);
588 DEBUG(dbgs() << "Legalized selection DAG:\n");
589 DEBUG(CurDAG->dump());
591 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
593 // Run the DAG combiner in post-legalize mode.
594 if (TimePassesIsEnabled) {
595 NamedRegionTimer T("DAG Combining 2", GroupName);
596 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
598 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
601 DEBUG(dbgs() << "Optimized legalized selection DAG:\n");
602 DEBUG(CurDAG->dump());
604 if (OptLevel != CodeGenOpt::None) {
606 ComputeLiveOutVRegInfo();
609 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
611 // Third, instruction select all of the operations to machine code, adding the
612 // code to the MachineBasicBlock.
613 if (TimePassesIsEnabled) {
614 NamedRegionTimer T("Instruction Selection", GroupName);
615 DoInstructionSelection();
617 DoInstructionSelection();
620 DEBUG(dbgs() << "Selected selection DAG:\n");
621 DEBUG(CurDAG->dump());
623 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
625 // Schedule machine code.
626 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
627 if (TimePassesIsEnabled) {
628 NamedRegionTimer T("Instruction Scheduling", GroupName);
629 Scheduler->Run(CurDAG, BB, BB->end());
631 Scheduler->Run(CurDAG, BB, BB->end());
634 if (ViewSUnitDAGs) Scheduler->viewGraph();
636 // Emit machine code to BB. This can change 'BB' to the last block being
638 if (TimePassesIsEnabled) {
639 NamedRegionTimer T("Instruction Creation", GroupName);
640 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
642 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
645 // Free the scheduler state.
646 if (TimePassesIsEnabled) {
647 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
653 DEBUG(dbgs() << "Selected machine code:\n");
657 void SelectionDAGISel::DoInstructionSelection() {
658 DEBUG(errs() << "===== Instruction selection begins:\n");
662 // Select target instructions for the DAG.
664 // Number all nodes with a topological order and set DAGSize.
665 DAGSize = CurDAG->AssignTopologicalOrder();
667 // Create a dummy node (which is not added to allnodes), that adds
668 // a reference to the root node, preventing it from being deleted,
669 // and tracking any changes of the root.
670 HandleSDNode Dummy(CurDAG->getRoot());
671 ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
674 // The AllNodes list is now topological-sorted. Visit the
675 // nodes by starting at the end of the list (the root of the
676 // graph) and preceding back toward the beginning (the entry
678 while (ISelPosition != CurDAG->allnodes_begin()) {
679 SDNode *Node = --ISelPosition;
680 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
681 // but there are currently some corner cases that it misses. Also, this
682 // makes it theoretically possible to disable the DAGCombiner.
683 if (Node->use_empty())
686 SDNode *ResNode = Select(Node);
688 // FIXME: This is pretty gross. 'Select' should be changed to not return
689 // anything at all and this code should be nuked with a tactical strike.
691 // If node should not be replaced, continue with the next one.
692 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
696 ReplaceUses(Node, ResNode);
698 // If after the replacement this node is not used any more,
699 // remove this dead node.
700 if (Node->use_empty()) { // Don't delete EntryToken, etc.
701 ISelUpdater ISU(ISelPosition);
702 CurDAG->RemoveDeadNode(Node, &ISU);
706 CurDAG->setRoot(Dummy.getValue());
708 DEBUG(errs() << "===== Instruction selection ends:\n");
710 PostprocessISelDAG();
714 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
716 const TargetInstrInfo &TII) {
717 // Initialize the Fast-ISel state, if needed.
718 FastISel *FastIS = 0;
720 FastIS = TLI.createFastISel(MF, FuncInfo->ValueMap, FuncInfo->MBBMap,
721 FuncInfo->StaticAllocaMap
723 , FuncInfo->CatchInfoLost
727 // Iterate over all basic blocks in the function.
728 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
729 BasicBlock *LLVMBB = &*I;
730 BB = FuncInfo->MBBMap[LLVMBB];
732 BasicBlock::iterator const Begin = LLVMBB->begin();
733 BasicBlock::iterator const End = LLVMBB->end();
734 BasicBlock::iterator BI = Begin;
736 // Lower any arguments needed in this block if this is the entry block.
737 bool SuppressFastISel = false;
738 if (LLVMBB == &Fn.getEntryBlock()) {
739 LowerArguments(LLVMBB);
741 // If any of the arguments has the byval attribute, forgo
742 // fast-isel in the entry block.
745 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
747 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
748 if (EnableFastISelVerbose || EnableFastISelAbort)
749 dbgs() << "FastISel skips entry block due to byval argument\n";
750 SuppressFastISel = true;
756 if (BB->isLandingPad()) {
757 // Add a label to mark the beginning of the landing pad. Deletion of the
758 // landing pad can thus be detected via the MachineModuleInfo.
759 MCSymbol *Label = MF.getMMI().addLandingPad(BB);
761 const TargetInstrDesc &II = TII.get(TargetOpcode::EH_LABEL);
762 BuildMI(BB, SDB->getCurDebugLoc(), II).addSym(Label);
764 // Mark exception register as live in.
765 unsigned Reg = TLI.getExceptionAddressRegister();
766 if (Reg) BB->addLiveIn(Reg);
768 // Mark exception selector register as live in.
769 Reg = TLI.getExceptionSelectorRegister();
770 if (Reg) BB->addLiveIn(Reg);
772 // FIXME: Hack around an exception handling flaw (PR1508): the personality
773 // function and list of typeids logically belong to the invoke (or, if you
774 // like, the basic block containing the invoke), and need to be associated
775 // with it in the dwarf exception handling tables. Currently however the
776 // information is provided by an intrinsic (eh.selector) that can be moved
777 // to unexpected places by the optimizers: if the unwind edge is critical,
778 // then breaking it can result in the intrinsics being in the successor of
779 // the landing pad, not the landing pad itself. This results
780 // in exceptions not being caught because no typeids are associated with
781 // the invoke. This may not be the only way things can go wrong, but it
782 // is the only way we try to work around for the moment.
783 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
785 if (Br && Br->isUnconditional()) { // Critical edge?
786 BasicBlock::iterator I, E;
787 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
788 if (isa<EHSelectorInst>(I))
792 // No catch info found - try to extract some from the successor.
793 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF.getMMI(), *FuncInfo);
797 // Before doing SelectionDAG ISel, see if FastISel has been requested.
798 if (FastIS && !SuppressFastISel) {
799 // Emit code for any incoming arguments. This must happen before
800 // beginning FastISel on the entry block.
801 if (LLVMBB == &Fn.getEntryBlock()) {
802 CurDAG->setRoot(SDB->getControlRoot());
806 FastIS->startNewBlock(BB);
807 // Do FastISel on as many instructions as possible.
808 for (; BI != End; ++BI) {
809 // Just before the terminator instruction, insert instructions to
810 // feed PHI nodes in successor blocks.
811 if (isa<TerminatorInst>(BI))
812 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
813 ++NumFastIselFailures;
814 ResetDebugLoc(SDB, FastIS);
815 if (EnableFastISelVerbose || EnableFastISelAbort) {
816 dbgs() << "FastISel miss: ";
819 assert(!EnableFastISelAbort &&
820 "FastISel didn't handle a PHI in a successor");
824 SetDebugLoc(BI, SDB, FastIS, &MF);
826 // Try to select the instruction with FastISel.
827 if (FastIS->SelectInstruction(BI)) {
828 ResetDebugLoc(SDB, FastIS);
832 // Clear out the debug location so that it doesn't carry over to
833 // unrelated instructions.
834 ResetDebugLoc(SDB, FastIS);
836 // Then handle certain instructions as single-LLVM-Instruction blocks.
837 if (isa<CallInst>(BI)) {
838 ++NumFastIselFailures;
839 if (EnableFastISelVerbose || EnableFastISelAbort) {
840 dbgs() << "FastISel missed call: ";
844 if (!BI->getType()->isVoidTy()) {
845 unsigned &R = FuncInfo->ValueMap[BI];
847 R = FuncInfo->CreateRegForValue(BI);
850 bool HadTailCall = false;
851 SelectBasicBlock(LLVMBB, BI, llvm::next(BI), HadTailCall);
853 // If the call was emitted as a tail call, we're done with the block.
859 // If the instruction was codegen'd with multiple blocks,
860 // inform the FastISel object where to resume inserting.
861 FastIS->setCurrentBlock(BB);
865 // Otherwise, give up on FastISel for the rest of the block.
866 // For now, be a little lenient about non-branch terminators.
867 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
868 ++NumFastIselFailures;
869 if (EnableFastISelVerbose || EnableFastISelAbort) {
870 dbgs() << "FastISel miss: ";
873 if (EnableFastISelAbort)
874 // The "fast" selector couldn't handle something and bailed.
875 // For the purpose of debugging, just abort.
876 llvm_unreachable("FastISel didn't select the entire block");
882 // Run SelectionDAG instruction selection on the remainder of the block
883 // not handled by FastISel. If FastISel is not run, this is the entire
887 SelectBasicBlock(LLVMBB, BI, End, HadTailCall);
897 SelectionDAGISel::FinishBasicBlock() {
899 DEBUG(dbgs() << "Target-post-processed machine code:\n");
902 DEBUG(dbgs() << "Total amount of phi nodes to update: "
903 << SDB->PHINodesToUpdate.size() << "\n");
904 DEBUG(for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i)
905 dbgs() << "Node " << i << " : ("
906 << SDB->PHINodesToUpdate[i].first
907 << ", " << SDB->PHINodesToUpdate[i].second << ")\n");
909 // Next, now that we know what the last MBB the LLVM BB expanded is, update
910 // PHI nodes in successors.
911 if (SDB->SwitchCases.empty() &&
912 SDB->JTCases.empty() &&
913 SDB->BitTestCases.empty()) {
914 for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i) {
915 MachineInstr *PHI = SDB->PHINodesToUpdate[i].first;
916 assert(PHI->isPHI() &&
917 "This is not a machine PHI node that we are updating!");
918 if (!BB->isSuccessor(PHI->getParent()))
920 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[i].second,
922 PHI->addOperand(MachineOperand::CreateMBB(BB));
924 SDB->PHINodesToUpdate.clear();
928 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
929 // Lower header first, if it wasn't already lowered
930 if (!SDB->BitTestCases[i].Emitted) {
931 // Set the current basic block to the mbb we wish to insert the code into
932 BB = SDB->BitTestCases[i].Parent;
933 SDB->setCurrentBasicBlock(BB);
935 SDB->visitBitTestHeader(SDB->BitTestCases[i]);
936 CurDAG->setRoot(SDB->getRoot());
941 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
942 // Set the current basic block to the mbb we wish to insert the code into
943 BB = SDB->BitTestCases[i].Cases[j].ThisBB;
944 SDB->setCurrentBasicBlock(BB);
947 SDB->visitBitTestCase(SDB->BitTestCases[i].Cases[j+1].ThisBB,
948 SDB->BitTestCases[i].Reg,
949 SDB->BitTestCases[i].Cases[j]);
951 SDB->visitBitTestCase(SDB->BitTestCases[i].Default,
952 SDB->BitTestCases[i].Reg,
953 SDB->BitTestCases[i].Cases[j]);
956 CurDAG->setRoot(SDB->getRoot());
962 for (unsigned pi = 0, pe = SDB->PHINodesToUpdate.size(); pi != pe; ++pi) {
963 MachineInstr *PHI = SDB->PHINodesToUpdate[pi].first;
964 MachineBasicBlock *PHIBB = PHI->getParent();
965 assert(PHI->isPHI() &&
966 "This is not a machine PHI node that we are updating!");
967 // This is "default" BB. We have two jumps to it. From "header" BB and
968 // from last "case" BB.
969 if (PHIBB == SDB->BitTestCases[i].Default) {
970 PHI->addOperand(MachineOperand::
971 CreateReg(SDB->PHINodesToUpdate[pi].second, false));
972 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
973 PHI->addOperand(MachineOperand::
974 CreateReg(SDB->PHINodesToUpdate[pi].second, false));
975 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
978 // One of "cases" BB.
979 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
981 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
982 if (cBB->isSuccessor(PHIBB)) {
983 PHI->addOperand(MachineOperand::
984 CreateReg(SDB->PHINodesToUpdate[pi].second, false));
985 PHI->addOperand(MachineOperand::CreateMBB(cBB));
990 SDB->BitTestCases.clear();
992 // If the JumpTable record is filled in, then we need to emit a jump table.
993 // Updating the PHI nodes is tricky in this case, since we need to determine
994 // whether the PHI is a successor of the range check MBB or the jump table MBB
995 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
996 // Lower header first, if it wasn't already lowered
997 if (!SDB->JTCases[i].first.Emitted) {
998 // Set the current basic block to the mbb we wish to insert the code into
999 BB = SDB->JTCases[i].first.HeaderBB;
1000 SDB->setCurrentBasicBlock(BB);
1002 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first);
1003 CurDAG->setRoot(SDB->getRoot());
1004 CodeGenAndEmitDAG();
1008 // Set the current basic block to the mbb we wish to insert the code into
1009 BB = SDB->JTCases[i].second.MBB;
1010 SDB->setCurrentBasicBlock(BB);
1012 SDB->visitJumpTable(SDB->JTCases[i].second);
1013 CurDAG->setRoot(SDB->getRoot());
1014 CodeGenAndEmitDAG();
1018 for (unsigned pi = 0, pe = SDB->PHINodesToUpdate.size(); pi != pe; ++pi) {
1019 MachineInstr *PHI = SDB->PHINodesToUpdate[pi].first;
1020 MachineBasicBlock *PHIBB = PHI->getParent();
1021 assert(PHI->isPHI() &&
1022 "This is not a machine PHI node that we are updating!");
1023 // "default" BB. We can go there only from header BB.
1024 if (PHIBB == SDB->JTCases[i].second.Default) {
1026 (MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second, false));
1028 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
1030 // JT BB. Just iterate over successors here
1031 if (BB->isSuccessor(PHIBB)) {
1033 (MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second, false));
1034 PHI->addOperand(MachineOperand::CreateMBB(BB));
1038 SDB->JTCases.clear();
1040 // If the switch block involved a branch to one of the actual successors, we
1041 // need to update PHI nodes in that block.
1042 for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i) {
1043 MachineInstr *PHI = SDB->PHINodesToUpdate[i].first;
1044 assert(PHI->isPHI() &&
1045 "This is not a machine PHI node that we are updating!");
1046 if (BB->isSuccessor(PHI->getParent())) {
1047 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[i].second,
1049 PHI->addOperand(MachineOperand::CreateMBB(BB));
1053 // If we generated any switch lowering information, build and codegen any
1054 // additional DAGs necessary.
1055 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1056 // Set the current basic block to the mbb we wish to insert the code into
1057 MachineBasicBlock *ThisBB = BB = SDB->SwitchCases[i].ThisBB;
1058 SDB->setCurrentBasicBlock(BB);
1061 SDB->visitSwitchCase(SDB->SwitchCases[i]);
1062 CurDAG->setRoot(SDB->getRoot());
1063 CodeGenAndEmitDAG();
1065 // Handle any PHI nodes in successors of this chunk, as if we were coming
1066 // from the original BB before switch expansion. Note that PHI nodes can
1067 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1068 // handle them the right number of times.
1069 while ((BB = SDB->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
1070 // If new BB's are created during scheduling, the edges may have been
1071 // updated. That is, the edge from ThisBB to BB may have been split and
1072 // BB's predecessor is now another block.
1073 DenseMap<MachineBasicBlock*, MachineBasicBlock*>::iterator EI =
1074 SDB->EdgeMapping.find(BB);
1075 if (EI != SDB->EdgeMapping.end())
1076 ThisBB = EI->second;
1078 // BB may have been removed from the CFG if a branch was constant folded.
1079 if (ThisBB->isSuccessor(BB)) {
1080 for (MachineBasicBlock::iterator Phi = BB->begin();
1081 Phi != BB->end() && Phi->isPHI();
1083 // This value for this PHI node is recorded in PHINodesToUpdate.
1084 for (unsigned pn = 0; ; ++pn) {
1085 assert(pn != SDB->PHINodesToUpdate.size() &&
1086 "Didn't find PHI entry!");
1087 if (SDB->PHINodesToUpdate[pn].first == Phi) {
1088 Phi->addOperand(MachineOperand::
1089 CreateReg(SDB->PHINodesToUpdate[pn].second,
1091 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1098 // Don't process RHS if same block as LHS.
1099 if (BB == SDB->SwitchCases[i].FalseBB)
1100 SDB->SwitchCases[i].FalseBB = 0;
1102 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1103 SDB->SwitchCases[i].TrueBB = SDB->SwitchCases[i].FalseBB;
1104 SDB->SwitchCases[i].FalseBB = 0;
1106 assert(SDB->SwitchCases[i].TrueBB == 0 && SDB->SwitchCases[i].FalseBB == 0);
1109 SDB->SwitchCases.clear();
1111 SDB->PHINodesToUpdate.clear();
1115 /// Create the scheduler. If a specific scheduler was specified
1116 /// via the SchedulerRegistry, use it, otherwise select the
1117 /// one preferred by the target.
1119 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1120 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1124 RegisterScheduler::setDefault(Ctor);
1127 return Ctor(this, OptLevel);
1130 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1131 return new ScheduleHazardRecognizer();
1134 //===----------------------------------------------------------------------===//
1135 // Helper functions used by the generated instruction selector.
1136 //===----------------------------------------------------------------------===//
1137 // Calls to these methods are generated by tblgen.
1139 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1140 /// the dag combiner simplified the 255, we still want to match. RHS is the
1141 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1142 /// specified in the .td file (e.g. 255).
1143 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1144 int64_t DesiredMaskS) const {
1145 const APInt &ActualMask = RHS->getAPIntValue();
1146 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1148 // If the actual mask exactly matches, success!
1149 if (ActualMask == DesiredMask)
1152 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1153 if (ActualMask.intersects(~DesiredMask))
1156 // Otherwise, the DAG Combiner may have proven that the value coming in is
1157 // either already zero or is not demanded. Check for known zero input bits.
1158 APInt NeededMask = DesiredMask & ~ActualMask;
1159 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1162 // TODO: check to see if missing bits are just not demanded.
1164 // Otherwise, this pattern doesn't match.
1168 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1169 /// the dag combiner simplified the 255, we still want to match. RHS is the
1170 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1171 /// specified in the .td file (e.g. 255).
1172 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1173 int64_t DesiredMaskS) const {
1174 const APInt &ActualMask = RHS->getAPIntValue();
1175 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1177 // If the actual mask exactly matches, success!
1178 if (ActualMask == DesiredMask)
1181 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1182 if (ActualMask.intersects(~DesiredMask))
1185 // Otherwise, the DAG Combiner may have proven that the value coming in is
1186 // either already zero or is not demanded. Check for known zero input bits.
1187 APInt NeededMask = DesiredMask & ~ActualMask;
1189 APInt KnownZero, KnownOne;
1190 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1192 // If all the missing bits in the or are already known to be set, match!
1193 if ((NeededMask & KnownOne) == NeededMask)
1196 // TODO: check to see if missing bits are just not demanded.
1198 // Otherwise, this pattern doesn't match.
1203 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1204 /// by tblgen. Others should not call it.
1205 void SelectionDAGISel::
1206 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1207 std::vector<SDValue> InOps;
1208 std::swap(InOps, Ops);
1210 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1211 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1212 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1214 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1215 if (InOps[e-1].getValueType() == MVT::Flag)
1216 --e; // Don't process a flag operand if it is here.
1219 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1220 if (!InlineAsm::isMemKind(Flags)) {
1221 // Just skip over this operand, copying the operands verbatim.
1222 Ops.insert(Ops.end(), InOps.begin()+i,
1223 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1224 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1226 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1227 "Memory operand with multiple values?");
1228 // Otherwise, this is a memory operand. Ask the target to select it.
1229 std::vector<SDValue> SelOps;
1230 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1231 report_fatal_error("Could not match memory address. Inline asm"
1234 // Add this to the output node.
1236 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1237 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1238 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1243 // Add the flag input back if present.
1244 if (e != InOps.size())
1245 Ops.push_back(InOps.back());
1248 /// findFlagUse - Return use of EVT::Flag value produced by the specified
1251 static SDNode *findFlagUse(SDNode *N) {
1252 unsigned FlagResNo = N->getNumValues()-1;
1253 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1254 SDUse &Use = I.getUse();
1255 if (Use.getResNo() == FlagResNo)
1256 return Use.getUser();
1261 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1262 /// This function recursively traverses up the operand chain, ignoring
1264 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1265 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1266 bool IgnoreChains) {
1267 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1268 // greater than all of its (recursive) operands. If we scan to a point where
1269 // 'use' is smaller than the node we're scanning for, then we know we will
1272 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1273 // happen because we scan down to newly selected nodes in the case of flag
1275 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1278 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1279 // won't fail if we scan it again.
1280 if (!Visited.insert(Use))
1283 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1284 // Ignore chain uses, they are validated by HandleMergeInputChains.
1285 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1288 SDNode *N = Use->getOperand(i).getNode();
1290 if (Use == ImmedUse || Use == Root)
1291 continue; // We are not looking for immediate use.
1296 // Traverse up the operand chain.
1297 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1303 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1304 /// operand node N of U during instruction selection that starts at Root.
1305 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1306 SDNode *Root) const {
1307 if (OptLevel == CodeGenOpt::None) return false;
1308 return N.hasOneUse();
1311 /// IsLegalToFold - Returns true if the specific operand node N of
1312 /// U can be folded during instruction selection that starts at Root.
1313 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1314 bool IgnoreChains) const {
1315 if (OptLevel == CodeGenOpt::None) return false;
1317 // If Root use can somehow reach N through a path that that doesn't contain
1318 // U then folding N would create a cycle. e.g. In the following
1319 // diagram, Root can reach N through X. If N is folded into into Root, then
1320 // X is both a predecessor and a successor of U.
1331 // * indicates nodes to be folded together.
1333 // If Root produces a flag, then it gets (even more) interesting. Since it
1334 // will be "glued" together with its flag use in the scheduler, we need to
1335 // check if it might reach N.
1354 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1355 // (call it Fold), then X is a predecessor of FU and a successor of
1356 // Fold. But since Fold and FU are flagged together, this will create
1357 // a cycle in the scheduling graph.
1359 // If the node has flags, walk down the graph to the "lowest" node in the
1361 EVT VT = Root->getValueType(Root->getNumValues()-1);
1362 while (VT == MVT::Flag) {
1363 SDNode *FU = findFlagUse(Root);
1367 VT = Root->getValueType(Root->getNumValues()-1);
1369 // If our query node has a flag result with a use, we've walked up it. If
1370 // the user (which has already been selected) has a chain or indirectly uses
1371 // the chain, our WalkChainUsers predicate will not consider it. Because of
1372 // this, we cannot ignore chains in this predicate.
1373 IgnoreChains = false;
1377 SmallPtrSet<SDNode*, 16> Visited;
1378 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1381 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1382 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1383 SelectInlineAsmMemoryOperands(Ops);
1385 std::vector<EVT> VTs;
1386 VTs.push_back(MVT::Other);
1387 VTs.push_back(MVT::Flag);
1388 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
1389 VTs, &Ops[0], Ops.size());
1391 return New.getNode();
1394 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1395 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1398 /// GetVBR - decode a vbr encoding whose top bit is set.
1399 ALWAYS_INLINE static uint64_t
1400 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1401 assert(Val >= 128 && "Not a VBR");
1402 Val &= 127; // Remove first vbr bit.
1407 NextBits = MatcherTable[Idx++];
1408 Val |= (NextBits&127) << Shift;
1410 } while (NextBits & 128);
1416 /// UpdateChainsAndFlags - When a match is complete, this method updates uses of
1417 /// interior flag and chain results to use the new flag and chain results.
1418 void SelectionDAGISel::
1419 UpdateChainsAndFlags(SDNode *NodeToMatch, SDValue InputChain,
1420 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1422 const SmallVectorImpl<SDNode*> &FlagResultNodesMatched,
1423 bool isMorphNodeTo) {
1424 SmallVector<SDNode*, 4> NowDeadNodes;
1426 ISelUpdater ISU(ISelPosition);
1428 // Now that all the normal results are replaced, we replace the chain and
1429 // flag results if present.
1430 if (!ChainNodesMatched.empty()) {
1431 assert(InputChain.getNode() != 0 &&
1432 "Matched input chains but didn't produce a chain");
1433 // Loop over all of the nodes we matched that produced a chain result.
1434 // Replace all the chain results with the final chain we ended up with.
1435 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1436 SDNode *ChainNode = ChainNodesMatched[i];
1438 // If this node was already deleted, don't look at it.
1439 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1442 // Don't replace the results of the root node if we're doing a
1444 if (ChainNode == NodeToMatch && isMorphNodeTo)
1447 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1448 if (ChainVal.getValueType() == MVT::Flag)
1449 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1450 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1451 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1453 // If the node became dead and we haven't already seen it, delete it.
1454 if (ChainNode->use_empty() &&
1455 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1456 NowDeadNodes.push_back(ChainNode);
1460 // If the result produces a flag, update any flag results in the matched
1461 // pattern with the flag result.
1462 if (InputFlag.getNode() != 0) {
1463 // Handle any interior nodes explicitly marked.
1464 for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
1465 SDNode *FRN = FlagResultNodesMatched[i];
1467 // If this node was already deleted, don't look at it.
1468 if (FRN->getOpcode() == ISD::DELETED_NODE)
1471 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
1472 "Doesn't have a flag result");
1473 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1476 // If the node became dead and we haven't already seen it, delete it.
1477 if (FRN->use_empty() &&
1478 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1479 NowDeadNodes.push_back(FRN);
1483 if (!NowDeadNodes.empty())
1484 CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1486 DEBUG(errs() << "ISEL: Match complete!\n");
1492 CR_LeadsToInteriorNode
1495 /// WalkChainUsers - Walk down the users of the specified chained node that is
1496 /// part of the pattern we're matching, looking at all of the users we find.
1497 /// This determines whether something is an interior node, whether we have a
1498 /// non-pattern node in between two pattern nodes (which prevent folding because
1499 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1500 /// between pattern nodes (in which case the TF becomes part of the pattern).
1502 /// The walk we do here is guaranteed to be small because we quickly get down to
1503 /// already selected nodes "below" us.
1505 WalkChainUsers(SDNode *ChainedNode,
1506 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1507 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1508 ChainResult Result = CR_Simple;
1510 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1511 E = ChainedNode->use_end(); UI != E; ++UI) {
1512 // Make sure the use is of the chain, not some other value we produce.
1513 if (UI.getUse().getValueType() != MVT::Other) continue;
1517 // If we see an already-selected machine node, then we've gone beyond the
1518 // pattern that we're selecting down into the already selected chunk of the
1520 if (User->isMachineOpcode() ||
1521 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1524 if (User->getOpcode() == ISD::CopyToReg ||
1525 User->getOpcode() == ISD::CopyFromReg ||
1526 User->getOpcode() == ISD::INLINEASM ||
1527 User->getOpcode() == ISD::EH_LABEL) {
1528 // If their node ID got reset to -1 then they've already been selected.
1529 // Treat them like a MachineOpcode.
1530 if (User->getNodeId() == -1)
1534 // If we have a TokenFactor, we handle it specially.
1535 if (User->getOpcode() != ISD::TokenFactor) {
1536 // If the node isn't a token factor and isn't part of our pattern, then it
1537 // must be a random chained node in between two nodes we're selecting.
1538 // This happens when we have something like:
1543 // Because we structurally match the load/store as a read/modify/write,
1544 // but the call is chained between them. We cannot fold in this case
1545 // because it would induce a cycle in the graph.
1546 if (!std::count(ChainedNodesInPattern.begin(),
1547 ChainedNodesInPattern.end(), User))
1548 return CR_InducesCycle;
1550 // Otherwise we found a node that is part of our pattern. For example in:
1554 // This would happen when we're scanning down from the load and see the
1555 // store as a user. Record that there is a use of ChainedNode that is
1556 // part of the pattern and keep scanning uses.
1557 Result = CR_LeadsToInteriorNode;
1558 InteriorChainedNodes.push_back(User);
1562 // If we found a TokenFactor, there are two cases to consider: first if the
1563 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1564 // uses of the TF are in our pattern) we just want to ignore it. Second,
1565 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1571 // | \ DAG's like cheese
1574 // [TokenFactor] [Op]
1581 // In this case, the TokenFactor becomes part of our match and we rewrite it
1582 // as a new TokenFactor.
1584 // To distinguish these two cases, do a recursive walk down the uses.
1585 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1587 // If the uses of the TokenFactor are just already-selected nodes, ignore
1588 // it, it is "below" our pattern.
1590 case CR_InducesCycle:
1591 // If the uses of the TokenFactor lead to nodes that are not part of our
1592 // pattern that are not selected, folding would turn this into a cycle,
1594 return CR_InducesCycle;
1595 case CR_LeadsToInteriorNode:
1596 break; // Otherwise, keep processing.
1599 // Okay, we know we're in the interesting interior case. The TokenFactor
1600 // is now going to be considered part of the pattern so that we rewrite its
1601 // uses (it may have uses that are not part of the pattern) with the
1602 // ultimate chain result of the generated code. We will also add its chain
1603 // inputs as inputs to the ultimate TokenFactor we create.
1604 Result = CR_LeadsToInteriorNode;
1605 ChainedNodesInPattern.push_back(User);
1606 InteriorChainedNodes.push_back(User);
1613 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1614 /// operation for when the pattern matched at least one node with a chains. The
1615 /// input vector contains a list of all of the chained nodes that we match. We
1616 /// must determine if this is a valid thing to cover (i.e. matching it won't
1617 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1618 /// be used as the input node chain for the generated nodes.
1620 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1621 SelectionDAG *CurDAG) {
1622 // Walk all of the chained nodes we've matched, recursively scanning down the
1623 // users of the chain result. This adds any TokenFactor nodes that are caught
1624 // in between chained nodes to the chained and interior nodes list.
1625 SmallVector<SDNode*, 3> InteriorChainedNodes;
1626 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1627 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1628 InteriorChainedNodes) == CR_InducesCycle)
1629 return SDValue(); // Would induce a cycle.
1632 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1633 // that we are interested in. Form our input TokenFactor node.
1634 SmallVector<SDValue, 3> InputChains;
1635 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1636 // Add the input chain of this node to the InputChains list (which will be
1637 // the operands of the generated TokenFactor) if it's not an interior node.
1638 SDNode *N = ChainNodesMatched[i];
1639 if (N->getOpcode() != ISD::TokenFactor) {
1640 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1643 // Otherwise, add the input chain.
1644 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1645 assert(InChain.getValueType() == MVT::Other && "Not a chain");
1646 InputChains.push_back(InChain);
1650 // If we have a token factor, we want to add all inputs of the token factor
1651 // that are not part of the pattern we're matching.
1652 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1653 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1654 N->getOperand(op).getNode()))
1655 InputChains.push_back(N->getOperand(op));
1660 if (InputChains.size() == 1)
1661 return InputChains[0];
1662 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1663 MVT::Other, &InputChains[0], InputChains.size());
1666 /// MorphNode - Handle morphing a node in place for the selector.
1667 SDNode *SelectionDAGISel::
1668 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1669 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1670 // It is possible we're using MorphNodeTo to replace a node with no
1671 // normal results with one that has a normal result (or we could be
1672 // adding a chain) and the input could have flags and chains as well.
1673 // In this case we need to shift the operands down.
1674 // FIXME: This is a horrible hack and broken in obscure cases, no worse
1675 // than the old isel though.
1676 int OldFlagResultNo = -1, OldChainResultNo = -1;
1678 unsigned NTMNumResults = Node->getNumValues();
1679 if (Node->getValueType(NTMNumResults-1) == MVT::Flag) {
1680 OldFlagResultNo = NTMNumResults-1;
1681 if (NTMNumResults != 1 &&
1682 Node->getValueType(NTMNumResults-2) == MVT::Other)
1683 OldChainResultNo = NTMNumResults-2;
1684 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1685 OldChainResultNo = NTMNumResults-1;
1687 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1688 // that this deletes operands of the old node that become dead.
1689 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1691 // MorphNodeTo can operate in two ways: if an existing node with the
1692 // specified operands exists, it can just return it. Otherwise, it
1693 // updates the node in place to have the requested operands.
1695 // If we updated the node in place, reset the node ID. To the isel,
1696 // this should be just like a newly allocated machine node.
1700 unsigned ResNumResults = Res->getNumValues();
1701 // Move the flag if needed.
1702 if ((EmitNodeInfo & OPFL_FlagOutput) && OldFlagResultNo != -1 &&
1703 (unsigned)OldFlagResultNo != ResNumResults-1)
1704 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldFlagResultNo),
1705 SDValue(Res, ResNumResults-1));
1707 if ((EmitNodeInfo & OPFL_FlagOutput) != 0)
1710 // Move the chain reference if needed.
1711 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1712 (unsigned)OldChainResultNo != ResNumResults-1)
1713 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1714 SDValue(Res, ResNumResults-1));
1716 // Otherwise, no replacement happened because the node already exists. Replace
1717 // Uses of the old node with the new one.
1719 CurDAG->ReplaceAllUsesWith(Node, Res);
1724 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1725 ALWAYS_INLINE static bool
1726 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1727 SDValue N, const SmallVectorImpl<SDValue> &RecordedNodes) {
1728 // Accept if it is exactly the same as a previously recorded node.
1729 unsigned RecNo = MatcherTable[MatcherIndex++];
1730 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1731 return N == RecordedNodes[RecNo];
1734 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1735 ALWAYS_INLINE static bool
1736 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1737 SelectionDAGISel &SDISel) {
1738 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1741 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
1742 ALWAYS_INLINE static bool
1743 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1744 SelectionDAGISel &SDISel, SDNode *N) {
1745 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1748 ALWAYS_INLINE static bool
1749 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1751 uint16_t Opc = MatcherTable[MatcherIndex++];
1752 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1753 return N->getOpcode() == Opc;
1756 ALWAYS_INLINE static bool
1757 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1758 SDValue N, const TargetLowering &TLI) {
1759 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1760 if (N.getValueType() == VT) return true;
1762 // Handle the case when VT is iPTR.
1763 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
1766 ALWAYS_INLINE static bool
1767 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1768 SDValue N, const TargetLowering &TLI,
1770 if (ChildNo >= N.getNumOperands())
1771 return false; // Match fails if out of range child #.
1772 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
1776 ALWAYS_INLINE static bool
1777 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1779 return cast<CondCodeSDNode>(N)->get() ==
1780 (ISD::CondCode)MatcherTable[MatcherIndex++];
1783 ALWAYS_INLINE static bool
1784 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1785 SDValue N, const TargetLowering &TLI) {
1786 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1787 if (cast<VTSDNode>(N)->getVT() == VT)
1790 // Handle the case when VT is iPTR.
1791 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
1794 ALWAYS_INLINE static bool
1795 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1797 int64_t Val = MatcherTable[MatcherIndex++];
1799 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1801 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
1802 return C != 0 && C->getSExtValue() == Val;
1805 ALWAYS_INLINE static bool
1806 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1807 SDValue N, SelectionDAGISel &SDISel) {
1808 int64_t Val = MatcherTable[MatcherIndex++];
1810 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1812 if (N->getOpcode() != ISD::AND) return false;
1814 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1815 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
1818 ALWAYS_INLINE static bool
1819 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1820 SDValue N, SelectionDAGISel &SDISel) {
1821 int64_t Val = MatcherTable[MatcherIndex++];
1823 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1825 if (N->getOpcode() != ISD::OR) return false;
1827 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1828 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
1831 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
1832 /// scope, evaluate the current node. If the current predicate is known to
1833 /// fail, set Result=true and return anything. If the current predicate is
1834 /// known to pass, set Result=false and return the MatcherIndex to continue
1835 /// with. If the current predicate is unknown, set Result=false and return the
1836 /// MatcherIndex to continue with.
1837 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
1838 unsigned Index, SDValue N,
1839 bool &Result, SelectionDAGISel &SDISel,
1840 SmallVectorImpl<SDValue> &RecordedNodes){
1841 switch (Table[Index++]) {
1844 return Index-1; // Could not evaluate this predicate.
1845 case SelectionDAGISel::OPC_CheckSame:
1846 Result = !::CheckSame(Table, Index, N, RecordedNodes);
1848 case SelectionDAGISel::OPC_CheckPatternPredicate:
1849 Result = !::CheckPatternPredicate(Table, Index, SDISel);
1851 case SelectionDAGISel::OPC_CheckPredicate:
1852 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
1854 case SelectionDAGISel::OPC_CheckOpcode:
1855 Result = !::CheckOpcode(Table, Index, N.getNode());
1857 case SelectionDAGISel::OPC_CheckType:
1858 Result = !::CheckType(Table, Index, N, SDISel.TLI);
1860 case SelectionDAGISel::OPC_CheckChild0Type:
1861 case SelectionDAGISel::OPC_CheckChild1Type:
1862 case SelectionDAGISel::OPC_CheckChild2Type:
1863 case SelectionDAGISel::OPC_CheckChild3Type:
1864 case SelectionDAGISel::OPC_CheckChild4Type:
1865 case SelectionDAGISel::OPC_CheckChild5Type:
1866 case SelectionDAGISel::OPC_CheckChild6Type:
1867 case SelectionDAGISel::OPC_CheckChild7Type:
1868 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
1869 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
1871 case SelectionDAGISel::OPC_CheckCondCode:
1872 Result = !::CheckCondCode(Table, Index, N);
1874 case SelectionDAGISel::OPC_CheckValueType:
1875 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
1877 case SelectionDAGISel::OPC_CheckInteger:
1878 Result = !::CheckInteger(Table, Index, N);
1880 case SelectionDAGISel::OPC_CheckAndImm:
1881 Result = !::CheckAndImm(Table, Index, N, SDISel);
1883 case SelectionDAGISel::OPC_CheckOrImm:
1884 Result = !::CheckOrImm(Table, Index, N, SDISel);
1891 /// FailIndex - If this match fails, this is the index to continue with.
1894 /// NodeStack - The node stack when the scope was formed.
1895 SmallVector<SDValue, 4> NodeStack;
1897 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
1898 unsigned NumRecordedNodes;
1900 /// NumMatchedMemRefs - The number of matched memref entries.
1901 unsigned NumMatchedMemRefs;
1903 /// InputChain/InputFlag - The current chain/flag
1904 SDValue InputChain, InputFlag;
1906 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
1907 bool HasChainNodesMatched, HasFlagResultNodesMatched;
1910 SDNode *SelectionDAGISel::
1911 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
1912 unsigned TableSize) {
1913 // FIXME: Should these even be selected? Handle these cases in the caller?
1914 switch (NodeToMatch->getOpcode()) {
1917 case ISD::EntryToken: // These nodes remain the same.
1918 case ISD::BasicBlock:
1920 //case ISD::VALUETYPE:
1921 //case ISD::CONDCODE:
1922 case ISD::HANDLENODE:
1923 case ISD::MDNODE_SDNODE:
1924 case ISD::TargetConstant:
1925 case ISD::TargetConstantFP:
1926 case ISD::TargetConstantPool:
1927 case ISD::TargetFrameIndex:
1928 case ISD::TargetExternalSymbol:
1929 case ISD::TargetBlockAddress:
1930 case ISD::TargetJumpTable:
1931 case ISD::TargetGlobalTLSAddress:
1932 case ISD::TargetGlobalAddress:
1933 case ISD::TokenFactor:
1934 case ISD::CopyFromReg:
1935 case ISD::CopyToReg:
1937 NodeToMatch->setNodeId(-1); // Mark selected.
1939 case ISD::AssertSext:
1940 case ISD::AssertZext:
1941 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
1942 NodeToMatch->getOperand(0));
1944 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
1945 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
1948 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
1950 // Set up the node stack with NodeToMatch as the only node on the stack.
1951 SmallVector<SDValue, 8> NodeStack;
1952 SDValue N = SDValue(NodeToMatch, 0);
1953 NodeStack.push_back(N);
1955 // MatchScopes - Scopes used when matching, if a match failure happens, this
1956 // indicates where to continue checking.
1957 SmallVector<MatchScope, 8> MatchScopes;
1959 // RecordedNodes - This is the set of nodes that have been recorded by the
1961 SmallVector<SDValue, 8> RecordedNodes;
1963 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
1965 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
1967 // These are the current input chain and flag for use when generating nodes.
1968 // Various Emit operations change these. For example, emitting a copytoreg
1969 // uses and updates these.
1970 SDValue InputChain, InputFlag;
1972 // ChainNodesMatched - If a pattern matches nodes that have input/output
1973 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
1974 // which ones they are. The result is captured into this list so that we can
1975 // update the chain results when the pattern is complete.
1976 SmallVector<SDNode*, 3> ChainNodesMatched;
1977 SmallVector<SDNode*, 3> FlagResultNodesMatched;
1979 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
1980 NodeToMatch->dump(CurDAG);
1983 // Determine where to start the interpreter. Normally we start at opcode #0,
1984 // but if the state machine starts with an OPC_SwitchOpcode, then we
1985 // accelerate the first lookup (which is guaranteed to be hot) with the
1986 // OpcodeOffset table.
1987 unsigned MatcherIndex = 0;
1989 if (!OpcodeOffset.empty()) {
1990 // Already computed the OpcodeOffset table, just index into it.
1991 if (N.getOpcode() < OpcodeOffset.size())
1992 MatcherIndex = OpcodeOffset[N.getOpcode()];
1993 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
1995 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
1996 // Otherwise, the table isn't computed, but the state machine does start
1997 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
1998 // is the first time we're selecting an instruction.
2001 // Get the size of this case.
2002 unsigned CaseSize = MatcherTable[Idx++];
2004 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2005 if (CaseSize == 0) break;
2007 // Get the opcode, add the index to the table.
2008 uint16_t Opc = MatcherTable[Idx++];
2009 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2010 if (Opc >= OpcodeOffset.size())
2011 OpcodeOffset.resize((Opc+1)*2);
2012 OpcodeOffset[Opc] = Idx;
2016 // Okay, do the lookup for the first opcode.
2017 if (N.getOpcode() < OpcodeOffset.size())
2018 MatcherIndex = OpcodeOffset[N.getOpcode()];
2022 assert(MatcherIndex < TableSize && "Invalid index");
2024 unsigned CurrentOpcodeIndex = MatcherIndex;
2026 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2029 // Okay, the semantics of this operation are that we should push a scope
2030 // then evaluate the first child. However, pushing a scope only to have
2031 // the first check fail (which then pops it) is inefficient. If we can
2032 // determine immediately that the first check (or first several) will
2033 // immediately fail, don't even bother pushing a scope for them.
2037 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2038 if (NumToSkip & 128)
2039 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2040 // Found the end of the scope with no match.
2041 if (NumToSkip == 0) {
2046 FailIndex = MatcherIndex+NumToSkip;
2048 unsigned MatcherIndexOfPredicate = MatcherIndex;
2049 (void)MatcherIndexOfPredicate; // silence warning.
2051 // If we can't evaluate this predicate without pushing a scope (e.g. if
2052 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2053 // push the scope and evaluate the full predicate chain.
2055 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2056 Result, *this, RecordedNodes);
2060 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
2061 << "index " << MatcherIndexOfPredicate
2062 << ", continuing at " << FailIndex << "\n");
2063 ++NumDAGIselRetries;
2065 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2066 // move to the next case.
2067 MatcherIndex = FailIndex;
2070 // If the whole scope failed to match, bail.
2071 if (FailIndex == 0) break;
2073 // Push a MatchScope which indicates where to go if the first child fails
2075 MatchScope NewEntry;
2076 NewEntry.FailIndex = FailIndex;
2077 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2078 NewEntry.NumRecordedNodes = RecordedNodes.size();
2079 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2080 NewEntry.InputChain = InputChain;
2081 NewEntry.InputFlag = InputFlag;
2082 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2083 NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
2084 MatchScopes.push_back(NewEntry);
2087 case OPC_RecordNode:
2088 // Remember this node, it may end up being an operand in the pattern.
2089 RecordedNodes.push_back(N);
2092 case OPC_RecordChild0: case OPC_RecordChild1:
2093 case OPC_RecordChild2: case OPC_RecordChild3:
2094 case OPC_RecordChild4: case OPC_RecordChild5:
2095 case OPC_RecordChild6: case OPC_RecordChild7: {
2096 unsigned ChildNo = Opcode-OPC_RecordChild0;
2097 if (ChildNo >= N.getNumOperands())
2098 break; // Match fails if out of range child #.
2100 RecordedNodes.push_back(N->getOperand(ChildNo));
2103 case OPC_RecordMemRef:
2104 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2107 case OPC_CaptureFlagInput:
2108 // If the current node has an input flag, capture it in InputFlag.
2109 if (N->getNumOperands() != 0 &&
2110 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
2111 InputFlag = N->getOperand(N->getNumOperands()-1);
2114 case OPC_MoveChild: {
2115 unsigned ChildNo = MatcherTable[MatcherIndex++];
2116 if (ChildNo >= N.getNumOperands())
2117 break; // Match fails if out of range child #.
2118 N = N.getOperand(ChildNo);
2119 NodeStack.push_back(N);
2123 case OPC_MoveParent:
2124 // Pop the current node off the NodeStack.
2125 NodeStack.pop_back();
2126 assert(!NodeStack.empty() && "Node stack imbalance!");
2127 N = NodeStack.back();
2131 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2133 case OPC_CheckPatternPredicate:
2134 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2136 case OPC_CheckPredicate:
2137 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2141 case OPC_CheckComplexPat: {
2142 unsigned CPNum = MatcherTable[MatcherIndex++];
2143 unsigned RecNo = MatcherTable[MatcherIndex++];
2144 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2145 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo], CPNum,
2150 case OPC_CheckOpcode:
2151 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2155 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
2158 case OPC_SwitchOpcode: {
2159 unsigned CurNodeOpcode = N.getOpcode();
2160 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2163 // Get the size of this case.
2164 CaseSize = MatcherTable[MatcherIndex++];
2166 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2167 if (CaseSize == 0) break;
2169 uint16_t Opc = MatcherTable[MatcherIndex++];
2170 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2172 // If the opcode matches, then we will execute this case.
2173 if (CurNodeOpcode == Opc)
2176 // Otherwise, skip over this case.
2177 MatcherIndex += CaseSize;
2180 // If no cases matched, bail out.
2181 if (CaseSize == 0) break;
2183 // Otherwise, execute the case we found.
2184 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2185 << " to " << MatcherIndex << "\n");
2189 case OPC_SwitchType: {
2190 MVT::SimpleValueType CurNodeVT = N.getValueType().getSimpleVT().SimpleTy;
2191 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2194 // Get the size of this case.
2195 CaseSize = MatcherTable[MatcherIndex++];
2197 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2198 if (CaseSize == 0) break;
2200 MVT::SimpleValueType CaseVT =
2201 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2202 if (CaseVT == MVT::iPTR)
2203 CaseVT = TLI.getPointerTy().SimpleTy;
2205 // If the VT matches, then we will execute this case.
2206 if (CurNodeVT == CaseVT)
2209 // Otherwise, skip over this case.
2210 MatcherIndex += CaseSize;
2213 // If no cases matched, bail out.
2214 if (CaseSize == 0) break;
2216 // Otherwise, execute the case we found.
2217 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2218 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2221 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2222 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2223 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2224 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2225 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2226 Opcode-OPC_CheckChild0Type))
2229 case OPC_CheckCondCode:
2230 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2232 case OPC_CheckValueType:
2233 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
2235 case OPC_CheckInteger:
2236 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2238 case OPC_CheckAndImm:
2239 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2241 case OPC_CheckOrImm:
2242 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2245 case OPC_CheckFoldableChainNode: {
2246 assert(NodeStack.size() != 1 && "No parent node");
2247 // Verify that all intermediate nodes between the root and this one have
2249 bool HasMultipleUses = false;
2250 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2251 if (!NodeStack[i].hasOneUse()) {
2252 HasMultipleUses = true;
2255 if (HasMultipleUses) break;
2257 // Check to see that the target thinks this is profitable to fold and that
2258 // we can fold it without inducing cycles in the graph.
2259 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2261 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2262 NodeToMatch, true/*We validate our own chains*/))
2267 case OPC_EmitInteger: {
2268 MVT::SimpleValueType VT =
2269 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2270 int64_t Val = MatcherTable[MatcherIndex++];
2272 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2273 RecordedNodes.push_back(CurDAG->getTargetConstant(Val, VT));
2276 case OPC_EmitRegister: {
2277 MVT::SimpleValueType VT =
2278 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2279 unsigned RegNo = MatcherTable[MatcherIndex++];
2280 RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
2284 case OPC_EmitConvertToTarget: {
2285 // Convert from IMM/FPIMM to target version.
2286 unsigned RecNo = MatcherTable[MatcherIndex++];
2287 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2288 SDValue Imm = RecordedNodes[RecNo];
2290 if (Imm->getOpcode() == ISD::Constant) {
2291 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2292 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2293 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2294 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2295 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2298 RecordedNodes.push_back(Imm);
2302 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2303 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2304 // These are space-optimized forms of OPC_EmitMergeInputChains.
2305 assert(InputChain.getNode() == 0 &&
2306 "EmitMergeInputChains should be the first chain producing node");
2307 assert(ChainNodesMatched.empty() &&
2308 "Should only have one EmitMergeInputChains per match");
2310 // Read all of the chained nodes.
2311 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2312 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2313 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2315 // FIXME: What if other value results of the node have uses not matched
2317 if (ChainNodesMatched.back() != NodeToMatch &&
2318 !RecordedNodes[RecNo].hasOneUse()) {
2319 ChainNodesMatched.clear();
2323 // Merge the input chains if they are not intra-pattern references.
2324 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2326 if (InputChain.getNode() == 0)
2327 break; // Failed to merge.
2331 case OPC_EmitMergeInputChains: {
2332 assert(InputChain.getNode() == 0 &&
2333 "EmitMergeInputChains should be the first chain producing node");
2334 // This node gets a list of nodes we matched in the input that have
2335 // chains. We want to token factor all of the input chains to these nodes
2336 // together. However, if any of the input chains is actually one of the
2337 // nodes matched in this pattern, then we have an intra-match reference.
2338 // Ignore these because the newly token factored chain should not refer to
2340 unsigned NumChains = MatcherTable[MatcherIndex++];
2341 assert(NumChains != 0 && "Can't TF zero chains");
2343 assert(ChainNodesMatched.empty() &&
2344 "Should only have one EmitMergeInputChains per match");
2346 // Read all of the chained nodes.
2347 for (unsigned i = 0; i != NumChains; ++i) {
2348 unsigned RecNo = MatcherTable[MatcherIndex++];
2349 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2350 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2352 // FIXME: What if other value results of the node have uses not matched
2354 if (ChainNodesMatched.back() != NodeToMatch &&
2355 !RecordedNodes[RecNo].hasOneUse()) {
2356 ChainNodesMatched.clear();
2361 // If the inner loop broke out, the match fails.
2362 if (ChainNodesMatched.empty())
2365 // Merge the input chains if they are not intra-pattern references.
2366 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2368 if (InputChain.getNode() == 0)
2369 break; // Failed to merge.
2374 case OPC_EmitCopyToReg: {
2375 unsigned RecNo = MatcherTable[MatcherIndex++];
2376 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2377 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2379 if (InputChain.getNode() == 0)
2380 InputChain = CurDAG->getEntryNode();
2382 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2383 DestPhysReg, RecordedNodes[RecNo],
2386 InputFlag = InputChain.getValue(1);
2390 case OPC_EmitNodeXForm: {
2391 unsigned XFormNo = MatcherTable[MatcherIndex++];
2392 unsigned RecNo = MatcherTable[MatcherIndex++];
2393 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2394 RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
2399 case OPC_MorphNodeTo: {
2400 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2401 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2402 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2403 // Get the result VT list.
2404 unsigned NumVTs = MatcherTable[MatcherIndex++];
2405 SmallVector<EVT, 4> VTs;
2406 for (unsigned i = 0; i != NumVTs; ++i) {
2407 MVT::SimpleValueType VT =
2408 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2409 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2413 if (EmitNodeInfo & OPFL_Chain)
2414 VTs.push_back(MVT::Other);
2415 if (EmitNodeInfo & OPFL_FlagOutput)
2416 VTs.push_back(MVT::Flag);
2418 // This is hot code, so optimize the two most common cases of 1 and 2
2421 if (VTs.size() == 1)
2422 VTList = CurDAG->getVTList(VTs[0]);
2423 else if (VTs.size() == 2)
2424 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2426 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2428 // Get the operand list.
2429 unsigned NumOps = MatcherTable[MatcherIndex++];
2430 SmallVector<SDValue, 8> Ops;
2431 for (unsigned i = 0; i != NumOps; ++i) {
2432 unsigned RecNo = MatcherTable[MatcherIndex++];
2434 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2436 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2437 Ops.push_back(RecordedNodes[RecNo]);
2440 // If there are variadic operands to add, handle them now.
2441 if (EmitNodeInfo & OPFL_VariadicInfo) {
2442 // Determine the start index to copy from.
2443 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2444 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2445 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2446 "Invalid variadic node");
2447 // Copy all of the variadic operands, not including a potential flag
2449 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2451 SDValue V = NodeToMatch->getOperand(i);
2452 if (V.getValueType() == MVT::Flag) break;
2457 // If this has chain/flag inputs, add them.
2458 if (EmitNodeInfo & OPFL_Chain)
2459 Ops.push_back(InputChain);
2460 if ((EmitNodeInfo & OPFL_FlagInput) && InputFlag.getNode() != 0)
2461 Ops.push_back(InputFlag);
2465 if (Opcode != OPC_MorphNodeTo) {
2466 // If this is a normal EmitNode command, just create the new node and
2467 // add the results to the RecordedNodes list.
2468 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2469 VTList, Ops.data(), Ops.size());
2471 // Add all the non-flag/non-chain results to the RecordedNodes list.
2472 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2473 if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
2474 RecordedNodes.push_back(SDValue(Res, i));
2478 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2482 // If the node had chain/flag results, update our notion of the current
2484 if (EmitNodeInfo & OPFL_FlagOutput) {
2485 InputFlag = SDValue(Res, VTs.size()-1);
2486 if (EmitNodeInfo & OPFL_Chain)
2487 InputChain = SDValue(Res, VTs.size()-2);
2488 } else if (EmitNodeInfo & OPFL_Chain)
2489 InputChain = SDValue(Res, VTs.size()-1);
2491 // If the OPFL_MemRefs flag is set on this node, slap all of the
2492 // accumulated memrefs onto it.
2494 // FIXME: This is vastly incorrect for patterns with multiple outputs
2495 // instructions that access memory and for ComplexPatterns that match
2497 if (EmitNodeInfo & OPFL_MemRefs) {
2498 MachineSDNode::mmo_iterator MemRefs =
2499 MF->allocateMemRefsArray(MatchedMemRefs.size());
2500 std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
2501 cast<MachineSDNode>(Res)
2502 ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
2506 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2507 << " node: "; Res->dump(CurDAG); errs() << "\n");
2509 // If this was a MorphNodeTo then we're completely done!
2510 if (Opcode == OPC_MorphNodeTo) {
2511 // Update chain and flag uses.
2512 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
2513 InputFlag, FlagResultNodesMatched, true);
2520 case OPC_MarkFlagResults: {
2521 unsigned NumNodes = MatcherTable[MatcherIndex++];
2523 // Read and remember all the flag-result nodes.
2524 for (unsigned i = 0; i != NumNodes; ++i) {
2525 unsigned RecNo = MatcherTable[MatcherIndex++];
2527 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2529 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2530 FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2535 case OPC_CompleteMatch: {
2536 // The match has been completed, and any new nodes (if any) have been
2537 // created. Patch up references to the matched dag to use the newly
2539 unsigned NumResults = MatcherTable[MatcherIndex++];
2541 for (unsigned i = 0; i != NumResults; ++i) {
2542 unsigned ResSlot = MatcherTable[MatcherIndex++];
2544 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2546 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2547 SDValue Res = RecordedNodes[ResSlot];
2549 assert(i < NodeToMatch->getNumValues() &&
2550 NodeToMatch->getValueType(i) != MVT::Other &&
2551 NodeToMatch->getValueType(i) != MVT::Flag &&
2552 "Invalid number of results to complete!");
2553 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2554 NodeToMatch->getValueType(i) == MVT::iPTR ||
2555 Res.getValueType() == MVT::iPTR ||
2556 NodeToMatch->getValueType(i).getSizeInBits() ==
2557 Res.getValueType().getSizeInBits()) &&
2558 "invalid replacement");
2559 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2562 // If the root node defines a flag, add it to the flag nodes to update
2564 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Flag)
2565 FlagResultNodesMatched.push_back(NodeToMatch);
2567 // Update chain and flag uses.
2568 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
2569 InputFlag, FlagResultNodesMatched, false);
2571 assert(NodeToMatch->use_empty() &&
2572 "Didn't replace all uses of the node?");
2574 // FIXME: We just return here, which interacts correctly with SelectRoot
2575 // above. We should fix this to not return an SDNode* anymore.
2580 // If the code reached this point, then the match failed. See if there is
2581 // another child to try in the current 'Scope', otherwise pop it until we
2582 // find a case to check.
2583 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
2584 ++NumDAGIselRetries;
2586 if (MatchScopes.empty()) {
2587 CannotYetSelect(NodeToMatch);
2591 // Restore the interpreter state back to the point where the scope was
2593 MatchScope &LastScope = MatchScopes.back();
2594 RecordedNodes.resize(LastScope.NumRecordedNodes);
2596 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2597 N = NodeStack.back();
2599 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2600 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2601 MatcherIndex = LastScope.FailIndex;
2603 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2605 InputChain = LastScope.InputChain;
2606 InputFlag = LastScope.InputFlag;
2607 if (!LastScope.HasChainNodesMatched)
2608 ChainNodesMatched.clear();
2609 if (!LastScope.HasFlagResultNodesMatched)
2610 FlagResultNodesMatched.clear();
2612 // Check to see what the offset is at the new MatcherIndex. If it is zero
2613 // we have reached the end of this scope, otherwise we have another child
2614 // in the current scope to try.
2615 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2616 if (NumToSkip & 128)
2617 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2619 // If we have another child in this scope to match, update FailIndex and
2621 if (NumToSkip != 0) {
2622 LastScope.FailIndex = MatcherIndex+NumToSkip;
2626 // End of this scope, pop it and try the next child in the containing
2628 MatchScopes.pop_back();
2635 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2637 raw_string_ostream Msg(msg);
2638 Msg << "Cannot yet select: ";
2640 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2641 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2642 N->getOpcode() != ISD::INTRINSIC_VOID) {
2643 N->printrFull(Msg, CurDAG);
2645 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2647 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2648 if (iid < Intrinsic::num_intrinsics)
2649 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2650 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2651 Msg << "target intrinsic %" << TII->getName(iid);
2653 Msg << "unknown intrinsic #" << iid;
2655 report_fatal_error(Msg.str());
2658 char SelectionDAGISel::ID = 0;