switch the value# in OPC_CompleteMatch and OPC_EmitNode to use a
[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
221 enum BuiltinOpcodes {
222   OPC_Push, OPC_Push2,
223   OPC_RecordNode,
224   OPC_RecordMemRef,
225   OPC_CaptureFlagInput,
226   OPC_MoveChild,
227   OPC_MoveParent,
228   OPC_CheckSame,
229   OPC_CheckPatternPredicate,
230   OPC_CheckPredicate,
231   OPC_CheckOpcode,
232   OPC_CheckMultiOpcode,
233   OPC_CheckType,
234   OPC_CheckInteger1, OPC_CheckInteger2, OPC_CheckInteger4, OPC_CheckInteger8,
235   OPC_CheckCondCode,
236   OPC_CheckValueType,
237   OPC_CheckComplexPat,
238   OPC_CheckAndImm1, OPC_CheckAndImm2, OPC_CheckAndImm4, OPC_CheckAndImm8,
239   OPC_CheckOrImm1, OPC_CheckOrImm2, OPC_CheckOrImm4, OPC_CheckOrImm8,
240   OPC_CheckFoldableChainNode,
241   OPC_CheckChainCompatible,
242   
243   OPC_EmitInteger1, OPC_EmitInteger2, OPC_EmitInteger4, OPC_EmitInteger8,
244   OPC_EmitRegister,
245   OPC_EmitConvertToTarget,
246   OPC_EmitMergeInputChains,
247   OPC_EmitCopyToReg,
248   OPC_EmitNodeXForm,
249   OPC_EmitNode,
250   OPC_CompleteMatch
251 };
252
253 enum {
254   OPFL_None      = 0,     // Node has no chain or flag input and isn't variadic.
255   OPFL_Chain     = 1,     // Node has a chain input.
256   OPFL_Flag      = 2,     // Node has a flag input.
257   OPFL_MemRefs   = 4,     // Node gets accumulated MemRefs.
258   OPFL_Variadic0 = 1<<3,  // Node is variadic, root has 0 fixed inputs.
259   OPFL_Variadic1 = 2<<3,  // Node is variadic, root has 1 fixed inputs.
260   OPFL_Variadic2 = 3<<3,  // Node is variadic, root has 2 fixed inputs.
261   OPFL_Variadic3 = 4<<3,  // Node is variadic, root has 3 fixed inputs.
262   OPFL_Variadic4 = 5<<3,  // Node is variadic, root has 4 fixed inputs.
263   OPFL_Variadic5 = 6<<3,  // Node is variadic, root has 5 fixed inputs.
264   OPFL_Variadic6 = 7<<3,  // Node is variadic, root has 6 fixed inputs.
265   
266   OPFL_VariadicInfo = OPFL_Variadic6
267 };
268
269 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
270 /// number of fixed arity values that should be skipped when copying from the
271 /// root.
272 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
273   return ((Flags&OPFL_VariadicInfo) >> 3)-1;
274 }
275
276 struct MatchScope {
277   /// FailIndex - If this match fails, this is the index to continue with.
278   unsigned FailIndex;
279   
280   /// NodeStackSize - The size of the node stack when the scope was formed.
281   unsigned NodeStackSize;
282   
283   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
284   unsigned NumRecordedNodes;
285   
286   /// NumMatchedMemRefs - The number of matched memref entries.
287   unsigned NumMatchedMemRefs;
288   
289   /// InputChain/InputFlag - The current chain/flag 
290   SDValue InputChain, InputFlag;
291
292   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
293   bool HasChainNodesMatched;
294 };
295
296 SDNode *SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
297                          unsigned TableSize) {
298   // FIXME: Should these even be selected?  Handle these cases in the caller?
299   switch (NodeToMatch->getOpcode()) {
300   default:
301     break;
302   case ISD::EntryToken:       // These nodes remain the same.
303   case ISD::BasicBlock:
304   case ISD::Register:
305   case ISD::HANDLENODE:
306   case ISD::TargetConstant:
307   case ISD::TargetConstantFP:
308   case ISD::TargetConstantPool:
309   case ISD::TargetFrameIndex:
310   case ISD::TargetExternalSymbol:
311   case ISD::TargetBlockAddress:
312   case ISD::TargetJumpTable:
313   case ISD::TargetGlobalTLSAddress:
314   case ISD::TargetGlobalAddress:
315   case ISD::TokenFactor:
316   case ISD::CopyFromReg:
317   case ISD::CopyToReg:
318     return 0;
319   case ISD::AssertSext:
320   case ISD::AssertZext:
321     ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
322     return 0;
323   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
324   case ISD::EH_LABEL:  return Select_EH_LABEL(NodeToMatch);
325   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
326   }
327   
328   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
329
330   // Set up the node stack with NodeToMatch as the only node on the stack.
331   SmallVector<SDValue, 8> NodeStack;
332   SDValue N = SDValue(NodeToMatch, 0);
333   NodeStack.push_back(N);
334
335   // MatchScopes - Scopes used when matching, if a match failure happens, this
336   // indicates where to continue checking.
337   SmallVector<MatchScope, 8> MatchScopes;
338   
339   // RecordedNodes - This is the set of nodes that have been recorded by the
340   // state machine.
341   SmallVector<SDValue, 8> RecordedNodes;
342   
343   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
344   // pattern.
345   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
346   
347   // These are the current input chain and flag for use when generating nodes.
348   // Various Emit operations change these.  For example, emitting a copytoreg
349   // uses and updates these.
350   SDValue InputChain, InputFlag;
351   
352   // ChainNodesMatched - If a pattern matches nodes that have input/output
353   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
354   // which ones they are.  The result is captured into this list so that we can
355   // update the chain results when the pattern is complete.
356   SmallVector<SDNode*, 3> ChainNodesMatched;
357   
358   DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
359         NodeToMatch->dump(CurDAG);
360         errs() << '\n');
361   
362   // Interpreter starts at opcode #0.
363   unsigned MatcherIndex = 0;
364   while (1) {
365     assert(MatcherIndex < TableSize && "Invalid index");
366     switch ((BuiltinOpcodes)MatcherTable[MatcherIndex++]) {
367     case OPC_Push: {
368       unsigned NumToSkip = MatcherTable[MatcherIndex++];
369       MatchScope NewEntry;
370       NewEntry.FailIndex = MatcherIndex+NumToSkip;
371       NewEntry.NodeStackSize = NodeStack.size();
372       NewEntry.NumRecordedNodes = RecordedNodes.size();
373       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
374       NewEntry.InputChain = InputChain;
375       NewEntry.InputFlag = InputFlag;
376       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
377       MatchScopes.push_back(NewEntry);
378       continue;
379     }
380     case OPC_Push2: {
381       unsigned NumToSkip = GetInt2(MatcherTable, MatcherIndex);
382       MatchScope NewEntry;
383       NewEntry.FailIndex = MatcherIndex+NumToSkip;
384       NewEntry.NodeStackSize = NodeStack.size();
385       NewEntry.NumRecordedNodes = RecordedNodes.size();
386       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
387       NewEntry.InputChain = InputChain;
388       NewEntry.InputFlag = InputFlag;
389       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
390       MatchScopes.push_back(NewEntry);
391       continue;
392     }
393     case OPC_RecordNode:
394       // Remember this node, it may end up being an operand in the pattern.
395       RecordedNodes.push_back(N);
396       continue;
397     case OPC_RecordMemRef:
398       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
399       continue;
400         
401     case OPC_CaptureFlagInput:
402       // If the current node has an input flag, capture it in InputFlag.
403       if (N->getNumOperands() != 0 &&
404           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
405         InputFlag = N->getOperand(N->getNumOperands()-1);
406       continue;
407         
408     case OPC_MoveChild: {
409       unsigned Child = MatcherTable[MatcherIndex++];
410       if (Child >= N.getNumOperands())
411         break;  // Match fails if out of range child #.
412       N = N.getOperand(Child);
413       NodeStack.push_back(N);
414       continue;
415     }
416         
417     case OPC_MoveParent:
418       // Pop the current node off the NodeStack.
419       NodeStack.pop_back();
420       assert(!NodeStack.empty() && "Node stack imbalance!");
421       N = NodeStack.back();  
422       continue;
423      
424     case OPC_CheckSame: {
425       // Accept if it is exactly the same as a previously recorded node.
426       unsigned RecNo = MatcherTable[MatcherIndex++];
427       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
428       if (N != RecordedNodes[RecNo]) break;
429       continue;
430     }
431     case OPC_CheckPatternPredicate:
432       if (!CheckPatternPredicate(MatcherTable[MatcherIndex++])) break;
433       continue;
434     case OPC_CheckPredicate:
435       if (!CheckNodePredicate(N.getNode(), MatcherTable[MatcherIndex++])) break;
436       continue;
437     case OPC_CheckComplexPat:
438       if (!CheckComplexPattern(NodeToMatch, N, 
439                                MatcherTable[MatcherIndex++], RecordedNodes))
440         break;
441       continue;
442     case OPC_CheckOpcode:
443       if (N->getOpcode() != MatcherTable[MatcherIndex++]) break;
444       continue;
445         
446     case OPC_CheckMultiOpcode: {
447       unsigned NumOps = MatcherTable[MatcherIndex++];
448       bool OpcodeEquals = false;
449       for (unsigned i = 0; i != NumOps; ++i)
450         OpcodeEquals |= N->getOpcode() == MatcherTable[MatcherIndex++];
451       if (!OpcodeEquals) break;
452       continue;
453     }
454         
455     case OPC_CheckType: {
456       MVT::SimpleValueType VT =
457         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
458       if (N.getValueType() != VT) {
459         // Handle the case when VT is iPTR.
460         if (VT != MVT::iPTR || N.getValueType() != TLI.getPointerTy())
461           break;
462       }
463       continue;
464     }
465     case OPC_CheckCondCode:
466       if (cast<CondCodeSDNode>(N)->get() !=
467           (ISD::CondCode)MatcherTable[MatcherIndex++]) break;
468       continue;
469     case OPC_CheckValueType: {
470       MVT::SimpleValueType VT =
471         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
472       if (cast<VTSDNode>(N)->getVT() != VT) {
473         // Handle the case when VT is iPTR.
474         if (VT != MVT::iPTR || cast<VTSDNode>(N)->getVT() != TLI.getPointerTy())
475           break;
476       }
477       continue;
478     }
479     case OPC_CheckInteger1:
480       if (CheckInteger(N, GetInt1(MatcherTable, MatcherIndex))) break;
481       continue;
482     case OPC_CheckInteger2:
483       if (CheckInteger(N, GetInt2(MatcherTable, MatcherIndex))) break;
484       continue;
485     case OPC_CheckInteger4:
486       if (CheckInteger(N, GetInt4(MatcherTable, MatcherIndex))) break;
487       continue;
488     case OPC_CheckInteger8:
489       if (CheckInteger(N, GetInt8(MatcherTable, MatcherIndex))) break;
490       continue;
491         
492     case OPC_CheckAndImm1:
493       if (CheckAndImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
494       continue;
495     case OPC_CheckAndImm2:
496       if (CheckAndImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
497       continue;
498     case OPC_CheckAndImm4:
499       if (CheckAndImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
500       continue;
501     case OPC_CheckAndImm8:
502       if (CheckAndImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
503       continue;
504
505     case OPC_CheckOrImm1:
506       if (CheckOrImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
507       continue;
508     case OPC_CheckOrImm2:
509       if (CheckOrImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
510       continue;
511     case OPC_CheckOrImm4:
512       if (CheckOrImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
513       continue;
514     case OPC_CheckOrImm8:
515       if (CheckOrImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
516       continue;
517         
518     case OPC_CheckFoldableChainNode: {
519       assert(NodeStack.size() != 1 && "No parent node");
520       // Verify that all intermediate nodes between the root and this one have
521       // a single use.
522       bool HasMultipleUses = false;
523       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
524         if (!NodeStack[i].hasOneUse()) {
525           HasMultipleUses = true;
526           break;
527         }
528       if (HasMultipleUses) break;
529
530       // Check to see that the target thinks this is profitable to fold and that
531       // we can fold it without inducing cycles in the graph.
532       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
533                               NodeToMatch) ||
534           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
535                          NodeToMatch))
536         break;
537       
538       continue;
539     }
540     case OPC_CheckChainCompatible: {
541       unsigned PrevNode = MatcherTable[MatcherIndex++];
542       assert(PrevNode < RecordedNodes.size() && "Invalid CheckChainCompatible");
543       SDValue PrevChainedNode = RecordedNodes[PrevNode];
544       SDValue ThisChainedNode = RecordedNodes.back();
545       
546       // We have two nodes with chains, verify that their input chains are good.
547       assert(PrevChainedNode.getOperand(0).getValueType() == MVT::Other &&
548              ThisChainedNode.getOperand(0).getValueType() == MVT::Other &&
549              "Invalid chained nodes");
550       
551       if (!IsChainCompatible(// Input chain of the previous node.
552                              PrevChainedNode.getOperand(0).getNode(),
553                              // Node with chain.
554                              ThisChainedNode.getNode()))
555         break;
556       continue;
557     }
558         
559     case OPC_EmitInteger1: {
560       MVT::SimpleValueType VT =
561         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
562       EmitInteger(GetInt1(MatcherTable, MatcherIndex), VT, RecordedNodes);
563       continue;
564     }
565     case OPC_EmitInteger2: {
566       MVT::SimpleValueType VT =
567         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
568       EmitInteger(GetInt2(MatcherTable, MatcherIndex), VT, RecordedNodes);
569       continue;
570     }
571     case OPC_EmitInteger4: {
572       MVT::SimpleValueType VT =
573         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
574       EmitInteger(GetInt4(MatcherTable, MatcherIndex), VT, RecordedNodes);
575       continue;
576     }
577     case OPC_EmitInteger8: {
578       MVT::SimpleValueType VT =
579        (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
580       EmitInteger(GetInt8(MatcherTable, MatcherIndex), VT, RecordedNodes);
581       continue;
582     }
583         
584     case OPC_EmitRegister: {
585       MVT::SimpleValueType VT =
586         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
587       unsigned RegNo = MatcherTable[MatcherIndex++];
588       RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
589       continue;
590     }
591         
592     case OPC_EmitConvertToTarget:  {
593       // Convert from IMM/FPIMM to target version.
594       unsigned RecNo = MatcherTable[MatcherIndex++];
595       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
596       SDValue Imm = RecordedNodes[RecNo];
597
598       if (Imm->getOpcode() == ISD::Constant) {
599         int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
600         Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
601       } else if (Imm->getOpcode() == ISD::ConstantFP) {
602         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
603         Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
604       }
605       
606       RecordedNodes.push_back(Imm);
607       continue;
608     }
609         
610     case OPC_EmitMergeInputChains: {
611       assert(InputChain.getNode() == 0 &&
612              "EmitMergeInputChains should be the first chain producing node");
613       // This node gets a list of nodes we matched in the input that have
614       // chains.  We want to token factor all of the input chains to these nodes
615       // together.  However, if any of the input chains is actually one of the
616       // nodes matched in this pattern, then we have an intra-match reference.
617       // Ignore these because the newly token factored chain should not refer to
618       // the old nodes.
619       unsigned NumChains = MatcherTable[MatcherIndex++];
620       assert(NumChains != 0 && "Can't TF zero chains");
621       
622       // The common case here is that we have exactly one chain, which is really
623       // cheap to handle, just do it.
624       if (NumChains == 1) {
625         unsigned RecNo = MatcherTable[MatcherIndex++];
626         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
627         ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
628         InputChain = RecordedNodes[RecNo].getOperand(0);
629         assert(InputChain.getValueType() == MVT::Other && "Not a chain");
630         continue;
631       }
632       
633       // Read all of the chained nodes.
634       assert(ChainNodesMatched.empty() &&
635              "Should only have one EmitMergeInputChains per match");
636       for (unsigned i = 0; i != NumChains; ++i) {
637         unsigned RecNo = MatcherTable[MatcherIndex++];
638         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
639         ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
640       }
641
642       // Walk all the chained nodes, adding the input chains if they are not in
643       // ChainedNodes (and this, not in the matched pattern).  This is an N^2
644       // algorithm, but # chains is usually 2 here, at most 3 for MSP430.
645       SmallVector<SDValue, 3> InputChains;
646       for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
647         SDValue InChain = ChainNodesMatched[i]->getOperand(0);
648         assert(InChain.getValueType() == MVT::Other && "Not a chain");
649         bool Invalid = false;
650         for (unsigned j = 0; j != e; ++j)
651           Invalid |= ChainNodesMatched[j] == InChain.getNode();
652         if (!Invalid)
653           InputChains.push_back(InChain);
654       }
655
656       SDValue Res;
657       if (InputChains.size() == 1)
658         InputChain = InputChains[0];
659       else
660         InputChain = CurDAG->getNode(ISD::TokenFactor,
661                                      NodeToMatch->getDebugLoc(), MVT::Other,
662                                      &InputChains[0], InputChains.size());
663       continue;
664     }
665         
666     case OPC_EmitCopyToReg: {
667       unsigned RecNo = MatcherTable[MatcherIndex++];
668       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
669       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
670       
671       if (InputChain.getNode() == 0)
672         InputChain = CurDAG->getEntryNode();
673       
674       InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
675                                         DestPhysReg, RecordedNodes[RecNo],
676                                         InputFlag);
677       
678       InputFlag = InputChain.getValue(1);
679       continue;
680     }
681         
682     case OPC_EmitNodeXForm: {
683       unsigned XFormNo = MatcherTable[MatcherIndex++];
684       unsigned RecNo = MatcherTable[MatcherIndex++];
685       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
686       RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
687       continue;
688     }
689         
690     case OPC_EmitNode: {
691       uint16_t TargetOpc = GetInt2(MatcherTable, MatcherIndex);
692       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
693       // Get the result VT list.
694       unsigned NumVTs = MatcherTable[MatcherIndex++];
695       assert(NumVTs != 0 && "Invalid node result");
696       SmallVector<EVT, 4> VTs;
697       for (unsigned i = 0; i != NumVTs; ++i) {
698         MVT::SimpleValueType VT =
699           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
700         if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
701         VTs.push_back(VT);
702       }
703       
704       // FIXME: Use faster version for the common 'one VT' case?
705       SDVTList VTList = CurDAG->getVTList(VTs.data(), VTs.size());
706
707       // Get the operand list.
708       unsigned NumOps = MatcherTable[MatcherIndex++];
709       SmallVector<SDValue, 8> Ops;
710       for (unsigned i = 0; i != NumOps; ++i) {
711         unsigned RecNo = MatcherTable[MatcherIndex++];
712         if (RecNo & 128)
713           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
714         
715         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
716         Ops.push_back(RecordedNodes[RecNo]);
717       }
718       
719       // If there are variadic operands to add, handle them now.
720       if (EmitNodeInfo & OPFL_VariadicInfo) {
721         // Determine the start index to copy from.
722         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
723         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
724         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
725                "Invalid variadic node");
726         // Copy all of the variadic operands, not including a potential flag
727         // input.
728         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
729              i != e; ++i) {
730           SDValue V = NodeToMatch->getOperand(i);
731           if (V.getValueType() == MVT::Flag) break;
732           Ops.push_back(V);
733         }
734       }
735       
736       // If this has chain/flag inputs, add them.
737       if (EmitNodeInfo & OPFL_Chain)
738         Ops.push_back(InputChain);
739       if ((EmitNodeInfo & OPFL_Flag) && InputFlag.getNode() != 0)
740         Ops.push_back(InputFlag);
741       
742       // Create the node.
743       MachineSDNode *Res = CurDAG->getMachineNode(TargetOpc,
744                                                   NodeToMatch->getDebugLoc(),
745                                                   VTList,
746                                                   Ops.data(), Ops.size());
747       // Add all the non-flag/non-chain results to the RecordedNodes list.
748       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
749         if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
750         RecordedNodes.push_back(SDValue(Res, i));
751       }
752       
753       // If the node had chain/flag results, update our notion of the current
754       // chain and flag.
755       if (VTs.back() == MVT::Flag) {
756         InputFlag = SDValue(Res, VTs.size()-1);
757         if (EmitNodeInfo & OPFL_Chain)
758           InputChain = SDValue(Res, VTs.size()-2);
759       } else if (EmitNodeInfo & OPFL_Chain)
760         InputChain = SDValue(Res, VTs.size()-1);
761
762       // If the OPFL_MemRefs flag is set on this node, slap all of the
763       // accumulated memrefs onto it.
764       //
765       // FIXME: This is vastly incorrect for patterns with multiple outputs
766       // instructions that access memory and for ComplexPatterns that match
767       // loads.
768       if (EmitNodeInfo & OPFL_MemRefs) {
769         MachineSDNode::mmo_iterator MemRefs =
770           MF->allocateMemRefsArray(MatchedMemRefs.size());
771         std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
772         Res->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
773       }
774       
775       DEBUG(errs() << "  Created node: "; Res->dump(CurDAG); errs() << "\n");
776       continue;
777     }
778       
779     case OPC_CompleteMatch: {
780       // The match has been completed, and any new nodes (if any) have been
781       // created.  Patch up references to the matched dag to use the newly
782       // created nodes.
783       unsigned NumResults = MatcherTable[MatcherIndex++];
784
785       for (unsigned i = 0; i != NumResults; ++i) {
786         unsigned ResSlot = MatcherTable[MatcherIndex++];
787         if (ResSlot & 128)
788           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
789         
790         assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
791         SDValue Res = RecordedNodes[ResSlot];
792         
793         // FIXME2: Eliminate this horrible hack by fixing the 'Gen' program
794         // after (parallel) on input patterns are removed.  This would also
795         // allow us to stop encoding #results in OPC_CompleteMatch's table
796         // entry.
797         if (NodeToMatch->getNumValues() <= i ||
798             NodeToMatch->getValueType(i) == MVT::Other ||
799             NodeToMatch->getValueType(i) == MVT::Flag)
800           break;
801         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
802                 NodeToMatch->getValueType(i) == MVT::iPTR ||
803                 Res.getValueType() == MVT::iPTR ||
804                 NodeToMatch->getValueType(i).getSizeInBits() ==
805                     Res.getValueType().getSizeInBits()) &&
806                "invalid replacement");
807         ReplaceUses(SDValue(NodeToMatch, i), Res);
808       }
809       
810       // Now that all the normal results are replaced, we replace the chain and
811       // flag results if present.
812       if (!ChainNodesMatched.empty()) {
813         assert(InputChain.getNode() != 0 &&
814                "Matched input chains but didn't produce a chain");
815         // Loop over all of the nodes we matched that produced a chain result.
816         // Replace all the chain results with the final chain we ended up with.
817         for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
818           SDNode *ChainNode = ChainNodesMatched[i];
819           SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
820           if (ChainVal.getValueType() == MVT::Flag)
821             ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
822           assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
823           ReplaceUses(ChainVal, InputChain);
824         }
825       }
826       // If the root node produces a flag, make sure to replace its flag
827       // result with the resultant flag.
828       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) ==
829             MVT::Flag)
830         ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues()-1),
831                     InputFlag);
832       
833       assert(NodeToMatch->use_empty() &&
834              "Didn't replace all uses of the node?");
835       
836       DEBUG(errs() << "ISEL: Match complete!\n");
837       
838       // FIXME: We just return here, which interacts correctly with SelectRoot
839       // above.  We should fix this to not return an SDNode* anymore.
840       return 0;
841     }
842     }
843     
844     // If the code reached this point, then the match failed pop out to the next
845     // match scope.
846     if (MatchScopes.empty()) {
847       CannotYetSelect(NodeToMatch);
848       return 0;
849     }
850     
851     const MatchScope &LastScope = MatchScopes.back();
852     RecordedNodes.resize(LastScope.NumRecordedNodes);
853     NodeStack.resize(LastScope.NodeStackSize);
854     N = NodeStack.back();
855
856     DEBUG(errs() << "  Match failed at index " << MatcherIndex
857                  << " continuing at " << LastScope.FailIndex << "\n");
858     
859     if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
860       MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
861     MatcherIndex = LastScope.FailIndex;
862     
863     InputChain = LastScope.InputChain;
864     InputFlag = LastScope.InputFlag;
865     if (!LastScope.HasChainNodesMatched)
866       ChainNodesMatched.clear();
867     
868     MatchScopes.pop_back();
869   }
870 }
871     
872
873 #endif /* LLVM_CODEGEN_DAGISEL_HEADER_H */