Move a few containers out of ScheduleDAGInstrs::BuildSchedGraph
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
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 implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/FastISel.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/GCMetadata.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/ScheduleDAGSDNodes.h"
37 #include "llvm/CodeGen/SchedulerRegistry.h"
38 #include "llvm/CodeGen/SelectionDAG.h"
39 #include "llvm/CodeGen/DwarfWriter.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetFrameInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/Timer.h"
51 #include <algorithm>
52 using namespace llvm;
53
54 static cl::opt<bool>
55 EnableValueProp("enable-value-prop", cl::Hidden);
56 static cl::opt<bool>
57 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
58 #ifndef NDEBUG
59 static cl::opt<bool>
60 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
61           cl::desc("Enable verbose messages in the \"fast\" "
62                    "instruction selector"));
63 static cl::opt<bool>
64 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
65           cl::desc("Enable abort calls when \"fast\" instruction fails"));
66 #else
67 static const bool EnableFastISelVerbose = false,
68                   EnableFastISelAbort = false;
69 #endif
70 static cl::opt<bool>
71 SchedLiveInCopies("schedule-livein-copies",
72                   cl::desc("Schedule copies of livein registers"),
73                   cl::init(false));
74
75 #ifndef NDEBUG
76 static cl::opt<bool>
77 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
78           cl::desc("Pop up a window to show dags before the first "
79                    "dag combine pass"));
80 static cl::opt<bool>
81 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
82           cl::desc("Pop up a window to show dags before legalize types"));
83 static cl::opt<bool>
84 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
85           cl::desc("Pop up a window to show dags before legalize"));
86 static cl::opt<bool>
87 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
88           cl::desc("Pop up a window to show dags before the second "
89                    "dag combine pass"));
90 static cl::opt<bool>
91 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
92           cl::desc("Pop up a window to show dags before the post legalize types"
93                    " dag combine pass"));
94 static cl::opt<bool>
95 ViewISelDAGs("view-isel-dags", cl::Hidden,
96           cl::desc("Pop up a window to show isel dags as they are selected"));
97 static cl::opt<bool>
98 ViewSchedDAGs("view-sched-dags", cl::Hidden,
99           cl::desc("Pop up a window to show sched dags as they are processed"));
100 static cl::opt<bool>
101 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
102       cl::desc("Pop up a window to show SUnit dags after they are processed"));
103 #else
104 static const bool ViewDAGCombine1 = false,
105                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
106                   ViewDAGCombine2 = false,
107                   ViewDAGCombineLT = false,
108                   ViewISelDAGs = false, ViewSchedDAGs = false,
109                   ViewSUnitDAGs = false;
110 #endif
111
112 //===---------------------------------------------------------------------===//
113 ///
114 /// RegisterScheduler class - Track the registration of instruction schedulers.
115 ///
116 //===---------------------------------------------------------------------===//
117 MachinePassRegistry RegisterScheduler::Registry;
118
119 //===---------------------------------------------------------------------===//
120 ///
121 /// ISHeuristic command line option for instruction schedulers.
122 ///
123 //===---------------------------------------------------------------------===//
124 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
125                RegisterPassParser<RegisterScheduler> >
126 ISHeuristic("pre-RA-sched",
127             cl::init(&createDefaultScheduler),
128             cl::desc("Instruction schedulers available (before register"
129                      " allocation):"));
130
131 static RegisterScheduler
132 defaultListDAGScheduler("default", "Best scheduler for the target",
133                         createDefaultScheduler);
134
135 namespace llvm {
136   //===--------------------------------------------------------------------===//
137   /// createDefaultScheduler - This creates an instruction scheduler appropriate
138   /// for the target.
139   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
140                                       bool Fast) {
141     const TargetLowering &TLI = IS->getTargetLowering();
142
143     if (Fast)
144       return createFastDAGScheduler(IS, Fast);
145     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
146       return createTDListDAGScheduler(IS, Fast);
147     assert(TLI.getSchedulingPreference() ==
148          TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
149     return createBURRListDAGScheduler(IS, Fast);
150   }
151 }
152
153 // EmitInstrWithCustomInserter - This method should be implemented by targets
154 // that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
155 // instructions are special in various ways, which require special support to
156 // insert.  The specified MachineInstr is created but not inserted into any
157 // basic blocks, and the scheduler passes ownership of it to this method.
158 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
159                                                        MachineBasicBlock *MBB) {
160   cerr << "If a target marks an instruction with "
161        << "'usesCustomDAGSchedInserter', it must implement "
162        << "TargetLowering::EmitInstrWithCustomInserter!\n";
163   abort();
164   return 0;  
165 }
166
167 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
168 /// physical register has only a single copy use, then coalesced the copy
169 /// if possible.
170 static void EmitLiveInCopy(MachineBasicBlock *MBB,
171                            MachineBasicBlock::iterator &InsertPos,
172                            unsigned VirtReg, unsigned PhysReg,
173                            const TargetRegisterClass *RC,
174                            DenseMap<MachineInstr*, unsigned> &CopyRegMap,
175                            const MachineRegisterInfo &MRI,
176                            const TargetRegisterInfo &TRI,
177                            const TargetInstrInfo &TII) {
178   unsigned NumUses = 0;
179   MachineInstr *UseMI = NULL;
180   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
181          UE = MRI.use_end(); UI != UE; ++UI) {
182     UseMI = &*UI;
183     if (++NumUses > 1)
184       break;
185   }
186
187   // If the number of uses is not one, or the use is not a move instruction,
188   // don't coalesce. Also, only coalesce away a virtual register to virtual
189   // register copy.
190   bool Coalesced = false;
191   unsigned SrcReg, DstReg;
192   if (NumUses == 1 &&
193       TII.isMoveInstr(*UseMI, SrcReg, DstReg) &&
194       TargetRegisterInfo::isVirtualRegister(DstReg)) {
195     VirtReg = DstReg;
196     Coalesced = true;
197   }
198
199   // Now find an ideal location to insert the copy.
200   MachineBasicBlock::iterator Pos = InsertPos;
201   while (Pos != MBB->begin()) {
202     MachineInstr *PrevMI = prior(Pos);
203     DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
204     // copyRegToReg might emit multiple instructions to do a copy.
205     unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
206     if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
207       // This is what the BB looks like right now:
208       // r1024 = mov r0
209       // ...
210       // r1    = mov r1024
211       //
212       // We want to insert "r1025 = mov r1". Inserting this copy below the
213       // move to r1024 makes it impossible for that move to be coalesced.
214       //
215       // r1025 = mov r1
216       // r1024 = mov r0
217       // ...
218       // r1    = mov 1024
219       // r2    = mov 1025
220       break; // Woot! Found a good location.
221     --Pos;
222   }
223
224   TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
225   CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
226   if (Coalesced) {
227     if (&*InsertPos == UseMI) ++InsertPos;
228     MBB->erase(UseMI);
229   }
230 }
231
232 /// EmitLiveInCopies - If this is the first basic block in the function,
233 /// and if it has live ins that need to be copied into vregs, emit the
234 /// copies into the block.
235 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
236                              const MachineRegisterInfo &MRI,
237                              const TargetRegisterInfo &TRI,
238                              const TargetInstrInfo &TII) {
239   if (SchedLiveInCopies) {
240     // Emit the copies at a heuristically-determined location in the block.
241     DenseMap<MachineInstr*, unsigned> CopyRegMap;
242     MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
243     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
244            E = MRI.livein_end(); LI != E; ++LI)
245       if (LI->second) {
246         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
247         EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
248                        RC, CopyRegMap, MRI, TRI, TII);
249       }
250   } else {
251     // Emit the copies into the top of the block.
252     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
253            E = MRI.livein_end(); LI != E; ++LI)
254       if (LI->second) {
255         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
256         TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
257                          LI->second, LI->first, RC, RC);
258       }
259   }
260 }
261
262 //===----------------------------------------------------------------------===//
263 // SelectionDAGISel code
264 //===----------------------------------------------------------------------===//
265
266 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, bool fast) :
267   FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
268   FuncInfo(new FunctionLoweringInfo(TLI)),
269   CurDAG(new SelectionDAG(TLI, *FuncInfo)),
270   SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
271   GFI(),
272   Fast(fast),
273   DAGSize(0)
274 {}
275
276 SelectionDAGISel::~SelectionDAGISel() {
277   delete SDL;
278   delete CurDAG;
279   delete FuncInfo;
280 }
281
282 unsigned SelectionDAGISel::MakeReg(MVT VT) {
283   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
284 }
285
286 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
287   AU.addRequired<AliasAnalysis>();
288   AU.addRequired<GCModuleInfo>();
289   AU.addRequired<DwarfWriter>();
290   AU.setPreservesAll();
291 }
292
293 bool SelectionDAGISel::runOnFunction(Function &Fn) {
294   // Do some sanity-checking on the command-line options.
295   assert((!EnableFastISelVerbose || EnableFastISel) &&
296          "-fast-isel-verbose requires -fast-isel");
297   assert((!EnableFastISelAbort || EnableFastISel) &&
298          "-fast-isel-abort requires -fast-isel");
299
300   // Get alias analysis for load/store combining.
301   AA = &getAnalysis<AliasAnalysis>();
302
303   TargetMachine &TM = TLI.getTargetMachine();
304   MF = &MachineFunction::construct(&Fn, TM);
305   const TargetInstrInfo &TII = *TM.getInstrInfo();
306   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
307
308   if (MF->getFunction()->hasGC())
309     GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
310   else
311     GFI = 0;
312   RegInfo = &MF->getRegInfo();
313   DOUT << "\n\n\n=== " << Fn.getName() << "\n";
314
315   FuncInfo->set(Fn, *MF, EnableFastISel);
316   MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
317   DwarfWriter *DW = getAnalysisToUpdate<DwarfWriter>();
318   CurDAG->init(*MF, MMI, DW);
319   SDL->init(GFI, *AA);
320
321   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
322     if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
323       // Mark landing pad.
324       FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
325
326   SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
327
328   // If the first basic block in the function has live ins that need to be
329   // copied into vregs, emit the copies into the top of the block before
330   // emitting the code for the block.
331   EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
332
333   // Add function live-ins to entry block live-in set.
334   for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
335          E = RegInfo->livein_end(); I != E; ++I)
336     MF->begin()->addLiveIn(I->first);
337
338 #ifndef NDEBUG
339   assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
340          "Not all catch info was assigned to a landing pad!");
341 #endif
342
343   FuncInfo->clear();
344
345   return true;
346 }
347
348 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
349                           MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
350   for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
351     if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
352       // Apply the catch info to DestBB.
353       AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
354 #ifndef NDEBUG
355       if (!FLI.MBBMap[SrcBB]->isLandingPad())
356         FLI.CatchInfoFound.insert(EHSel);
357 #endif
358     }
359 }
360
361 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
362 /// whether object offset >= 0.
363 static bool
364 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
365   if (!isa<FrameIndexSDNode>(Op)) return false;
366
367   FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
368   int FrameIdx =  FrameIdxNode->getIndex();
369   return MFI->isFixedObjectIndex(FrameIdx) &&
370     MFI->getObjectOffset(FrameIdx) >= 0;
371 }
372
373 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
374 /// possibly be overwritten when lowering the outgoing arguments in a tail
375 /// call. Currently the implementation of this call is very conservative and
376 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
377 /// virtual registers would be overwritten by direct lowering.
378 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
379                                                     MachineFrameInfo *MFI) {
380   RegisterSDNode * OpReg = NULL;
381   if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
382       (Op.getOpcode()== ISD::CopyFromReg &&
383        (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
384        (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
385       (Op.getOpcode() == ISD::LOAD &&
386        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
387       (Op.getOpcode() == ISD::MERGE_VALUES &&
388        Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
389        IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
390                                        getOperand(1))))
391     return true;
392   return false;
393 }
394
395 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
396 /// DAG and fixes their tailcall attribute operand.
397 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 
398                                            const TargetLowering& TLI) {
399   SDNode * Ret = NULL;
400   SDValue Terminator = DAG.getRoot();
401
402   // Find RET node.
403   if (Terminator.getOpcode() == ISD::RET) {
404     Ret = Terminator.getNode();
405   }
406  
407   // Fix tail call attribute of CALL nodes.
408   for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
409          BI = DAG.allnodes_end(); BI != BE; ) {
410     --BI;
411     if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
412       SDValue OpRet(Ret, 0);
413       SDValue OpCall(BI, 0);
414       bool isMarkedTailCall = TheCall->isTailCall();
415       // If CALL node has tail call attribute set to true and the call is not
416       // eligible (no RET or the target rejects) the attribute is fixed to
417       // false. The TargetLowering::IsEligibleForTailCallOptimization function
418       // must correctly identify tail call optimizable calls.
419       if (!isMarkedTailCall) continue;
420       if (Ret==NULL ||
421           !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
422         // Not eligible. Mark CALL node as non tail call. Note that we
423         // can modify the call node in place since calls are not CSE'd.
424         TheCall->setNotTailCall();
425       } else {
426         // Look for tail call clobbered arguments. Emit a series of
427         // copyto/copyfrom virtual register nodes to protect them.
428         SmallVector<SDValue, 32> Ops;
429         SDValue Chain = TheCall->getChain(), InFlag;
430         Ops.push_back(Chain);
431         Ops.push_back(TheCall->getCallee());
432         for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
433           SDValue Arg = TheCall->getArg(i);
434           bool isByVal = TheCall->getArgFlags(i).isByVal();
435           MachineFunction &MF = DAG.getMachineFunction();
436           MachineFrameInfo *MFI = MF.getFrameInfo();
437           if (!isByVal &&
438               IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
439             MVT VT = Arg.getValueType();
440             unsigned VReg = MF.getRegInfo().
441               createVirtualRegister(TLI.getRegClassFor(VT));
442             Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
443             InFlag = Chain.getValue(1);
444             Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
445             Chain = Arg.getValue(1);
446             InFlag = Arg.getValue(2);
447           }
448           Ops.push_back(Arg);
449           Ops.push_back(TheCall->getArgFlagsVal(i));
450         }
451         // Link in chain of CopyTo/CopyFromReg.
452         Ops[0] = Chain;
453         DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
454       }
455     }
456   }
457 }
458
459 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
460                                         BasicBlock::iterator Begin,
461                                         BasicBlock::iterator End) {
462   SDL->setCurrentBasicBlock(BB);
463
464   // Lower all of the non-terminator instructions.
465   for (BasicBlock::iterator I = Begin; I != End; ++I)
466     if (!isa<TerminatorInst>(I))
467       SDL->visit(*I);
468
469   // Ensure that all instructions which are used outside of their defining
470   // blocks are available as virtual registers.  Invoke is handled elsewhere.
471   for (BasicBlock::iterator I = Begin; I != End; ++I)
472     if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
473       DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I);
474       if (VMI != FuncInfo->ValueMap.end())
475         SDL->CopyValueToVirtualRegister(I, VMI->second);
476     }
477
478   // Handle PHI nodes in successor blocks.
479   if (End == LLVMBB->end()) {
480     HandlePHINodesInSuccessorBlocks(LLVMBB);
481
482     // Lower the terminator after the copies are emitted.
483     SDL->visit(*LLVMBB->getTerminator());
484   }
485     
486   // Make sure the root of the DAG is up-to-date.
487   CurDAG->setRoot(SDL->getControlRoot());
488
489   // Check whether calls in this block are real tail calls. Fix up CALL nodes
490   // with correct tailcall attribute so that the target can rely on the tailcall
491   // attribute indicating whether the call is really eligible for tail call
492   // optimization.
493   if (PerformTailCallOpt)
494     CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
495
496   // Final step, emit the lowered DAG as machine code.
497   CodeGenAndEmitDAG();
498   SDL->clear();
499 }
500
501 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
502   SmallPtrSet<SDNode*, 128> VisitedNodes;
503   SmallVector<SDNode*, 128> Worklist;
504   
505   Worklist.push_back(CurDAG->getRoot().getNode());
506   
507   APInt Mask;
508   APInt KnownZero;
509   APInt KnownOne;
510   
511   while (!Worklist.empty()) {
512     SDNode *N = Worklist.back();
513     Worklist.pop_back();
514     
515     // If we've already seen this node, ignore it.
516     if (!VisitedNodes.insert(N))
517       continue;
518     
519     // Otherwise, add all chain operands to the worklist.
520     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
521       if (N->getOperand(i).getValueType() == MVT::Other)
522         Worklist.push_back(N->getOperand(i).getNode());
523     
524     // If this is a CopyToReg with a vreg dest, process it.
525     if (N->getOpcode() != ISD::CopyToReg)
526       continue;
527     
528     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
529     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
530       continue;
531     
532     // Ignore non-scalar or non-integer values.
533     SDValue Src = N->getOperand(2);
534     MVT SrcVT = Src.getValueType();
535     if (!SrcVT.isInteger() || SrcVT.isVector())
536       continue;
537     
538     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
539     Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
540     CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
541     
542     // Only install this information if it tells us something.
543     if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
544       DestReg -= TargetRegisterInfo::FirstVirtualRegister;
545       FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
546       if (DestReg >= FLI.LiveOutRegInfo.size())
547         FLI.LiveOutRegInfo.resize(DestReg+1);
548       FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
549       LOI.NumSignBits = NumSignBits;
550       LOI.KnownOne = NumSignBits;
551       LOI.KnownZero = NumSignBits;
552     }
553   }
554 }
555
556 void SelectionDAGISel::CodeGenAndEmitDAG() {
557   std::string GroupName;
558   if (TimePassesIsEnabled)
559     GroupName = "Instruction Selection and Scheduling";
560   std::string BlockName;
561   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
562       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
563       ViewSUnitDAGs)
564     BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
565                 BB->getBasicBlock()->getName();
566
567   DOUT << "Initial selection DAG:\n";
568   DEBUG(CurDAG->dump());
569
570   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
571
572   // Run the DAG combiner in pre-legalize mode.
573   if (TimePassesIsEnabled) {
574     NamedRegionTimer T("DAG Combining 1", GroupName);
575     CurDAG->Combine(Unrestricted, *AA, Fast);
576   } else {
577     CurDAG->Combine(Unrestricted, *AA, Fast);
578   }
579   
580   DOUT << "Optimized lowered selection DAG:\n";
581   DEBUG(CurDAG->dump());
582   
583   // Second step, hack on the DAG until it only uses operations and types that
584   // the target supports.
585   if (!DisableLegalizeTypes) {
586     if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
587                                                  BlockName);
588
589     bool Changed;
590     if (TimePassesIsEnabled) {
591       NamedRegionTimer T("Type Legalization", GroupName);
592       Changed = CurDAG->LegalizeTypes();
593     } else {
594       Changed = CurDAG->LegalizeTypes();
595     }
596
597     DOUT << "Type-legalized selection DAG:\n";
598     DEBUG(CurDAG->dump());
599
600     if (Changed) {
601       if (ViewDAGCombineLT)
602         CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
603
604       // Run the DAG combiner in post-type-legalize mode.
605       if (TimePassesIsEnabled) {
606         NamedRegionTimer T("DAG Combining after legalize types", GroupName);
607         CurDAG->Combine(NoIllegalTypes, *AA, Fast);
608       } else {
609         CurDAG->Combine(NoIllegalTypes, *AA, Fast);
610       }
611
612       DOUT << "Optimized type-legalized selection DAG:\n";
613       DEBUG(CurDAG->dump());
614     }
615   }
616   
617   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
618
619   if (TimePassesIsEnabled) {
620     NamedRegionTimer T("DAG Legalization", GroupName);
621     CurDAG->Legalize(DisableLegalizeTypes);
622   } else {
623     CurDAG->Legalize(DisableLegalizeTypes);
624   }
625   
626   DOUT << "Legalized selection DAG:\n";
627   DEBUG(CurDAG->dump());
628   
629   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
630
631   // Run the DAG combiner in post-legalize mode.
632   if (TimePassesIsEnabled) {
633     NamedRegionTimer T("DAG Combining 2", GroupName);
634     CurDAG->Combine(NoIllegalOperations, *AA, Fast);
635   } else {
636     CurDAG->Combine(NoIllegalOperations, *AA, Fast);
637   }
638   
639   DOUT << "Optimized legalized selection DAG:\n";
640   DEBUG(CurDAG->dump());
641
642   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
643   
644   if (!Fast && EnableValueProp)
645     ComputeLiveOutVRegInfo();
646
647   // Third, instruction select all of the operations to machine code, adding the
648   // code to the MachineBasicBlock.
649   if (TimePassesIsEnabled) {
650     NamedRegionTimer T("Instruction Selection", GroupName);
651     InstructionSelect();
652   } else {
653     InstructionSelect();
654   }
655
656   DOUT << "Selected selection DAG:\n";
657   DEBUG(CurDAG->dump());
658
659   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
660
661   // Schedule machine code.
662   ScheduleDAG *Scheduler;
663   if (TimePassesIsEnabled) {
664     NamedRegionTimer T("Instruction Scheduling", GroupName);
665     Scheduler = Schedule();
666   } else {
667     Scheduler = Schedule();
668   }
669
670   if (ViewSUnitDAGs) Scheduler->viewGraph();
671
672   // Emit machine code to BB.  This can change 'BB' to the last block being 
673   // inserted into.
674   if (TimePassesIsEnabled) {
675     NamedRegionTimer T("Instruction Creation", GroupName);
676     BB = Scheduler->EmitSchedule();
677   } else {
678     BB = Scheduler->EmitSchedule();
679   }
680
681   // Free the scheduler state.
682   if (TimePassesIsEnabled) {
683     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
684     delete Scheduler;
685   } else {
686     delete Scheduler;
687   }
688
689   DOUT << "Selected machine code:\n";
690   DEBUG(BB->dump());
691 }  
692
693 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
694                                             MachineFunction &MF,
695                                             MachineModuleInfo *MMI,
696                                             DwarfWriter *DW,
697                                             const TargetInstrInfo &TII) {
698   // Initialize the Fast-ISel state, if needed.
699   FastISel *FastIS = 0;
700   if (EnableFastISel)
701     FastIS = TLI.createFastISel(MF, MMI, DW,
702                                 FuncInfo->ValueMap,
703                                 FuncInfo->MBBMap,
704                                 FuncInfo->StaticAllocaMap
705 #ifndef NDEBUG
706                                 , FuncInfo->CatchInfoLost
707 #endif
708                                 );
709
710   // Iterate over all basic blocks in the function.
711   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
712     BasicBlock *LLVMBB = &*I;
713     BB = FuncInfo->MBBMap[LLVMBB];
714
715     BasicBlock::iterator const Begin = LLVMBB->begin();
716     BasicBlock::iterator const End = LLVMBB->end();
717     BasicBlock::iterator BI = Begin;
718
719     // Lower any arguments needed in this block if this is the entry block.
720     bool SuppressFastISel = false;
721     if (LLVMBB == &Fn.getEntryBlock()) {
722       LowerArguments(LLVMBB);
723
724       // If any of the arguments has the byval attribute, forgo
725       // fast-isel in the entry block.
726       if (FastIS) {
727         unsigned j = 1;
728         for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
729              I != E; ++I, ++j)
730           if (Fn.paramHasAttr(j, Attribute::ByVal)) {
731             if (EnableFastISelVerbose || EnableFastISelAbort)
732               cerr << "FastISel skips entry block due to byval argument\n";
733             SuppressFastISel = true;
734             break;
735           }
736       }
737     }
738
739     if (MMI && BB->isLandingPad()) {
740       // Add a label to mark the beginning of the landing pad.  Deletion of the
741       // landing pad can thus be detected via the MachineModuleInfo.
742       unsigned LabelID = MMI->addLandingPad(BB);
743
744       const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
745       BuildMI(BB, II).addImm(LabelID);
746
747       // Mark exception register as live in.
748       unsigned Reg = TLI.getExceptionAddressRegister();
749       if (Reg) BB->addLiveIn(Reg);
750
751       // Mark exception selector register as live in.
752       Reg = TLI.getExceptionSelectorRegister();
753       if (Reg) BB->addLiveIn(Reg);
754
755       // FIXME: Hack around an exception handling flaw (PR1508): the personality
756       // function and list of typeids logically belong to the invoke (or, if you
757       // like, the basic block containing the invoke), and need to be associated
758       // with it in the dwarf exception handling tables.  Currently however the
759       // information is provided by an intrinsic (eh.selector) that can be moved
760       // to unexpected places by the optimizers: if the unwind edge is critical,
761       // then breaking it can result in the intrinsics being in the successor of
762       // the landing pad, not the landing pad itself.  This results in exceptions
763       // not being caught because no typeids are associated with the invoke.
764       // This may not be the only way things can go wrong, but it is the only way
765       // we try to work around for the moment.
766       BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
767
768       if (Br && Br->isUnconditional()) { // Critical edge?
769         BasicBlock::iterator I, E;
770         for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
771           if (isa<EHSelectorInst>(I))
772             break;
773
774         if (I == E)
775           // No catch info found - try to extract some from the successor.
776           copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
777       }
778     }
779
780     // Before doing SelectionDAG ISel, see if FastISel has been requested.
781     if (FastIS && !SuppressFastISel) {
782       // Emit code for any incoming arguments. This must happen before
783       // beginning FastISel on the entry block.
784       if (LLVMBB == &Fn.getEntryBlock()) {
785         CurDAG->setRoot(SDL->getControlRoot());
786         CodeGenAndEmitDAG();
787         SDL->clear();
788       }
789       FastIS->startNewBlock(BB);
790       // Do FastISel on as many instructions as possible.
791       for (; BI != End; ++BI) {
792         // Just before the terminator instruction, insert instructions to
793         // feed PHI nodes in successor blocks.
794         if (isa<TerminatorInst>(BI))
795           if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
796             if (EnableFastISelVerbose || EnableFastISelAbort) {
797               cerr << "FastISel miss: ";
798               BI->dump();
799             }
800             if (EnableFastISelAbort)
801               assert(0 && "FastISel didn't handle a PHI in a successor");
802             break;
803           }
804
805         // First try normal tablegen-generated "fast" selection.
806         if (FastIS->SelectInstruction(BI))
807           continue;
808
809         // Next, try calling the target to attempt to handle the instruction.
810         if (FastIS->TargetSelectInstruction(BI))
811           continue;
812
813         // Then handle certain instructions as single-LLVM-Instruction blocks.
814         if (isa<CallInst>(BI)) {
815           if (EnableFastISelVerbose || EnableFastISelAbort) {
816             cerr << "FastISel missed call: ";
817             BI->dump();
818           }
819
820           if (BI->getType() != Type::VoidTy) {
821             unsigned &R = FuncInfo->ValueMap[BI];
822             if (!R)
823               R = FuncInfo->CreateRegForValue(BI);
824           }
825
826           SelectBasicBlock(LLVMBB, BI, next(BI));
827           // If the instruction was codegen'd with multiple blocks,
828           // inform the FastISel object where to resume inserting.
829           FastIS->setCurrentBlock(BB);
830           continue;
831         }
832
833         // Otherwise, give up on FastISel for the rest of the block.
834         // For now, be a little lenient about non-branch terminators.
835         if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
836           if (EnableFastISelVerbose || EnableFastISelAbort) {
837             cerr << "FastISel miss: ";
838             BI->dump();
839           }
840           if (EnableFastISelAbort)
841             // The "fast" selector couldn't handle something and bailed.
842             // For the purpose of debugging, just abort.
843             assert(0 && "FastISel didn't select the entire block");
844         }
845         break;
846       }
847     }
848
849     // Run SelectionDAG instruction selection on the remainder of the block
850     // not handled by FastISel. If FastISel is not run, this is the entire
851     // block.
852     if (BI != End)
853       SelectBasicBlock(LLVMBB, BI, End);
854
855     FinishBasicBlock();
856   }
857
858   delete FastIS;
859 }
860
861 void
862 SelectionDAGISel::FinishBasicBlock() {
863
864   DOUT << "Target-post-processed machine code:\n";
865   DEBUG(BB->dump());
866
867   DOUT << "Total amount of phi nodes to update: "
868        << SDL->PHINodesToUpdate.size() << "\n";
869   DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
870           DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
871                << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
872   
873   // Next, now that we know what the last MBB the LLVM BB expanded is, update
874   // PHI nodes in successors.
875   if (SDL->SwitchCases.empty() &&
876       SDL->JTCases.empty() &&
877       SDL->BitTestCases.empty()) {
878     for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
879       MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
880       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
881              "This is not a machine PHI node that we are updating!");
882       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
883                                                 false));
884       PHI->addOperand(MachineOperand::CreateMBB(BB));
885     }
886     SDL->PHINodesToUpdate.clear();
887     return;
888   }
889
890   for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
891     // Lower header first, if it wasn't already lowered
892     if (!SDL->BitTestCases[i].Emitted) {
893       // Set the current basic block to the mbb we wish to insert the code into
894       BB = SDL->BitTestCases[i].Parent;
895       SDL->setCurrentBasicBlock(BB);
896       // Emit the code
897       SDL->visitBitTestHeader(SDL->BitTestCases[i]);
898       CurDAG->setRoot(SDL->getRoot());
899       CodeGenAndEmitDAG();
900       SDL->clear();
901     }    
902
903     for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
904       // Set the current basic block to the mbb we wish to insert the code into
905       BB = SDL->BitTestCases[i].Cases[j].ThisBB;
906       SDL->setCurrentBasicBlock(BB);
907       // Emit the code
908       if (j+1 != ej)
909         SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
910                               SDL->BitTestCases[i].Reg,
911                               SDL->BitTestCases[i].Cases[j]);
912       else
913         SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
914                               SDL->BitTestCases[i].Reg,
915                               SDL->BitTestCases[i].Cases[j]);
916         
917         
918       CurDAG->setRoot(SDL->getRoot());
919       CodeGenAndEmitDAG();
920       SDL->clear();
921     }
922
923     // Update PHI Nodes
924     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
925       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
926       MachineBasicBlock *PHIBB = PHI->getParent();
927       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
928              "This is not a machine PHI node that we are updating!");
929       // This is "default" BB. We have two jumps to it. From "header" BB and
930       // from last "case" BB.
931       if (PHIBB == SDL->BitTestCases[i].Default) {
932         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
933                                                   false));
934         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
935         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
936                                                   false));
937         PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
938                                                   back().ThisBB));
939       }
940       // One of "cases" BB.
941       for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
942            j != ej; ++j) {
943         MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
944         if (cBB->succ_end() !=
945             std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
946           PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
947                                                     false));
948           PHI->addOperand(MachineOperand::CreateMBB(cBB));
949         }
950       }
951     }
952   }
953   SDL->BitTestCases.clear();
954
955   // If the JumpTable record is filled in, then we need to emit a jump table.
956   // Updating the PHI nodes is tricky in this case, since we need to determine
957   // whether the PHI is a successor of the range check MBB or the jump table MBB
958   for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
959     // Lower header first, if it wasn't already lowered
960     if (!SDL->JTCases[i].first.Emitted) {
961       // Set the current basic block to the mbb we wish to insert the code into
962       BB = SDL->JTCases[i].first.HeaderBB;
963       SDL->setCurrentBasicBlock(BB);
964       // Emit the code
965       SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
966       CurDAG->setRoot(SDL->getRoot());
967       CodeGenAndEmitDAG();
968       SDL->clear();
969     }
970     
971     // Set the current basic block to the mbb we wish to insert the code into
972     BB = SDL->JTCases[i].second.MBB;
973     SDL->setCurrentBasicBlock(BB);
974     // Emit the code
975     SDL->visitJumpTable(SDL->JTCases[i].second);
976     CurDAG->setRoot(SDL->getRoot());
977     CodeGenAndEmitDAG();
978     SDL->clear();
979     
980     // Update PHI Nodes
981     for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
982       MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
983       MachineBasicBlock *PHIBB = PHI->getParent();
984       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
985              "This is not a machine PHI node that we are updating!");
986       // "default" BB. We can go there only from header BB.
987       if (PHIBB == SDL->JTCases[i].second.Default) {
988         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
989                                                   false));
990         PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
991       }
992       // JT BB. Just iterate over successors here
993       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
994         PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
995                                                   false));
996         PHI->addOperand(MachineOperand::CreateMBB(BB));
997       }
998     }
999   }
1000   SDL->JTCases.clear();
1001   
1002   // If the switch block involved a branch to one of the actual successors, we
1003   // need to update PHI nodes in that block.
1004   for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1005     MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1006     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1007            "This is not a machine PHI node that we are updating!");
1008     if (BB->isSuccessor(PHI->getParent())) {
1009       PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1010                                                 false));
1011       PHI->addOperand(MachineOperand::CreateMBB(BB));
1012     }
1013   }
1014   
1015   // If we generated any switch lowering information, build and codegen any
1016   // additional DAGs necessary.
1017   for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1018     // Set the current basic block to the mbb we wish to insert the code into
1019     BB = SDL->SwitchCases[i].ThisBB;
1020     SDL->setCurrentBasicBlock(BB);
1021     
1022     // Emit the code
1023     SDL->visitSwitchCase(SDL->SwitchCases[i]);
1024     CurDAG->setRoot(SDL->getRoot());
1025     CodeGenAndEmitDAG();
1026     SDL->clear();
1027     
1028     // Handle any PHI nodes in successors of this chunk, as if we were coming
1029     // from the original BB before switch expansion.  Note that PHI nodes can
1030     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1031     // handle them the right number of times.
1032     while ((BB = SDL->SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
1033       for (MachineBasicBlock::iterator Phi = BB->begin();
1034            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1035         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1036         for (unsigned pn = 0; ; ++pn) {
1037           assert(pn != SDL->PHINodesToUpdate.size() &&
1038                  "Didn't find PHI entry!");
1039           if (SDL->PHINodesToUpdate[pn].first == Phi) {
1040             Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1041                                                       second, false));
1042             Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1043             break;
1044           }
1045         }
1046       }
1047       
1048       // Don't process RHS if same block as LHS.
1049       if (BB == SDL->SwitchCases[i].FalseBB)
1050         SDL->SwitchCases[i].FalseBB = 0;
1051       
1052       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
1053       SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1054       SDL->SwitchCases[i].FalseBB = 0;
1055     }
1056     assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1057   }
1058   SDL->SwitchCases.clear();
1059
1060   SDL->PHINodesToUpdate.clear();
1061 }
1062
1063
1064 /// Schedule - Pick a safe ordering for instructions for each
1065 /// target node in the graph.
1066 ///
1067 ScheduleDAG *SelectionDAGISel::Schedule() {
1068   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1069   
1070   if (!Ctor) {
1071     Ctor = ISHeuristic;
1072     RegisterScheduler::setDefault(Ctor);
1073   }
1074   
1075   ScheduleDAG *Scheduler = Ctor(this, Fast);
1076   Scheduler->Run(CurDAG, BB);
1077
1078   return Scheduler;
1079 }
1080
1081
1082 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1083   return new HazardRecognizer();
1084 }
1085
1086 //===----------------------------------------------------------------------===//
1087 // Helper functions used by the generated instruction selector.
1088 //===----------------------------------------------------------------------===//
1089 // Calls to these methods are generated by tblgen.
1090
1091 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1092 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1093 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1094 /// specified in the .td file (e.g. 255).
1095 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 
1096                                     int64_t DesiredMaskS) const {
1097   const APInt &ActualMask = RHS->getAPIntValue();
1098   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1099   
1100   // If the actual mask exactly matches, success!
1101   if (ActualMask == DesiredMask)
1102     return true;
1103   
1104   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1105   if (ActualMask.intersects(~DesiredMask))
1106     return false;
1107   
1108   // Otherwise, the DAG Combiner may have proven that the value coming in is
1109   // either already zero or is not demanded.  Check for known zero input bits.
1110   APInt NeededMask = DesiredMask & ~ActualMask;
1111   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1112     return true;
1113   
1114   // TODO: check to see if missing bits are just not demanded.
1115
1116   // Otherwise, this pattern doesn't match.
1117   return false;
1118 }
1119
1120 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
1121 /// the dag combiner simplified the 255, we still want to match.  RHS is the
1122 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1123 /// specified in the .td file (e.g. 255).
1124 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 
1125                                    int64_t DesiredMaskS) const {
1126   const APInt &ActualMask = RHS->getAPIntValue();
1127   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1128   
1129   // If the actual mask exactly matches, success!
1130   if (ActualMask == DesiredMask)
1131     return true;
1132   
1133   // If the actual AND mask is allowing unallowed bits, this doesn't match.
1134   if (ActualMask.intersects(~DesiredMask))
1135     return false;
1136   
1137   // Otherwise, the DAG Combiner may have proven that the value coming in is
1138   // either already zero or is not demanded.  Check for known zero input bits.
1139   APInt NeededMask = DesiredMask & ~ActualMask;
1140   
1141   APInt KnownZero, KnownOne;
1142   CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1143   
1144   // If all the missing bits in the or are already known to be set, match!
1145   if ((NeededMask & KnownOne) == NeededMask)
1146     return true;
1147   
1148   // TODO: check to see if missing bits are just not demanded.
1149   
1150   // Otherwise, this pattern doesn't match.
1151   return false;
1152 }
1153
1154
1155 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1156 /// by tblgen.  Others should not call it.
1157 void SelectionDAGISel::
1158 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1159   std::vector<SDValue> InOps;
1160   std::swap(InOps, Ops);
1161
1162   Ops.push_back(InOps[0]);  // input chain.
1163   Ops.push_back(InOps[1]);  // input asm string.
1164
1165   unsigned i = 2, e = InOps.size();
1166   if (InOps[e-1].getValueType() == MVT::Flag)
1167     --e;  // Don't process a flag operand if it is here.
1168   
1169   while (i != e) {
1170     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1171     if ((Flags & 7) != 4 /*MEM*/) {
1172       // Just skip over this operand, copying the operands verbatim.
1173       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
1174       i += (Flags >> 3) + 1;
1175     } else {
1176       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
1177       // Otherwise, this is a memory operand.  Ask the target to select it.
1178       std::vector<SDValue> SelOps;
1179       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1180         cerr << "Could not match memory address.  Inline asm failure!\n";
1181         exit(1);
1182       }
1183       
1184       // Add this to the output node.
1185       MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1186       Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1187                                               IntPtrTy));
1188       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1189       i += 2;
1190     }
1191   }
1192   
1193   // Add the flag input back if present.
1194   if (e != InOps.size())
1195     Ops.push_back(InOps.back());
1196 }
1197
1198 char SelectionDAGISel::ID = 0;