blob: 304e1bc026bbcd97efdcfc3a548e584315f0bed7 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Dan Gohman84fbac52009-02-06 17:22:58 +000015#include "ScheduleDAGSDNodes.h"
Dan Gohman2048b852009-11-23 18:04:58 +000016#include "SelectionDAGBuilder.h"
Dan Gohman4c3fd9f2010-07-07 16:01:37 +000017#include "llvm/CodeGen/FunctionLoweringInfo.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000018#include "llvm/CodeGen/SelectionDAGISel.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000019#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel713f0432009-09-16 21:09:07 +000020#include "llvm/Analysis/DebugInfo.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000021#include "llvm/Constants.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000022#include "llvm/Function.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner75c478a2009-10-27 17:02:08 +000027#include "llvm/LLVMContext.h"
Bill Wendling9af7e9a2010-05-26 19:46:12 +000028#include "llvm/Module.h"
Dan Gohman78eca172008-08-19 22:33:34 +000029#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000030#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000031#include "llvm/CodeGen/GCMetadata.h"
Bill Wendlingb92187a2010-05-14 21:14:32 +000032#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000035#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanfc54c552009-01-15 22:18:12 +000037#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000038#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000040#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmane1f188f2009-10-29 22:30:23 +000041#include "llvm/Target/TargetIntrinsicInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000042#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetLowering.h"
44#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000045#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000047#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000048#include "llvm/Support/ErrorHandling.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000049#include "llvm/Support/Timer.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000050#include "llvm/Support/raw_ostream.h"
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000051#include "llvm/ADT/Statistic.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000052#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000053using namespace llvm;
54
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000055STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
Devang Patel948f7d02010-10-25 20:55:43 +000056STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
57STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
Chris Lattnerbed993d2010-03-28 19:46:56 +000058STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
Nick Lewyckya568d662010-10-26 00:51:57 +000059
60#ifndef NDEBUG
Devang Patel948f7d02010-10-25 20:55:43 +000061STATISTIC(NumBBWithOutOfOrderLineInfo,
62 "Number of blocks with out of order line number info");
63STATISTIC(NumMBBWithOutOfOrderLineInfo,
64 "Number of machine blocks with out of order line number info");
Nick Lewyckya568d662010-10-26 00:51:57 +000065#endif
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000066
Chris Lattneread0d882008-06-17 06:09:18 +000067static cl::opt<bool>
Dan Gohman293d5f82008-09-09 22:06:46 +000068EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
Dan Gohmand659d502008-10-20 21:30:12 +000069 cl::desc("Enable verbose messages in the \"fast\" "
Dan Gohman293d5f82008-09-09 22:06:46 +000070 "instruction selector"));
71static cl::opt<bool>
Dan Gohman4344a5d2008-09-09 23:05:00 +000072EnableFastISelAbort("fast-isel-abort", cl::Hidden,
73 cl::desc("Enable abort calls when \"fast\" instruction fails"));
Chris Lattneread0d882008-06-17 06:09:18 +000074
Chris Lattnerda8abb02005-09-01 18:44:10 +000075#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000076static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000077ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
78 cl::desc("Pop up a window to show dags before the first "
79 "dag combine pass"));
80static cl::opt<bool>
81ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
82 cl::desc("Pop up a window to show dags before legalize types"));
83static cl::opt<bool>
84ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
85 cl::desc("Pop up a window to show dags before legalize"));
86static cl::opt<bool>
87ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
88 cl::desc("Pop up a window to show dags before the second "
89 "dag combine pass"));
90static cl::opt<bool>
Duncan Sands25cf2272008-11-24 14:53:14 +000091ViewDAGCombineLT("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"));
94static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000095ViewISelDAGs("view-isel-dags", cl::Hidden,
96 cl::desc("Pop up a window to show isel dags as they are selected"));
97static cl::opt<bool>
98ViewSchedDAGs("view-sched-dags", cl::Hidden,
99 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +0000100static cl::opt<bool>
101ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +0000102 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +0000103#else
Dan Gohman462dc7f2008-07-21 20:00:07 +0000104static const bool ViewDAGCombine1 = false,
105 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
106 ViewDAGCombine2 = false,
Duncan Sands25cf2272008-11-24 14:53:14 +0000107 ViewDAGCombineLT = false,
Dan Gohman462dc7f2008-07-21 20:00:07 +0000108 ViewISelDAGs = false, ViewSchedDAGs = false,
109 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +0000110#endif
111
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000112//===---------------------------------------------------------------------===//
113///
114/// RegisterScheduler class - Track the registration of instruction schedulers.
115///
116//===---------------------------------------------------------------------===//
117MachinePassRegistry RegisterScheduler::Registry;
118
119//===---------------------------------------------------------------------===//
120///
121/// ISHeuristic command line option for instruction schedulers.
122///
123//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000124static cl::opt<RegisterScheduler::FunctionPassCtor, false,
125 RegisterPassParser<RegisterScheduler> >
126ISHeuristic("pre-RA-sched",
127 cl::init(&createDefaultScheduler),
128 cl::desc("Instruction schedulers available (before register"
129 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000130
Dan Gohman844731a2008-05-13 00:00:25 +0000131static RegisterScheduler
Dan Gohmanb8cab922008-10-14 20:25:08 +0000132defaultListDAGScheduler("default", "Best scheduler for the target",
Dan Gohman844731a2008-05-13 00:00:25 +0000133 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000134
Chris Lattner1c08c712005-01-07 07:47:53 +0000135namespace llvm {
136 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000137 /// createDefaultScheduler - This creates an instruction scheduler appropriate
138 /// for the target.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000139 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
Bill Wendling98a366d2009-04-29 23:29:43 +0000140 CodeGenOpt::Level OptLevel) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000141 const TargetLowering &TLI = IS->getTargetLowering();
142
Bill Wendling98a366d2009-04-29 23:29:43 +0000143 if (OptLevel == CodeGenOpt::None)
Dan Gohmane667e012010-07-16 02:01:19 +0000144 return createSourceListDAGScheduler(IS, OptLevel);
Evan Cheng211ffa12010-05-19 20:19:50 +0000145 if (TLI.getSchedulingPreference() == Sched::Latency)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000146 return createTDListDAGScheduler(IS, OptLevel);
Evan Cheng15a16de2010-05-20 06:13:19 +0000147 if (TLI.getSchedulingPreference() == Sched::RegPressure)
148 return createBURRListDAGScheduler(IS, OptLevel);
Evan Cheng70017e42010-07-24 00:39:05 +0000149 if (TLI.getSchedulingPreference() == Sched::Hybrid)
150 return createHybridListDAGScheduler(IS, OptLevel);
151 assert(TLI.getSchedulingPreference() == Sched::ILP &&
Evan Cheng211ffa12010-05-19 20:19:50 +0000152 "Unknown sched type!");
Evan Cheng70017e42010-07-24 00:39:05 +0000153 return createILPListDAGScheduler(IS, OptLevel);
Jim Laskey9373beb2006-08-01 19:14:14 +0000154 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000155}
156
Evan Chengff9b3732008-01-30 18:18:23 +0000157// EmitInstrWithCustomInserter - This method should be implemented by targets
Dan Gohman533297b2009-10-29 18:10:34 +0000158// that mark instructions with the 'usesCustomInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +0000159// instructions are special in various ways, which require special support to
160// insert. The specified MachineInstr is created but not inserted into any
Dan Gohman533297b2009-10-29 18:10:34 +0000161// basic blocks, and this method is called to expand it into a sequence of
162// instructions, potentially also creating new basic blocks and control flow.
163// When new basic blocks are inserted and the edges from MBB to its successors
164// are modified, the method should insert pairs of <OldSucc, NewSucc> into the
165// DenseMap.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000166MachineBasicBlock *
167TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
168 MachineBasicBlock *MBB) const {
Torok Edwinf3689232009-07-12 20:07:01 +0000169#ifndef NDEBUG
David Greene1a053232010-01-05 01:26:11 +0000170 dbgs() << "If a target marks an instruction with "
Dan Gohman533297b2009-10-29 18:10:34 +0000171 "'usesCustomInserter', it must implement "
Torok Edwinf3689232009-07-12 20:07:01 +0000172 "TargetLowering::EmitInstrWithCustomInserter!";
173#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000174 llvm_unreachable(0);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000175 return 0;
Chris Lattner025c39b2005-08-26 20:54:47 +0000176}
177
Chris Lattner7041ee32005-01-11 05:56:49 +0000178//===----------------------------------------------------------------------===//
179// SelectionDAGISel code
180//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000181
Dan Gohmanf0757b02010-04-21 01:34:56 +0000182SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm, CodeGenOpt::Level OL) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000183 MachineFunctionPass(ID), TM(tm), TLI(*tm.getTargetLowering()),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000184 FuncInfo(new FunctionLoweringInfo(TLI)),
Dan Gohman7451d3e2010-05-29 17:03:36 +0000185 CurDAG(new SelectionDAG(tm)),
Dan Gohman55e59c12010-04-19 19:05:59 +0000186 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000187 GFI(),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000188 OptLevel(OL),
Owen Anderson081c34b2010-10-19 17:21:58 +0000189 DAGSize(0) {
190 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
191 initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
192 }
Dan Gohman7c3234c2008-08-27 23:52:12 +0000193
194SelectionDAGISel::~SelectionDAGISel() {
Dan Gohman2048b852009-11-23 18:04:58 +0000195 delete SDB;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000196 delete CurDAG;
197 delete FuncInfo;
198}
199
Chris Lattner495a0b52005-08-17 06:37:43 +0000200void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000201 AU.addRequired<AliasAnalysis>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000202 AU.addPreserved<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000203 AU.addRequired<GCModuleInfo>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000204 AU.addPreserved<GCModuleInfo>();
Dan Gohmanad2afc22009-07-31 18:16:33 +0000205 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner495a0b52005-08-17 06:37:43 +0000206}
Chris Lattner1c08c712005-01-07 07:47:53 +0000207
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000208/// FunctionCallsSetJmp - Return true if the function has a call to setjmp or
Bill Wendling8d717c72010-05-26 20:39:00 +0000209/// other function that gcc recognizes as "returning twice". This is used to
210/// limit code-gen optimizations on the machine function.
Bill Wendling804a2312010-05-26 21:53:50 +0000211///
212/// FIXME: Remove after <rdar://problem/8031714> is fixed.
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000213static bool FunctionCallsSetJmp(const Function *F) {
214 const Module *M = F->getParent();
Bill Wendling8d717c72010-05-26 20:39:00 +0000215 static const char *ReturnsTwiceFns[] = {
216 "setjmp",
217 "sigsetjmp",
218 "setjmp_syscall",
219 "savectx",
220 "qsetjmp",
221 "vfork",
222 "getcontext"
223 };
224#define NUM_RETURNS_TWICE_FNS sizeof(ReturnsTwiceFns) / sizeof(const char *)
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000225
Bill Wendling8d717c72010-05-26 20:39:00 +0000226 for (unsigned I = 0; I < NUM_RETURNS_TWICE_FNS; ++I)
227 if (const Function *Callee = M->getFunction(ReturnsTwiceFns[I])) {
228 if (!Callee->use_empty())
229 for (Value::const_use_iterator
230 I = Callee->use_begin(), E = Callee->use_end();
231 I != E; ++I)
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000232 if (const CallInst *CI = dyn_cast<CallInst>(*I))
Bill Wendling8d717c72010-05-26 20:39:00 +0000233 if (CI->getParent()->getParent() == F)
234 return true;
235 }
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000236
237 return false;
Bill Wendling8d717c72010-05-26 20:39:00 +0000238#undef NUM_RETURNS_TWICE_FNS
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000239}
240
Dan Gohmanad2afc22009-07-31 18:16:33 +0000241bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
Dan Gohman4344a5d2008-09-09 23:05:00 +0000242 // Do some sanity-checking on the command-line options.
243 assert((!EnableFastISelVerbose || EnableFastISel) &&
244 "-fast-isel-verbose requires -fast-isel");
245 assert((!EnableFastISelAbort || EnableFastISel) &&
246 "-fast-isel-abort requires -fast-isel");
247
Dan Gohmanae541aa2010-04-15 04:33:49 +0000248 const Function &Fn = *mf.getFunction();
Dan Gohman8a110532008-09-05 22:59:21 +0000249 const TargetInstrInfo &TII = *TM.getInstrInfo();
250 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
251
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000252 MF = &mf;
Dan Gohman79ce2762009-01-15 19:20:50 +0000253 RegInfo = &MF->getRegInfo();
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000254 AA = &getAnalysis<AliasAnalysis>();
255 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
256
David Greene1a053232010-01-05 01:26:11 +0000257 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000258
Chris Lattnerde6e7832010-04-05 06:10:13 +0000259 CurDAG->init(*MF);
Dan Gohman7451d3e2010-05-29 17:03:36 +0000260 FuncInfo->set(Fn, *MF);
Dan Gohman2048b852009-11-23 18:04:58 +0000261 SDB->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000262
Dan Gohman6a732b52010-04-14 20:05:00 +0000263 SelectAllBasicBlocks(Fn);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000264
Dan Gohman1b79a2f2010-05-01 00:33:28 +0000265 // If the first basic block in the function has live ins that need to be
Dan Gohman8a110532008-09-05 22:59:21 +0000266 // copied into vregs, emit the copies into the top of the block before
267 // emitting the code for the block.
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000268 MachineBasicBlock *EntryMBB = MF->begin();
269 RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
270
Devang Patel394427b2010-05-26 20:18:50 +0000271 DenseMap<unsigned, unsigned> LiveInMap;
272 if (!FuncInfo->ArgDbgValues.empty())
273 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
274 E = RegInfo->livein_end(); LI != E; ++LI)
275 if (LI->second)
276 LiveInMap.insert(std::make_pair(LI->first, LI->second));
277
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000278 // Insert DBG_VALUE instructions for function arguments to the entry block.
279 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
280 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
281 unsigned Reg = MI->getOperand(0).getReg();
282 if (TargetRegisterInfo::isPhysicalRegister(Reg))
283 EntryMBB->insert(EntryMBB->begin(), MI);
284 else {
285 MachineInstr *Def = RegInfo->getVRegDef(Reg);
286 MachineBasicBlock::iterator InsertPos = Def;
Evan Chengf1ced252010-05-04 00:58:39 +0000287 // FIXME: VR def may not be in entry block.
288 Def->getParent()->insert(llvm::next(InsertPos), MI);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000289 }
Devang Patel394427b2010-05-26 20:18:50 +0000290
291 // If Reg is live-in then update debug info to track its copy in a vreg.
292 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
293 if (LDI != LiveInMap.end()) {
294 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
295 MachineBasicBlock::iterator InsertPos = Def;
296 const MDNode *Variable =
297 MI->getOperand(MI->getNumOperands()-1).getMetadata();
298 unsigned Offset = MI->getOperand(1).getImm();
299 // Def is never a terminator here, so it is ok to increment InsertPos.
300 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
301 TII.get(TargetOpcode::DBG_VALUE))
302 .addReg(LDI->second, RegState::Debug)
303 .addImm(Offset).addMetadata(Variable);
Devang Patel44cfe142010-09-21 20:56:33 +0000304
305 // If this vreg is directly copied into an exported register then
306 // that COPY instructions also need DBG_VALUE, if it is the only
307 // user of LDI->second.
308 MachineInstr *CopyUseMI = NULL;
309 for (MachineRegisterInfo::use_iterator
310 UI = RegInfo->use_begin(LDI->second);
311 MachineInstr *UseMI = UI.skipInstruction();) {
312 if (UseMI->isDebugValue()) continue;
313 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
314 CopyUseMI = UseMI; continue;
315 }
316 // Otherwise this is another use or second copy use.
317 CopyUseMI = NULL; break;
318 }
319 if (CopyUseMI) {
320 MachineInstr *NewMI =
321 BuildMI(*MF, CopyUseMI->getDebugLoc(),
322 TII.get(TargetOpcode::DBG_VALUE))
323 .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
324 .addImm(Offset).addMetadata(Variable);
325 EntryMBB->insertAfter(CopyUseMI, NewMI);
326 }
Devang Patel394427b2010-05-26 20:18:50 +0000327 }
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000328 }
329
Bill Wendling53f76022010-05-17 23:09:50 +0000330 // Determine if there are any calls in this machine function.
331 MachineFrameInfo *MFI = MF->getFrameInfo();
332 if (!MFI->hasCalls()) {
333 for (MachineFunction::const_iterator
334 I = MF->begin(), E = MF->end(); I != E; ++I) {
335 const MachineBasicBlock *MBB = I;
336 for (MachineBasicBlock::const_iterator
337 II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
338 const TargetInstrDesc &TID = TM.getInstrInfo()->get(II->getOpcode());
Bill Wendling8886c492010-07-09 19:44:12 +0000339
340 // Operand 1 of an inline asm instruction indicates whether the asm
341 // needs stack or not.
Bill Wendlingc930cbc2010-07-08 22:38:02 +0000342 if ((II->isInlineAsm() && II->getOperand(1).getImm()) ||
343 (TID.isCall() && !TID.isReturn())) {
Bill Wendling53f76022010-05-17 23:09:50 +0000344 MFI->setHasCalls(true);
345 goto done;
346 }
347 }
348 }
349 done:;
350 }
351
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000352 // Determine if there is a call to setjmp in the machine function.
353 MF->setCallsSetJmp(FunctionCallsSetJmp(&Fn));
354
Dan Gohman84023e02010-07-10 09:00:22 +0000355 // Replace forward-declared registers with the registers containing
356 // the desired value.
357 MachineRegisterInfo &MRI = MF->getRegInfo();
358 for (DenseMap<unsigned, unsigned>::iterator
359 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
360 I != E; ++I) {
361 unsigned From = I->first;
362 unsigned To = I->second;
363 // If To is also scheduled to be replaced, find what its ultimate
364 // replacement is.
365 for (;;) {
366 DenseMap<unsigned, unsigned>::iterator J =
367 FuncInfo->RegFixups.find(To);
368 if (J == E) break;
369 To = J->second;
370 }
371 // Replace it.
372 MRI.replaceRegWith(From, To);
373 }
374
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000375 // Release function-specific state. SDB and CurDAG are already cleared
376 // at this point.
377 FuncInfo->clear();
Dan Gohman8a110532008-09-05 22:59:21 +0000378
Chris Lattner1c08c712005-01-07 07:47:53 +0000379 return true;
380}
381
Devang Pateldf8370b2010-10-25 21:31:46 +0000382void
Dan Gohman84023e02010-07-10 09:00:22 +0000383SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
Dan Gohmana9a33212010-04-20 00:29:35 +0000384 BasicBlock::const_iterator End,
385 bool &HadTailCall) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000386 // Lower all of the non-terminator instructions. If a call is emitted
Dan Gohmanf89d1dc2010-04-16 05:06:56 +0000387 // as a tail call, cease emitting nodes for this block. Terminators
388 // are handled below.
Dan Gohmanc105a2b2010-04-22 20:55:53 +0000389 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
Dan Gohmanf89d1dc2010-04-16 05:06:56 +0000390 SDB->visit(*I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000391
Chris Lattnera651cf62005-01-17 19:43:36 +0000392 // Make sure the root of the DAG is up-to-date.
Dan Gohman2048b852009-11-23 18:04:58 +0000393 CurDAG->setRoot(SDB->getControlRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000394 HadTailCall = SDB->HasTailCall;
395 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000396
397 // Final step, emit the lowered DAG as machine code.
Dan Gohman84023e02010-07-10 09:00:22 +0000398 CodeGenAndEmitDAG();
Devang Pateldf8370b2010-10-25 21:31:46 +0000399 return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000400}
401
Dan Gohmanf350b272008-08-23 02:25:05 +0000402void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +0000403 SmallPtrSet<SDNode*, 128> VisitedNodes;
404 SmallVector<SDNode*, 128> Worklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000405
Gabor Greifba36cb52008-08-28 21:40:38 +0000406 Worklist.push_back(CurDAG->getRoot().getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000407
Chris Lattneread0d882008-06-17 06:09:18 +0000408 APInt Mask;
409 APInt KnownZero;
410 APInt KnownOne;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000412 do {
413 SDNode *N = Worklist.pop_back_val();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000414
Chris Lattneread0d882008-06-17 06:09:18 +0000415 // If we've already seen this node, ignore it.
416 if (!VisitedNodes.insert(N))
417 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000418
Chris Lattneread0d882008-06-17 06:09:18 +0000419 // Otherwise, add all chain operands to the worklist.
420 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +0000421 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +0000422 Worklist.push_back(N->getOperand(i).getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000423
Chris Lattneread0d882008-06-17 06:09:18 +0000424 // If this is a CopyToReg with a vreg dest, process it.
425 if (N->getOpcode() != ISD::CopyToReg)
426 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000427
Chris Lattneread0d882008-06-17 06:09:18 +0000428 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
429 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
430 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000431
Chris Lattneread0d882008-06-17 06:09:18 +0000432 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +0000433 SDValue Src = N->getOperand(2);
Owen Andersone50ed302009-08-10 22:56:29 +0000434 EVT SrcVT = Src.getValueType();
Chris Lattneread0d882008-06-17 06:09:18 +0000435 if (!SrcVT.isInteger() || SrcVT.isVector())
436 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Dan Gohmanf350b272008-08-23 02:25:05 +0000438 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +0000439 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +0000440 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000441
Chris Lattneread0d882008-06-17 06:09:18 +0000442 // Only install this information if it tells us something.
443 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
444 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000445 if (DestReg >= FuncInfo->LiveOutRegInfo.size())
446 FuncInfo->LiveOutRegInfo.resize(DestReg+1);
447 FunctionLoweringInfo::LiveOutInfo &LOI =
448 FuncInfo->LiveOutRegInfo[DestReg];
Chris Lattneread0d882008-06-17 06:09:18 +0000449 LOI.NumSignBits = NumSignBits;
Dan Gohmana80efce2009-03-27 23:55:04 +0000450 LOI.KnownOne = KnownOne;
451 LOI.KnownZero = KnownZero;
Chris Lattneread0d882008-06-17 06:09:18 +0000452 }
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000453 } while (!Worklist.empty());
Chris Lattneread0d882008-06-17 06:09:18 +0000454}
455
Dan Gohman84023e02010-07-10 09:00:22 +0000456void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +0000457 std::string GroupName;
458 if (TimePassesIsEnabled)
459 GroupName = "Instruction Selection and Scheduling";
460 std::string BlockName;
461 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
Duncan Sands25cf2272008-11-24 14:53:14 +0000462 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
463 ViewSUnitDAGs)
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000464 BlockName = MF->getFunction()->getNameStr() + ":" +
Dan Gohman84023e02010-07-10 09:00:22 +0000465 FuncInfo->MBB->getBasicBlock()->getNameStr();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000466
Dan Gohman927f8662010-06-18 16:00:29 +0000467 DEBUG(dbgs() << "Initial selection DAG:\n"; CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000468
Dan Gohmanf350b272008-08-23 02:25:05 +0000469 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +0000470
Chris Lattneraf21d552005-10-10 16:47:10 +0000471 // Run the DAG combiner in pre-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000472 {
473 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000474 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000475 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000476
Dan Gohman927f8662010-06-18 16:00:29 +0000477 DEBUG(dbgs() << "Optimized lowered selection DAG:\n"; CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000478
Chris Lattner1c08c712005-01-07 07:47:53 +0000479 // Second step, hack on the DAG until it only uses operations and types that
480 // the target supports.
Dan Gohman714efc62009-12-05 17:51:33 +0000481 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
482 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000483
Dan Gohman714efc62009-12-05 17:51:33 +0000484 bool Changed;
Dan Gohman03c3dc72010-06-18 15:56:31 +0000485 {
486 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000487 Changed = CurDAG->LegalizeTypes();
488 }
489
Dan Gohman927f8662010-06-18 16:00:29 +0000490 DEBUG(dbgs() << "Type-legalized selection DAG:\n"; CurDAG->dump());
Dan Gohman714efc62009-12-05 17:51:33 +0000491
492 if (Changed) {
493 if (ViewDAGCombineLT)
494 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
495
496 // Run the DAG combiner in post-type-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000497 {
498 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
499 TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000500 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000501 }
502
Dan Gohman927f8662010-06-18 16:00:29 +0000503 DEBUG(dbgs() << "Optimized type-legalized selection DAG:\n";
504 CurDAG->dump());
Dan Gohman714efc62009-12-05 17:51:33 +0000505 }
Dan Gohman462dc7f2008-07-21 20:00:07 +0000506
Dan Gohman03c3dc72010-06-18 15:56:31 +0000507 {
508 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000509 Changed = CurDAG->LegalizeVectors();
510 }
Duncan Sands25cf2272008-11-24 14:53:14 +0000511
Dan Gohman714efc62009-12-05 17:51:33 +0000512 if (Changed) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000513 {
514 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
Bill Wendling98820072009-12-28 01:51:30 +0000515 CurDAG->LegalizeTypes();
Eli Friedman5c22c802009-05-23 12:35:30 +0000516 }
517
Dan Gohman714efc62009-12-05 17:51:33 +0000518 if (ViewDAGCombineLT)
519 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
Eli Friedman5c22c802009-05-23 12:35:30 +0000520
Dan Gohman714efc62009-12-05 17:51:33 +0000521 // Run the DAG combiner in post-type-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000522 {
523 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
524 TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000525 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Eli Friedman5c22c802009-05-23 12:35:30 +0000526 }
Dan Gohman714efc62009-12-05 17:51:33 +0000527
Dan Gohman927f8662010-06-18 16:00:29 +0000528 DEBUG(dbgs() << "Optimized vector-legalized selection DAG:\n";
529 CurDAG->dump());
Chris Lattner70587ea2008-07-10 23:37:50 +0000530 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000531
Dan Gohmanf350b272008-08-23 02:25:05 +0000532 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000533
Dan Gohman03c3dc72010-06-18 15:56:31 +0000534 {
535 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
Dan Gohman714efc62009-12-05 17:51:33 +0000536 CurDAG->Legalize(OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000537 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538
Dan Gohman927f8662010-06-18 16:00:29 +0000539 DEBUG(dbgs() << "Legalized selection DAG:\n"; CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000540
Dan Gohmanf350b272008-08-23 02:25:05 +0000541 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000542
Chris Lattneraf21d552005-10-10 16:47:10 +0000543 // Run the DAG combiner in post-legalize mode.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000544 {
545 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000546 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000547 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000548
Dan Gohman927f8662010-06-18 16:00:29 +0000549 DEBUG(dbgs() << "Optimized legalized selection DAG:\n"; CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +0000550
Dan Gohman4e39e9d2010-06-24 14:30:44 +0000551 if (OptLevel != CodeGenOpt::None)
Dan Gohmanf350b272008-08-23 02:25:05 +0000552 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +0000553
Chris Lattner552186d2010-03-14 19:27:55 +0000554 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
555
Chris Lattnera33ef482005-03-30 01:10:47 +0000556 // Third, instruction select all of the operations to machine code, adding the
557 // code to the MachineBasicBlock.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000558 {
559 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
Chris Lattner7c306da2010-03-02 06:34:30 +0000560 DoInstructionSelection();
Evan Chengebffb662008-07-01 17:59:20 +0000561 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000562
Dan Gohman927f8662010-06-18 16:00:29 +0000563 DEBUG(dbgs() << "Selected selection DAG:\n"; CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000564
Dan Gohmanf350b272008-08-23 02:25:05 +0000565 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000566
Dan Gohman5e843682008-07-14 18:19:29 +0000567 // Schedule machine code.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000568 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
Dan Gohman03c3dc72010-06-18 15:56:31 +0000569 {
570 NamedRegionTimer T("Instruction Scheduling", GroupName,
571 TimePassesIsEnabled);
Dan Gohman84023e02010-07-10 09:00:22 +0000572 Scheduler->Run(CurDAG, FuncInfo->MBB, FuncInfo->InsertPt);
Dan Gohman5e843682008-07-14 18:19:29 +0000573 }
574
Dan Gohman462dc7f2008-07-21 20:00:07 +0000575 if (ViewSUnitDAGs) Scheduler->viewGraph();
576
Daniel Dunbara279bc32009-09-20 02:20:51 +0000577 // Emit machine code to BB. This can change 'BB' to the last block being
Evan Chengdb8d56b2008-06-30 20:45:06 +0000578 // inserted into.
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +0000579 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
Dan Gohman03c3dc72010-06-18 15:56:31 +0000580 {
581 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
Dan Gohman84023e02010-07-10 09:00:22 +0000582
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +0000583 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule();
Dan Gohman84023e02010-07-10 09:00:22 +0000584 FuncInfo->InsertPt = Scheduler->InsertPos;
Dan Gohman5e843682008-07-14 18:19:29 +0000585 }
586
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +0000587 // If the block was split, make sure we update any references that are used to
588 // update PHI nodes later on.
589 if (FirstMBB != LastMBB)
590 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
591
Dan Gohman5e843682008-07-14 18:19:29 +0000592 // Free the scheduler state.
Dan Gohman03c3dc72010-06-18 15:56:31 +0000593 {
594 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
595 TimePassesIsEnabled);
Dan Gohman5e843682008-07-14 18:19:29 +0000596 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +0000597 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000598
Dan Gohman95140a42010-05-01 00:25:44 +0000599 // Free the SelectionDAG state, now that we're finished with it.
600 CurDAG->clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000601}
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner7c306da2010-03-02 06:34:30 +0000603void SelectionDAGISel::DoInstructionSelection() {
604 DEBUG(errs() << "===== Instruction selection begins:\n");
605
606 PreprocessISelDAG();
607
608 // Select target instructions for the DAG.
609 {
610 // Number all nodes with a topological order and set DAGSize.
611 DAGSize = CurDAG->AssignTopologicalOrder();
612
613 // Create a dummy node (which is not added to allnodes), that adds
614 // a reference to the root node, preventing it from being deleted,
615 // and tracking any changes of the root.
616 HandleSDNode Dummy(CurDAG->getRoot());
617 ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
618 ++ISelPosition;
619
620 // The AllNodes list is now topological-sorted. Visit the
621 // nodes by starting at the end of the list (the root of the
622 // graph) and preceding back toward the beginning (the entry
623 // node).
624 while (ISelPosition != CurDAG->allnodes_begin()) {
625 SDNode *Node = --ISelPosition;
626 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
627 // but there are currently some corner cases that it misses. Also, this
628 // makes it theoretically possible to disable the DAGCombiner.
629 if (Node->use_empty())
630 continue;
631
632 SDNode *ResNode = Select(Node);
633
Chris Lattner82dd3d32010-03-02 07:50:03 +0000634 // FIXME: This is pretty gross. 'Select' should be changed to not return
635 // anything at all and this code should be nuked with a tactical strike.
636
Chris Lattner7c306da2010-03-02 06:34:30 +0000637 // If node should not be replaced, continue with the next one.
Chris Lattner82dd3d32010-03-02 07:50:03 +0000638 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
Chris Lattner7c306da2010-03-02 06:34:30 +0000639 continue;
640 // Replace node.
641 if (ResNode)
642 ReplaceUses(Node, ResNode);
643
644 // If after the replacement this node is not used any more,
645 // remove this dead node.
646 if (Node->use_empty()) { // Don't delete EntryToken, etc.
647 ISelUpdater ISU(ISelPosition);
648 CurDAG->RemoveDeadNode(Node, &ISU);
649 }
650 }
651
652 CurDAG->setRoot(Dummy.getValue());
653 }
Bill Wendling53f76022010-05-17 23:09:50 +0000654
Chris Lattner7c306da2010-03-02 06:34:30 +0000655 DEBUG(errs() << "===== Instruction selection ends:\n");
656
657 PostprocessISelDAG();
Chris Lattner7c306da2010-03-02 06:34:30 +0000658}
659
Dan Gohman25208642010-04-14 19:53:31 +0000660/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
661/// do other setup for EH landing-pad blocks.
Dan Gohman84023e02010-07-10 09:00:22 +0000662void SelectionDAGISel::PrepareEHLandingPad() {
Dan Gohman25208642010-04-14 19:53:31 +0000663 // Add a label to mark the beginning of the landing pad. Deletion of the
664 // landing pad can thus be detected via the MachineModuleInfo.
Dan Gohman84023e02010-07-10 09:00:22 +0000665 MCSymbol *Label = MF->getMMI().addLandingPad(FuncInfo->MBB);
Dan Gohman25208642010-04-14 19:53:31 +0000666
Dan Gohman55e59c12010-04-19 19:05:59 +0000667 const TargetInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
Dan Gohman84023e02010-07-10 09:00:22 +0000668 BuildMI(*FuncInfo->MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
669 .addSym(Label);
Dan Gohman25208642010-04-14 19:53:31 +0000670
671 // Mark exception register as live in.
672 unsigned Reg = TLI.getExceptionAddressRegister();
Dan Gohman84023e02010-07-10 09:00:22 +0000673 if (Reg) FuncInfo->MBB->addLiveIn(Reg);
Dan Gohman25208642010-04-14 19:53:31 +0000674
675 // Mark exception selector register as live in.
676 Reg = TLI.getExceptionSelectorRegister();
Dan Gohman84023e02010-07-10 09:00:22 +0000677 if (Reg) FuncInfo->MBB->addLiveIn(Reg);
Dan Gohman25208642010-04-14 19:53:31 +0000678
679 // FIXME: Hack around an exception handling flaw (PR1508): the personality
680 // function and list of typeids logically belong to the invoke (or, if you
681 // like, the basic block containing the invoke), and need to be associated
682 // with it in the dwarf exception handling tables. Currently however the
683 // information is provided by an intrinsic (eh.selector) that can be moved
684 // to unexpected places by the optimizers: if the unwind edge is critical,
685 // then breaking it can result in the intrinsics being in the successor of
686 // the landing pad, not the landing pad itself. This results
687 // in exceptions not being caught because no typeids are associated with
688 // the invoke. This may not be the only way things can go wrong, but it
689 // is the only way we try to work around for the moment.
Dan Gohman84023e02010-07-10 09:00:22 +0000690 const BasicBlock *LLVMBB = FuncInfo->MBB->getBasicBlock();
Dan Gohman25208642010-04-14 19:53:31 +0000691 const BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
692
693 if (Br && Br->isUnconditional()) { // Critical edge?
694 BasicBlock::const_iterator I, E;
695 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
696 if (isa<EHSelectorInst>(I))
697 break;
698
699 if (I == E)
700 // No catch info found - try to extract some from the successor.
701 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF->getMMI(), *FuncInfo);
702 }
703}
Chris Lattner7c306da2010-03-02 06:34:30 +0000704
Chris Lattnerbeac75d2010-09-05 02:18:34 +0000705
706
707
708bool SelectionDAGISel::TryToFoldFastISelLoad(const LoadInst *LI,
709 FastISel *FastIS) {
710 // Don't try to fold volatile loads. Target has to deal with alignment
711 // constraints.
712 if (LI->isVolatile()) return false;
713
714 // Figure out which vreg this is going into.
715 unsigned LoadReg = FastIS->getRegForValue(LI);
716 assert(LoadReg && "Load isn't already assigned a vreg? ");
717
718 // Check to see what the uses of this vreg are. If it has no uses, or more
719 // than one use (at the machine instr level) then we can't fold it.
720 MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(LoadReg);
721 if (RI == RegInfo->reg_end())
722 return false;
723
724 // See if there is exactly one use of the vreg. If there are multiple uses,
725 // then the instruction got lowered to multiple machine instructions or the
726 // use of the loaded value ended up being multiple operands of the result, in
727 // either case, we can't fold this.
728 MachineRegisterInfo::reg_iterator PostRI = RI; ++PostRI;
729 if (PostRI != RegInfo->reg_end())
730 return false;
731
732 assert(RI.getOperand().isUse() &&
733 "The only use of the vreg must be a use, we haven't emitted the def!");
734
735 // Ask the target to try folding the load.
736 return FastIS->TryToFoldLoad(&*RI, RI.getOperandNo(), LI);
737}
738
Devang Patel948f7d02010-10-25 20:55:43 +0000739#ifndef NDEBUG
740/// CheckLineNumbers - Check if basic block instructions follow source order
741/// or not.
742static void CheckLineNumbers(const BasicBlock *BB) {
743 unsigned Line = 0;
744 unsigned Col = 0;
745 for (BasicBlock::const_iterator BI = BB->begin(),
746 BE = BB->end(); BI != BE; ++BI) {
747 const DebugLoc DL = BI->getDebugLoc();
748 if (DL.isUnknown()) continue;
749 unsigned L = DL.getLine();
750 unsigned C = DL.getCol();
751 if (L < Line || (L == Line && C < Col)) {
752 ++NumBBWithOutOfOrderLineInfo;
753 return;
754 }
755 Line = L;
756 Col = C;
757 }
758}
Chris Lattnerbeac75d2010-09-05 02:18:34 +0000759
Devang Patel948f7d02010-10-25 20:55:43 +0000760/// CheckLineNumbers - Check if machine basic block instructions follow source
761/// order or not.
762static void CheckLineNumbers(const MachineBasicBlock *MBB) {
763 unsigned Line = 0;
764 unsigned Col = 0;
765 for (MachineBasicBlock::const_iterator MBI = MBB->begin(),
766 MBE = MBB->end(); MBI != MBE; ++MBI) {
767 const DebugLoc DL = MBI->getDebugLoc();
768 if (DL.isUnknown()) continue;
769 unsigned L = DL.getLine();
770 unsigned C = DL.getCol();
771 if (L < Line || (L == Line && C < Col)) {
772 ++NumMBBWithOutOfOrderLineInfo;
773 return;
774 }
775 Line = L;
776 Col = C;
777 }
778}
779#endif
Chris Lattnerbeac75d2010-09-05 02:18:34 +0000780
Dan Gohman46510a72010-04-15 01:51:59 +0000781void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000782 // Initialize the Fast-ISel state, if needed.
783 FastISel *FastIS = 0;
784 if (EnableFastISel)
Dan Gohmana4160c32010-07-07 16:29:44 +0000785 FastIS = TLI.createFastISel(*FuncInfo);
Dan Gohmana43abd12008-09-29 21:55:50 +0000786
787 // Iterate over all basic blocks in the function.
Dan Gohman46510a72010-04-15 01:51:59 +0000788 for (Function::const_iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
789 const BasicBlock *LLVMBB = &*I;
Devang Patel948f7d02010-10-25 20:55:43 +0000790#ifndef NDEBUG
791 CheckLineNumbers(LLVMBB);
792#endif
Dan Gohman84023e02010-07-10 09:00:22 +0000793 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
794 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
Dan Gohmanf350b272008-08-23 02:25:05 +0000795
Dan Gohmanba5be5c2010-04-20 15:00:41 +0000796 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
Dan Gohman46510a72010-04-15 01:51:59 +0000797 BasicBlock::const_iterator const End = LLVMBB->end();
Dan Gohman84023e02010-07-10 09:00:22 +0000798 BasicBlock::const_iterator BI = End;
Dan Gohman5edd3612008-08-28 20:28:56 +0000799
Dan Gohman84023e02010-07-10 09:00:22 +0000800 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
801
802 // Setup an EH landing-pad block.
803 if (FuncInfo->MBB->isLandingPad())
804 PrepareEHLandingPad();
805
Dan Gohmanf5951412010-07-08 01:00:56 +0000806 // Lower any arguments needed in this block if this is the entry block.
807 if (LLVMBB == &Fn.getEntryBlock())
808 LowerArguments(LLVMBB);
809
Dan Gohmanf350b272008-08-23 02:25:05 +0000810 // Before doing SelectionDAG ISel, see if FastISel has been requested.
Dan Gohmand725f042010-05-01 02:44:23 +0000811 if (FastIS) {
Dan Gohman84023e02010-07-10 09:00:22 +0000812 FastIS->startNewBlock();
813
Dan Gohmanf5951412010-07-08 01:00:56 +0000814 // Emit code for any incoming arguments. This must happen before
815 // beginning FastISel on the entry block.
816 if (LLVMBB == &Fn.getEntryBlock()) {
817 CurDAG->setRoot(SDB->getControlRoot());
818 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +0000819 CodeGenAndEmitDAG();
820
821 // If we inserted any instructions at the beginning, make a note of
822 // where they are, so we can be sure to emit subsequent instructions
823 // after them.
824 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
825 FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
826 else
827 FastIS->setLastLocalValue(0);
Dan Gohmanf5951412010-07-08 01:00:56 +0000828 }
Dan Gohman84023e02010-07-10 09:00:22 +0000829
Dan Gohmana43abd12008-09-29 21:55:50 +0000830 // Do FastISel on as many instructions as possible.
Dan Gohman84023e02010-07-10 09:00:22 +0000831 for (; BI != Begin; --BI) {
832 const Instruction *Inst = llvm::prior(BI);
833
834 // If we no longer require this instruction, skip it.
835 if (!Inst->mayWriteToMemory() &&
836 !isa<TerminatorInst>(Inst) &&
837 !isa<DbgInfoIntrinsic>(Inst) &&
838 !FuncInfo->isExportedInst(Inst))
Dan Gohman20d4be12010-07-01 02:58:57 +0000839 continue;
Dan Gohman84023e02010-07-10 09:00:22 +0000840
841 // Bottom-up: reset the insert pos at the top, after any local-value
842 // instructions.
843 FastIS->recomputeInsertPt();
Dan Gohman20d4be12010-07-01 02:58:57 +0000844
Dan Gohman21c14e32010-01-12 04:32:35 +0000845 // Try to select the instruction with FastISel.
Chris Lattnerbeac75d2010-09-05 02:18:34 +0000846 if (FastIS->SelectInstruction(Inst)) {
847 // If fast isel succeeded, check to see if there is a single-use
848 // non-volatile load right before the selected instruction, and see if
849 // the load is used by the instruction. If so, try to fold it.
850 const Instruction *BeforeInst = 0;
851 if (Inst != Begin)
852 BeforeInst = llvm::prior(llvm::prior(BI));
853 if (BeforeInst && isa<LoadInst>(BeforeInst) &&
854 BeforeInst->hasOneUse() && *BeforeInst->use_begin() == Inst &&
855 TryToFoldFastISelLoad(cast<LoadInst>(BeforeInst), FastIS)) {
856 // If we succeeded, don't re-select the load.
857 --BI;
858 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000859 continue;
Chris Lattnerbeac75d2010-09-05 02:18:34 +0000860 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000861
862 // Then handle certain instructions as single-LLVM-Instruction blocks.
Dan Gohman84023e02010-07-10 09:00:22 +0000863 if (isa<CallInst>(Inst)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000864 ++NumFastIselFailures;
Dan Gohmana43abd12008-09-29 21:55:50 +0000865 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000866 dbgs() << "FastISel missed call: ";
Dan Gohman84023e02010-07-10 09:00:22 +0000867 Inst->dump();
Dan Gohmana43abd12008-09-29 21:55:50 +0000868 }
869
Dan Gohman84023e02010-07-10 09:00:22 +0000870 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
871 unsigned &R = FuncInfo->ValueMap[Inst];
Dan Gohmana43abd12008-09-29 21:55:50 +0000872 if (!R)
Dan Gohman84023e02010-07-10 09:00:22 +0000873 R = FuncInfo->CreateRegs(Inst->getType());
Dan Gohmana43abd12008-09-29 21:55:50 +0000874 }
875
Dan Gohmanb4afb132009-11-20 02:51:26 +0000876 bool HadTailCall = false;
Devang Pateldf8370b2010-10-25 21:31:46 +0000877 SelectBasicBlock(Inst, BI, HadTailCall);
Dan Gohmanb4afb132009-11-20 02:51:26 +0000878
879 // If the call was emitted as a tail call, we're done with the block.
880 if (HadTailCall) {
Dan Gohman84023e02010-07-10 09:00:22 +0000881 --BI;
Dan Gohmanb4afb132009-11-20 02:51:26 +0000882 break;
883 }
884
Dan Gohmana43abd12008-09-29 21:55:50 +0000885 continue;
Dan Gohmanf350b272008-08-23 02:25:05 +0000886 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000887
888 // Otherwise, give up on FastISel for the rest of the block.
889 // For now, be a little lenient about non-branch terminators.
Dan Gohman84023e02010-07-10 09:00:22 +0000890 if (!isa<TerminatorInst>(Inst) || isa<BranchInst>(Inst)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000891 ++NumFastIselFailures;
Dan Gohmana43abd12008-09-29 21:55:50 +0000892 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000893 dbgs() << "FastISel miss: ";
Dan Gohman84023e02010-07-10 09:00:22 +0000894 Inst->dump();
Dan Gohmana43abd12008-09-29 21:55:50 +0000895 }
896 if (EnableFastISelAbort)
897 // The "fast" selector couldn't handle something and bailed.
898 // For the purpose of debugging, just abort.
Torok Edwinc23197a2009-07-14 16:55:14 +0000899 llvm_unreachable("FastISel didn't select the entire block");
Dan Gohmana43abd12008-09-29 21:55:50 +0000900 }
901 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000902 }
Dan Gohman84023e02010-07-10 09:00:22 +0000903
904 FastIS->recomputeInsertPt();
Dan Gohmanf350b272008-08-23 02:25:05 +0000905 }
906
Devang Pateldf8370b2010-10-25 21:31:46 +0000907 if (Begin != BI)
908 ++NumDAGBlocks;
909 else
910 ++NumFastIselBlocks;
911
Dan Gohmand2ff6472008-09-02 20:17:56 +0000912 // Run SelectionDAG instruction selection on the remainder of the block
913 // not handled by FastISel. If FastISel is not run, this is the entire
Dan Gohman3df24e62008-09-03 23:12:08 +0000914 // block.
Dan Gohman84023e02010-07-10 09:00:22 +0000915 bool HadTailCall;
Devang Pateldf8370b2010-10-25 21:31:46 +0000916 SelectBasicBlock(Begin, BI, HadTailCall);
Dan Gohmanf350b272008-08-23 02:25:05 +0000917
Dan Gohman84023e02010-07-10 09:00:22 +0000918 FinishBasicBlock();
Dan Gohman620427d2010-04-22 19:55:20 +0000919 FuncInfo->PHINodesToUpdate.clear();
Evan Cheng39fd6e82008-08-07 00:43:25 +0000920 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000921
922 delete FastIS;
Devang Patel948f7d02010-10-25 20:55:43 +0000923#ifndef NDEBUG
924 for (MachineFunction::const_iterator MBI = MF->begin(), MBE = MF->end();
925 MBI != MBE; ++MBI)
926 CheckLineNumbers(MBI);
927#endif
Dan Gohman0e5f1302008-07-07 23:02:41 +0000928}
929
Dan Gohmanfed90b62008-07-28 21:51:04 +0000930void
Dan Gohman84023e02010-07-10 09:00:22 +0000931SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +0000932
David Greene1a053232010-01-05 01:26:11 +0000933 DEBUG(dbgs() << "Total amount of phi nodes to update: "
Dan Gohman927f8662010-06-18 16:00:29 +0000934 << FuncInfo->PHINodesToUpdate.size() << "\n";
935 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
David Greene1a053232010-01-05 01:26:11 +0000936 dbgs() << "Node " << i << " : ("
Dan Gohman620427d2010-04-22 19:55:20 +0000937 << FuncInfo->PHINodesToUpdate[i].first
938 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000939
Chris Lattnera33ef482005-03-30 01:10:47 +0000940 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +0000941 // PHI nodes in successors.
Dan Gohman2048b852009-11-23 18:04:58 +0000942 if (SDB->SwitchCases.empty() &&
943 SDB->JTCases.empty() &&
944 SDB->BitTestCases.empty()) {
Dan Gohman620427d2010-04-22 19:55:20 +0000945 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
946 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
Chris Lattner518bb532010-02-09 19:54:29 +0000947 assert(PHI->isPHI() &&
Nate Begemanf15485a2006-03-27 01:32:24 +0000948 "This is not a machine PHI node that we are updating!");
Dan Gohman84023e02010-07-10 09:00:22 +0000949 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
Jakob Stoklund Olesen580bba22010-03-05 21:49:10 +0000950 continue;
Dan Gohman620427d2010-04-22 19:55:20 +0000951 PHI->addOperand(
952 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
Dan Gohman84023e02010-07-10 09:00:22 +0000953 PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
Nate Begemanf15485a2006-03-27 01:32:24 +0000954 }
955 return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000956 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000957
Dan Gohman2048b852009-11-23 18:04:58 +0000958 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000959 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +0000960 if (!SDB->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000961 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +0000962 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
963 FuncInfo->InsertPt = FuncInfo->MBB->end();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000964 // Emit the code
Dan Gohman84023e02010-07-10 09:00:22 +0000965 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
Dan Gohman2048b852009-11-23 18:04:58 +0000966 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000967 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +0000968 CodeGenAndEmitDAG();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000969 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000970
Dan Gohman2048b852009-11-23 18:04:58 +0000971 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000972 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +0000973 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
974 FuncInfo->InsertPt = FuncInfo->MBB->end();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000975 // Emit the code
976 if (j+1 != ej)
Dan Gohman2048b852009-11-23 18:04:58 +0000977 SDB->visitBitTestCase(SDB->BitTestCases[i].Cases[j+1].ThisBB,
978 SDB->BitTestCases[i].Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +0000979 SDB->BitTestCases[i].Cases[j],
Dan Gohman84023e02010-07-10 09:00:22 +0000980 FuncInfo->MBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000981 else
Dan Gohman2048b852009-11-23 18:04:58 +0000982 SDB->visitBitTestCase(SDB->BitTestCases[i].Default,
983 SDB->BitTestCases[i].Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +0000984 SDB->BitTestCases[i].Cases[j],
Dan Gohman84023e02010-07-10 09:00:22 +0000985 FuncInfo->MBB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000986
987
Dan Gohman2048b852009-11-23 18:04:58 +0000988 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000989 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +0000990 CodeGenAndEmitDAG();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000991 }
992
993 // Update PHI Nodes
Dan Gohman620427d2010-04-22 19:55:20 +0000994 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
995 pi != pe; ++pi) {
996 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000997 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000998 assert(PHI->isPHI() &&
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000999 "This is not a machine PHI node that we are updating!");
1000 // This is "default" BB. We have two jumps to it. From "header" BB and
1001 // from last "case" BB.
Dan Gohman2048b852009-11-23 18:04:58 +00001002 if (PHIBB == SDB->BitTestCases[i].Default) {
Jim Grosbachf4549b02010-01-15 00:36:15 +00001003 PHI->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +00001004 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1005 false));
Dan Gohman2048b852009-11-23 18:04:58 +00001006 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
Jim Grosbachf4549b02010-01-15 00:36:15 +00001007 PHI->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +00001008 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1009 false));
Dan Gohman2048b852009-11-23 18:04:58 +00001010 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001011 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001012 }
1013 // One of "cases" BB.
Dan Gohman2048b852009-11-23 18:04:58 +00001014 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001015 j != ej; ++j) {
Dan Gohman2048b852009-11-23 18:04:58 +00001016 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001017 if (cBB->isSuccessor(PHIBB)) {
Jim Grosbachf4549b02010-01-15 00:36:15 +00001018 PHI->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +00001019 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1020 false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001021 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001022 }
1023 }
1024 }
1025 }
Dan Gohman2048b852009-11-23 18:04:58 +00001026 SDB->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001027
Nate Begeman9453eea2006-04-23 06:26:20 +00001028 // If the JumpTable record is filled in, then we need to emit a jump table.
1029 // Updating the PHI nodes is tricky in this case, since we need to determine
1030 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001031 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001032 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +00001033 if (!SDB->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001034 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001035 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1036 FuncInfo->InsertPt = FuncInfo->MBB->end();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001037 // Emit the code
Dan Gohman99be8ae2010-04-19 22:41:47 +00001038 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
Dan Gohman84023e02010-07-10 09:00:22 +00001039 FuncInfo->MBB);
Dan Gohman2048b852009-11-23 18:04:58 +00001040 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +00001041 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001042 CodeGenAndEmitDAG();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001043 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001044
Nate Begeman37efe672006-04-22 18:53:45 +00001045 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001046 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1047 FuncInfo->InsertPt = FuncInfo->MBB->end();
Nate Begeman37efe672006-04-22 18:53:45 +00001048 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +00001049 SDB->visitJumpTable(SDB->JTCases[i].second);
1050 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +00001051 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001052 CodeGenAndEmitDAG();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001053
Nate Begeman37efe672006-04-22 18:53:45 +00001054 // Update PHI Nodes
Dan Gohman620427d2010-04-22 19:55:20 +00001055 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1056 pi != pe; ++pi) {
1057 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +00001058 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +00001059 assert(PHI->isPHI() &&
Nate Begeman37efe672006-04-22 18:53:45 +00001060 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001061 // "default" BB. We can go there only from header BB.
Dan Gohman2048b852009-11-23 18:04:58 +00001062 if (PHIBB == SDB->JTCases[i].second.Default) {
Evan Chengce319102009-09-19 09:51:03 +00001063 PHI->addOperand
Dan Gohman620427d2010-04-22 19:55:20 +00001064 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1065 false));
Evan Chengce319102009-09-19 09:51:03 +00001066 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +00001067 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00001068 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001069 // JT BB. Just iterate over successors here
Dan Gohman84023e02010-07-10 09:00:22 +00001070 if (FuncInfo->MBB->isSuccessor(PHIBB)) {
Evan Chengce319102009-09-19 09:51:03 +00001071 PHI->addOperand
Dan Gohman620427d2010-04-22 19:55:20 +00001072 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1073 false));
Dan Gohman84023e02010-07-10 09:00:22 +00001074 PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
Nate Begeman37efe672006-04-22 18:53:45 +00001075 }
1076 }
Nate Begeman37efe672006-04-22 18:53:45 +00001077 }
Dan Gohman2048b852009-11-23 18:04:58 +00001078 SDB->JTCases.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001079
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001080 // If the switch block involved a branch to one of the actual successors, we
1081 // need to update PHI nodes in that block.
Dan Gohman620427d2010-04-22 19:55:20 +00001082 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1083 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
Chris Lattner518bb532010-02-09 19:54:29 +00001084 assert(PHI->isPHI() &&
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001085 "This is not a machine PHI node that we are updating!");
Dan Gohman84023e02010-07-10 09:00:22 +00001086 if (FuncInfo->MBB->isSuccessor(PHI->getParent())) {
Dan Gohman620427d2010-04-22 19:55:20 +00001087 PHI->addOperand(
1088 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
Dan Gohman84023e02010-07-10 09:00:22 +00001089 PHI->addOperand(MachineOperand::CreateMBB(FuncInfo->MBB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001090 }
1091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001092
Nate Begemanf15485a2006-03-27 01:32:24 +00001093 // If we generated any switch lowering information, build and codegen any
1094 // additional DAGs necessary.
Dan Gohman2048b852009-11-23 18:04:58 +00001095 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001096 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman84023e02010-07-10 09:00:22 +00001097 MachineBasicBlock *ThisBB = FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1098 FuncInfo->InsertPt = FuncInfo->MBB->end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001099
Dan Gohman95140a42010-05-01 00:25:44 +00001100 // Determine the unique successors.
1101 SmallVector<MachineBasicBlock *, 2> Succs;
1102 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1103 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1104 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1105
1106 // Emit the code. Note that this could result in ThisBB being split, so
1107 // we need to check for updates.
Dan Gohman84023e02010-07-10 09:00:22 +00001108 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
Dan Gohman2048b852009-11-23 18:04:58 +00001109 CurDAG->setRoot(SDB->getRoot());
Dan Gohman95140a42010-05-01 00:25:44 +00001110 SDB->clear();
Dan Gohman84023e02010-07-10 09:00:22 +00001111 CodeGenAndEmitDAG();
1112 ThisBB = FuncInfo->MBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001114 // Handle any PHI nodes in successors of this chunk, as if we were coming
1115 // from the original BB before switch expansion. Note that PHI nodes can
1116 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1117 // handle them the right number of times.
Dan Gohman95140a42010-05-01 00:25:44 +00001118 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
Dan Gohman84023e02010-07-10 09:00:22 +00001119 FuncInfo->MBB = Succs[i];
1120 FuncInfo->InsertPt = FuncInfo->MBB->end();
1121 // FuncInfo->MBB may have been removed from the CFG if a branch was
1122 // constant folded.
1123 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1124 for (MachineBasicBlock::iterator Phi = FuncInfo->MBB->begin();
1125 Phi != FuncInfo->MBB->end() && Phi->isPHI();
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001126 ++Phi) {
1127 // This value for this PHI node is recorded in PHINodesToUpdate.
1128 for (unsigned pn = 0; ; ++pn) {
Dan Gohman620427d2010-04-22 19:55:20 +00001129 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001130 "Didn't find PHI entry!");
Dan Gohman620427d2010-04-22 19:55:20 +00001131 if (FuncInfo->PHINodesToUpdate[pn].first == Phi) {
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001132 Phi->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +00001133 CreateReg(FuncInfo->PHINodesToUpdate[pn].second,
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001134 false));
1135 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1136 break;
1137 }
Evan Cheng8be58a12009-09-18 08:26:06 +00001138 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001139 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001140 }
1141 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001142 }
Dan Gohman2048b852009-11-23 18:04:58 +00001143 SDB->SwitchCases.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00001144}
Evan Chenga9c20912006-01-21 02:32:06 +00001145
Jim Laskey13ec7022006-08-01 14:21:23 +00001146
Dan Gohman0a3776d2009-02-06 18:26:51 +00001147/// Create the scheduler. If a specific scheduler was specified
1148/// via the SchedulerRegistry, use it, otherwise select the
1149/// one preferred by the target.
Dan Gohman5e843682008-07-14 18:19:29 +00001150///
Dan Gohman47ac0f02009-02-11 04:27:20 +00001151ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001152 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001153
Jim Laskey13ec7022006-08-01 14:21:23 +00001154 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001155 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00001156 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00001157 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001158
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001159 return Ctor(this, OptLevel);
Evan Chenga9c20912006-01-21 02:32:06 +00001160}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001161
Dan Gohmanfc54c552009-01-15 22:18:12 +00001162ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1163 return new ScheduleHazardRecognizer();
Jim Laskey9ff542f2006-08-01 18:29:48 +00001164}
1165
Chris Lattner75548062006-10-11 03:58:02 +00001166//===----------------------------------------------------------------------===//
1167// Helper functions used by the generated instruction selector.
1168//===----------------------------------------------------------------------===//
1169// Calls to these methods are generated by tblgen.
1170
1171/// CheckAndMask - The isel is trying to match something like (and X, 255). If
1172/// the dag combiner simplified the 255, we still want to match. RHS is the
1173/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1174/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001175bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00001176 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001177 const APInt &ActualMask = RHS->getAPIntValue();
1178 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001179
Chris Lattner75548062006-10-11 03:58:02 +00001180 // If the actual mask exactly matches, success!
1181 if (ActualMask == DesiredMask)
1182 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001183
Chris Lattner75548062006-10-11 03:58:02 +00001184 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001185 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001186 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001187
Chris Lattner75548062006-10-11 03:58:02 +00001188 // Otherwise, the DAG Combiner may have proven that the value coming in is
1189 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001190 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00001191 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00001192 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001193
Chris Lattner75548062006-10-11 03:58:02 +00001194 // TODO: check to see if missing bits are just not demanded.
1195
1196 // Otherwise, this pattern doesn't match.
1197 return false;
1198}
1199
1200/// CheckOrMask - The isel is trying to match something like (or X, 255). If
1201/// the dag combiner simplified the 255, we still want to match. RHS is the
1202/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1203/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001204bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001205 int64_t DesiredMaskS) const {
1206 const APInt &ActualMask = RHS->getAPIntValue();
1207 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001208
Chris Lattner75548062006-10-11 03:58:02 +00001209 // If the actual mask exactly matches, success!
1210 if (ActualMask == DesiredMask)
1211 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001212
Chris Lattner75548062006-10-11 03:58:02 +00001213 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001214 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001215 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001216
Chris Lattner75548062006-10-11 03:58:02 +00001217 // Otherwise, the DAG Combiner may have proven that the value coming in is
1218 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001219 APInt NeededMask = DesiredMask & ~ActualMask;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001220
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001221 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00001222 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001223
Chris Lattner75548062006-10-11 03:58:02 +00001224 // If all the missing bits in the or are already known to be set, match!
1225 if ((NeededMask & KnownOne) == NeededMask)
1226 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001227
Chris Lattner75548062006-10-11 03:58:02 +00001228 // TODO: check to see if missing bits are just not demanded.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001229
Chris Lattner75548062006-10-11 03:58:02 +00001230 // Otherwise, this pattern doesn't match.
1231 return false;
1232}
1233
Jim Laskey9ff542f2006-08-01 18:29:48 +00001234
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001235/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1236/// by tblgen. Others should not call it.
1237void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00001238SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00001239 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001240 std::swap(InOps, Ops);
1241
Chris Lattnerdecc2672010-04-07 05:20:54 +00001242 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1243 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1244 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
Dale Johannesenf1e309e2010-07-02 20:16:09 +00001245 Ops.push_back(InOps[InlineAsm::Op_IsAlignStack]); // 3
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001246
Chris Lattnerdecc2672010-04-07 05:20:54 +00001247 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
Owen Anderson825b72b2009-08-11 20:47:22 +00001248 if (InOps[e-1].getValueType() == MVT::Flag)
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001249 --e; // Don't process a flag operand if it is here.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001250
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001251 while (i != e) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00001252 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00001253 if (!InlineAsm::isMemKind(Flags)) {
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001254 // Just skip over this operand, copying the operands verbatim.
Evan Cheng697cbbf2009-03-20 18:03:34 +00001255 Ops.insert(Ops.end(), InOps.begin()+i,
1256 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1257 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001258 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00001259 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1260 "Memory operand with multiple values?");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001261 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00001262 std::vector<SDValue> SelOps;
Chris Lattnerdecc2672010-04-07 05:20:54 +00001263 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
Chris Lattner75361b62010-04-07 22:58:41 +00001264 report_fatal_error("Could not match memory address. Inline asm"
Chris Lattner87d677c2010-04-07 23:50:38 +00001265 " failure!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001266
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001267 // Add this to the output node.
Chris Lattnerdecc2672010-04-07 05:20:54 +00001268 unsigned NewFlags =
1269 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1270 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001271 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1272 i += 2;
1273 }
1274 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001276 // Add the flag input back if present.
1277 if (e != InOps.size())
1278 Ops.push_back(InOps.back());
1279}
Devang Patel794fd752007-05-01 21:15:47 +00001280
Owen Andersone50ed302009-08-10 22:56:29 +00001281/// findFlagUse - Return use of EVT::Flag value produced by the specified
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001282/// SDNode.
1283///
1284static SDNode *findFlagUse(SDNode *N) {
1285 unsigned FlagResNo = N->getNumValues()-1;
1286 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1287 SDUse &Use = I.getUse();
1288 if (Use.getResNo() == FlagResNo)
1289 return Use.getUser();
1290 }
1291 return NULL;
1292}
1293
1294/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1295/// This function recursively traverses up the operand chain, ignoring
1296/// certain nodes.
1297static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
Chris Lattnerd1b73822010-03-02 22:20:06 +00001298 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1299 bool IgnoreChains) {
Chris Lattnerda244a02010-02-23 19:32:27 +00001300 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1301 // greater than all of its (recursive) operands. If we scan to a point where
1302 // 'use' is smaller than the node we're scanning for, then we know we will
1303 // never find it.
1304 //
1305 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1306 // happen because we scan down to newly selected nodes in the case of flag
1307 // uses.
1308 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1309 return false;
1310
1311 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1312 // won't fail if we scan it again.
1313 if (!Visited.insert(Use))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001314 return false;
1315
1316 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001317 // Ignore chain uses, they are validated by HandleMergeInputChains.
1318 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1319 continue;
1320
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001321 SDNode *N = Use->getOperand(i).getNode();
1322 if (N == Def) {
1323 if (Use == ImmedUse || Use == Root)
1324 continue; // We are not looking for immediate use.
1325 assert(N != Root);
1326 return true;
1327 }
1328
1329 // Traverse up the operand chain.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001330 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001331 return true;
1332 }
1333 return false;
1334}
1335
Evan Cheng014bf212010-02-15 19:41:07 +00001336/// IsProfitableToFold - Returns true if it's profitable to fold the specific
1337/// operand node N of U during instruction selection that starts at Root.
1338bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1339 SDNode *Root) const {
1340 if (OptLevel == CodeGenOpt::None) return false;
1341 return N.hasOneUse();
1342}
1343
1344/// IsLegalToFold - Returns true if the specific operand node N of
1345/// U can be folded during instruction selection that starts at Root.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001346bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
Dan Gohmand858e902010-04-17 15:26:15 +00001347 CodeGenOpt::Level OptLevel,
1348 bool IgnoreChains) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001349 if (OptLevel == CodeGenOpt::None) return false;
1350
1351 // If Root use can somehow reach N through a path that that doesn't contain
1352 // U then folding N would create a cycle. e.g. In the following
1353 // diagram, Root can reach N through X. If N is folded into into Root, then
1354 // X is both a predecessor and a successor of U.
1355 //
1356 // [N*] //
1357 // ^ ^ //
1358 // / \ //
1359 // [U*] [X]? //
1360 // ^ ^ //
1361 // \ / //
1362 // \ / //
1363 // [Root*] //
1364 //
1365 // * indicates nodes to be folded together.
1366 //
1367 // If Root produces a flag, then it gets (even more) interesting. Since it
1368 // will be "glued" together with its flag use in the scheduler, we need to
1369 // check if it might reach N.
1370 //
1371 // [N*] //
1372 // ^ ^ //
1373 // / \ //
1374 // [U*] [X]? //
1375 // ^ ^ //
1376 // \ \ //
1377 // \ | //
1378 // [Root*] | //
1379 // ^ | //
1380 // f | //
1381 // | / //
1382 // [Y] / //
1383 // ^ / //
1384 // f / //
1385 // | / //
1386 // [FU] //
1387 //
1388 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1389 // (call it Fold), then X is a predecessor of FU and a successor of
1390 // Fold. But since Fold and FU are flagged together, this will create
1391 // a cycle in the scheduling graph.
1392
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001393 // If the node has flags, walk down the graph to the "lowest" node in the
1394 // flagged set.
Owen Andersone50ed302009-08-10 22:56:29 +00001395 EVT VT = Root->getValueType(Root->getNumValues()-1);
Owen Anderson825b72b2009-08-11 20:47:22 +00001396 while (VT == MVT::Flag) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001397 SDNode *FU = findFlagUse(Root);
1398 if (FU == NULL)
1399 break;
1400 Root = FU;
1401 VT = Root->getValueType(Root->getNumValues()-1);
Chris Lattner18fdaba2010-03-05 06:19:13 +00001402
1403 // If our query node has a flag result with a use, we've walked up it. If
1404 // the user (which has already been selected) has a chain or indirectly uses
1405 // the chain, our WalkChainUsers predicate will not consider it. Because of
1406 // this, we cannot ignore chains in this predicate.
1407 IgnoreChains = false;
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001408 }
Chris Lattner18fdaba2010-03-05 06:19:13 +00001409
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001410
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001411 SmallPtrSet<SDNode*, 16> Visited;
1412 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001413}
1414
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001415SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1416 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
Dan Gohmane1f188f2009-10-29 22:30:23 +00001417 SelectInlineAsmMemoryOperands(Ops);
1418
1419 std::vector<EVT> VTs;
1420 VTs.push_back(MVT::Other);
1421 VTs.push_back(MVT::Flag);
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001422 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
Dan Gohmane1f188f2009-10-29 22:30:23 +00001423 VTs, &Ops[0], Ops.size());
Chris Lattnerd1b73822010-03-02 22:20:06 +00001424 New->setNodeId(-1);
Dan Gohmane1f188f2009-10-29 22:30:23 +00001425 return New.getNode();
1426}
1427
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001428SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
Chris Lattner518bb532010-02-09 19:54:29 +00001429 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
Dan Gohmane1f188f2009-10-29 22:30:23 +00001430}
1431
Chris Lattner2a49d572010-02-28 22:37:22 +00001432/// GetVBR - decode a vbr encoding whose top bit is set.
Chandler Carruth19e57022010-10-23 08:40:19 +00001433LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
Chris Lattner2a49d572010-02-28 22:37:22 +00001434GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1435 assert(Val >= 128 && "Not a VBR");
1436 Val &= 127; // Remove first vbr bit.
1437
1438 unsigned Shift = 7;
1439 uint64_t NextBits;
1440 do {
Chris Lattner14df8dc2010-02-28 22:38:43 +00001441 NextBits = MatcherTable[Idx++];
Chris Lattner2a49d572010-02-28 22:37:22 +00001442 Val |= (NextBits&127) << Shift;
1443 Shift += 7;
1444 } while (NextBits & 128);
1445
1446 return Val;
1447}
1448
Chris Lattner2a49d572010-02-28 22:37:22 +00001449
1450/// UpdateChainsAndFlags - When a match is complete, this method updates uses of
1451/// interior flag and chain results to use the new flag and chain results.
Chris Lattner82dd3d32010-03-02 07:50:03 +00001452void SelectionDAGISel::
1453UpdateChainsAndFlags(SDNode *NodeToMatch, SDValue InputChain,
1454 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1455 SDValue InputFlag,
1456 const SmallVectorImpl<SDNode*> &FlagResultNodesMatched,
1457 bool isMorphNodeTo) {
1458 SmallVector<SDNode*, 4> NowDeadNodes;
1459
1460 ISelUpdater ISU(ISelPosition);
1461
Chris Lattner2a49d572010-02-28 22:37:22 +00001462 // Now that all the normal results are replaced, we replace the chain and
1463 // flag results if present.
1464 if (!ChainNodesMatched.empty()) {
1465 assert(InputChain.getNode() != 0 &&
1466 "Matched input chains but didn't produce a chain");
1467 // Loop over all of the nodes we matched that produced a chain result.
1468 // Replace all the chain results with the final chain we ended up with.
1469 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1470 SDNode *ChainNode = ChainNodesMatched[i];
1471
Chris Lattner82dd3d32010-03-02 07:50:03 +00001472 // If this node was already deleted, don't look at it.
1473 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1474 continue;
1475
Chris Lattner2a49d572010-02-28 22:37:22 +00001476 // Don't replace the results of the root node if we're doing a
1477 // MorphNodeTo.
1478 if (ChainNode == NodeToMatch && isMorphNodeTo)
1479 continue;
1480
1481 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1482 if (ChainVal.getValueType() == MVT::Flag)
1483 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1484 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
Chris Lattner82dd3d32010-03-02 07:50:03 +00001485 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1486
Chris Lattner856fb392010-03-28 05:28:31 +00001487 // If the node became dead and we haven't already seen it, delete it.
1488 if (ChainNode->use_empty() &&
1489 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001490 NowDeadNodes.push_back(ChainNode);
Chris Lattner2a49d572010-02-28 22:37:22 +00001491 }
1492 }
1493
1494 // If the result produces a flag, update any flag results in the matched
1495 // pattern with the flag result.
1496 if (InputFlag.getNode() != 0) {
1497 // Handle any interior nodes explicitly marked.
1498 for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
1499 SDNode *FRN = FlagResultNodesMatched[i];
Chris Lattner82dd3d32010-03-02 07:50:03 +00001500
1501 // If this node was already deleted, don't look at it.
1502 if (FRN->getOpcode() == ISD::DELETED_NODE)
1503 continue;
1504
Chris Lattner2a49d572010-02-28 22:37:22 +00001505 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
1506 "Doesn't have a flag result");
1507 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
Chris Lattner82dd3d32010-03-02 07:50:03 +00001508 InputFlag, &ISU);
1509
Chris Lattner19e37cb2010-03-28 04:54:33 +00001510 // If the node became dead and we haven't already seen it, delete it.
1511 if (FRN->use_empty() &&
1512 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001513 NowDeadNodes.push_back(FRN);
Chris Lattner2a49d572010-02-28 22:37:22 +00001514 }
1515 }
1516
Chris Lattner82dd3d32010-03-02 07:50:03 +00001517 if (!NowDeadNodes.empty())
1518 CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1519
Chris Lattner2a49d572010-02-28 22:37:22 +00001520 DEBUG(errs() << "ISEL: Match complete!\n");
1521}
1522
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001523enum ChainResult {
1524 CR_Simple,
1525 CR_InducesCycle,
1526 CR_LeadsToInteriorNode
1527};
1528
1529/// WalkChainUsers - Walk down the users of the specified chained node that is
1530/// part of the pattern we're matching, looking at all of the users we find.
1531/// This determines whether something is an interior node, whether we have a
1532/// non-pattern node in between two pattern nodes (which prevent folding because
1533/// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1534/// between pattern nodes (in which case the TF becomes part of the pattern).
1535///
1536/// The walk we do here is guaranteed to be small because we quickly get down to
1537/// already selected nodes "below" us.
1538static ChainResult
1539WalkChainUsers(SDNode *ChainedNode,
1540 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1541 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1542 ChainResult Result = CR_Simple;
1543
1544 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1545 E = ChainedNode->use_end(); UI != E; ++UI) {
1546 // Make sure the use is of the chain, not some other value we produce.
1547 if (UI.getUse().getValueType() != MVT::Other) continue;
1548
1549 SDNode *User = *UI;
1550
1551 // If we see an already-selected machine node, then we've gone beyond the
1552 // pattern that we're selecting down into the already selected chunk of the
1553 // DAG.
1554 if (User->isMachineOpcode() ||
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001555 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1556 continue;
Chris Lattnerd1b73822010-03-02 22:20:06 +00001557
1558 if (User->getOpcode() == ISD::CopyToReg ||
1559 User->getOpcode() == ISD::CopyFromReg ||
Chris Lattner7561d482010-03-14 02:33:54 +00001560 User->getOpcode() == ISD::INLINEASM ||
1561 User->getOpcode() == ISD::EH_LABEL) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001562 // If their node ID got reset to -1 then they've already been selected.
1563 // Treat them like a MachineOpcode.
1564 if (User->getNodeId() == -1)
1565 continue;
1566 }
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001567
1568 // If we have a TokenFactor, we handle it specially.
1569 if (User->getOpcode() != ISD::TokenFactor) {
1570 // If the node isn't a token factor and isn't part of our pattern, then it
1571 // must be a random chained node in between two nodes we're selecting.
1572 // This happens when we have something like:
1573 // x = load ptr
1574 // call
1575 // y = x+4
1576 // store y -> ptr
1577 // Because we structurally match the load/store as a read/modify/write,
1578 // but the call is chained between them. We cannot fold in this case
1579 // because it would induce a cycle in the graph.
1580 if (!std::count(ChainedNodesInPattern.begin(),
1581 ChainedNodesInPattern.end(), User))
1582 return CR_InducesCycle;
1583
1584 // Otherwise we found a node that is part of our pattern. For example in:
1585 // x = load ptr
1586 // y = x+4
1587 // store y -> ptr
1588 // This would happen when we're scanning down from the load and see the
1589 // store as a user. Record that there is a use of ChainedNode that is
1590 // part of the pattern and keep scanning uses.
1591 Result = CR_LeadsToInteriorNode;
1592 InteriorChainedNodes.push_back(User);
1593 continue;
1594 }
1595
1596 // If we found a TokenFactor, there are two cases to consider: first if the
1597 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1598 // uses of the TF are in our pattern) we just want to ignore it. Second,
1599 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1600 // [Load chain]
1601 // ^
1602 // |
1603 // [Load]
1604 // ^ ^
1605 // | \ DAG's like cheese
1606 // / \ do you?
1607 // / |
1608 // [TokenFactor] [Op]
1609 // ^ ^
1610 // | |
1611 // \ /
1612 // \ /
1613 // [Store]
1614 //
1615 // In this case, the TokenFactor becomes part of our match and we rewrite it
1616 // as a new TokenFactor.
1617 //
1618 // To distinguish these two cases, do a recursive walk down the uses.
1619 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1620 case CR_Simple:
1621 // If the uses of the TokenFactor are just already-selected nodes, ignore
1622 // it, it is "below" our pattern.
1623 continue;
1624 case CR_InducesCycle:
1625 // If the uses of the TokenFactor lead to nodes that are not part of our
1626 // pattern that are not selected, folding would turn this into a cycle,
1627 // bail out now.
1628 return CR_InducesCycle;
1629 case CR_LeadsToInteriorNode:
1630 break; // Otherwise, keep processing.
1631 }
1632
1633 // Okay, we know we're in the interesting interior case. The TokenFactor
1634 // is now going to be considered part of the pattern so that we rewrite its
1635 // uses (it may have uses that are not part of the pattern) with the
1636 // ultimate chain result of the generated code. We will also add its chain
1637 // inputs as inputs to the ultimate TokenFactor we create.
1638 Result = CR_LeadsToInteriorNode;
1639 ChainedNodesInPattern.push_back(User);
1640 InteriorChainedNodes.push_back(User);
1641 continue;
1642 }
1643
1644 return Result;
1645}
1646
Chris Lattner6b307922010-03-02 00:00:03 +00001647/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
Chris Lattner00592ec2010-03-02 19:34:59 +00001648/// operation for when the pattern matched at least one node with a chains. The
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001649/// input vector contains a list of all of the chained nodes that we match. We
1650/// must determine if this is a valid thing to cover (i.e. matching it won't
1651/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1652/// be used as the input node chain for the generated nodes.
Chris Lattner6b307922010-03-02 00:00:03 +00001653static SDValue
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001654HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
Chris Lattner6b307922010-03-02 00:00:03 +00001655 SelectionDAG *CurDAG) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001656 // Walk all of the chained nodes we've matched, recursively scanning down the
1657 // users of the chain result. This adds any TokenFactor nodes that are caught
1658 // in between chained nodes to the chained and interior nodes list.
1659 SmallVector<SDNode*, 3> InteriorChainedNodes;
1660 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1661 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1662 InteriorChainedNodes) == CR_InducesCycle)
1663 return SDValue(); // Would induce a cycle.
1664 }
Chris Lattner6b307922010-03-02 00:00:03 +00001665
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001666 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1667 // that we are interested in. Form our input TokenFactor node.
Chris Lattner6b307922010-03-02 00:00:03 +00001668 SmallVector<SDValue, 3> InputChains;
1669 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001670 // Add the input chain of this node to the InputChains list (which will be
1671 // the operands of the generated TokenFactor) if it's not an interior node.
1672 SDNode *N = ChainNodesMatched[i];
1673 if (N->getOpcode() != ISD::TokenFactor) {
1674 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1675 continue;
1676
1677 // Otherwise, add the input chain.
1678 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1679 assert(InChain.getValueType() == MVT::Other && "Not a chain");
Chris Lattner6b307922010-03-02 00:00:03 +00001680 InputChains.push_back(InChain);
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001681 continue;
1682 }
1683
1684 // If we have a token factor, we want to add all inputs of the token factor
1685 // that are not part of the pattern we're matching.
1686 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1687 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
Chris Lattner6183fbd2010-03-02 02:37:23 +00001688 N->getOperand(op).getNode()))
1689 InputChains.push_back(N->getOperand(op));
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001690 }
Chris Lattner6b307922010-03-02 00:00:03 +00001691 }
1692
1693 SDValue Res;
1694 if (InputChains.size() == 1)
1695 return InputChains[0];
1696 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1697 MVT::Other, &InputChains[0], InputChains.size());
1698}
Chris Lattner2a49d572010-02-28 22:37:22 +00001699
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001700/// MorphNode - Handle morphing a node in place for the selector.
1701SDNode *SelectionDAGISel::
1702MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1703 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1704 // It is possible we're using MorphNodeTo to replace a node with no
1705 // normal results with one that has a normal result (or we could be
1706 // adding a chain) and the input could have flags and chains as well.
Chris Lattnercaa88702010-03-28 08:43:23 +00001707 // In this case we need to shift the operands down.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001708 // FIXME: This is a horrible hack and broken in obscure cases, no worse
Chris Lattnera6f86932010-03-27 18:54:50 +00001709 // than the old isel though.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001710 int OldFlagResultNo = -1, OldChainResultNo = -1;
1711
1712 unsigned NTMNumResults = Node->getNumValues();
1713 if (Node->getValueType(NTMNumResults-1) == MVT::Flag) {
1714 OldFlagResultNo = NTMNumResults-1;
1715 if (NTMNumResults != 1 &&
1716 Node->getValueType(NTMNumResults-2) == MVT::Other)
1717 OldChainResultNo = NTMNumResults-2;
1718 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1719 OldChainResultNo = NTMNumResults-1;
1720
Chris Lattner61c97f62010-03-02 07:14:49 +00001721 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1722 // that this deletes operands of the old node that become dead.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001723 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1724
1725 // MorphNodeTo can operate in two ways: if an existing node with the
1726 // specified operands exists, it can just return it. Otherwise, it
1727 // updates the node in place to have the requested operands.
1728 if (Res == Node) {
1729 // If we updated the node in place, reset the node ID. To the isel,
1730 // this should be just like a newly allocated machine node.
1731 Res->setNodeId(-1);
1732 }
1733
1734 unsigned ResNumResults = Res->getNumValues();
1735 // Move the flag if needed.
1736 if ((EmitNodeInfo & OPFL_FlagOutput) && OldFlagResultNo != -1 &&
1737 (unsigned)OldFlagResultNo != ResNumResults-1)
1738 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldFlagResultNo),
1739 SDValue(Res, ResNumResults-1));
1740
1741 if ((EmitNodeInfo & OPFL_FlagOutput) != 0)
Bill Wendlingd9cb7ca2010-07-04 08:58:43 +00001742 --ResNumResults;
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001743
1744 // Move the chain reference if needed.
1745 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1746 (unsigned)OldChainResultNo != ResNumResults-1)
1747 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1748 SDValue(Res, ResNumResults-1));
1749
1750 // Otherwise, no replacement happened because the node already exists. Replace
1751 // Uses of the old node with the new one.
1752 if (Res != Node)
1753 CurDAG->ReplaceAllUsesWith(Node, Res);
1754
1755 return Res;
1756}
1757
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001758/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
Chandler Carruth19e57022010-10-23 08:40:19 +00001759LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001760CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
Chris Lattnerd847bc22010-09-21 22:00:25 +00001761 SDValue N,
1762 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
Chris Lattnerda828e32010-03-03 07:46:25 +00001763 // Accept if it is exactly the same as a previously recorded node.
1764 unsigned RecNo = MatcherTable[MatcherIndex++];
1765 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00001766 return N == RecordedNodes[RecNo].first;
Chris Lattnerda828e32010-03-03 07:46:25 +00001767}
1768
1769/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
Chandler Carruth19e57022010-10-23 08:40:19 +00001770LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001771CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1772 SelectionDAGISel &SDISel) {
1773 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1774}
1775
1776/// CheckNodePredicate - Implements OP_CheckNodePredicate.
Chandler Carruth19e57022010-10-23 08:40:19 +00001777LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001778CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1779 SelectionDAGISel &SDISel, SDNode *N) {
1780 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1781}
1782
Chandler Carruth19e57022010-10-23 08:40:19 +00001783LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001784CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1785 SDNode *N) {
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00001786 uint16_t Opc = MatcherTable[MatcherIndex++];
1787 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1788 return N->getOpcode() == Opc;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001789}
1790
Chandler Carruth19e57022010-10-23 08:40:19 +00001791LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001792CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1793 SDValue N, const TargetLowering &TLI) {
1794 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1795 if (N.getValueType() == VT) return true;
1796
1797 // Handle the case when VT is iPTR.
1798 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
1799}
1800
Chandler Carruth19e57022010-10-23 08:40:19 +00001801LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001802CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1803 SDValue N, const TargetLowering &TLI,
1804 unsigned ChildNo) {
1805 if (ChildNo >= N.getNumOperands())
1806 return false; // Match fails if out of range child #.
1807 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
1808}
1809
1810
Chandler Carruth19e57022010-10-23 08:40:19 +00001811LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001812CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1813 SDValue N) {
1814 return cast<CondCodeSDNode>(N)->get() ==
1815 (ISD::CondCode)MatcherTable[MatcherIndex++];
1816}
1817
Chandler Carruth19e57022010-10-23 08:40:19 +00001818LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001819CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1820 SDValue N, const TargetLowering &TLI) {
1821 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1822 if (cast<VTSDNode>(N)->getVT() == VT)
1823 return true;
1824
1825 // Handle the case when VT is iPTR.
1826 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
1827}
1828
Chandler Carruth19e57022010-10-23 08:40:19 +00001829LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001830CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1831 SDValue N) {
1832 int64_t Val = MatcherTable[MatcherIndex++];
1833 if (Val & 128)
1834 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1835
1836 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
1837 return C != 0 && C->getSExtValue() == Val;
1838}
1839
Chandler Carruth19e57022010-10-23 08:40:19 +00001840LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001841CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1842 SDValue N, SelectionDAGISel &SDISel) {
1843 int64_t Val = MatcherTable[MatcherIndex++];
1844 if (Val & 128)
1845 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1846
1847 if (N->getOpcode() != ISD::AND) return false;
1848
1849 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1850 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
1851}
1852
Chandler Carruth19e57022010-10-23 08:40:19 +00001853LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001854CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1855 SDValue N, SelectionDAGISel &SDISel) {
1856 int64_t Val = MatcherTable[MatcherIndex++];
1857 if (Val & 128)
1858 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1859
1860 if (N->getOpcode() != ISD::OR) return false;
1861
1862 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1863 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
1864}
1865
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001866/// IsPredicateKnownToFail - If we know how and can do so without pushing a
1867/// scope, evaluate the current node. If the current predicate is known to
1868/// fail, set Result=true and return anything. If the current predicate is
1869/// known to pass, set Result=false and return the MatcherIndex to continue
1870/// with. If the current predicate is unknown, set Result=false and return the
1871/// MatcherIndex to continue with.
1872static unsigned IsPredicateKnownToFail(const unsigned char *Table,
1873 unsigned Index, SDValue N,
Chris Lattnerda828e32010-03-03 07:46:25 +00001874 bool &Result, SelectionDAGISel &SDISel,
Chris Lattnerd847bc22010-09-21 22:00:25 +00001875 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001876 switch (Table[Index++]) {
1877 default:
1878 Result = false;
1879 return Index-1; // Could not evaluate this predicate.
Chris Lattnerda828e32010-03-03 07:46:25 +00001880 case SelectionDAGISel::OPC_CheckSame:
1881 Result = !::CheckSame(Table, Index, N, RecordedNodes);
1882 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001883 case SelectionDAGISel::OPC_CheckPatternPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00001884 Result = !::CheckPatternPredicate(Table, Index, SDISel);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001885 return Index;
1886 case SelectionDAGISel::OPC_CheckPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00001887 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001888 return Index;
1889 case SelectionDAGISel::OPC_CheckOpcode:
1890 Result = !::CheckOpcode(Table, Index, N.getNode());
1891 return Index;
1892 case SelectionDAGISel::OPC_CheckType:
1893 Result = !::CheckType(Table, Index, N, SDISel.TLI);
1894 return Index;
1895 case SelectionDAGISel::OPC_CheckChild0Type:
1896 case SelectionDAGISel::OPC_CheckChild1Type:
1897 case SelectionDAGISel::OPC_CheckChild2Type:
1898 case SelectionDAGISel::OPC_CheckChild3Type:
1899 case SelectionDAGISel::OPC_CheckChild4Type:
1900 case SelectionDAGISel::OPC_CheckChild5Type:
1901 case SelectionDAGISel::OPC_CheckChild6Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00001902 case SelectionDAGISel::OPC_CheckChild7Type:
1903 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
1904 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001905 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00001906 case SelectionDAGISel::OPC_CheckCondCode:
1907 Result = !::CheckCondCode(Table, Index, N);
1908 return Index;
1909 case SelectionDAGISel::OPC_CheckValueType:
1910 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
1911 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001912 case SelectionDAGISel::OPC_CheckInteger:
1913 Result = !::CheckInteger(Table, Index, N);
1914 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00001915 case SelectionDAGISel::OPC_CheckAndImm:
1916 Result = !::CheckAndImm(Table, Index, N, SDISel);
1917 return Index;
1918 case SelectionDAGISel::OPC_CheckOrImm:
1919 Result = !::CheckOrImm(Table, Index, N, SDISel);
1920 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001921 }
1922}
1923
Dan Gohmanb3579832010-04-15 17:08:50 +00001924namespace {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001925
Chris Lattner2a49d572010-02-28 22:37:22 +00001926struct MatchScope {
1927 /// FailIndex - If this match fails, this is the index to continue with.
1928 unsigned FailIndex;
1929
1930 /// NodeStack - The node stack when the scope was formed.
1931 SmallVector<SDValue, 4> NodeStack;
1932
1933 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
1934 unsigned NumRecordedNodes;
1935
1936 /// NumMatchedMemRefs - The number of matched memref entries.
1937 unsigned NumMatchedMemRefs;
1938
1939 /// InputChain/InputFlag - The current chain/flag
1940 SDValue InputChain, InputFlag;
1941
1942 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
1943 bool HasChainNodesMatched, HasFlagResultNodesMatched;
1944};
1945
Dan Gohmanb3579832010-04-15 17:08:50 +00001946}
1947
Chris Lattner2a49d572010-02-28 22:37:22 +00001948SDNode *SelectionDAGISel::
1949SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
1950 unsigned TableSize) {
1951 // FIXME: Should these even be selected? Handle these cases in the caller?
1952 switch (NodeToMatch->getOpcode()) {
1953 default:
1954 break;
1955 case ISD::EntryToken: // These nodes remain the same.
1956 case ISD::BasicBlock:
1957 case ISD::Register:
Chris Lattner3b9d6212010-03-14 17:53:23 +00001958 //case ISD::VALUETYPE:
1959 //case ISD::CONDCODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00001960 case ISD::HANDLENODE:
Chris Lattnerdecc2672010-04-07 05:20:54 +00001961 case ISD::MDNODE_SDNODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00001962 case ISD::TargetConstant:
1963 case ISD::TargetConstantFP:
1964 case ISD::TargetConstantPool:
1965 case ISD::TargetFrameIndex:
1966 case ISD::TargetExternalSymbol:
1967 case ISD::TargetBlockAddress:
1968 case ISD::TargetJumpTable:
1969 case ISD::TargetGlobalTLSAddress:
1970 case ISD::TargetGlobalAddress:
1971 case ISD::TokenFactor:
1972 case ISD::CopyFromReg:
1973 case ISD::CopyToReg:
Chris Lattner7561d482010-03-14 02:33:54 +00001974 case ISD::EH_LABEL:
Chris Lattnerd1b73822010-03-02 22:20:06 +00001975 NodeToMatch->setNodeId(-1); // Mark selected.
Chris Lattner2a49d572010-02-28 22:37:22 +00001976 return 0;
1977 case ISD::AssertSext:
1978 case ISD::AssertZext:
1979 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
1980 NodeToMatch->getOperand(0));
1981 return 0;
1982 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
Chris Lattner2a49d572010-02-28 22:37:22 +00001983 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
1984 }
1985
1986 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
1987
1988 // Set up the node stack with NodeToMatch as the only node on the stack.
1989 SmallVector<SDValue, 8> NodeStack;
1990 SDValue N = SDValue(NodeToMatch, 0);
1991 NodeStack.push_back(N);
1992
1993 // MatchScopes - Scopes used when matching, if a match failure happens, this
1994 // indicates where to continue checking.
1995 SmallVector<MatchScope, 8> MatchScopes;
1996
1997 // RecordedNodes - This is the set of nodes that have been recorded by the
Chris Lattnerd847bc22010-09-21 22:00:25 +00001998 // state machine. The second value is the parent of the node, or null if the
1999 // root is recorded.
2000 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
Chris Lattner2a49d572010-02-28 22:37:22 +00002001
2002 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2003 // pattern.
2004 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2005
2006 // These are the current input chain and flag for use when generating nodes.
2007 // Various Emit operations change these. For example, emitting a copytoreg
2008 // uses and updates these.
2009 SDValue InputChain, InputFlag;
2010
2011 // ChainNodesMatched - If a pattern matches nodes that have input/output
2012 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2013 // which ones they are. The result is captured into this list so that we can
2014 // update the chain results when the pattern is complete.
2015 SmallVector<SDNode*, 3> ChainNodesMatched;
2016 SmallVector<SDNode*, 3> FlagResultNodesMatched;
2017
2018 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
2019 NodeToMatch->dump(CurDAG);
2020 errs() << '\n');
2021
Chris Lattner7390eeb2010-03-01 18:47:11 +00002022 // Determine where to start the interpreter. Normally we start at opcode #0,
2023 // but if the state machine starts with an OPC_SwitchOpcode, then we
2024 // accelerate the first lookup (which is guaranteed to be hot) with the
2025 // OpcodeOffset table.
Chris Lattner2a49d572010-02-28 22:37:22 +00002026 unsigned MatcherIndex = 0;
Chris Lattner7390eeb2010-03-01 18:47:11 +00002027
2028 if (!OpcodeOffset.empty()) {
2029 // Already computed the OpcodeOffset table, just index into it.
2030 if (N.getOpcode() < OpcodeOffset.size())
2031 MatcherIndex = OpcodeOffset[N.getOpcode()];
2032 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
2033
2034 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2035 // Otherwise, the table isn't computed, but the state machine does start
2036 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2037 // is the first time we're selecting an instruction.
2038 unsigned Idx = 1;
2039 while (1) {
2040 // Get the size of this case.
2041 unsigned CaseSize = MatcherTable[Idx++];
2042 if (CaseSize & 128)
2043 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2044 if (CaseSize == 0) break;
2045
2046 // Get the opcode, add the index to the table.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002047 uint16_t Opc = MatcherTable[Idx++];
2048 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
Chris Lattner7390eeb2010-03-01 18:47:11 +00002049 if (Opc >= OpcodeOffset.size())
2050 OpcodeOffset.resize((Opc+1)*2);
2051 OpcodeOffset[Opc] = Idx;
2052 Idx += CaseSize;
2053 }
2054
2055 // Okay, do the lookup for the first opcode.
2056 if (N.getOpcode() < OpcodeOffset.size())
2057 MatcherIndex = OpcodeOffset[N.getOpcode()];
2058 }
2059
Chris Lattner2a49d572010-02-28 22:37:22 +00002060 while (1) {
2061 assert(MatcherIndex < TableSize && "Invalid index");
Dan Gohman19b38262010-03-09 02:15:05 +00002062#ifndef NDEBUG
2063 unsigned CurrentOpcodeIndex = MatcherIndex;
2064#endif
Chris Lattner2a49d572010-02-28 22:37:22 +00002065 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2066 switch (Opcode) {
2067 case OPC_Scope: {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002068 // Okay, the semantics of this operation are that we should push a scope
2069 // then evaluate the first child. However, pushing a scope only to have
2070 // the first check fail (which then pops it) is inefficient. If we can
2071 // determine immediately that the first check (or first several) will
2072 // immediately fail, don't even bother pushing a scope for them.
2073 unsigned FailIndex;
2074
2075 while (1) {
2076 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2077 if (NumToSkip & 128)
2078 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2079 // Found the end of the scope with no match.
2080 if (NumToSkip == 0) {
2081 FailIndex = 0;
2082 break;
2083 }
2084
2085 FailIndex = MatcherIndex+NumToSkip;
2086
Chris Lattnera6f86932010-03-27 18:54:50 +00002087 unsigned MatcherIndexOfPredicate = MatcherIndex;
2088 (void)MatcherIndexOfPredicate; // silence warning.
2089
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002090 // If we can't evaluate this predicate without pushing a scope (e.g. if
2091 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2092 // push the scope and evaluate the full predicate chain.
2093 bool Result;
2094 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
Chris Lattnerda828e32010-03-03 07:46:25 +00002095 Result, *this, RecordedNodes);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002096 if (!Result)
2097 break;
2098
Chris Lattnera6f86932010-03-27 18:54:50 +00002099 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
2100 << "index " << MatcherIndexOfPredicate
2101 << ", continuing at " << FailIndex << "\n");
Chris Lattnerbed993d2010-03-28 19:46:56 +00002102 ++NumDAGIselRetries;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002103
2104 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2105 // move to the next case.
2106 MatcherIndex = FailIndex;
2107 }
2108
2109 // If the whole scope failed to match, bail.
2110 if (FailIndex == 0) break;
2111
Chris Lattner2a49d572010-02-28 22:37:22 +00002112 // Push a MatchScope which indicates where to go if the first child fails
2113 // to match.
2114 MatchScope NewEntry;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002115 NewEntry.FailIndex = FailIndex;
Chris Lattner2a49d572010-02-28 22:37:22 +00002116 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2117 NewEntry.NumRecordedNodes = RecordedNodes.size();
2118 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2119 NewEntry.InputChain = InputChain;
2120 NewEntry.InputFlag = InputFlag;
2121 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2122 NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
2123 MatchScopes.push_back(NewEntry);
2124 continue;
2125 }
Chris Lattnerd847bc22010-09-21 22:00:25 +00002126 case OPC_RecordNode: {
Chris Lattner2a49d572010-02-28 22:37:22 +00002127 // Remember this node, it may end up being an operand in the pattern.
Chris Lattnerd847bc22010-09-21 22:00:25 +00002128 SDNode *Parent = 0;
2129 if (NodeStack.size() > 1)
2130 Parent = NodeStack[NodeStack.size()-2].getNode();
2131 RecordedNodes.push_back(std::make_pair(N, Parent));
Chris Lattner2a49d572010-02-28 22:37:22 +00002132 continue;
Chris Lattnerd847bc22010-09-21 22:00:25 +00002133 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002134
2135 case OPC_RecordChild0: case OPC_RecordChild1:
2136 case OPC_RecordChild2: case OPC_RecordChild3:
2137 case OPC_RecordChild4: case OPC_RecordChild5:
2138 case OPC_RecordChild6: case OPC_RecordChild7: {
2139 unsigned ChildNo = Opcode-OPC_RecordChild0;
2140 if (ChildNo >= N.getNumOperands())
2141 break; // Match fails if out of range child #.
2142
Chris Lattnerd847bc22010-09-21 22:00:25 +00002143 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2144 N.getNode()));
Chris Lattner2a49d572010-02-28 22:37:22 +00002145 continue;
2146 }
2147 case OPC_RecordMemRef:
2148 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2149 continue;
2150
2151 case OPC_CaptureFlagInput:
2152 // If the current node has an input flag, capture it in InputFlag.
2153 if (N->getNumOperands() != 0 &&
2154 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
2155 InputFlag = N->getOperand(N->getNumOperands()-1);
2156 continue;
2157
2158 case OPC_MoveChild: {
2159 unsigned ChildNo = MatcherTable[MatcherIndex++];
2160 if (ChildNo >= N.getNumOperands())
2161 break; // Match fails if out of range child #.
2162 N = N.getOperand(ChildNo);
2163 NodeStack.push_back(N);
2164 continue;
2165 }
2166
2167 case OPC_MoveParent:
2168 // Pop the current node off the NodeStack.
2169 NodeStack.pop_back();
2170 assert(!NodeStack.empty() && "Node stack imbalance!");
2171 N = NodeStack.back();
2172 continue;
2173
Chris Lattnerda828e32010-03-03 07:46:25 +00002174 case OPC_CheckSame:
2175 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002176 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002177 case OPC_CheckPatternPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002178 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002179 continue;
2180 case OPC_CheckPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002181 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2182 N.getNode()))
2183 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002184 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002185 case OPC_CheckComplexPat: {
2186 unsigned CPNum = MatcherTable[MatcherIndex++];
2187 unsigned RecNo = MatcherTable[MatcherIndex++];
2188 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002189 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2190 RecordedNodes[RecNo].first, CPNum,
Chris Lattner57bf8a42010-03-04 01:23:08 +00002191 RecordedNodes))
Chris Lattner2a49d572010-02-28 22:37:22 +00002192 break;
2193 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002194 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002195 case OPC_CheckOpcode:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002196 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2197 continue;
2198
2199 case OPC_CheckType:
2200 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002201 continue;
2202
Chris Lattnereb669212010-03-01 06:59:22 +00002203 case OPC_SwitchOpcode: {
2204 unsigned CurNodeOpcode = N.getOpcode();
Chris Lattner7d892d62010-03-01 07:43:08 +00002205 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
Chris Lattnereb669212010-03-01 06:59:22 +00002206 unsigned CaseSize;
2207 while (1) {
2208 // Get the size of this case.
2209 CaseSize = MatcherTable[MatcherIndex++];
2210 if (CaseSize & 128)
2211 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2212 if (CaseSize == 0) break;
2213
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002214 uint16_t Opc = MatcherTable[MatcherIndex++];
2215 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2216
Chris Lattnereb669212010-03-01 06:59:22 +00002217 // If the opcode matches, then we will execute this case.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002218 if (CurNodeOpcode == Opc)
Chris Lattnereb669212010-03-01 06:59:22 +00002219 break;
2220
2221 // Otherwise, skip over this case.
2222 MatcherIndex += CaseSize;
2223 }
2224
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002225 // If no cases matched, bail out.
Chris Lattnereb669212010-03-01 06:59:22 +00002226 if (CaseSize == 0) break;
2227
2228 // Otherwise, execute the case we found.
2229 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2230 << " to " << MatcherIndex << "\n");
2231 continue;
2232 }
2233
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002234 case OPC_SwitchType: {
Duncan Sandscdfad362010-11-03 12:17:33 +00002235 MVT CurNodeVT = N.getValueType().getSimpleVT();
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002236 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2237 unsigned CaseSize;
2238 while (1) {
2239 // Get the size of this case.
2240 CaseSize = MatcherTable[MatcherIndex++];
2241 if (CaseSize & 128)
2242 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2243 if (CaseSize == 0) break;
2244
Duncan Sandscdfad362010-11-03 12:17:33 +00002245 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002246 if (CaseVT == MVT::iPTR)
Duncan Sandscdfad362010-11-03 12:17:33 +00002247 CaseVT = TLI.getPointerTy();
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002248
2249 // If the VT matches, then we will execute this case.
2250 if (CurNodeVT == CaseVT)
2251 break;
2252
2253 // Otherwise, skip over this case.
2254 MatcherIndex += CaseSize;
2255 }
2256
2257 // If no cases matched, bail out.
2258 if (CaseSize == 0) break;
2259
2260 // Otherwise, execute the case we found.
2261 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2262 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2263 continue;
2264 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002265 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2266 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2267 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00002268 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2269 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2270 Opcode-OPC_CheckChild0Type))
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002271 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002272 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002273 case OPC_CheckCondCode:
Chris Lattnerda828e32010-03-03 07:46:25 +00002274 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002275 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002276 case OPC_CheckValueType:
2277 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002278 continue;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002279 case OPC_CheckInteger:
2280 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002281 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002282 case OPC_CheckAndImm:
2283 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002284 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002285 case OPC_CheckOrImm:
2286 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002287 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002288
2289 case OPC_CheckFoldableChainNode: {
2290 assert(NodeStack.size() != 1 && "No parent node");
2291 // Verify that all intermediate nodes between the root and this one have
2292 // a single use.
2293 bool HasMultipleUses = false;
2294 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2295 if (!NodeStack[i].hasOneUse()) {
2296 HasMultipleUses = true;
2297 break;
2298 }
2299 if (HasMultipleUses) break;
2300
2301 // Check to see that the target thinks this is profitable to fold and that
2302 // we can fold it without inducing cycles in the graph.
2303 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2304 NodeToMatch) ||
2305 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
Dan Gohmand858e902010-04-17 15:26:15 +00002306 NodeToMatch, OptLevel,
2307 true/*We validate our own chains*/))
Chris Lattner2a49d572010-02-28 22:37:22 +00002308 break;
2309
2310 continue;
2311 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002312 case OPC_EmitInteger: {
2313 MVT::SimpleValueType VT =
2314 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2315 int64_t Val = MatcherTable[MatcherIndex++];
2316 if (Val & 128)
2317 Val = GetVBR(Val, MatcherTable, MatcherIndex);
Chris Lattnerd847bc22010-09-21 22:00:25 +00002318 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002319 CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002320 continue;
2321 }
2322 case OPC_EmitRegister: {
2323 MVT::SimpleValueType VT =
2324 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2325 unsigned RegNo = MatcherTable[MatcherIndex++];
Chris Lattnerd847bc22010-09-21 22:00:25 +00002326 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002327 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002328 continue;
2329 }
2330
2331 case OPC_EmitConvertToTarget: {
2332 // Convert from IMM/FPIMM to target version.
2333 unsigned RecNo = MatcherTable[MatcherIndex++];
2334 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002335 SDValue Imm = RecordedNodes[RecNo].first;
Chris Lattner2a49d572010-02-28 22:37:22 +00002336
2337 if (Imm->getOpcode() == ISD::Constant) {
2338 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2339 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2340 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2341 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2342 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2343 }
2344
Chris Lattnerd847bc22010-09-21 22:00:25 +00002345 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
Chris Lattner2a49d572010-02-28 22:37:22 +00002346 continue;
2347 }
2348
Chris Lattneraa4e3392010-03-28 05:50:16 +00002349 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2350 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2351 // These are space-optimized forms of OPC_EmitMergeInputChains.
2352 assert(InputChain.getNode() == 0 &&
2353 "EmitMergeInputChains should be the first chain producing node");
2354 assert(ChainNodesMatched.empty() &&
2355 "Should only have one EmitMergeInputChains per match");
2356
2357 // Read all of the chained nodes.
2358 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2359 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002360 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
Chris Lattneraa4e3392010-03-28 05:50:16 +00002361
2362 // FIXME: What if other value results of the node have uses not matched
2363 // by this pattern?
2364 if (ChainNodesMatched.back() != NodeToMatch &&
Chris Lattnerd847bc22010-09-21 22:00:25 +00002365 !RecordedNodes[RecNo].first.hasOneUse()) {
Chris Lattneraa4e3392010-03-28 05:50:16 +00002366 ChainNodesMatched.clear();
2367 break;
2368 }
2369
2370 // Merge the input chains if they are not intra-pattern references.
2371 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2372
2373 if (InputChain.getNode() == 0)
2374 break; // Failed to merge.
2375 continue;
2376 }
2377
Chris Lattner2a49d572010-02-28 22:37:22 +00002378 case OPC_EmitMergeInputChains: {
2379 assert(InputChain.getNode() == 0 &&
2380 "EmitMergeInputChains should be the first chain producing node");
2381 // This node gets a list of nodes we matched in the input that have
2382 // chains. We want to token factor all of the input chains to these nodes
2383 // together. However, if any of the input chains is actually one of the
2384 // nodes matched in this pattern, then we have an intra-match reference.
2385 // Ignore these because the newly token factored chain should not refer to
2386 // the old nodes.
2387 unsigned NumChains = MatcherTable[MatcherIndex++];
2388 assert(NumChains != 0 && "Can't TF zero chains");
2389
2390 assert(ChainNodesMatched.empty() &&
2391 "Should only have one EmitMergeInputChains per match");
2392
Chris Lattner2a49d572010-02-28 22:37:22 +00002393 // Read all of the chained nodes.
Chris Lattner00592ec2010-03-02 19:34:59 +00002394 for (unsigned i = 0; i != NumChains; ++i) {
2395 unsigned RecNo = MatcherTable[MatcherIndex++];
Chris Lattner2a49d572010-02-28 22:37:22 +00002396 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002397 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
Chris Lattner2a49d572010-02-28 22:37:22 +00002398
2399 // FIXME: What if other value results of the node have uses not matched
2400 // by this pattern?
2401 if (ChainNodesMatched.back() != NodeToMatch &&
Chris Lattnerd847bc22010-09-21 22:00:25 +00002402 !RecordedNodes[RecNo].first.hasOneUse()) {
Chris Lattner2a49d572010-02-28 22:37:22 +00002403 ChainNodesMatched.clear();
2404 break;
2405 }
2406 }
Chris Lattner6b307922010-03-02 00:00:03 +00002407
2408 // If the inner loop broke out, the match fails.
2409 if (ChainNodesMatched.empty())
2410 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002411
Chris Lattner6b307922010-03-02 00:00:03 +00002412 // Merge the input chains if they are not intra-pattern references.
2413 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2414
2415 if (InputChain.getNode() == 0)
2416 break; // Failed to merge.
Chris Lattner2a49d572010-02-28 22:37:22 +00002417
Chris Lattner2a49d572010-02-28 22:37:22 +00002418 continue;
2419 }
2420
2421 case OPC_EmitCopyToReg: {
2422 unsigned RecNo = MatcherTable[MatcherIndex++];
2423 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2424 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2425
2426 if (InputChain.getNode() == 0)
2427 InputChain = CurDAG->getEntryNode();
2428
2429 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
Chris Lattnerd847bc22010-09-21 22:00:25 +00002430 DestPhysReg, RecordedNodes[RecNo].first,
Chris Lattner2a49d572010-02-28 22:37:22 +00002431 InputFlag);
2432
2433 InputFlag = InputChain.getValue(1);
2434 continue;
2435 }
2436
2437 case OPC_EmitNodeXForm: {
2438 unsigned XFormNo = MatcherTable[MatcherIndex++];
2439 unsigned RecNo = MatcherTable[MatcherIndex++];
2440 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002441 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002442 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002443 continue;
2444 }
2445
2446 case OPC_EmitNode:
2447 case OPC_MorphNodeTo: {
Chris Lattner14df8dc2010-02-28 22:38:43 +00002448 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2449 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
Chris Lattner2a49d572010-02-28 22:37:22 +00002450 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2451 // Get the result VT list.
2452 unsigned NumVTs = MatcherTable[MatcherIndex++];
2453 SmallVector<EVT, 4> VTs;
2454 for (unsigned i = 0; i != NumVTs; ++i) {
2455 MVT::SimpleValueType VT =
2456 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2457 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2458 VTs.push_back(VT);
2459 }
2460
2461 if (EmitNodeInfo & OPFL_Chain)
2462 VTs.push_back(MVT::Other);
2463 if (EmitNodeInfo & OPFL_FlagOutput)
2464 VTs.push_back(MVT::Flag);
2465
Chris Lattner7d892d62010-03-01 07:43:08 +00002466 // This is hot code, so optimize the two most common cases of 1 and 2
2467 // results.
2468 SDVTList VTList;
2469 if (VTs.size() == 1)
2470 VTList = CurDAG->getVTList(VTs[0]);
2471 else if (VTs.size() == 2)
2472 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2473 else
2474 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
Chris Lattner2a49d572010-02-28 22:37:22 +00002475
2476 // Get the operand list.
2477 unsigned NumOps = MatcherTable[MatcherIndex++];
2478 SmallVector<SDValue, 8> Ops;
2479 for (unsigned i = 0; i != NumOps; ++i) {
2480 unsigned RecNo = MatcherTable[MatcherIndex++];
2481 if (RecNo & 128)
2482 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2483
2484 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002485 Ops.push_back(RecordedNodes[RecNo].first);
Chris Lattner2a49d572010-02-28 22:37:22 +00002486 }
2487
2488 // If there are variadic operands to add, handle them now.
2489 if (EmitNodeInfo & OPFL_VariadicInfo) {
2490 // Determine the start index to copy from.
2491 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2492 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2493 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2494 "Invalid variadic node");
2495 // Copy all of the variadic operands, not including a potential flag
2496 // input.
2497 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2498 i != e; ++i) {
2499 SDValue V = NodeToMatch->getOperand(i);
2500 if (V.getValueType() == MVT::Flag) break;
2501 Ops.push_back(V);
2502 }
2503 }
2504
2505 // If this has chain/flag inputs, add them.
2506 if (EmitNodeInfo & OPFL_Chain)
2507 Ops.push_back(InputChain);
2508 if ((EmitNodeInfo & OPFL_FlagInput) && InputFlag.getNode() != 0)
2509 Ops.push_back(InputFlag);
2510
2511 // Create the node.
2512 SDNode *Res = 0;
2513 if (Opcode != OPC_MorphNodeTo) {
2514 // If this is a normal EmitNode command, just create the new node and
2515 // add the results to the RecordedNodes list.
2516 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2517 VTList, Ops.data(), Ops.size());
2518
2519 // Add all the non-flag/non-chain results to the RecordedNodes list.
2520 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2521 if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
Chris Lattnerd847bc22010-09-21 22:00:25 +00002522 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
Oscar Fuentesdf30bdb2010-09-23 16:59:36 +00002523 (SDNode*) 0));
Chris Lattner2a49d572010-02-28 22:37:22 +00002524 }
2525
2526 } else {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00002527 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2528 EmitNodeInfo);
Chris Lattner2a49d572010-02-28 22:37:22 +00002529 }
2530
2531 // If the node had chain/flag results, update our notion of the current
2532 // chain and flag.
Chris Lattner82dd3d32010-03-02 07:50:03 +00002533 if (EmitNodeInfo & OPFL_FlagOutput) {
Chris Lattner2a49d572010-02-28 22:37:22 +00002534 InputFlag = SDValue(Res, VTs.size()-1);
2535 if (EmitNodeInfo & OPFL_Chain)
2536 InputChain = SDValue(Res, VTs.size()-2);
2537 } else if (EmitNodeInfo & OPFL_Chain)
2538 InputChain = SDValue(Res, VTs.size()-1);
2539
2540 // If the OPFL_MemRefs flag is set on this node, slap all of the
2541 // accumulated memrefs onto it.
2542 //
2543 // FIXME: This is vastly incorrect for patterns with multiple outputs
2544 // instructions that access memory and for ComplexPatterns that match
2545 // loads.
2546 if (EmitNodeInfo & OPFL_MemRefs) {
2547 MachineSDNode::mmo_iterator MemRefs =
2548 MF->allocateMemRefsArray(MatchedMemRefs.size());
2549 std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
2550 cast<MachineSDNode>(Res)
2551 ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
2552 }
2553
2554 DEBUG(errs() << " "
2555 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2556 << " node: "; Res->dump(CurDAG); errs() << "\n");
2557
2558 // If this was a MorphNodeTo then we're completely done!
2559 if (Opcode == OPC_MorphNodeTo) {
2560 // Update chain and flag uses.
2561 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
Chris Lattner82dd3d32010-03-02 07:50:03 +00002562 InputFlag, FlagResultNodesMatched, true);
2563 return Res;
Chris Lattner2a49d572010-02-28 22:37:22 +00002564 }
2565
2566 continue;
2567 }
2568
2569 case OPC_MarkFlagResults: {
2570 unsigned NumNodes = MatcherTable[MatcherIndex++];
2571
2572 // Read and remember all the flag-result nodes.
2573 for (unsigned i = 0; i != NumNodes; ++i) {
2574 unsigned RecNo = MatcherTable[MatcherIndex++];
2575 if (RecNo & 128)
2576 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2577
2578 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002579 FlagResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
Chris Lattner2a49d572010-02-28 22:37:22 +00002580 }
2581 continue;
2582 }
2583
2584 case OPC_CompleteMatch: {
2585 // The match has been completed, and any new nodes (if any) have been
2586 // created. Patch up references to the matched dag to use the newly
2587 // created nodes.
2588 unsigned NumResults = MatcherTable[MatcherIndex++];
2589
2590 for (unsigned i = 0; i != NumResults; ++i) {
2591 unsigned ResSlot = MatcherTable[MatcherIndex++];
2592 if (ResSlot & 128)
2593 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2594
2595 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
Chris Lattnerd847bc22010-09-21 22:00:25 +00002596 SDValue Res = RecordedNodes[ResSlot].first;
Chris Lattner2a49d572010-02-28 22:37:22 +00002597
Chris Lattnerb0e483e2010-03-28 05:54:03 +00002598 assert(i < NodeToMatch->getNumValues() &&
2599 NodeToMatch->getValueType(i) != MVT::Other &&
2600 NodeToMatch->getValueType(i) != MVT::Flag &&
2601 "Invalid number of results to complete!");
Chris Lattner2a49d572010-02-28 22:37:22 +00002602 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2603 NodeToMatch->getValueType(i) == MVT::iPTR ||
2604 Res.getValueType() == MVT::iPTR ||
2605 NodeToMatch->getValueType(i).getSizeInBits() ==
2606 Res.getValueType().getSizeInBits()) &&
2607 "invalid replacement");
2608 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2609 }
2610
2611 // If the root node defines a flag, add it to the flag nodes to update
2612 // list.
2613 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Flag)
2614 FlagResultNodesMatched.push_back(NodeToMatch);
2615
2616 // Update chain and flag uses.
2617 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
Chris Lattner82dd3d32010-03-02 07:50:03 +00002618 InputFlag, FlagResultNodesMatched, false);
Chris Lattner2a49d572010-02-28 22:37:22 +00002619
2620 assert(NodeToMatch->use_empty() &&
2621 "Didn't replace all uses of the node?");
2622
2623 // FIXME: We just return here, which interacts correctly with SelectRoot
2624 // above. We should fix this to not return an SDNode* anymore.
2625 return 0;
2626 }
2627 }
2628
2629 // If the code reached this point, then the match failed. See if there is
2630 // another child to try in the current 'Scope', otherwise pop it until we
2631 // find a case to check.
Dan Gohman19b38262010-03-09 02:15:05 +00002632 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
Chris Lattnerbed993d2010-03-28 19:46:56 +00002633 ++NumDAGIselRetries;
Chris Lattner2a49d572010-02-28 22:37:22 +00002634 while (1) {
2635 if (MatchScopes.empty()) {
2636 CannotYetSelect(NodeToMatch);
2637 return 0;
2638 }
2639
2640 // Restore the interpreter state back to the point where the scope was
2641 // formed.
2642 MatchScope &LastScope = MatchScopes.back();
2643 RecordedNodes.resize(LastScope.NumRecordedNodes);
2644 NodeStack.clear();
2645 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2646 N = NodeStack.back();
2647
Chris Lattner2a49d572010-02-28 22:37:22 +00002648 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2649 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2650 MatcherIndex = LastScope.FailIndex;
2651
Dan Gohman19b38262010-03-09 02:15:05 +00002652 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2653
Chris Lattner2a49d572010-02-28 22:37:22 +00002654 InputChain = LastScope.InputChain;
2655 InputFlag = LastScope.InputFlag;
2656 if (!LastScope.HasChainNodesMatched)
2657 ChainNodesMatched.clear();
2658 if (!LastScope.HasFlagResultNodesMatched)
2659 FlagResultNodesMatched.clear();
2660
2661 // Check to see what the offset is at the new MatcherIndex. If it is zero
2662 // we have reached the end of this scope, otherwise we have another child
2663 // in the current scope to try.
2664 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2665 if (NumToSkip & 128)
2666 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2667
2668 // If we have another child in this scope to match, update FailIndex and
2669 // try it.
2670 if (NumToSkip != 0) {
2671 LastScope.FailIndex = MatcherIndex+NumToSkip;
2672 break;
2673 }
2674
2675 // End of this scope, pop it and try the next child in the containing
2676 // scope.
2677 MatchScopes.pop_back();
2678 }
2679 }
2680}
2681
2682
2683
Dan Gohmaneeb3a002010-01-05 01:24:18 +00002684void SelectionDAGISel::CannotYetSelect(SDNode *N) {
Dan Gohmane1f188f2009-10-29 22:30:23 +00002685 std::string msg;
2686 raw_string_ostream Msg(msg);
2687 Msg << "Cannot yet select: ";
Chris Lattner2c4afd12010-03-04 00:21:16 +00002688
2689 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2690 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2691 N->getOpcode() != ISD::INTRINSIC_VOID) {
2692 N->printrFull(Msg, CurDAG);
2693 } else {
2694 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2695 unsigned iid =
2696 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2697 if (iid < Intrinsic::num_intrinsics)
2698 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2699 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2700 Msg << "target intrinsic %" << TII->getName(iid);
2701 else
2702 Msg << "unknown intrinsic #" << iid;
2703 }
Chris Lattner75361b62010-04-07 22:58:41 +00002704 report_fatal_error(Msg.str());
Dan Gohmane1f188f2009-10-29 22:30:23 +00002705}
2706
Devang Patel19974732007-05-03 01:11:54 +00002707char SelectionDAGISel::ID = 0;