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