enhance the new isel to use SelectNodeTo for most patterns,
[oota-llvm.git] / include / llvm / CodeGen / DAGISelHeader.h
1 //==-llvm/CodeGen/DAGISelHeader.h - Common DAG ISel definitions  -*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides definitions of the common, target-independent methods and 
11 // data, which is used by SelectionDAG-based instruction selectors.
12 //
13 // *** NOTE: This file is #included into the middle of the target
14 // instruction selector class.  These functions are really methods.
15 // This is a little awkward, but it allows this code to be shared
16 // by all the targets while still being able to call into
17 // target-specific code without using a virtual function call.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_CODEGEN_DAGISEL_HEADER_H
22 #define LLVM_CODEGEN_DAGISEL_HEADER_H
23
24 /// ISelPosition - Node iterator marking the current position of
25 /// instruction selection as it procedes through the topologically-sorted
26 /// node list.
27 SelectionDAG::allnodes_iterator ISelPosition;
28
29 /// ChainNotReachable - Returns true if Chain does not reach Op.
30 static bool ChainNotReachable(SDNode *Chain, SDNode *Op) {
31   if (Chain->getOpcode() == ISD::EntryToken)
32     return true;
33   if (Chain->getOpcode() == ISD::TokenFactor)
34     return false;
35   if (Chain->getNumOperands() > 0) {
36     SDValue C0 = Chain->getOperand(0);
37     if (C0.getValueType() == MVT::Other)
38       return C0.getNode() != Op && ChainNotReachable(C0.getNode(), Op);
39   }
40   return true;
41 }
42
43 /// IsChainCompatible - Returns true if Chain is Op or Chain does not reach Op.
44 /// This is used to ensure that there are no nodes trapped between Chain, which
45 /// is the first chain node discovered in a pattern and Op, a later node, that
46 /// will not be selected into the pattern.
47 static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {
48   return Chain == Op || ChainNotReachable(Chain, Op);
49 }
50
51
52 /// ISelUpdater - helper class to handle updates of the 
53 /// instruciton selection graph.
54 class VISIBILITY_HIDDEN ISelUpdater : public SelectionDAG::DAGUpdateListener {
55   SelectionDAG::allnodes_iterator &ISelPosition;
56 public:
57   explicit ISelUpdater(SelectionDAG::allnodes_iterator &isp)
58     : ISelPosition(isp) {}
59   
60   /// NodeDeleted - Handle nodes deleted from the graph. If the
61   /// node being deleted is the current ISelPosition node, update
62   /// ISelPosition.
63   ///
64   virtual void NodeDeleted(SDNode *N, SDNode *E) {
65     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
66       ++ISelPosition;
67   }
68
69   /// NodeUpdated - Ignore updates for now.
70   virtual void NodeUpdated(SDNode *N) {}
71 };
72
73 /// ReplaceUses - replace all uses of the old node F with the use
74 /// of the new node T.
75 DISABLE_INLINE void ReplaceUses(SDValue F, SDValue T) {
76   ISelUpdater ISU(ISelPosition);
77   CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISU);
78 }
79
80 /// ReplaceUses - replace all uses of the old nodes F with the use
81 /// of the new nodes T.
82 DISABLE_INLINE void ReplaceUses(const SDValue *F, const SDValue *T,
83                                 unsigned Num) {
84   ISelUpdater ISU(ISelPosition);
85   CurDAG->ReplaceAllUsesOfValuesWith(F, T, Num, &ISU);
86 }
87
88 /// ReplaceUses - replace all uses of the old node F with the use
89 /// of the new node T.
90 DISABLE_INLINE void ReplaceUses(SDNode *F, SDNode *T) {
91   ISelUpdater ISU(ISelPosition);
92   CurDAG->ReplaceAllUsesWith(F, T, &ISU);
93 }
94
95 /// SelectRoot - Top level entry to DAG instruction selector.
96 /// Selects instructions starting at the root of the current DAG.
97 void SelectRoot(SelectionDAG &DAG) {
98   SelectRootInit();
99
100   // Create a dummy node (which is not added to allnodes), that adds
101   // a reference to the root node, preventing it from being deleted,
102   // and tracking any changes of the root.
103   HandleSDNode Dummy(CurDAG->getRoot());
104   ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
105   ++ISelPosition;
106
107   // The AllNodes list is now topological-sorted. Visit the
108   // nodes by starting at the end of the list (the root of the
109   // graph) and preceding back toward the beginning (the entry
110   // node).
111   while (ISelPosition != CurDAG->allnodes_begin()) {
112     SDNode *Node = --ISelPosition;
113     // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
114     // but there are currently some corner cases that it misses. Also, this
115     // makes it theoretically possible to disable the DAGCombiner.
116     if (Node->use_empty())
117       continue;
118
119     SDNode *ResNode = Select(Node);
120     // If node should not be replaced, continue with the next one.
121     if (ResNode == Node)
122       continue;
123     // Replace node.
124     if (ResNode)
125       ReplaceUses(Node, ResNode);
126
127     // If after the replacement this node is not used any more,
128     // remove this dead node.
129     if (Node->use_empty()) { // Don't delete EntryToken, etc.
130       ISelUpdater ISU(ISelPosition);
131       CurDAG->RemoveDeadNode(Node, &ISU);
132     }
133   }
134
135   CurDAG->setRoot(Dummy.getValue());
136 }
137
138
139 /// CheckInteger - Return true if the specified node is not a ConstantSDNode or
140 /// if it doesn't have the specified value.
141 static bool CheckInteger(SDValue V, int64_t Val) {
142   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
143   return C == 0 || C->getSExtValue() != Val;
144 }
145
146 /// CheckAndImmediate - Check to see if the specified node is an and with an
147 /// immediate returning true on failure.
148 ///
149 /// FIXME: Inline this gunk into CheckAndMask.
150 bool CheckAndImmediate(SDValue V, int64_t Val) {
151   if (V->getOpcode() == ISD::AND)
152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(V->getOperand(1)))
153       if (CheckAndMask(V.getOperand(0), C, Val))
154         return false;
155   return true;
156 }
157
158 /// CheckOrImmediate - Check to see if the specified node is an or with an
159 /// immediate returning true on failure.
160 ///
161 /// FIXME: Inline this gunk into CheckOrMask.
162 bool CheckOrImmediate(SDValue V, int64_t Val) {
163   if (V->getOpcode() == ISD::OR)
164     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(V->getOperand(1)))
165       if (CheckOrMask(V.getOperand(0), C, Val))
166         return false;
167   return true;
168 }
169
170 void EmitInteger(int64_t Val, MVT::SimpleValueType VT,
171                  SmallVectorImpl<SDValue> &RecordedNodes) {
172   RecordedNodes.push_back(CurDAG->getTargetConstant(Val, VT));
173 }
174
175 // These functions are marked always inline so that Idx doesn't get pinned to
176 // the stack.
177 ALWAYS_INLINE static int8_t
178 GetInt1(const unsigned char *MatcherTable, unsigned &Idx) {
179   return MatcherTable[Idx++];
180 }
181
182 ALWAYS_INLINE static int16_t
183 GetInt2(const unsigned char *MatcherTable, unsigned &Idx) {
184   int16_t Val = (uint8_t)GetInt1(MatcherTable, Idx);
185   Val |= int16_t(GetInt1(MatcherTable, Idx)) << 8;
186   return Val;
187 }
188
189 ALWAYS_INLINE static int32_t
190 GetInt4(const unsigned char *MatcherTable, unsigned &Idx) {
191   int32_t Val = (uint16_t)GetInt2(MatcherTable, Idx);
192   Val |= int32_t(GetInt2(MatcherTable, Idx)) << 16;
193   return Val;
194 }
195
196 ALWAYS_INLINE static int64_t
197 GetInt8(const unsigned char *MatcherTable, unsigned &Idx) {
198   int64_t Val = (uint32_t)GetInt4(MatcherTable, Idx);
199   Val |= int64_t(GetInt4(MatcherTable, Idx)) << 32;
200   return Val;
201 }
202
203 /// GetVBR - decode a vbr encoding whose top bit is set.
204 ALWAYS_INLINE static unsigned
205 GetVBR(unsigned Val, const unsigned char *MatcherTable, unsigned &Idx) {
206   assert(Val >= 128 && "Not a VBR");
207   Val &= 127;  // Remove first vbr bit.
208   
209   unsigned Shift = 7;
210   unsigned NextBits;
211   do {
212     NextBits = GetInt1(MatcherTable, Idx);
213     Val |= (NextBits&127) << Shift;
214     Shift += 7;
215   } while (NextBits & 128);
216   
217   return Val;
218 }
219
220 /// UpdateChainsAndFlags - When a match is complete, this method updates uses of
221 /// interior flag and chain results to use the new flag and chain results.
222 void UpdateChainsAndFlags(SDNode *NodeToMatch, SDValue InputChain,
223                           const SmallVectorImpl<SDNode*> &ChainNodesMatched,
224                           SDValue InputFlag,
225                           const SmallVectorImpl<SDNode*>&FlagResultNodesMatched,
226                           bool isSelectNodeTo) {
227   // Now that all the normal results are replaced, we replace the chain and
228   // flag results if present.
229   if (!ChainNodesMatched.empty()) {
230     assert(InputChain.getNode() != 0 &&
231            "Matched input chains but didn't produce a chain");
232     // Loop over all of the nodes we matched that produced a chain result.
233     // Replace all the chain results with the final chain we ended up with.
234     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
235       SDNode *ChainNode = ChainNodesMatched[i];
236       
237       // Don't replace the results of the root node if we're doing a
238       // SelectNodeTo.
239       if (ChainNode == NodeToMatch && isSelectNodeTo)
240         continue;
241       
242       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
243       if (ChainVal.getValueType() == MVT::Flag)
244         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
245       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
246       ReplaceUses(ChainVal, InputChain);
247     }
248   }
249   
250   // If the result produces a flag, update any flag results in the matched
251   // pattern with the flag result.
252   if (InputFlag.getNode() != 0) {
253     // Handle any interior nodes explicitly marked.
254     for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
255       SDNode *FRN = FlagResultNodesMatched[i];
256       assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
257              "Doesn't have a flag result");
258       ReplaceUses(SDValue(FRN, FRN->getNumValues()-1), InputFlag);
259     }
260   }
261   
262   DEBUG(errs() << "ISEL: Match complete!\n");
263 }
264
265
266 enum BuiltinOpcodes {
267   OPC_Scope,
268   OPC_RecordNode,
269   OPC_RecordChild0, OPC_RecordChild1, OPC_RecordChild2, OPC_RecordChild3, 
270   OPC_RecordChild4, OPC_RecordChild5, OPC_RecordChild6, OPC_RecordChild7,
271   OPC_RecordMemRef,
272   OPC_CaptureFlagInput,
273   OPC_MoveChild,
274   OPC_MoveParent,
275   OPC_CheckSame,
276   OPC_CheckPatternPredicate,
277   OPC_CheckPredicate,
278   OPC_CheckOpcode,
279   OPC_CheckMultiOpcode,
280   OPC_CheckType,
281   OPC_CheckChild0Type, OPC_CheckChild1Type, OPC_CheckChild2Type,
282   OPC_CheckChild3Type, OPC_CheckChild4Type, OPC_CheckChild5Type,
283   OPC_CheckChild6Type, OPC_CheckChild7Type,
284   OPC_CheckInteger1, OPC_CheckInteger2, OPC_CheckInteger4, OPC_CheckInteger8,
285   OPC_CheckCondCode,
286   OPC_CheckValueType,
287   OPC_CheckComplexPat,
288   OPC_CheckAndImm1, OPC_CheckAndImm2, OPC_CheckAndImm4, OPC_CheckAndImm8,
289   OPC_CheckOrImm1, OPC_CheckOrImm2, OPC_CheckOrImm4, OPC_CheckOrImm8,
290   OPC_CheckFoldableChainNode,
291   OPC_CheckChainCompatible,
292   
293   OPC_EmitInteger1, OPC_EmitInteger2, OPC_EmitInteger4, OPC_EmitInteger8,
294   OPC_EmitRegister,
295   OPC_EmitConvertToTarget,
296   OPC_EmitMergeInputChains,
297   OPC_EmitCopyToReg,
298   OPC_EmitNodeXForm,
299   OPC_EmitNode,
300   OPC_SelectNodeTo,
301   OPC_MarkFlagResults,
302   OPC_CompleteMatch
303 };
304
305 enum {
306   OPFL_None      = 0,     // Node has no chain or flag input and isn't variadic.
307   OPFL_Chain     = 1,     // Node has a chain input.
308   OPFL_Flag      = 2,     // Node has a flag input.
309   OPFL_MemRefs   = 4,     // Node gets accumulated MemRefs.
310   OPFL_Variadic0 = 1<<3,  // Node is variadic, root has 0 fixed inputs.
311   OPFL_Variadic1 = 2<<3,  // Node is variadic, root has 1 fixed inputs.
312   OPFL_Variadic2 = 3<<3,  // Node is variadic, root has 2 fixed inputs.
313   OPFL_Variadic3 = 4<<3,  // Node is variadic, root has 3 fixed inputs.
314   OPFL_Variadic4 = 5<<3,  // Node is variadic, root has 4 fixed inputs.
315   OPFL_Variadic5 = 6<<3,  // Node is variadic, root has 5 fixed inputs.
316   OPFL_Variadic6 = 7<<3,  // Node is variadic, root has 6 fixed inputs.
317   
318   OPFL_VariadicInfo = OPFL_Variadic6
319 };
320
321 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
322 /// number of fixed arity values that should be skipped when copying from the
323 /// root.
324 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
325   return ((Flags&OPFL_VariadicInfo) >> 3)-1;
326 }
327
328 struct MatchScope {
329   /// FailIndex - If this match fails, this is the index to continue with.
330   unsigned FailIndex;
331   
332   /// NodeStack - The node stack when the scope was formed.
333   SmallVector<SDValue, 4> NodeStack;
334   
335   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
336   unsigned NumRecordedNodes;
337   
338   /// NumMatchedMemRefs - The number of matched memref entries.
339   unsigned NumMatchedMemRefs;
340   
341   /// InputChain/InputFlag - The current chain/flag 
342   SDValue InputChain, InputFlag;
343
344   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
345   bool HasChainNodesMatched, HasFlagResultNodesMatched;
346 };
347
348 SDNode *SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
349                          unsigned TableSize) {
350   // FIXME: Should these even be selected?  Handle these cases in the caller?
351   switch (NodeToMatch->getOpcode()) {
352   default:
353     break;
354   case ISD::EntryToken:       // These nodes remain the same.
355   case ISD::BasicBlock:
356   case ISD::Register:
357   case ISD::HANDLENODE:
358   case ISD::TargetConstant:
359   case ISD::TargetConstantFP:
360   case ISD::TargetConstantPool:
361   case ISD::TargetFrameIndex:
362   case ISD::TargetExternalSymbol:
363   case ISD::TargetBlockAddress:
364   case ISD::TargetJumpTable:
365   case ISD::TargetGlobalTLSAddress:
366   case ISD::TargetGlobalAddress:
367   case ISD::TokenFactor:
368   case ISD::CopyFromReg:
369   case ISD::CopyToReg:
370     return 0;
371   case ISD::AssertSext:
372   case ISD::AssertZext:
373     ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
374     return 0;
375   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
376   case ISD::EH_LABEL:  return Select_EH_LABEL(NodeToMatch);
377   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
378   }
379   
380   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
381
382   // Set up the node stack with NodeToMatch as the only node on the stack.
383   SmallVector<SDValue, 8> NodeStack;
384   SDValue N = SDValue(NodeToMatch, 0);
385   NodeStack.push_back(N);
386
387   // MatchScopes - Scopes used when matching, if a match failure happens, this
388   // indicates where to continue checking.
389   SmallVector<MatchScope, 8> MatchScopes;
390   
391   // RecordedNodes - This is the set of nodes that have been recorded by the
392   // state machine.
393   SmallVector<SDValue, 8> RecordedNodes;
394   
395   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
396   // pattern.
397   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
398   
399   // These are the current input chain and flag for use when generating nodes.
400   // Various Emit operations change these.  For example, emitting a copytoreg
401   // uses and updates these.
402   SDValue InputChain, InputFlag;
403   
404   // ChainNodesMatched - If a pattern matches nodes that have input/output
405   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
406   // which ones they are.  The result is captured into this list so that we can
407   // update the chain results when the pattern is complete.
408   SmallVector<SDNode*, 3> ChainNodesMatched;
409   SmallVector<SDNode*, 3> FlagResultNodesMatched;
410   
411   DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
412         NodeToMatch->dump(CurDAG);
413         errs() << '\n');
414   
415   // Interpreter starts at opcode #0.
416   unsigned MatcherIndex = 0;
417   while (1) {
418     assert(MatcherIndex < TableSize && "Invalid index");
419     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
420     switch (Opcode) {
421     case OPC_Scope: {
422       unsigned NumToSkip = MatcherTable[MatcherIndex++];
423       if (NumToSkip & 128)
424         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
425       assert(NumToSkip != 0 &&
426              "First entry of OPC_Scope shouldn't be 0, scope has no children?");
427
428       // Push a MatchScope which indicates where to go if the first child fails
429       // to match.
430       MatchScope NewEntry;
431       NewEntry.FailIndex = MatcherIndex+NumToSkip;
432       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
433       NewEntry.NumRecordedNodes = RecordedNodes.size();
434       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
435       NewEntry.InputChain = InputChain;
436       NewEntry.InputFlag = InputFlag;
437       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
438       NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
439       MatchScopes.push_back(NewEntry);
440       continue;
441     }
442     case OPC_RecordNode:
443       // Remember this node, it may end up being an operand in the pattern.
444       RecordedNodes.push_back(N);
445       continue;
446         
447     case OPC_RecordChild0: case OPC_RecordChild1:
448     case OPC_RecordChild2: case OPC_RecordChild3:
449     case OPC_RecordChild4: case OPC_RecordChild5:
450     case OPC_RecordChild6: case OPC_RecordChild7: {
451       unsigned ChildNo = Opcode-OPC_RecordChild0;
452       if (ChildNo >= N.getNumOperands())
453         break;  // Match fails if out of range child #.
454
455       RecordedNodes.push_back(N->getOperand(ChildNo));
456       continue;
457     }
458     case OPC_RecordMemRef:
459       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
460       continue;
461         
462     case OPC_CaptureFlagInput:
463       // If the current node has an input flag, capture it in InputFlag.
464       if (N->getNumOperands() != 0 &&
465           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
466         InputFlag = N->getOperand(N->getNumOperands()-1);
467       continue;
468         
469     case OPC_MoveChild: {
470       unsigned ChildNo = MatcherTable[MatcherIndex++];
471       if (ChildNo >= N.getNumOperands())
472         break;  // Match fails if out of range child #.
473       N = N.getOperand(ChildNo);
474       NodeStack.push_back(N);
475       continue;
476     }
477         
478     case OPC_MoveParent:
479       // Pop the current node off the NodeStack.
480       NodeStack.pop_back();
481       assert(!NodeStack.empty() && "Node stack imbalance!");
482       N = NodeStack.back();  
483       continue;
484      
485     case OPC_CheckSame: {
486       // Accept if it is exactly the same as a previously recorded node.
487       unsigned RecNo = MatcherTable[MatcherIndex++];
488       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
489       if (N != RecordedNodes[RecNo]) break;
490       continue;
491     }
492     case OPC_CheckPatternPredicate:
493       if (!CheckPatternPredicate(MatcherTable[MatcherIndex++])) break;
494       continue;
495     case OPC_CheckPredicate:
496       if (!CheckNodePredicate(N.getNode(), MatcherTable[MatcherIndex++])) break;
497       continue;
498     case OPC_CheckComplexPat:
499       if (!CheckComplexPattern(NodeToMatch, N, 
500                                MatcherTable[MatcherIndex++], RecordedNodes))
501         break;
502       continue;
503     case OPC_CheckOpcode:
504       if (N->getOpcode() != MatcherTable[MatcherIndex++]) break;
505       continue;
506         
507     case OPC_CheckMultiOpcode: {
508       unsigned NumOps = MatcherTable[MatcherIndex++];
509       bool OpcodeEquals = false;
510       for (unsigned i = 0; i != NumOps; ++i)
511         OpcodeEquals |= N->getOpcode() == MatcherTable[MatcherIndex++];
512       if (!OpcodeEquals) break;
513       continue;
514     }
515         
516     case OPC_CheckType: {
517       MVT::SimpleValueType VT =
518         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
519       if (N.getValueType() != VT) {
520         // Handle the case when VT is iPTR.
521         if (VT != MVT::iPTR || N.getValueType() != TLI.getPointerTy())
522           break;
523       }
524       continue;
525     }
526     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
527     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
528     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
529     case OPC_CheckChild6Type: case OPC_CheckChild7Type: {
530       unsigned ChildNo = Opcode-OPC_CheckChild0Type;
531       if (ChildNo >= N.getNumOperands())
532         break;  // Match fails if out of range child #.
533       
534       MVT::SimpleValueType VT =
535         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
536       EVT ChildVT = N.getOperand(ChildNo).getValueType();
537       if (ChildVT != VT) {
538         // Handle the case when VT is iPTR.
539         if (VT != MVT::iPTR || ChildVT != TLI.getPointerTy())
540           break;
541       }
542       continue;
543     }
544     case OPC_CheckCondCode:
545       if (cast<CondCodeSDNode>(N)->get() !=
546           (ISD::CondCode)MatcherTable[MatcherIndex++]) break;
547       continue;
548     case OPC_CheckValueType: {
549       MVT::SimpleValueType VT =
550         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
551       if (cast<VTSDNode>(N)->getVT() != VT) {
552         // Handle the case when VT is iPTR.
553         if (VT != MVT::iPTR || cast<VTSDNode>(N)->getVT() != TLI.getPointerTy())
554           break;
555       }
556       continue;
557     }
558     case OPC_CheckInteger1:
559       if (CheckInteger(N, GetInt1(MatcherTable, MatcherIndex))) break;
560       continue;
561     case OPC_CheckInteger2:
562       if (CheckInteger(N, GetInt2(MatcherTable, MatcherIndex))) break;
563       continue;
564     case OPC_CheckInteger4:
565       if (CheckInteger(N, GetInt4(MatcherTable, MatcherIndex))) break;
566       continue;
567     case OPC_CheckInteger8:
568       if (CheckInteger(N, GetInt8(MatcherTable, MatcherIndex))) break;
569       continue;
570         
571     case OPC_CheckAndImm1:
572       if (CheckAndImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
573       continue;
574     case OPC_CheckAndImm2:
575       if (CheckAndImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
576       continue;
577     case OPC_CheckAndImm4:
578       if (CheckAndImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
579       continue;
580     case OPC_CheckAndImm8:
581       if (CheckAndImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
582       continue;
583
584     case OPC_CheckOrImm1:
585       if (CheckOrImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
586       continue;
587     case OPC_CheckOrImm2:
588       if (CheckOrImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
589       continue;
590     case OPC_CheckOrImm4:
591       if (CheckOrImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
592       continue;
593     case OPC_CheckOrImm8:
594       if (CheckOrImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
595       continue;
596         
597     case OPC_CheckFoldableChainNode: {
598       assert(NodeStack.size() != 1 && "No parent node");
599       // Verify that all intermediate nodes between the root and this one have
600       // a single use.
601       bool HasMultipleUses = false;
602       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
603         if (!NodeStack[i].hasOneUse()) {
604           HasMultipleUses = true;
605           break;
606         }
607       if (HasMultipleUses) break;
608
609       // Check to see that the target thinks this is profitable to fold and that
610       // we can fold it without inducing cycles in the graph.
611       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
612                               NodeToMatch) ||
613           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
614                          NodeToMatch))
615         break;
616       
617       continue;
618     }
619     case OPC_CheckChainCompatible: {
620       unsigned PrevNode = MatcherTable[MatcherIndex++];
621       assert(PrevNode < RecordedNodes.size() && "Invalid CheckChainCompatible");
622       SDValue PrevChainedNode = RecordedNodes[PrevNode];
623       SDValue ThisChainedNode = RecordedNodes.back();
624       
625       // We have two nodes with chains, verify that their input chains are good.
626       assert(PrevChainedNode.getOperand(0).getValueType() == MVT::Other &&
627              ThisChainedNode.getOperand(0).getValueType() == MVT::Other &&
628              "Invalid chained nodes");
629       
630       if (!IsChainCompatible(// Input chain of the previous node.
631                              PrevChainedNode.getOperand(0).getNode(),
632                              // Node with chain.
633                              ThisChainedNode.getNode()))
634         break;
635       continue;
636     }
637         
638     case OPC_EmitInteger1: {
639       MVT::SimpleValueType VT =
640         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
641       EmitInteger(GetInt1(MatcherTable, MatcherIndex), VT, RecordedNodes);
642       continue;
643     }
644     case OPC_EmitInteger2: {
645       MVT::SimpleValueType VT =
646         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
647       EmitInteger(GetInt2(MatcherTable, MatcherIndex), VT, RecordedNodes);
648       continue;
649     }
650     case OPC_EmitInteger4: {
651       MVT::SimpleValueType VT =
652         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
653       EmitInteger(GetInt4(MatcherTable, MatcherIndex), VT, RecordedNodes);
654       continue;
655     }
656     case OPC_EmitInteger8: {
657       MVT::SimpleValueType VT =
658        (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
659       EmitInteger(GetInt8(MatcherTable, MatcherIndex), VT, RecordedNodes);
660       continue;
661     }
662         
663     case OPC_EmitRegister: {
664       MVT::SimpleValueType VT =
665         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
666       unsigned RegNo = MatcherTable[MatcherIndex++];
667       RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
668       continue;
669     }
670         
671     case OPC_EmitConvertToTarget:  {
672       // Convert from IMM/FPIMM to target version.
673       unsigned RecNo = MatcherTable[MatcherIndex++];
674       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
675       SDValue Imm = RecordedNodes[RecNo];
676
677       if (Imm->getOpcode() == ISD::Constant) {
678         int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
679         Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
680       } else if (Imm->getOpcode() == ISD::ConstantFP) {
681         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
682         Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
683       }
684       
685       RecordedNodes.push_back(Imm);
686       continue;
687     }
688         
689     case OPC_EmitMergeInputChains: {
690       assert(InputChain.getNode() == 0 &&
691              "EmitMergeInputChains should be the first chain producing node");
692       // This node gets a list of nodes we matched in the input that have
693       // chains.  We want to token factor all of the input chains to these nodes
694       // together.  However, if any of the input chains is actually one of the
695       // nodes matched in this pattern, then we have an intra-match reference.
696       // Ignore these because the newly token factored chain should not refer to
697       // the old nodes.
698       unsigned NumChains = MatcherTable[MatcherIndex++];
699       assert(NumChains != 0 && "Can't TF zero chains");
700
701       assert(ChainNodesMatched.empty() &&
702              "Should only have one EmitMergeInputChains per match");
703
704       // Handle the first chain.
705       unsigned RecNo = MatcherTable[MatcherIndex++];
706       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
707       ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
708       
709       // If the chained node is not the root, we can't fold it if it has
710       // multiple uses.
711       // FIXME: What if other value results of the node have uses not matched by
712       // this pattern?
713       if (ChainNodesMatched.back() != NodeToMatch &&
714           !RecordedNodes[RecNo].hasOneUse()) {
715         ChainNodesMatched.clear();
716         break;
717       }
718       
719       // The common case here is that we have exactly one chain, which is really
720       // cheap to handle, just do it.
721       if (NumChains == 1) {
722         InputChain = RecordedNodes[RecNo].getOperand(0);
723         assert(InputChain.getValueType() == MVT::Other && "Not a chain");
724         continue;
725       }
726       
727       // Read all of the chained nodes.
728       for (unsigned i = 1; i != NumChains; ++i) {
729         RecNo = MatcherTable[MatcherIndex++];
730         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
731         ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
732         
733         // FIXME: What if other value results of the node have uses not matched by
734         // this pattern?
735         if (ChainNodesMatched.back() != NodeToMatch &&
736             !RecordedNodes[RecNo].hasOneUse()) {
737           ChainNodesMatched.clear();
738           break;
739         }
740       }
741
742       // Walk all the chained nodes, adding the input chains if they are not in
743       // ChainedNodes (and this, not in the matched pattern).  This is an N^2
744       // algorithm, but # chains is usually 2 here, at most 3 for MSP430.
745       SmallVector<SDValue, 3> InputChains;
746       for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
747         SDValue InChain = ChainNodesMatched[i]->getOperand(0);
748         assert(InChain.getValueType() == MVT::Other && "Not a chain");
749         bool Invalid = false;
750         for (unsigned j = 0; j != e; ++j)
751           Invalid |= ChainNodesMatched[j] == InChain.getNode();
752         if (!Invalid)
753           InputChains.push_back(InChain);
754       }
755
756       SDValue Res;
757       if (InputChains.size() == 1)
758         InputChain = InputChains[0];
759       else
760         InputChain = CurDAG->getNode(ISD::TokenFactor,
761                                      NodeToMatch->getDebugLoc(), MVT::Other,
762                                      &InputChains[0], InputChains.size());
763       continue;
764     }
765         
766     case OPC_EmitCopyToReg: {
767       unsigned RecNo = MatcherTable[MatcherIndex++];
768       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
769       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
770       
771       if (InputChain.getNode() == 0)
772         InputChain = CurDAG->getEntryNode();
773       
774       InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
775                                         DestPhysReg, RecordedNodes[RecNo],
776                                         InputFlag);
777       
778       InputFlag = InputChain.getValue(1);
779       continue;
780     }
781         
782     case OPC_EmitNodeXForm: {
783       unsigned XFormNo = MatcherTable[MatcherIndex++];
784       unsigned RecNo = MatcherTable[MatcherIndex++];
785       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
786       RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
787       continue;
788     }
789         
790     case OPC_EmitNode:
791     case OPC_SelectNodeTo: {
792       uint16_t TargetOpc = GetInt2(MatcherTable, MatcherIndex);
793       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
794       // Get the result VT list.
795       unsigned NumVTs = MatcherTable[MatcherIndex++];
796       assert(NumVTs != 0 && "Invalid node result");
797       SmallVector<EVT, 4> VTs;
798       for (unsigned i = 0; i != NumVTs; ++i) {
799         MVT::SimpleValueType VT =
800           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
801         if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
802         VTs.push_back(VT);
803       }
804       
805       // FIXME: Use faster version for the common 'one VT' case?
806       SDVTList VTList = CurDAG->getVTList(VTs.data(), VTs.size());
807
808       // Get the operand list.
809       unsigned NumOps = MatcherTable[MatcherIndex++];
810       SmallVector<SDValue, 8> Ops;
811       for (unsigned i = 0; i != NumOps; ++i) {
812         unsigned RecNo = MatcherTable[MatcherIndex++];
813         if (RecNo & 128)
814           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
815         
816         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
817         Ops.push_back(RecordedNodes[RecNo]);
818       }
819       
820       // If there are variadic operands to add, handle them now.
821       if (EmitNodeInfo & OPFL_VariadicInfo) {
822         // Determine the start index to copy from.
823         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
824         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
825         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
826                "Invalid variadic node");
827         // Copy all of the variadic operands, not including a potential flag
828         // input.
829         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
830              i != e; ++i) {
831           SDValue V = NodeToMatch->getOperand(i);
832           if (V.getValueType() == MVT::Flag) break;
833           Ops.push_back(V);
834         }
835       }
836       
837       // If this has chain/flag inputs, add them.
838       if (EmitNodeInfo & OPFL_Chain)
839         Ops.push_back(InputChain);
840       if ((EmitNodeInfo & OPFL_Flag) && InputFlag.getNode() != 0)
841         Ops.push_back(InputFlag);
842       
843       // Create the node.
844       SDNode *Res = 0;
845       if (Opcode == OPC_SelectNodeTo) {
846         // It is possible we're using SelectNodeTo to replace a node with no
847         // normal results with one that has a normal result (or we could be
848         // adding a chain) and the input could have flags and chains as well.
849         // In this case we need to shifting the operands down.
850         // FIXME: This is a horrible hack and broken in obscure cases, no worse
851         // than the old isel though.  We should sink this into SelectNodeTo.
852         int OldFlagResultNo = -1, OldChainResultNo = -1;
853         
854         unsigned NTMNumResults = NodeToMatch->getNumValues();
855         if (NodeToMatch->getValueType(NTMNumResults-1) == MVT::Flag) {
856           OldFlagResultNo = NTMNumResults-1;
857           if (NTMNumResults != 1 &&
858               NodeToMatch->getValueType(NTMNumResults-2) == MVT::Other)
859             OldChainResultNo = NTMNumResults-2;
860         } else if (NodeToMatch->getValueType(NTMNumResults-1) == MVT::Other)
861           OldChainResultNo = NTMNumResults-1;
862         
863         Res = CurDAG->SelectNodeTo(NodeToMatch, TargetOpc, VTList,
864                                    Ops.data(), Ops.size());
865         
866         // FIXME: Whether the selected node has a flag result should come from
867         // flags on the node.
868         unsigned ResNumResults = Res->getNumValues();
869         if (Res->getValueType(ResNumResults-1) == MVT::Flag) {
870           // Move the flag if needed.
871           if (OldFlagResultNo != -1 &&
872               (unsigned)OldFlagResultNo != ResNumResults-1)
873             ReplaceUses(SDValue(Res, OldFlagResultNo), 
874                         SDValue(Res, ResNumResults-1));
875           --ResNumResults;
876         }
877
878         // Move the chain reference if needed.
879         if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
880             (unsigned)OldChainResultNo != ResNumResults-1)
881           ReplaceUses(SDValue(Res, OldChainResultNo), 
882                       SDValue(Res, ResNumResults-1));
883       } else {
884         Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
885                                      VTList, Ops.data(), Ops.size());
886       
887         // Add all the non-flag/non-chain results to the RecordedNodes list.
888         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
889           if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
890           RecordedNodes.push_back(SDValue(Res, i));
891         }
892       }
893       
894       // If the node had chain/flag results, update our notion of the current
895       // chain and flag.
896       if (VTs.back() == MVT::Flag) {
897         InputFlag = SDValue(Res, VTs.size()-1);
898         if (EmitNodeInfo & OPFL_Chain)
899           InputChain = SDValue(Res, VTs.size()-2);
900       } else if (EmitNodeInfo & OPFL_Chain)
901         InputChain = SDValue(Res, VTs.size()-1);
902
903       // If the OPFL_MemRefs flag is set on this node, slap all of the
904       // accumulated memrefs onto it.
905       //
906       // FIXME: This is vastly incorrect for patterns with multiple outputs
907       // instructions that access memory and for ComplexPatterns that match
908       // loads.
909       if (EmitNodeInfo & OPFL_MemRefs) {
910         MachineSDNode::mmo_iterator MemRefs =
911           MF->allocateMemRefsArray(MatchedMemRefs.size());
912         std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
913         cast<MachineSDNode>(Res)
914           ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
915       }
916       
917       DEBUG(errs() << "  "
918                    << (Opcode == OPC_SelectNodeTo ? "Selected" : "Created")
919                    << " node: "; Res->dump(CurDAG); errs() << "\n");
920       
921       // If this was a SelectNodeTo then we're completely done!
922       if (Opcode == OPC_SelectNodeTo) {
923         // Update chain and flag uses.
924         UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
925                              InputFlag, FlagResultNodesMatched, true);
926         return Res;
927       }
928       
929       continue;
930     }
931         
932     case OPC_MarkFlagResults: {
933       unsigned NumNodes = MatcherTable[MatcherIndex++];
934       
935       // Read and remember all the flag-result nodes.
936       for (unsigned i = 0; i != NumNodes; ++i) {
937         unsigned RecNo = MatcherTable[MatcherIndex++];
938         if (RecNo & 128)
939           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
940
941         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
942         FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
943       }
944       continue;
945     }
946       
947     case OPC_CompleteMatch: {
948       // The match has been completed, and any new nodes (if any) have been
949       // created.  Patch up references to the matched dag to use the newly
950       // created nodes.
951       unsigned NumResults = MatcherTable[MatcherIndex++];
952
953       for (unsigned i = 0; i != NumResults; ++i) {
954         unsigned ResSlot = MatcherTable[MatcherIndex++];
955         if (ResSlot & 128)
956           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
957         
958         assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
959         SDValue Res = RecordedNodes[ResSlot];
960         
961         // FIXME2: Eliminate this horrible hack by fixing the 'Gen' program
962         // after (parallel) on input patterns are removed.  This would also
963         // allow us to stop encoding #results in OPC_CompleteMatch's table
964         // entry.
965         if (NodeToMatch->getNumValues() <= i ||
966             NodeToMatch->getValueType(i) == MVT::Other ||
967             NodeToMatch->getValueType(i) == MVT::Flag)
968           break;
969         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
970                 NodeToMatch->getValueType(i) == MVT::iPTR ||
971                 Res.getValueType() == MVT::iPTR ||
972                 NodeToMatch->getValueType(i).getSizeInBits() ==
973                     Res.getValueType().getSizeInBits()) &&
974                "invalid replacement");
975         ReplaceUses(SDValue(NodeToMatch, i), Res);
976       }
977
978       // If the root node defines a flag, add it to the flag nodes to update
979       // list.
980       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Flag)
981         FlagResultNodesMatched.push_back(NodeToMatch);
982       
983       // Update chain and flag uses.
984       UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
985                            InputFlag, FlagResultNodesMatched, false);
986       
987       assert(NodeToMatch->use_empty() &&
988              "Didn't replace all uses of the node?");
989       
990       // FIXME: We just return here, which interacts correctly with SelectRoot
991       // above.  We should fix this to not return an SDNode* anymore.
992       return 0;
993     }
994     }
995     
996     // If the code reached this point, then the match failed.  See if there is
997     // another child to try in the current 'Scope', otherwise pop it until we
998     // find a case to check.
999     while (1) {
1000       if (MatchScopes.empty()) {
1001         CannotYetSelect(NodeToMatch);
1002         return 0;
1003       }
1004
1005       // Restore the interpreter state back to the point where the scope was
1006       // formed.
1007       MatchScope &LastScope = MatchScopes.back();
1008       RecordedNodes.resize(LastScope.NumRecordedNodes);
1009       NodeStack.clear();
1010       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
1011       N = NodeStack.back();
1012
1013       DEBUG(errs() << "  Match failed at index " << MatcherIndex
1014                    << " continuing at " << LastScope.FailIndex << "\n");
1015     
1016       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
1017         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
1018       MatcherIndex = LastScope.FailIndex;
1019       
1020       InputChain = LastScope.InputChain;
1021       InputFlag = LastScope.InputFlag;
1022       if (!LastScope.HasChainNodesMatched)
1023         ChainNodesMatched.clear();
1024       if (!LastScope.HasFlagResultNodesMatched)
1025         FlagResultNodesMatched.clear();
1026
1027       // Check to see what the offset is at the new MatcherIndex.  If it is zero
1028       // we have reached the end of this scope, otherwise we have another child
1029       // in the current scope to try.
1030       unsigned NumToSkip = MatcherTable[MatcherIndex++];
1031       if (NumToSkip & 128)
1032         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
1033
1034       // If we have another child in this scope to match, update FailIndex and
1035       // try it.
1036       if (NumToSkip != 0) {
1037         LastScope.FailIndex = MatcherIndex+NumToSkip;
1038         break;
1039       }
1040       
1041       // End of this scope, pop it and try the next child in the containing
1042       // scope.
1043       MatchScopes.pop_back();
1044     }
1045   }
1046 }
1047     
1048
1049 #endif /* LLVM_CODEGEN_DAGISEL_HEADER_H */