blob: fc830ac2482fccece64d9dd71115307a48cd3f44 [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 Gohman6277eb22009-11-23 17:16:22 +000017#include "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");
Chris Lattnerbed993d2010-03-28 19:46:56 +000056STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
Chris Lattnerc19ae9d2010-03-04 19:46:56 +000057
Chris Lattneread0d882008-06-17 06:09:18 +000058static cl::opt<bool>
Dan Gohman293d5f82008-09-09 22:06:46 +000059EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
Dan Gohmand659d502008-10-20 21:30:12 +000060 cl::desc("Enable verbose messages in the \"fast\" "
Dan Gohman293d5f82008-09-09 22:06:46 +000061 "instruction selector"));
62static cl::opt<bool>
Dan Gohman4344a5d2008-09-09 23:05:00 +000063EnableFastISelAbort("fast-isel-abort", cl::Hidden,
64 cl::desc("Enable abort calls when \"fast\" instruction fails"));
Chris Lattneread0d882008-06-17 06:09:18 +000065
Chris Lattnerda8abb02005-09-01 18:44:10 +000066#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000067static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000068ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
69 cl::desc("Pop up a window to show dags before the first "
70 "dag combine pass"));
71static cl::opt<bool>
72ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
73 cl::desc("Pop up a window to show dags before legalize types"));
74static cl::opt<bool>
75ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
76 cl::desc("Pop up a window to show dags before legalize"));
77static cl::opt<bool>
78ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
79 cl::desc("Pop up a window to show dags before the second "
80 "dag combine pass"));
81static cl::opt<bool>
Duncan Sands25cf2272008-11-24 14:53:14 +000082ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
83 cl::desc("Pop up a window to show dags before the post legalize types"
84 " dag combine pass"));
85static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000086ViewISelDAGs("view-isel-dags", cl::Hidden,
87 cl::desc("Pop up a window to show isel dags as they are selected"));
88static cl::opt<bool>
89ViewSchedDAGs("view-sched-dags", cl::Hidden,
90 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000091static cl::opt<bool>
92ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000093 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000094#else
Dan Gohman462dc7f2008-07-21 20:00:07 +000095static const bool ViewDAGCombine1 = false,
96 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
97 ViewDAGCombine2 = false,
Duncan Sands25cf2272008-11-24 14:53:14 +000098 ViewDAGCombineLT = false,
Dan Gohman462dc7f2008-07-21 20:00:07 +000099 ViewISelDAGs = false, ViewSchedDAGs = false,
100 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +0000101#endif
102
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000103//===---------------------------------------------------------------------===//
104///
105/// RegisterScheduler class - Track the registration of instruction schedulers.
106///
107//===---------------------------------------------------------------------===//
108MachinePassRegistry RegisterScheduler::Registry;
109
110//===---------------------------------------------------------------------===//
111///
112/// ISHeuristic command line option for instruction schedulers.
113///
114//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000115static cl::opt<RegisterScheduler::FunctionPassCtor, false,
116 RegisterPassParser<RegisterScheduler> >
117ISHeuristic("pre-RA-sched",
118 cl::init(&createDefaultScheduler),
119 cl::desc("Instruction schedulers available (before register"
120 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000121
Dan Gohman844731a2008-05-13 00:00:25 +0000122static RegisterScheduler
Dan Gohmanb8cab922008-10-14 20:25:08 +0000123defaultListDAGScheduler("default", "Best scheduler for the target",
Dan Gohman844731a2008-05-13 00:00:25 +0000124 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000125
Chris Lattner1c08c712005-01-07 07:47:53 +0000126namespace llvm {
127 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000128 /// createDefaultScheduler - This creates an instruction scheduler appropriate
129 /// for the target.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000130 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
Bill Wendling98a366d2009-04-29 23:29:43 +0000131 CodeGenOpt::Level OptLevel) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000132 const TargetLowering &TLI = IS->getTargetLowering();
133
Bill Wendling98a366d2009-04-29 23:29:43 +0000134 if (OptLevel == CodeGenOpt::None)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000135 return createFastDAGScheduler(IS, OptLevel);
Evan Cheng211ffa12010-05-19 20:19:50 +0000136 if (TLI.getSchedulingPreference() == Sched::Latency)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000137 return createTDListDAGScheduler(IS, OptLevel);
Evan Cheng15a16de2010-05-20 06:13:19 +0000138 if (TLI.getSchedulingPreference() == Sched::RegPressure)
139 return createBURRListDAGScheduler(IS, OptLevel);
140 assert(TLI.getSchedulingPreference() == Sched::Hybrid &&
Evan Cheng211ffa12010-05-19 20:19:50 +0000141 "Unknown sched type!");
Evan Cheng15a16de2010-05-20 06:13:19 +0000142 return createHybridListDAGScheduler(IS, OptLevel);
Jim Laskey9373beb2006-08-01 19:14:14 +0000143 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000144}
145
Evan Chengff9b3732008-01-30 18:18:23 +0000146// EmitInstrWithCustomInserter - This method should be implemented by targets
Dan Gohman533297b2009-10-29 18:10:34 +0000147// that mark instructions with the 'usesCustomInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +0000148// instructions are special in various ways, which require special support to
149// insert. The specified MachineInstr is created but not inserted into any
Dan Gohman533297b2009-10-29 18:10:34 +0000150// basic blocks, and this method is called to expand it into a sequence of
151// instructions, potentially also creating new basic blocks and control flow.
152// When new basic blocks are inserted and the edges from MBB to its successors
153// are modified, the method should insert pairs of <OldSucc, NewSucc> into the
154// DenseMap.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000155MachineBasicBlock *
156TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
157 MachineBasicBlock *MBB) const {
Torok Edwinf3689232009-07-12 20:07:01 +0000158#ifndef NDEBUG
David Greene1a053232010-01-05 01:26:11 +0000159 dbgs() << "If a target marks an instruction with "
Dan Gohman533297b2009-10-29 18:10:34 +0000160 "'usesCustomInserter', it must implement "
Torok Edwinf3689232009-07-12 20:07:01 +0000161 "TargetLowering::EmitInstrWithCustomInserter!";
162#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000163 llvm_unreachable(0);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000164 return 0;
Chris Lattner025c39b2005-08-26 20:54:47 +0000165}
166
Chris Lattner7041ee32005-01-11 05:56:49 +0000167//===----------------------------------------------------------------------===//
168// SelectionDAGISel code
169//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000170
Dan Gohmanf0757b02010-04-21 01:34:56 +0000171SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm, CodeGenOpt::Level OL) :
Dan Gohmanad2afc22009-07-31 18:16:33 +0000172 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000173 FuncInfo(new FunctionLoweringInfo(TLI)),
Dan Gohman50d2b1a2010-04-19 19:22:07 +0000174 CurDAG(new SelectionDAG(tm, *FuncInfo)),
Dan Gohman55e59c12010-04-19 19:05:59 +0000175 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000176 GFI(),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000177 OptLevel(OL),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000178 DAGSize(0)
179{}
180
181SelectionDAGISel::~SelectionDAGISel() {
Dan Gohman2048b852009-11-23 18:04:58 +0000182 delete SDB;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000183 delete CurDAG;
184 delete FuncInfo;
185}
186
Chris Lattner495a0b52005-08-17 06:37:43 +0000187void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000188 AU.addRequired<AliasAnalysis>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000189 AU.addPreserved<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000190 AU.addRequired<GCModuleInfo>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000191 AU.addPreserved<GCModuleInfo>();
Dan Gohmanad2afc22009-07-31 18:16:33 +0000192 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner495a0b52005-08-17 06:37:43 +0000193}
Chris Lattner1c08c712005-01-07 07:47:53 +0000194
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000195/// FunctionCallsSetJmp - Return true if the function has a call to setjmp or
196/// sigsetjmp. This is used to limit code-gen optimizations on the machine
197/// function.
198static bool FunctionCallsSetJmp(const Function *F) {
199 const Module *M = F->getParent();
200 const Function *SetJmp = M->getFunction("setjmp");
201 const Function *SigSetJmp = M->getFunction("sigsetjmp");
202
203 if (!SetJmp && !SigSetJmp)
204 return false;
205
206 if (SetJmp && !SetJmp->use_empty())
207 for (Value::const_use_iterator
208 I = SetJmp->use_begin(), E = SetJmp->use_end(); I != E; ++I)
209 if (const CallInst *CI = dyn_cast<CallInst>(I))
210 if (CI->getParent()->getParent() == F)
211 return true;
212
213 if (SigSetJmp && !SigSetJmp->use_empty())
214 for (Value::const_use_iterator
215 I = SigSetJmp->use_begin(), E = SigSetJmp->use_end(); I != E; ++I)
216 if (const CallInst *CI = dyn_cast<CallInst>(I))
217 if (CI->getParent()->getParent() == F)
218 return true;
219
220 return false;
221}
222
Dan Gohmanad2afc22009-07-31 18:16:33 +0000223bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
Dan Gohman4344a5d2008-09-09 23:05:00 +0000224 // Do some sanity-checking on the command-line options.
225 assert((!EnableFastISelVerbose || EnableFastISel) &&
226 "-fast-isel-verbose requires -fast-isel");
227 assert((!EnableFastISelAbort || EnableFastISel) &&
228 "-fast-isel-abort requires -fast-isel");
229
Dan Gohmanae541aa2010-04-15 04:33:49 +0000230 const Function &Fn = *mf.getFunction();
Dan Gohman8a110532008-09-05 22:59:21 +0000231 const TargetInstrInfo &TII = *TM.getInstrInfo();
232 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
233
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000234 MF = &mf;
Dan Gohman79ce2762009-01-15 19:20:50 +0000235 RegInfo = &MF->getRegInfo();
Dan Gohmanc0fb65d2010-04-14 17:02:07 +0000236 AA = &getAnalysis<AliasAnalysis>();
237 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
238
David Greene1a053232010-01-05 01:26:11 +0000239 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000240
Chris Lattnerde6e7832010-04-05 06:10:13 +0000241 CurDAG->init(*MF);
Dan Gohman6277eb22009-11-23 17:16:22 +0000242 FuncInfo->set(Fn, *MF, EnableFastISel);
Dan Gohman2048b852009-11-23 18:04:58 +0000243 SDB->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000244
Dan Gohman6a732b52010-04-14 20:05:00 +0000245 SelectAllBasicBlocks(Fn);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000246
Dan Gohman1b79a2f2010-05-01 00:33:28 +0000247 // If the first basic block in the function has live ins that need to be
Dan Gohman8a110532008-09-05 22:59:21 +0000248 // copied into vregs, emit the copies into the top of the block before
249 // emitting the code for the block.
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000250 MachineBasicBlock *EntryMBB = MF->begin();
251 RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
252
253 // Insert DBG_VALUE instructions for function arguments to the entry block.
254 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
255 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
256 unsigned Reg = MI->getOperand(0).getReg();
257 if (TargetRegisterInfo::isPhysicalRegister(Reg))
258 EntryMBB->insert(EntryMBB->begin(), MI);
259 else {
260 MachineInstr *Def = RegInfo->getVRegDef(Reg);
261 MachineBasicBlock::iterator InsertPos = Def;
Evan Chengf1ced252010-05-04 00:58:39 +0000262 // FIXME: VR def may not be in entry block.
263 Def->getParent()->insert(llvm::next(InsertPos), MI);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000264 }
265 }
266
Bill Wendling53f76022010-05-17 23:09:50 +0000267 // Determine if there are any calls in this machine function.
268 MachineFrameInfo *MFI = MF->getFrameInfo();
269 if (!MFI->hasCalls()) {
270 for (MachineFunction::const_iterator
271 I = MF->begin(), E = MF->end(); I != E; ++I) {
272 const MachineBasicBlock *MBB = I;
273 for (MachineBasicBlock::const_iterator
274 II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
275 const TargetInstrDesc &TID = TM.getInstrInfo()->get(II->getOpcode());
276 if (II->isInlineAsm() || (TID.isCall() && !TID.isReturn())) {
277 MFI->setHasCalls(true);
278 goto done;
279 }
280 }
281 }
282 done:;
283 }
284
Bill Wendling9af7e9a2010-05-26 19:46:12 +0000285 // Determine if there is a call to setjmp in the machine function.
286 MF->setCallsSetJmp(FunctionCallsSetJmp(&Fn));
287
Evan Cheng2ad0fcf2010-04-28 23:08:54 +0000288 // Release function-specific state. SDB and CurDAG are already cleared
289 // at this point.
290 FuncInfo->clear();
Dan Gohman8a110532008-09-05 22:59:21 +0000291
Chris Lattner1c08c712005-01-07 07:47:53 +0000292 return true;
293}
294
Dan Gohmana9a33212010-04-20 00:29:35 +0000295MachineBasicBlock *
296SelectionDAGISel::SelectBasicBlock(MachineBasicBlock *BB,
297 const BasicBlock *LLVMBB,
298 BasicBlock::const_iterator Begin,
299 BasicBlock::const_iterator End,
300 bool &HadTailCall) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000301 // Lower all of the non-terminator instructions. If a call is emitted
Dan Gohmanf89d1dc2010-04-16 05:06:56 +0000302 // as a tail call, cease emitting nodes for this block. Terminators
303 // are handled below.
Dan Gohmanc105a2b2010-04-22 20:55:53 +0000304 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
Dan Gohmanf89d1dc2010-04-16 05:06:56 +0000305 SDB->visit(*I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000306
Chris Lattnera651cf62005-01-17 19:43:36 +0000307 // Make sure the root of the DAG is up-to-date.
Dan Gohman2048b852009-11-23 18:04:58 +0000308 CurDAG->setRoot(SDB->getControlRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000309 HadTailCall = SDB->HasTailCall;
310 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000311
312 // Final step, emit the lowered DAG as machine code.
313 return CodeGenAndEmitDAG(BB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000314}
315
Evan Cheng54e146b2010-01-09 00:21:08 +0000316namespace {
317/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
318/// nodes from the worklist.
319class SDOPsWorkListRemover : public SelectionDAG::DAGUpdateListener {
320 SmallVector<SDNode*, 128> &Worklist;
Chris Lattner25e0ab92010-03-14 19:43:04 +0000321 SmallPtrSet<SDNode*, 128> &InWorklist;
Evan Cheng54e146b2010-01-09 00:21:08 +0000322public:
Chris Lattner25e0ab92010-03-14 19:43:04 +0000323 SDOPsWorkListRemover(SmallVector<SDNode*, 128> &wl,
324 SmallPtrSet<SDNode*, 128> &inwl)
325 : Worklist(wl), InWorklist(inwl) {}
Evan Cheng54e146b2010-01-09 00:21:08 +0000326
Chris Lattner25e0ab92010-03-14 19:43:04 +0000327 void RemoveFromWorklist(SDNode *N) {
328 if (!InWorklist.erase(N)) return;
329
330 SmallVector<SDNode*, 128>::iterator I =
331 std::find(Worklist.begin(), Worklist.end(), N);
332 assert(I != Worklist.end() && "Not in worklist");
333
334 *I = Worklist.back();
335 Worklist.pop_back();
336 }
337
Evan Cheng54e146b2010-01-09 00:21:08 +0000338 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattner25e0ab92010-03-14 19:43:04 +0000339 RemoveFromWorklist(N);
Evan Cheng54e146b2010-01-09 00:21:08 +0000340 }
341
342 virtual void NodeUpdated(SDNode *N) {
343 // Ignore updates.
344 }
345};
346}
347
Evan Cheng046632f2010-02-10 02:17:34 +0000348/// TrivialTruncElim - Eliminate some trivial nops that can result from
349/// ShrinkDemandedOps: (trunc (ext n)) -> n.
350static bool TrivialTruncElim(SDValue Op,
351 TargetLowering::TargetLoweringOpt &TLO) {
352 SDValue N0 = Op.getOperand(0);
353 EVT VT = Op.getValueType();
354 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
355 N0.getOpcode() == ISD::SIGN_EXTEND ||
356 N0.getOpcode() == ISD::ANY_EXTEND) &&
357 N0.getOperand(0).getValueType() == VT) {
358 return TLO.CombineTo(Op, N0.getOperand(0));
359 }
360 return false;
361}
362
Evan Cheng54eb4c22010-01-06 19:43:21 +0000363/// ShrinkDemandedOps - A late transformation pass that shrink expressions
364/// using TargetLowering::TargetLoweringOpt::ShrinkDemandedOp. It converts
365/// x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
Evan Chengd40d03e2010-01-06 19:38:29 +0000366void SelectionDAGISel::ShrinkDemandedOps() {
367 SmallVector<SDNode*, 128> Worklist;
Chris Lattner25e0ab92010-03-14 19:43:04 +0000368 SmallPtrSet<SDNode*, 128> InWorklist;
Evan Chengd40d03e2010-01-06 19:38:29 +0000369
370 // Add all the dag nodes to the worklist.
371 Worklist.reserve(CurDAG->allnodes_size());
372 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
Chris Lattner25e0ab92010-03-14 19:43:04 +0000373 E = CurDAG->allnodes_end(); I != E; ++I) {
Evan Chengd40d03e2010-01-06 19:38:29 +0000374 Worklist.push_back(I);
Chris Lattner25e0ab92010-03-14 19:43:04 +0000375 InWorklist.insert(I);
376 }
Evan Chengd40d03e2010-01-06 19:38:29 +0000377
Evan Chenge5b51ac2010-04-17 06:13:15 +0000378 TargetLowering::TargetLoweringOpt TLO(*CurDAG, true, true, true);
Evan Chengd40d03e2010-01-06 19:38:29 +0000379 while (!Worklist.empty()) {
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000380 SDNode *N = Worklist.pop_back_val();
Chris Lattner25e0ab92010-03-14 19:43:04 +0000381 InWorklist.erase(N);
Evan Chengd40d03e2010-01-06 19:38:29 +0000382
383 if (N->use_empty() && N != CurDAG->getRoot().getNode()) {
Chris Lattnerc4a3f232010-03-14 19:46:02 +0000384 // Deleting this node may make its operands dead, add them to the worklist
385 // if they aren't already there.
386 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
387 if (InWorklist.insert(N->getOperand(i).getNode()))
388 Worklist.push_back(N->getOperand(i).getNode());
389
Evan Cheng54e146b2010-01-09 00:21:08 +0000390 CurDAG->DeleteNode(N);
Evan Chengd40d03e2010-01-06 19:38:29 +0000391 continue;
392 }
393
394 // Run ShrinkDemandedOp on scalar binary operations.
Chris Lattner25e0ab92010-03-14 19:43:04 +0000395 if (N->getNumValues() != 1 ||
396 !N->getValueType(0).isSimple() || !N->getValueType(0).isInteger())
397 continue;
398
399 unsigned BitWidth = N->getValueType(0).getScalarType().getSizeInBits();
400 APInt Demanded = APInt::getAllOnesValue(BitWidth);
401 APInt KnownZero, KnownOne;
402 if (!TLI.SimplifyDemandedBits(SDValue(N, 0), Demanded,
403 KnownZero, KnownOne, TLO) &&
404 (N->getOpcode() != ISD::TRUNCATE ||
405 !TrivialTruncElim(SDValue(N, 0), TLO)))
406 continue;
407
408 // Revisit the node.
409 assert(!InWorklist.count(N) && "Already in worklist");
410 Worklist.push_back(N);
411 InWorklist.insert(N);
Evan Chengd40d03e2010-01-06 19:38:29 +0000412
Chris Lattner25e0ab92010-03-14 19:43:04 +0000413 // Replace the old value with the new one.
414 DEBUG(errs() << "\nShrinkDemandedOps replacing ";
415 TLO.Old.getNode()->dump(CurDAG);
416 errs() << "\nWith: ";
417 TLO.New.getNode()->dump(CurDAG);
418 errs() << '\n');
Evan Chengd40d03e2010-01-06 19:38:29 +0000419
Chris Lattner25e0ab92010-03-14 19:43:04 +0000420 if (InWorklist.insert(TLO.New.getNode()))
421 Worklist.push_back(TLO.New.getNode());
Evan Cheng54e146b2010-01-09 00:21:08 +0000422
Chris Lattner25e0ab92010-03-14 19:43:04 +0000423 SDOPsWorkListRemover DeadNodes(Worklist, InWorklist);
424 CurDAG->ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
Evan Chengd40d03e2010-01-06 19:38:29 +0000425
Chris Lattner25e0ab92010-03-14 19:43:04 +0000426 if (!TLO.Old.getNode()->use_empty()) continue;
427
428 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands();
429 i != e; ++i) {
430 SDNode *OpNode = TLO.Old.getNode()->getOperand(i).getNode();
431 if (OpNode->hasOneUse()) {
432 // Add OpNode to the end of the list to revisit.
433 DeadNodes.RemoveFromWorklist(OpNode);
434 Worklist.push_back(OpNode);
435 InWorklist.insert(OpNode);
Evan Chengd40d03e2010-01-06 19:38:29 +0000436 }
437 }
Chris Lattner25e0ab92010-03-14 19:43:04 +0000438
439 DeadNodes.RemoveFromWorklist(TLO.Old.getNode());
440 CurDAG->DeleteNode(TLO.Old.getNode());
Evan Chengd40d03e2010-01-06 19:38:29 +0000441 }
442}
443
Dan Gohmanf350b272008-08-23 02:25:05 +0000444void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +0000445 SmallPtrSet<SDNode*, 128> VisitedNodes;
446 SmallVector<SDNode*, 128> Worklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000447
Gabor Greifba36cb52008-08-28 21:40:38 +0000448 Worklist.push_back(CurDAG->getRoot().getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000449
Chris Lattneread0d882008-06-17 06:09:18 +0000450 APInt Mask;
451 APInt KnownZero;
452 APInt KnownOne;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000453
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000454 do {
455 SDNode *N = Worklist.pop_back_val();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000456
Chris Lattneread0d882008-06-17 06:09:18 +0000457 // If we've already seen this node, ignore it.
458 if (!VisitedNodes.insert(N))
459 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000460
Chris Lattneread0d882008-06-17 06:09:18 +0000461 // Otherwise, add all chain operands to the worklist.
462 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +0000463 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +0000464 Worklist.push_back(N->getOperand(i).getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000465
Chris Lattneread0d882008-06-17 06:09:18 +0000466 // If this is a CopyToReg with a vreg dest, process it.
467 if (N->getOpcode() != ISD::CopyToReg)
468 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000469
Chris Lattneread0d882008-06-17 06:09:18 +0000470 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
471 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
472 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000473
Chris Lattneread0d882008-06-17 06:09:18 +0000474 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +0000475 SDValue Src = N->getOperand(2);
Owen Andersone50ed302009-08-10 22:56:29 +0000476 EVT SrcVT = Src.getValueType();
Chris Lattneread0d882008-06-17 06:09:18 +0000477 if (!SrcVT.isInteger() || SrcVT.isVector())
478 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Dan Gohmanf350b272008-08-23 02:25:05 +0000480 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +0000481 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +0000482 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000483
Chris Lattneread0d882008-06-17 06:09:18 +0000484 // Only install this information if it tells us something.
485 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
486 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000487 if (DestReg >= FuncInfo->LiveOutRegInfo.size())
488 FuncInfo->LiveOutRegInfo.resize(DestReg+1);
489 FunctionLoweringInfo::LiveOutInfo &LOI =
490 FuncInfo->LiveOutRegInfo[DestReg];
Chris Lattneread0d882008-06-17 06:09:18 +0000491 LOI.NumSignBits = NumSignBits;
Dan Gohmana80efce2009-03-27 23:55:04 +0000492 LOI.KnownOne = KnownOne;
493 LOI.KnownZero = KnownZero;
Chris Lattneread0d882008-06-17 06:09:18 +0000494 }
Benjamin Kramer7b1e2a52010-01-07 17:27:56 +0000495 } while (!Worklist.empty());
Chris Lattneread0d882008-06-17 06:09:18 +0000496}
497
Dan Gohmana9a33212010-04-20 00:29:35 +0000498MachineBasicBlock *SelectionDAGISel::CodeGenAndEmitDAG(MachineBasicBlock *BB) {
Dan Gohman462dc7f2008-07-21 20:00:07 +0000499 std::string GroupName;
500 if (TimePassesIsEnabled)
501 GroupName = "Instruction Selection and Scheduling";
502 std::string BlockName;
503 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
Duncan Sands25cf2272008-11-24 14:53:14 +0000504 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
505 ViewSUnitDAGs)
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000506 BlockName = MF->getFunction()->getNameStr() + ":" +
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000507 BB->getBasicBlock()->getNameStr();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000508
David Greene1a053232010-01-05 01:26:11 +0000509 DEBUG(dbgs() << "Initial selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000510 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000511
Dan Gohmanf350b272008-08-23 02:25:05 +0000512 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +0000513
Chris Lattneraf21d552005-10-10 16:47:10 +0000514 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000515 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000516 NamedRegionTimer T("DAG Combining 1", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000517 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000518 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000519 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000520 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000521
David Greene1a053232010-01-05 01:26:11 +0000522 DEBUG(dbgs() << "Optimized lowered selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000523 DEBUG(CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000524
Chris Lattner1c08c712005-01-07 07:47:53 +0000525 // Second step, hack on the DAG until it only uses operations and types that
526 // the target supports.
Dan Gohman714efc62009-12-05 17:51:33 +0000527 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
528 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000529
Dan Gohman714efc62009-12-05 17:51:33 +0000530 bool Changed;
531 if (TimePassesIsEnabled) {
532 NamedRegionTimer T("Type Legalization", GroupName);
533 Changed = CurDAG->LegalizeTypes();
534 } else {
535 Changed = CurDAG->LegalizeTypes();
536 }
537
David Greene1a053232010-01-05 01:26:11 +0000538 DEBUG(dbgs() << "Type-legalized selection DAG:\n");
Dan Gohman714efc62009-12-05 17:51:33 +0000539 DEBUG(CurDAG->dump());
540
541 if (Changed) {
542 if (ViewDAGCombineLT)
543 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
544
545 // Run the DAG combiner in post-type-legalize mode.
Dan Gohman462dc7f2008-07-21 20:00:07 +0000546 if (TimePassesIsEnabled) {
Dan Gohman714efc62009-12-05 17:51:33 +0000547 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
548 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000549 } else {
Dan Gohman714efc62009-12-05 17:51:33 +0000550 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000551 }
552
David Greene1a053232010-01-05 01:26:11 +0000553 DEBUG(dbgs() << "Optimized type-legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000554 DEBUG(CurDAG->dump());
Dan Gohman714efc62009-12-05 17:51:33 +0000555 }
Dan Gohman462dc7f2008-07-21 20:00:07 +0000556
Dan Gohman714efc62009-12-05 17:51:33 +0000557 if (TimePassesIsEnabled) {
558 NamedRegionTimer T("Vector Legalization", GroupName);
559 Changed = CurDAG->LegalizeVectors();
560 } else {
561 Changed = CurDAG->LegalizeVectors();
562 }
Duncan Sands25cf2272008-11-24 14:53:14 +0000563
Dan Gohman714efc62009-12-05 17:51:33 +0000564 if (Changed) {
Eli Friedman5c22c802009-05-23 12:35:30 +0000565 if (TimePassesIsEnabled) {
Dan Gohman714efc62009-12-05 17:51:33 +0000566 NamedRegionTimer T("Type Legalization 2", GroupName);
Bill Wendling98820072009-12-28 01:51:30 +0000567 CurDAG->LegalizeTypes();
Eli Friedman5c22c802009-05-23 12:35:30 +0000568 } else {
Bill Wendling98820072009-12-28 01:51:30 +0000569 CurDAG->LegalizeTypes();
Eli Friedman5c22c802009-05-23 12:35:30 +0000570 }
571
Dan Gohman714efc62009-12-05 17:51:33 +0000572 if (ViewDAGCombineLT)
573 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
Eli Friedman5c22c802009-05-23 12:35:30 +0000574
Dan Gohman714efc62009-12-05 17:51:33 +0000575 // Run the DAG combiner in post-type-legalize mode.
576 if (TimePassesIsEnabled) {
577 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
578 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
579 } else {
580 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Eli Friedman5c22c802009-05-23 12:35:30 +0000581 }
Dan Gohman714efc62009-12-05 17:51:33 +0000582
David Greene1a053232010-01-05 01:26:11 +0000583 DEBUG(dbgs() << "Optimized vector-legalized selection DAG:\n");
Dan Gohman714efc62009-12-05 17:51:33 +0000584 DEBUG(CurDAG->dump());
Chris Lattner70587ea2008-07-10 23:37:50 +0000585 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000586
Dan Gohmanf350b272008-08-23 02:25:05 +0000587 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000588
Evan Chengebffb662008-07-01 17:59:20 +0000589 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000590 NamedRegionTimer T("DAG Legalization", GroupName);
Dan Gohman714efc62009-12-05 17:51:33 +0000591 CurDAG->Legalize(OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000592 } else {
Dan Gohman714efc62009-12-05 17:51:33 +0000593 CurDAG->Legalize(OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000594 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000595
David Greene1a053232010-01-05 01:26:11 +0000596 DEBUG(dbgs() << "Legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000597 DEBUG(CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000598
Dan Gohmanf350b272008-08-23 02:25:05 +0000599 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000600
Chris Lattneraf21d552005-10-10 16:47:10 +0000601 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000602 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000603 NamedRegionTimer T("DAG Combining 2", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000604 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000605 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000606 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000607 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
David Greene1a053232010-01-05 01:26:11 +0000609 DEBUG(dbgs() << "Optimized legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000610 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +0000611
Evan Chengd40d03e2010-01-06 19:38:29 +0000612 if (OptLevel != CodeGenOpt::None) {
613 ShrinkDemandedOps();
Dan Gohmanf350b272008-08-23 02:25:05 +0000614 ComputeLiveOutVRegInfo();
Evan Chengd40d03e2010-01-06 19:38:29 +0000615 }
Evan Cheng552c4a82006-04-28 02:09:19 +0000616
Chris Lattner552186d2010-03-14 19:27:55 +0000617 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
618
Chris Lattnera33ef482005-03-30 01:10:47 +0000619 // Third, instruction select all of the operations to machine code, adding the
620 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +0000621 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000622 NamedRegionTimer T("Instruction Selection", GroupName);
Chris Lattner7c306da2010-03-02 06:34:30 +0000623 DoInstructionSelection();
Evan Chengebffb662008-07-01 17:59:20 +0000624 } else {
Chris Lattner7c306da2010-03-02 06:34:30 +0000625 DoInstructionSelection();
Evan Chengebffb662008-07-01 17:59:20 +0000626 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000627
David Greene1a053232010-01-05 01:26:11 +0000628 DEBUG(dbgs() << "Selected selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000629 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000630
Dan Gohmanf350b272008-08-23 02:25:05 +0000631 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000632
Dan Gohman5e843682008-07-14 18:19:29 +0000633 // Schedule machine code.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000634 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
Dan Gohman5e843682008-07-14 18:19:29 +0000635 if (TimePassesIsEnabled) {
636 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000637 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000638 } else {
Dan Gohman47ac0f02009-02-11 04:27:20 +0000639 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000640 }
641
Dan Gohman462dc7f2008-07-21 20:00:07 +0000642 if (ViewSUnitDAGs) Scheduler->viewGraph();
643
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644 // Emit machine code to BB. This can change 'BB' to the last block being
Evan Chengdb8d56b2008-06-30 20:45:06 +0000645 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +0000646 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000647 NamedRegionTimer T("Instruction Creation", GroupName);
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000648 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +0000649 } else {
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000650 BB = Scheduler->EmitSchedule();
Dan Gohman5e843682008-07-14 18:19:29 +0000651 }
652
653 // Free the scheduler state.
654 if (TimePassesIsEnabled) {
655 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
656 delete Scheduler;
657 } else {
658 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +0000659 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000660
Dan Gohman95140a42010-05-01 00:25:44 +0000661 // Free the SelectionDAG state, now that we're finished with it.
662 CurDAG->clear();
663
Dan Gohmana9a33212010-04-20 00:29:35 +0000664 return BB;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000665}
Chris Lattner1c08c712005-01-07 07:47:53 +0000666
Chris Lattner7c306da2010-03-02 06:34:30 +0000667void SelectionDAGISel::DoInstructionSelection() {
668 DEBUG(errs() << "===== Instruction selection begins:\n");
669
670 PreprocessISelDAG();
671
672 // Select target instructions for the DAG.
673 {
674 // Number all nodes with a topological order and set DAGSize.
675 DAGSize = CurDAG->AssignTopologicalOrder();
676
677 // Create a dummy node (which is not added to allnodes), that adds
678 // a reference to the root node, preventing it from being deleted,
679 // and tracking any changes of the root.
680 HandleSDNode Dummy(CurDAG->getRoot());
681 ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
682 ++ISelPosition;
683
684 // The AllNodes list is now topological-sorted. Visit the
685 // nodes by starting at the end of the list (the root of the
686 // graph) and preceding back toward the beginning (the entry
687 // node).
688 while (ISelPosition != CurDAG->allnodes_begin()) {
689 SDNode *Node = --ISelPosition;
690 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
691 // but there are currently some corner cases that it misses. Also, this
692 // makes it theoretically possible to disable the DAGCombiner.
693 if (Node->use_empty())
694 continue;
695
696 SDNode *ResNode = Select(Node);
697
Chris Lattner82dd3d32010-03-02 07:50:03 +0000698 // FIXME: This is pretty gross. 'Select' should be changed to not return
699 // anything at all and this code should be nuked with a tactical strike.
700
Chris Lattner7c306da2010-03-02 06:34:30 +0000701 // If node should not be replaced, continue with the next one.
Chris Lattner82dd3d32010-03-02 07:50:03 +0000702 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
Chris Lattner7c306da2010-03-02 06:34:30 +0000703 continue;
704 // Replace node.
705 if (ResNode)
706 ReplaceUses(Node, ResNode);
707
708 // If after the replacement this node is not used any more,
709 // remove this dead node.
710 if (Node->use_empty()) { // Don't delete EntryToken, etc.
711 ISelUpdater ISU(ISelPosition);
712 CurDAG->RemoveDeadNode(Node, &ISU);
713 }
714 }
715
716 CurDAG->setRoot(Dummy.getValue());
717 }
Bill Wendling53f76022010-05-17 23:09:50 +0000718
Chris Lattner7c306da2010-03-02 06:34:30 +0000719 DEBUG(errs() << "===== Instruction selection ends:\n");
720
721 PostprocessISelDAG();
Chris Lattner7c306da2010-03-02 06:34:30 +0000722}
723
Dan Gohman25208642010-04-14 19:53:31 +0000724/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
725/// do other setup for EH landing-pad blocks.
726void SelectionDAGISel::PrepareEHLandingPad(MachineBasicBlock *BB) {
727 // Add a label to mark the beginning of the landing pad. Deletion of the
728 // landing pad can thus be detected via the MachineModuleInfo.
729 MCSymbol *Label = MF->getMMI().addLandingPad(BB);
730
Dan Gohman55e59c12010-04-19 19:05:59 +0000731 const TargetInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
Dan Gohman25208642010-04-14 19:53:31 +0000732 BuildMI(BB, SDB->getCurDebugLoc(), II).addSym(Label);
733
734 // Mark exception register as live in.
735 unsigned Reg = TLI.getExceptionAddressRegister();
736 if (Reg) BB->addLiveIn(Reg);
737
738 // Mark exception selector register as live in.
739 Reg = TLI.getExceptionSelectorRegister();
740 if (Reg) BB->addLiveIn(Reg);
741
742 // FIXME: Hack around an exception handling flaw (PR1508): the personality
743 // function and list of typeids logically belong to the invoke (or, if you
744 // like, the basic block containing the invoke), and need to be associated
745 // with it in the dwarf exception handling tables. Currently however the
746 // information is provided by an intrinsic (eh.selector) that can be moved
747 // to unexpected places by the optimizers: if the unwind edge is critical,
748 // then breaking it can result in the intrinsics being in the successor of
749 // the landing pad, not the landing pad itself. This results
750 // in exceptions not being caught because no typeids are associated with
751 // the invoke. This may not be the only way things can go wrong, but it
752 // is the only way we try to work around for the moment.
753 const BasicBlock *LLVMBB = BB->getBasicBlock();
754 const BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
755
756 if (Br && Br->isUnconditional()) { // Critical edge?
757 BasicBlock::const_iterator I, E;
758 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
759 if (isa<EHSelectorInst>(I))
760 break;
761
762 if (I == E)
763 // No catch info found - try to extract some from the successor.
764 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF->getMMI(), *FuncInfo);
765 }
766}
Chris Lattner7c306da2010-03-02 06:34:30 +0000767
Dan Gohman46510a72010-04-15 01:51:59 +0000768void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000769 // Initialize the Fast-ISel state, if needed.
770 FastISel *FastIS = 0;
771 if (EnableFastISel)
Dan Gohman6a732b52010-04-14 20:05:00 +0000772 FastIS = TLI.createFastISel(*MF, FuncInfo->ValueMap, FuncInfo->MBBMap,
Dan Gohmanf81eca02010-04-22 20:46:50 +0000773 FuncInfo->StaticAllocaMap,
774 FuncInfo->PHINodesToUpdate
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000775#ifndef NDEBUG
776 , FuncInfo->CatchInfoLost
777#endif
778 );
Dan Gohmana43abd12008-09-29 21:55:50 +0000779
780 // Iterate over all basic blocks in the function.
Dan Gohman46510a72010-04-15 01:51:59 +0000781 for (Function::const_iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
782 const BasicBlock *LLVMBB = &*I;
Dan Gohmana9a33212010-04-20 00:29:35 +0000783 MachineBasicBlock *BB = FuncInfo->MBBMap[LLVMBB];
Dan Gohmanf350b272008-08-23 02:25:05 +0000784
Dan Gohmanba5be5c2010-04-20 15:00:41 +0000785 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
Dan Gohman46510a72010-04-15 01:51:59 +0000786 BasicBlock::const_iterator const End = LLVMBB->end();
787 BasicBlock::const_iterator BI = Begin;
Dan Gohman5edd3612008-08-28 20:28:56 +0000788
789 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmand725f042010-05-01 02:44:23 +0000790 if (LLVMBB == &Fn.getEntryBlock())
Dan Gohman5edd3612008-08-28 20:28:56 +0000791 LowerArguments(LLVMBB);
Dan Gohmanf350b272008-08-23 02:25:05 +0000792
Dan Gohman25208642010-04-14 19:53:31 +0000793 // Setup an EH landing-pad block.
794 if (BB->isLandingPad())
795 PrepareEHLandingPad(BB);
796
Dan Gohmanf350b272008-08-23 02:25:05 +0000797 // Before doing SelectionDAG ISel, see if FastISel has been requested.
Dan Gohmand725f042010-05-01 02:44:23 +0000798 if (FastIS) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000799 // Emit code for any incoming arguments. This must happen before
800 // beginning FastISel on the entry block.
801 if (LLVMBB == &Fn.getEntryBlock()) {
Dan Gohman2048b852009-11-23 18:04:58 +0000802 CurDAG->setRoot(SDB->getControlRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000803 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000804 BB = CodeGenAndEmitDAG(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000805 }
Dan Gohman241f4642008-10-04 00:56:36 +0000806 FastIS->startNewBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000807 // Do FastISel on as many instructions as possible.
808 for (; BI != End; ++BI) {
Dan Gohman21c14e32010-01-12 04:32:35 +0000809 // Try to select the instruction with FastISel.
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000810 if (FastIS->SelectInstruction(BI))
Dan Gohmana43abd12008-09-29 21:55:50 +0000811 continue;
Dan Gohmana43abd12008-09-29 21:55:50 +0000812
813 // Then handle certain instructions as single-LLVM-Instruction blocks.
814 if (isa<CallInst>(BI)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000815 ++NumFastIselFailures;
Dan Gohmana43abd12008-09-29 21:55:50 +0000816 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000817 dbgs() << "FastISel missed call: ";
Dan Gohmana43abd12008-09-29 21:55:50 +0000818 BI->dump();
819 }
820
Dan Gohman33b7a292010-04-16 17:15:02 +0000821 if (!BI->getType()->isVoidTy() && !BI->use_empty()) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000822 unsigned &R = FuncInfo->ValueMap[BI];
823 if (!R)
824 R = FuncInfo->CreateRegForValue(BI);
825 }
826
Dan Gohmanb4afb132009-11-20 02:51:26 +0000827 bool HadTailCall = false;
Dan Gohmana9a33212010-04-20 00:29:35 +0000828 BB = SelectBasicBlock(BB, LLVMBB, BI, llvm::next(BI), HadTailCall);
Dan Gohmanb4afb132009-11-20 02:51:26 +0000829
830 // If the call was emitted as a tail call, we're done with the block.
831 if (HadTailCall) {
832 BI = End;
833 break;
834 }
835
Dan Gohman241f4642008-10-04 00:56:36 +0000836 // If the instruction was codegen'd with multiple blocks,
837 // inform the FastISel object where to resume inserting.
838 FastIS->setCurrentBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000839 continue;
Dan Gohmanf350b272008-08-23 02:25:05 +0000840 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000841
842 // Otherwise, give up on FastISel for the rest of the block.
843 // For now, be a little lenient about non-branch terminators.
844 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
Chris Lattnerc19ae9d2010-03-04 19:46:56 +0000845 ++NumFastIselFailures;
Dan Gohmana43abd12008-09-29 21:55:50 +0000846 if (EnableFastISelVerbose || EnableFastISelAbort) {
David Greene1a053232010-01-05 01:26:11 +0000847 dbgs() << "FastISel miss: ";
Dan Gohmana43abd12008-09-29 21:55:50 +0000848 BI->dump();
849 }
850 if (EnableFastISelAbort)
851 // The "fast" selector couldn't handle something and bailed.
852 // For the purpose of debugging, just abort.
Torok Edwinc23197a2009-07-14 16:55:14 +0000853 llvm_unreachable("FastISel didn't select the entire block");
Dan Gohmana43abd12008-09-29 21:55:50 +0000854 }
855 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000856 }
857 }
858
Dan Gohmand2ff6472008-09-02 20:17:56 +0000859 // Run SelectionDAG instruction selection on the remainder of the block
860 // not handled by FastISel. If FastISel is not run, this is the entire
Dan Gohman3df24e62008-09-03 23:12:08 +0000861 // block.
Devang Patel390f3ac2009-04-16 01:33:10 +0000862 if (BI != End) {
Dan Gohmanb4afb132009-11-20 02:51:26 +0000863 bool HadTailCall;
Dan Gohmana9a33212010-04-20 00:29:35 +0000864 BB = SelectBasicBlock(BB, LLVMBB, BI, End, HadTailCall);
Devang Patel390f3ac2009-04-16 01:33:10 +0000865 }
Dan Gohmanf350b272008-08-23 02:25:05 +0000866
Dan Gohmana9a33212010-04-20 00:29:35 +0000867 FinishBasicBlock(BB);
Dan Gohman620427d2010-04-22 19:55:20 +0000868 FuncInfo->PHINodesToUpdate.clear();
Evan Cheng39fd6e82008-08-07 00:43:25 +0000869 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000870
871 delete FastIS;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000872}
873
Dan Gohmanfed90b62008-07-28 21:51:04 +0000874void
Dan Gohmana9a33212010-04-20 00:29:35 +0000875SelectionDAGISel::FinishBasicBlock(MachineBasicBlock *BB) {
Dan Gohmanf350b272008-08-23 02:25:05 +0000876
David Greene1a053232010-01-05 01:26:11 +0000877 DEBUG(dbgs() << "Total amount of phi nodes to update: "
Dan Gohman620427d2010-04-22 19:55:20 +0000878 << FuncInfo->PHINodesToUpdate.size() << "\n");
879 DEBUG(for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
David Greene1a053232010-01-05 01:26:11 +0000880 dbgs() << "Node " << i << " : ("
Dan Gohman620427d2010-04-22 19:55:20 +0000881 << FuncInfo->PHINodesToUpdate[i].first
882 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000883
Chris Lattnera33ef482005-03-30 01:10:47 +0000884 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +0000885 // PHI nodes in successors.
Dan Gohman2048b852009-11-23 18:04:58 +0000886 if (SDB->SwitchCases.empty() &&
887 SDB->JTCases.empty() &&
888 SDB->BitTestCases.empty()) {
Dan Gohman620427d2010-04-22 19:55:20 +0000889 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
890 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
Chris Lattner518bb532010-02-09 19:54:29 +0000891 assert(PHI->isPHI() &&
Nate Begemanf15485a2006-03-27 01:32:24 +0000892 "This is not a machine PHI node that we are updating!");
Jakob Stoklund Olesen580bba22010-03-05 21:49:10 +0000893 if (!BB->isSuccessor(PHI->getParent()))
894 continue;
Dan Gohman620427d2010-04-22 19:55:20 +0000895 PHI->addOperand(
896 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000897 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +0000898 }
899 return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000900 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000901
Dan Gohman2048b852009-11-23 18:04:58 +0000902 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000903 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +0000904 if (!SDB->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000905 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000906 BB = SDB->BitTestCases[i].Parent;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000907 // Emit the code
Dan Gohman99be8ae2010-04-19 22:41:47 +0000908 SDB->visitBitTestHeader(SDB->BitTestCases[i], BB);
Dan Gohman2048b852009-11-23 18:04:58 +0000909 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000910 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000911 BB = CodeGenAndEmitDAG(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000912 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000913
Dan Gohman2048b852009-11-23 18:04:58 +0000914 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000915 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000916 BB = SDB->BitTestCases[i].Cases[j].ThisBB;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000917 // Emit the code
918 if (j+1 != ej)
Dan Gohman2048b852009-11-23 18:04:58 +0000919 SDB->visitBitTestCase(SDB->BitTestCases[i].Cases[j+1].ThisBB,
920 SDB->BitTestCases[i].Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +0000921 SDB->BitTestCases[i].Cases[j],
922 BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000923 else
Dan Gohman2048b852009-11-23 18:04:58 +0000924 SDB->visitBitTestCase(SDB->BitTestCases[i].Default,
925 SDB->BitTestCases[i].Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +0000926 SDB->BitTestCases[i].Cases[j],
927 BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000928
929
Dan Gohman2048b852009-11-23 18:04:58 +0000930 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000931 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000932 BB = CodeGenAndEmitDAG(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000933 }
934
935 // Update PHI Nodes
Dan Gohman620427d2010-04-22 19:55:20 +0000936 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
937 pi != pe; ++pi) {
938 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000939 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000940 assert(PHI->isPHI() &&
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000941 "This is not a machine PHI node that we are updating!");
942 // This is "default" BB. We have two jumps to it. From "header" BB and
943 // from last "case" BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000944 if (PHIBB == SDB->BitTestCases[i].Default) {
Jim Grosbachf4549b02010-01-15 00:36:15 +0000945 PHI->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +0000946 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
947 false));
Dan Gohman2048b852009-11-23 18:04:58 +0000948 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
Jim Grosbachf4549b02010-01-15 00:36:15 +0000949 PHI->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +0000950 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
951 false));
Dan Gohman2048b852009-11-23 18:04:58 +0000952 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000953 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000954 }
955 // One of "cases" BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000956 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
Dan Gohman7c3234c2008-08-27 23:52:12 +0000957 j != ej; ++j) {
Dan Gohman2048b852009-11-23 18:04:58 +0000958 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +0000959 if (cBB->isSuccessor(PHIBB)) {
Jim Grosbachf4549b02010-01-15 00:36:15 +0000960 PHI->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +0000961 CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
962 false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000963 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000964 }
965 }
966 }
967 }
Dan Gohman2048b852009-11-23 18:04:58 +0000968 SDB->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000969
Nate Begeman9453eea2006-04-23 06:26:20 +0000970 // If the JumpTable record is filled in, then we need to emit a jump table.
971 // Updating the PHI nodes is tricky in this case, since we need to determine
972 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman2048b852009-11-23 18:04:58 +0000973 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000974 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +0000975 if (!SDB->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000976 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000977 BB = SDB->JTCases[i].first.HeaderBB;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000978 // Emit the code
Dan Gohman99be8ae2010-04-19 22:41:47 +0000979 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
980 BB);
Dan Gohman2048b852009-11-23 18:04:58 +0000981 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000982 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000983 BB = CodeGenAndEmitDAG(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000984 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000985
Nate Begeman37efe672006-04-22 18:53:45 +0000986 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000987 BB = SDB->JTCases[i].second.MBB;
Nate Begeman37efe672006-04-22 18:53:45 +0000988 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +0000989 SDB->visitJumpTable(SDB->JTCases[i].second);
990 CurDAG->setRoot(SDB->getRoot());
Dan Gohman2048b852009-11-23 18:04:58 +0000991 SDB->clear();
Dan Gohman95140a42010-05-01 00:25:44 +0000992 BB = CodeGenAndEmitDAG(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000993
Nate Begeman37efe672006-04-22 18:53:45 +0000994 // Update PHI Nodes
Dan Gohman620427d2010-04-22 19:55:20 +0000995 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
996 pi != pe; ++pi) {
997 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +0000998 MachineBasicBlock *PHIBB = PHI->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000999 assert(PHI->isPHI() &&
Nate Begeman37efe672006-04-22 18:53:45 +00001000 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001001 // "default" BB. We can go there only from header BB.
Dan Gohman2048b852009-11-23 18:04:58 +00001002 if (PHIBB == SDB->JTCases[i].second.Default) {
Evan Chengce319102009-09-19 09:51:03 +00001003 PHI->addOperand
Dan Gohman620427d2010-04-22 19:55:20 +00001004 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1005 false));
Evan Chengce319102009-09-19 09:51:03 +00001006 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +00001007 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00001008 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001009 // JT BB. Just iterate over successors here
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001010 if (BB->isSuccessor(PHIBB)) {
Evan Chengce319102009-09-19 09:51:03 +00001011 PHI->addOperand
Dan Gohman620427d2010-04-22 19:55:20 +00001012 (MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[pi].second,
1013 false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001014 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00001015 }
1016 }
Nate Begeman37efe672006-04-22 18:53:45 +00001017 }
Dan Gohman2048b852009-11-23 18:04:58 +00001018 SDB->JTCases.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001019
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001020 // If the switch block involved a branch to one of the actual successors, we
1021 // need to update PHI nodes in that block.
Dan Gohman620427d2010-04-22 19:55:20 +00001022 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1023 MachineInstr *PHI = FuncInfo->PHINodesToUpdate[i].first;
Chris Lattner518bb532010-02-09 19:54:29 +00001024 assert(PHI->isPHI() &&
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001025 "This is not a machine PHI node that we are updating!");
1026 if (BB->isSuccessor(PHI->getParent())) {
Dan Gohman620427d2010-04-22 19:55:20 +00001027 PHI->addOperand(
1028 MachineOperand::CreateReg(FuncInfo->PHINodesToUpdate[i].second, false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001029 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001030 }
1031 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001032
Nate Begemanf15485a2006-03-27 01:32:24 +00001033 // If we generated any switch lowering information, build and codegen any
1034 // additional DAGs necessary.
Dan Gohman2048b852009-11-23 18:04:58 +00001035 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001036 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +00001037 MachineBasicBlock *ThisBB = BB = SDB->SwitchCases[i].ThisBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001038
Dan Gohman95140a42010-05-01 00:25:44 +00001039 // Determine the unique successors.
1040 SmallVector<MachineBasicBlock *, 2> Succs;
1041 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1042 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1043 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1044
1045 // Emit the code. Note that this could result in ThisBB being split, so
1046 // we need to check for updates.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001047 SDB->visitSwitchCase(SDB->SwitchCases[i], BB);
Dan Gohman2048b852009-11-23 18:04:58 +00001048 CurDAG->setRoot(SDB->getRoot());
Dan Gohman95140a42010-05-01 00:25:44 +00001049 SDB->clear();
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +00001050 ThisBB = CodeGenAndEmitDAG(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001051
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001052 // Handle any PHI nodes in successors of this chunk, as if we were coming
1053 // from the original BB before switch expansion. Note that PHI nodes can
1054 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1055 // handle them the right number of times.
Dan Gohman95140a42010-05-01 00:25:44 +00001056 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1057 BB = Succs[i];
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001058 // BB may have been removed from the CFG if a branch was constant folded.
1059 if (ThisBB->isSuccessor(BB)) {
1060 for (MachineBasicBlock::iterator Phi = BB->begin();
Chris Lattner518bb532010-02-09 19:54:29 +00001061 Phi != BB->end() && Phi->isPHI();
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001062 ++Phi) {
1063 // This value for this PHI node is recorded in PHINodesToUpdate.
1064 for (unsigned pn = 0; ; ++pn) {
Dan Gohman620427d2010-04-22 19:55:20 +00001065 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001066 "Didn't find PHI entry!");
Dan Gohman620427d2010-04-22 19:55:20 +00001067 if (FuncInfo->PHINodesToUpdate[pn].first == Phi) {
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001068 Phi->addOperand(MachineOperand::
Dan Gohman620427d2010-04-22 19:55:20 +00001069 CreateReg(FuncInfo->PHINodesToUpdate[pn].second,
Jakob Stoklund Olesendd437ba2010-01-11 21:02:33 +00001070 false));
1071 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1072 break;
1073 }
Evan Cheng8be58a12009-09-18 08:26:06 +00001074 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001075 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001076 }
1077 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001078 }
Dan Gohman2048b852009-11-23 18:04:58 +00001079 SDB->SwitchCases.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00001080}
Evan Chenga9c20912006-01-21 02:32:06 +00001081
Jim Laskey13ec7022006-08-01 14:21:23 +00001082
Dan Gohman0a3776d2009-02-06 18:26:51 +00001083/// Create the scheduler. If a specific scheduler was specified
1084/// via the SchedulerRegistry, use it, otherwise select the
1085/// one preferred by the target.
Dan Gohman5e843682008-07-14 18:19:29 +00001086///
Dan Gohman47ac0f02009-02-11 04:27:20 +00001087ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001088 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001089
Jim Laskey13ec7022006-08-01 14:21:23 +00001090 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001091 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00001092 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00001093 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001094
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001095 return Ctor(this, OptLevel);
Evan Chenga9c20912006-01-21 02:32:06 +00001096}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001097
Dan Gohmanfc54c552009-01-15 22:18:12 +00001098ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1099 return new ScheduleHazardRecognizer();
Jim Laskey9ff542f2006-08-01 18:29:48 +00001100}
1101
Chris Lattner75548062006-10-11 03:58:02 +00001102//===----------------------------------------------------------------------===//
1103// Helper functions used by the generated instruction selector.
1104//===----------------------------------------------------------------------===//
1105// Calls to these methods are generated by tblgen.
1106
1107/// CheckAndMask - The isel is trying to match something like (and X, 255). If
1108/// the dag combiner simplified the 255, we still want to match. RHS is the
1109/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1110/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001111bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00001112 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001113 const APInt &ActualMask = RHS->getAPIntValue();
1114 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattner75548062006-10-11 03:58:02 +00001116 // If the actual mask exactly matches, success!
1117 if (ActualMask == DesiredMask)
1118 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001119
Chris Lattner75548062006-10-11 03:58:02 +00001120 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001121 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001122 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001123
Chris Lattner75548062006-10-11 03:58:02 +00001124 // Otherwise, the DAG Combiner may have proven that the value coming in is
1125 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001126 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00001127 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00001128 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001129
Chris Lattner75548062006-10-11 03:58:02 +00001130 // TODO: check to see if missing bits are just not demanded.
1131
1132 // Otherwise, this pattern doesn't match.
1133 return false;
1134}
1135
1136/// CheckOrMask - The isel is trying to match something like (or X, 255). If
1137/// the dag combiner simplified the 255, we still want to match. RHS is the
1138/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1139/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001141 int64_t DesiredMaskS) const {
1142 const APInt &ActualMask = RHS->getAPIntValue();
1143 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001144
Chris Lattner75548062006-10-11 03:58:02 +00001145 // If the actual mask exactly matches, success!
1146 if (ActualMask == DesiredMask)
1147 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001148
Chris Lattner75548062006-10-11 03:58:02 +00001149 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001150 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001151 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152
Chris Lattner75548062006-10-11 03:58:02 +00001153 // Otherwise, the DAG Combiner may have proven that the value coming in is
1154 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001155 APInt NeededMask = DesiredMask & ~ActualMask;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001156
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001157 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00001158 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001159
Chris Lattner75548062006-10-11 03:58:02 +00001160 // If all the missing bits in the or are already known to be set, match!
1161 if ((NeededMask & KnownOne) == NeededMask)
1162 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001163
Chris Lattner75548062006-10-11 03:58:02 +00001164 // TODO: check to see if missing bits are just not demanded.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001165
Chris Lattner75548062006-10-11 03:58:02 +00001166 // Otherwise, this pattern doesn't match.
1167 return false;
1168}
1169
Jim Laskey9ff542f2006-08-01 18:29:48 +00001170
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001171/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1172/// by tblgen. Others should not call it.
1173void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00001174SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00001175 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001176 std::swap(InOps, Ops);
1177
Chris Lattnerdecc2672010-04-07 05:20:54 +00001178 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1179 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1180 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001181
Chris Lattnerdecc2672010-04-07 05:20:54 +00001182 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
Owen Anderson825b72b2009-08-11 20:47:22 +00001183 if (InOps[e-1].getValueType() == MVT::Flag)
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001184 --e; // Don't process a flag operand if it is here.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001185
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001186 while (i != e) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00001187 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00001188 if (!InlineAsm::isMemKind(Flags)) {
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001189 // Just skip over this operand, copying the operands verbatim.
Evan Cheng697cbbf2009-03-20 18:03:34 +00001190 Ops.insert(Ops.end(), InOps.begin()+i,
1191 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1192 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001193 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00001194 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1195 "Memory operand with multiple values?");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001196 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00001197 std::vector<SDValue> SelOps;
Chris Lattnerdecc2672010-04-07 05:20:54 +00001198 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
Chris Lattner75361b62010-04-07 22:58:41 +00001199 report_fatal_error("Could not match memory address. Inline asm"
Chris Lattner87d677c2010-04-07 23:50:38 +00001200 " failure!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001201
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001202 // Add this to the output node.
Chris Lattnerdecc2672010-04-07 05:20:54 +00001203 unsigned NewFlags =
1204 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1205 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001206 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1207 i += 2;
1208 }
1209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001210
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001211 // Add the flag input back if present.
1212 if (e != InOps.size())
1213 Ops.push_back(InOps.back());
1214}
Devang Patel794fd752007-05-01 21:15:47 +00001215
Owen Andersone50ed302009-08-10 22:56:29 +00001216/// findFlagUse - Return use of EVT::Flag value produced by the specified
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001217/// SDNode.
1218///
1219static SDNode *findFlagUse(SDNode *N) {
1220 unsigned FlagResNo = N->getNumValues()-1;
1221 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1222 SDUse &Use = I.getUse();
1223 if (Use.getResNo() == FlagResNo)
1224 return Use.getUser();
1225 }
1226 return NULL;
1227}
1228
1229/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1230/// This function recursively traverses up the operand chain, ignoring
1231/// certain nodes.
1232static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
Chris Lattnerd1b73822010-03-02 22:20:06 +00001233 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1234 bool IgnoreChains) {
Chris Lattnerda244a02010-02-23 19:32:27 +00001235 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1236 // greater than all of its (recursive) operands. If we scan to a point where
1237 // 'use' is smaller than the node we're scanning for, then we know we will
1238 // never find it.
1239 //
1240 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1241 // happen because we scan down to newly selected nodes in the case of flag
1242 // uses.
1243 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1244 return false;
1245
1246 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1247 // won't fail if we scan it again.
1248 if (!Visited.insert(Use))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001249 return false;
1250
1251 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001252 // Ignore chain uses, they are validated by HandleMergeInputChains.
1253 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1254 continue;
1255
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001256 SDNode *N = Use->getOperand(i).getNode();
1257 if (N == Def) {
1258 if (Use == ImmedUse || Use == Root)
1259 continue; // We are not looking for immediate use.
1260 assert(N != Root);
1261 return true;
1262 }
1263
1264 // Traverse up the operand chain.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001265 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001266 return true;
1267 }
1268 return false;
1269}
1270
Evan Cheng014bf212010-02-15 19:41:07 +00001271/// IsProfitableToFold - Returns true if it's profitable to fold the specific
1272/// operand node N of U during instruction selection that starts at Root.
1273bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1274 SDNode *Root) const {
1275 if (OptLevel == CodeGenOpt::None) return false;
1276 return N.hasOneUse();
1277}
1278
1279/// IsLegalToFold - Returns true if the specific operand node N of
1280/// U can be folded during instruction selection that starts at Root.
Chris Lattnerd1b73822010-03-02 22:20:06 +00001281bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
Dan Gohmand858e902010-04-17 15:26:15 +00001282 CodeGenOpt::Level OptLevel,
1283 bool IgnoreChains) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001284 if (OptLevel == CodeGenOpt::None) return false;
1285
1286 // If Root use can somehow reach N through a path that that doesn't contain
1287 // U then folding N would create a cycle. e.g. In the following
1288 // diagram, Root can reach N through X. If N is folded into into Root, then
1289 // X is both a predecessor and a successor of U.
1290 //
1291 // [N*] //
1292 // ^ ^ //
1293 // / \ //
1294 // [U*] [X]? //
1295 // ^ ^ //
1296 // \ / //
1297 // \ / //
1298 // [Root*] //
1299 //
1300 // * indicates nodes to be folded together.
1301 //
1302 // If Root produces a flag, then it gets (even more) interesting. Since it
1303 // will be "glued" together with its flag use in the scheduler, we need to
1304 // check if it might reach N.
1305 //
1306 // [N*] //
1307 // ^ ^ //
1308 // / \ //
1309 // [U*] [X]? //
1310 // ^ ^ //
1311 // \ \ //
1312 // \ | //
1313 // [Root*] | //
1314 // ^ | //
1315 // f | //
1316 // | / //
1317 // [Y] / //
1318 // ^ / //
1319 // f / //
1320 // | / //
1321 // [FU] //
1322 //
1323 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1324 // (call it Fold), then X is a predecessor of FU and a successor of
1325 // Fold. But since Fold and FU are flagged together, this will create
1326 // a cycle in the scheduling graph.
1327
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001328 // If the node has flags, walk down the graph to the "lowest" node in the
1329 // flagged set.
Owen Andersone50ed302009-08-10 22:56:29 +00001330 EVT VT = Root->getValueType(Root->getNumValues()-1);
Owen Anderson825b72b2009-08-11 20:47:22 +00001331 while (VT == MVT::Flag) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001332 SDNode *FU = findFlagUse(Root);
1333 if (FU == NULL)
1334 break;
1335 Root = FU;
1336 VT = Root->getValueType(Root->getNumValues()-1);
Chris Lattner18fdaba2010-03-05 06:19:13 +00001337
1338 // If our query node has a flag result with a use, we've walked up it. If
1339 // the user (which has already been selected) has a chain or indirectly uses
1340 // the chain, our WalkChainUsers predicate will not consider it. Because of
1341 // this, we cannot ignore chains in this predicate.
1342 IgnoreChains = false;
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001343 }
Chris Lattner18fdaba2010-03-05 06:19:13 +00001344
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001345
Chris Lattner9bbcd5e2010-03-05 05:49:45 +00001346 SmallPtrSet<SDNode*, 16> Visited;
1347 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001348}
1349
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001350SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1351 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
Dan Gohmane1f188f2009-10-29 22:30:23 +00001352 SelectInlineAsmMemoryOperands(Ops);
1353
1354 std::vector<EVT> VTs;
1355 VTs.push_back(MVT::Other);
1356 VTs.push_back(MVT::Flag);
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001357 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
Dan Gohmane1f188f2009-10-29 22:30:23 +00001358 VTs, &Ops[0], Ops.size());
Chris Lattnerd1b73822010-03-02 22:20:06 +00001359 New->setNodeId(-1);
Dan Gohmane1f188f2009-10-29 22:30:23 +00001360 return New.getNode();
1361}
1362
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001363SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
Chris Lattner518bb532010-02-09 19:54:29 +00001364 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
Dan Gohmane1f188f2009-10-29 22:30:23 +00001365}
1366
Chris Lattner2a49d572010-02-28 22:37:22 +00001367/// GetVBR - decode a vbr encoding whose top bit is set.
1368ALWAYS_INLINE static uint64_t
1369GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1370 assert(Val >= 128 && "Not a VBR");
1371 Val &= 127; // Remove first vbr bit.
1372
1373 unsigned Shift = 7;
1374 uint64_t NextBits;
1375 do {
Chris Lattner14df8dc2010-02-28 22:38:43 +00001376 NextBits = MatcherTable[Idx++];
Chris Lattner2a49d572010-02-28 22:37:22 +00001377 Val |= (NextBits&127) << Shift;
1378 Shift += 7;
1379 } while (NextBits & 128);
1380
1381 return Val;
1382}
1383
Chris Lattner2a49d572010-02-28 22:37:22 +00001384
1385/// UpdateChainsAndFlags - When a match is complete, this method updates uses of
1386/// interior flag and chain results to use the new flag and chain results.
Chris Lattner82dd3d32010-03-02 07:50:03 +00001387void SelectionDAGISel::
1388UpdateChainsAndFlags(SDNode *NodeToMatch, SDValue InputChain,
1389 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1390 SDValue InputFlag,
1391 const SmallVectorImpl<SDNode*> &FlagResultNodesMatched,
1392 bool isMorphNodeTo) {
1393 SmallVector<SDNode*, 4> NowDeadNodes;
1394
1395 ISelUpdater ISU(ISelPosition);
1396
Chris Lattner2a49d572010-02-28 22:37:22 +00001397 // Now that all the normal results are replaced, we replace the chain and
1398 // flag results if present.
1399 if (!ChainNodesMatched.empty()) {
1400 assert(InputChain.getNode() != 0 &&
1401 "Matched input chains but didn't produce a chain");
1402 // Loop over all of the nodes we matched that produced a chain result.
1403 // Replace all the chain results with the final chain we ended up with.
1404 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1405 SDNode *ChainNode = ChainNodesMatched[i];
1406
Chris Lattner82dd3d32010-03-02 07:50:03 +00001407 // If this node was already deleted, don't look at it.
1408 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1409 continue;
1410
Chris Lattner2a49d572010-02-28 22:37:22 +00001411 // Don't replace the results of the root node if we're doing a
1412 // MorphNodeTo.
1413 if (ChainNode == NodeToMatch && isMorphNodeTo)
1414 continue;
1415
1416 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1417 if (ChainVal.getValueType() == MVT::Flag)
1418 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1419 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
Chris Lattner82dd3d32010-03-02 07:50:03 +00001420 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain, &ISU);
1421
Chris Lattner856fb392010-03-28 05:28:31 +00001422 // If the node became dead and we haven't already seen it, delete it.
1423 if (ChainNode->use_empty() &&
1424 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001425 NowDeadNodes.push_back(ChainNode);
Chris Lattner2a49d572010-02-28 22:37:22 +00001426 }
1427 }
1428
1429 // If the result produces a flag, update any flag results in the matched
1430 // pattern with the flag result.
1431 if (InputFlag.getNode() != 0) {
1432 // Handle any interior nodes explicitly marked.
1433 for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
1434 SDNode *FRN = FlagResultNodesMatched[i];
Chris Lattner82dd3d32010-03-02 07:50:03 +00001435
1436 // If this node was already deleted, don't look at it.
1437 if (FRN->getOpcode() == ISD::DELETED_NODE)
1438 continue;
1439
Chris Lattner2a49d572010-02-28 22:37:22 +00001440 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
1441 "Doesn't have a flag result");
1442 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
Chris Lattner82dd3d32010-03-02 07:50:03 +00001443 InputFlag, &ISU);
1444
Chris Lattner19e37cb2010-03-28 04:54:33 +00001445 // If the node became dead and we haven't already seen it, delete it.
1446 if (FRN->use_empty() &&
1447 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
Chris Lattner82dd3d32010-03-02 07:50:03 +00001448 NowDeadNodes.push_back(FRN);
Chris Lattner2a49d572010-02-28 22:37:22 +00001449 }
1450 }
1451
Chris Lattner82dd3d32010-03-02 07:50:03 +00001452 if (!NowDeadNodes.empty())
1453 CurDAG->RemoveDeadNodes(NowDeadNodes, &ISU);
1454
Chris Lattner2a49d572010-02-28 22:37:22 +00001455 DEBUG(errs() << "ISEL: Match complete!\n");
1456}
1457
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001458enum ChainResult {
1459 CR_Simple,
1460 CR_InducesCycle,
1461 CR_LeadsToInteriorNode
1462};
1463
1464/// WalkChainUsers - Walk down the users of the specified chained node that is
1465/// part of the pattern we're matching, looking at all of the users we find.
1466/// This determines whether something is an interior node, whether we have a
1467/// non-pattern node in between two pattern nodes (which prevent folding because
1468/// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1469/// between pattern nodes (in which case the TF becomes part of the pattern).
1470///
1471/// The walk we do here is guaranteed to be small because we quickly get down to
1472/// already selected nodes "below" us.
1473static ChainResult
1474WalkChainUsers(SDNode *ChainedNode,
1475 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1476 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1477 ChainResult Result = CR_Simple;
1478
1479 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1480 E = ChainedNode->use_end(); UI != E; ++UI) {
1481 // Make sure the use is of the chain, not some other value we produce.
1482 if (UI.getUse().getValueType() != MVT::Other) continue;
1483
1484 SDNode *User = *UI;
1485
1486 // If we see an already-selected machine node, then we've gone beyond the
1487 // pattern that we're selecting down into the already selected chunk of the
1488 // DAG.
1489 if (User->isMachineOpcode() ||
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001490 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1491 continue;
Chris Lattnerd1b73822010-03-02 22:20:06 +00001492
1493 if (User->getOpcode() == ISD::CopyToReg ||
1494 User->getOpcode() == ISD::CopyFromReg ||
Chris Lattner7561d482010-03-14 02:33:54 +00001495 User->getOpcode() == ISD::INLINEASM ||
1496 User->getOpcode() == ISD::EH_LABEL) {
Chris Lattnerd1b73822010-03-02 22:20:06 +00001497 // If their node ID got reset to -1 then they've already been selected.
1498 // Treat them like a MachineOpcode.
1499 if (User->getNodeId() == -1)
1500 continue;
1501 }
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001502
1503 // If we have a TokenFactor, we handle it specially.
1504 if (User->getOpcode() != ISD::TokenFactor) {
1505 // If the node isn't a token factor and isn't part of our pattern, then it
1506 // must be a random chained node in between two nodes we're selecting.
1507 // This happens when we have something like:
1508 // x = load ptr
1509 // call
1510 // y = x+4
1511 // store y -> ptr
1512 // Because we structurally match the load/store as a read/modify/write,
1513 // but the call is chained between them. We cannot fold in this case
1514 // because it would induce a cycle in the graph.
1515 if (!std::count(ChainedNodesInPattern.begin(),
1516 ChainedNodesInPattern.end(), User))
1517 return CR_InducesCycle;
1518
1519 // Otherwise we found a node that is part of our pattern. For example in:
1520 // x = load ptr
1521 // y = x+4
1522 // store y -> ptr
1523 // This would happen when we're scanning down from the load and see the
1524 // store as a user. Record that there is a use of ChainedNode that is
1525 // part of the pattern and keep scanning uses.
1526 Result = CR_LeadsToInteriorNode;
1527 InteriorChainedNodes.push_back(User);
1528 continue;
1529 }
1530
1531 // If we found a TokenFactor, there are two cases to consider: first if the
1532 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1533 // uses of the TF are in our pattern) we just want to ignore it. Second,
1534 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1535 // [Load chain]
1536 // ^
1537 // |
1538 // [Load]
1539 // ^ ^
1540 // | \ DAG's like cheese
1541 // / \ do you?
1542 // / |
1543 // [TokenFactor] [Op]
1544 // ^ ^
1545 // | |
1546 // \ /
1547 // \ /
1548 // [Store]
1549 //
1550 // In this case, the TokenFactor becomes part of our match and we rewrite it
1551 // as a new TokenFactor.
1552 //
1553 // To distinguish these two cases, do a recursive walk down the uses.
1554 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1555 case CR_Simple:
1556 // If the uses of the TokenFactor are just already-selected nodes, ignore
1557 // it, it is "below" our pattern.
1558 continue;
1559 case CR_InducesCycle:
1560 // If the uses of the TokenFactor lead to nodes that are not part of our
1561 // pattern that are not selected, folding would turn this into a cycle,
1562 // bail out now.
1563 return CR_InducesCycle;
1564 case CR_LeadsToInteriorNode:
1565 break; // Otherwise, keep processing.
1566 }
1567
1568 // Okay, we know we're in the interesting interior case. The TokenFactor
1569 // is now going to be considered part of the pattern so that we rewrite its
1570 // uses (it may have uses that are not part of the pattern) with the
1571 // ultimate chain result of the generated code. We will also add its chain
1572 // inputs as inputs to the ultimate TokenFactor we create.
1573 Result = CR_LeadsToInteriorNode;
1574 ChainedNodesInPattern.push_back(User);
1575 InteriorChainedNodes.push_back(User);
1576 continue;
1577 }
1578
1579 return Result;
1580}
1581
Chris Lattner6b307922010-03-02 00:00:03 +00001582/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
Chris Lattner00592ec2010-03-02 19:34:59 +00001583/// operation for when the pattern matched at least one node with a chains. The
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001584/// input vector contains a list of all of the chained nodes that we match. We
1585/// must determine if this is a valid thing to cover (i.e. matching it won't
1586/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1587/// be used as the input node chain for the generated nodes.
Chris Lattner6b307922010-03-02 00:00:03 +00001588static SDValue
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001589HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
Chris Lattner6b307922010-03-02 00:00:03 +00001590 SelectionDAG *CurDAG) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001591 // Walk all of the chained nodes we've matched, recursively scanning down the
1592 // users of the chain result. This adds any TokenFactor nodes that are caught
1593 // in between chained nodes to the chained and interior nodes list.
1594 SmallVector<SDNode*, 3> InteriorChainedNodes;
1595 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1596 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1597 InteriorChainedNodes) == CR_InducesCycle)
1598 return SDValue(); // Would induce a cycle.
1599 }
Chris Lattner6b307922010-03-02 00:00:03 +00001600
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001601 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1602 // that we are interested in. Form our input TokenFactor node.
Chris Lattner6b307922010-03-02 00:00:03 +00001603 SmallVector<SDValue, 3> InputChains;
1604 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001605 // Add the input chain of this node to the InputChains list (which will be
1606 // the operands of the generated TokenFactor) if it's not an interior node.
1607 SDNode *N = ChainNodesMatched[i];
1608 if (N->getOpcode() != ISD::TokenFactor) {
1609 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1610 continue;
1611
1612 // Otherwise, add the input chain.
1613 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1614 assert(InChain.getValueType() == MVT::Other && "Not a chain");
Chris Lattner6b307922010-03-02 00:00:03 +00001615 InputChains.push_back(InChain);
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001616 continue;
1617 }
1618
1619 // If we have a token factor, we want to add all inputs of the token factor
1620 // that are not part of the pattern we're matching.
1621 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1622 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
Chris Lattner6183fbd2010-03-02 02:37:23 +00001623 N->getOperand(op).getNode()))
1624 InputChains.push_back(N->getOperand(op));
Chris Lattnerc6d7ad32010-03-02 02:22:10 +00001625 }
Chris Lattner6b307922010-03-02 00:00:03 +00001626 }
1627
1628 SDValue Res;
1629 if (InputChains.size() == 1)
1630 return InputChains[0];
1631 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1632 MVT::Other, &InputChains[0], InputChains.size());
1633}
Chris Lattner2a49d572010-02-28 22:37:22 +00001634
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001635/// MorphNode - Handle morphing a node in place for the selector.
1636SDNode *SelectionDAGISel::
1637MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1638 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1639 // It is possible we're using MorphNodeTo to replace a node with no
1640 // normal results with one that has a normal result (or we could be
1641 // adding a chain) and the input could have flags and chains as well.
Chris Lattnercaa88702010-03-28 08:43:23 +00001642 // In this case we need to shift the operands down.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001643 // FIXME: This is a horrible hack and broken in obscure cases, no worse
Chris Lattnera6f86932010-03-27 18:54:50 +00001644 // than the old isel though.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001645 int OldFlagResultNo = -1, OldChainResultNo = -1;
1646
1647 unsigned NTMNumResults = Node->getNumValues();
1648 if (Node->getValueType(NTMNumResults-1) == MVT::Flag) {
1649 OldFlagResultNo = NTMNumResults-1;
1650 if (NTMNumResults != 1 &&
1651 Node->getValueType(NTMNumResults-2) == MVT::Other)
1652 OldChainResultNo = NTMNumResults-2;
1653 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1654 OldChainResultNo = NTMNumResults-1;
1655
Chris Lattner61c97f62010-03-02 07:14:49 +00001656 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1657 // that this deletes operands of the old node that become dead.
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001658 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1659
1660 // MorphNodeTo can operate in two ways: if an existing node with the
1661 // specified operands exists, it can just return it. Otherwise, it
1662 // updates the node in place to have the requested operands.
1663 if (Res == Node) {
1664 // If we updated the node in place, reset the node ID. To the isel,
1665 // this should be just like a newly allocated machine node.
1666 Res->setNodeId(-1);
1667 }
1668
1669 unsigned ResNumResults = Res->getNumValues();
1670 // Move the flag if needed.
1671 if ((EmitNodeInfo & OPFL_FlagOutput) && OldFlagResultNo != -1 &&
1672 (unsigned)OldFlagResultNo != ResNumResults-1)
1673 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldFlagResultNo),
1674 SDValue(Res, ResNumResults-1));
1675
1676 if ((EmitNodeInfo & OPFL_FlagOutput) != 0)
1677 --ResNumResults;
1678
1679 // Move the chain reference if needed.
1680 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1681 (unsigned)OldChainResultNo != ResNumResults-1)
1682 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1683 SDValue(Res, ResNumResults-1));
1684
1685 // Otherwise, no replacement happened because the node already exists. Replace
1686 // Uses of the old node with the new one.
1687 if (Res != Node)
1688 CurDAG->ReplaceAllUsesWith(Node, Res);
1689
1690 return Res;
1691}
1692
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001693/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1694ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001695CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1696 SDValue N, const SmallVectorImpl<SDValue> &RecordedNodes) {
1697 // Accept if it is exactly the same as a previously recorded node.
1698 unsigned RecNo = MatcherTable[MatcherIndex++];
1699 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1700 return N == RecordedNodes[RecNo];
1701}
1702
1703/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1704ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001705CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1706 SelectionDAGISel &SDISel) {
1707 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1708}
1709
1710/// CheckNodePredicate - Implements OP_CheckNodePredicate.
1711ALWAYS_INLINE static bool
1712CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1713 SelectionDAGISel &SDISel, SDNode *N) {
1714 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1715}
1716
1717ALWAYS_INLINE static bool
1718CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1719 SDNode *N) {
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00001720 uint16_t Opc = MatcherTable[MatcherIndex++];
1721 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1722 return N->getOpcode() == Opc;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001723}
1724
1725ALWAYS_INLINE static bool
1726CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1727 SDValue N, const TargetLowering &TLI) {
1728 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1729 if (N.getValueType() == VT) return true;
1730
1731 // Handle the case when VT is iPTR.
1732 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
1733}
1734
1735ALWAYS_INLINE static bool
Chris Lattnerda828e32010-03-03 07:46:25 +00001736CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1737 SDValue N, const TargetLowering &TLI,
1738 unsigned ChildNo) {
1739 if (ChildNo >= N.getNumOperands())
1740 return false; // Match fails if out of range child #.
1741 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
1742}
1743
1744
1745ALWAYS_INLINE static bool
1746CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1747 SDValue N) {
1748 return cast<CondCodeSDNode>(N)->get() ==
1749 (ISD::CondCode)MatcherTable[MatcherIndex++];
1750}
1751
1752ALWAYS_INLINE static bool
1753CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1754 SDValue N, const TargetLowering &TLI) {
1755 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1756 if (cast<VTSDNode>(N)->getVT() == VT)
1757 return true;
1758
1759 // Handle the case when VT is iPTR.
1760 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
1761}
1762
1763ALWAYS_INLINE static bool
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001764CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1765 SDValue N) {
1766 int64_t Val = MatcherTable[MatcherIndex++];
1767 if (Val & 128)
1768 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1769
1770 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
1771 return C != 0 && C->getSExtValue() == Val;
1772}
1773
Chris Lattnerda828e32010-03-03 07:46:25 +00001774ALWAYS_INLINE static bool
1775CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1776 SDValue N, SelectionDAGISel &SDISel) {
1777 int64_t Val = MatcherTable[MatcherIndex++];
1778 if (Val & 128)
1779 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1780
1781 if (N->getOpcode() != ISD::AND) return false;
1782
1783 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1784 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
1785}
1786
1787ALWAYS_INLINE static bool
1788CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1789 SDValue N, SelectionDAGISel &SDISel) {
1790 int64_t Val = MatcherTable[MatcherIndex++];
1791 if (Val & 128)
1792 Val = GetVBR(Val, MatcherTable, MatcherIndex);
1793
1794 if (N->getOpcode() != ISD::OR) return false;
1795
1796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1797 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
1798}
1799
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001800/// IsPredicateKnownToFail - If we know how and can do so without pushing a
1801/// scope, evaluate the current node. If the current predicate is known to
1802/// fail, set Result=true and return anything. If the current predicate is
1803/// known to pass, set Result=false and return the MatcherIndex to continue
1804/// with. If the current predicate is unknown, set Result=false and return the
1805/// MatcherIndex to continue with.
1806static unsigned IsPredicateKnownToFail(const unsigned char *Table,
1807 unsigned Index, SDValue N,
Chris Lattnerda828e32010-03-03 07:46:25 +00001808 bool &Result, SelectionDAGISel &SDISel,
1809 SmallVectorImpl<SDValue> &RecordedNodes){
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001810 switch (Table[Index++]) {
1811 default:
1812 Result = false;
1813 return Index-1; // Could not evaluate this predicate.
Chris Lattnerda828e32010-03-03 07:46:25 +00001814 case SelectionDAGISel::OPC_CheckSame:
1815 Result = !::CheckSame(Table, Index, N, RecordedNodes);
1816 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001817 case SelectionDAGISel::OPC_CheckPatternPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00001818 Result = !::CheckPatternPredicate(Table, Index, SDISel);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001819 return Index;
1820 case SelectionDAGISel::OPC_CheckPredicate:
Chris Lattnerda828e32010-03-03 07:46:25 +00001821 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001822 return Index;
1823 case SelectionDAGISel::OPC_CheckOpcode:
1824 Result = !::CheckOpcode(Table, Index, N.getNode());
1825 return Index;
1826 case SelectionDAGISel::OPC_CheckType:
1827 Result = !::CheckType(Table, Index, N, SDISel.TLI);
1828 return Index;
1829 case SelectionDAGISel::OPC_CheckChild0Type:
1830 case SelectionDAGISel::OPC_CheckChild1Type:
1831 case SelectionDAGISel::OPC_CheckChild2Type:
1832 case SelectionDAGISel::OPC_CheckChild3Type:
1833 case SelectionDAGISel::OPC_CheckChild4Type:
1834 case SelectionDAGISel::OPC_CheckChild5Type:
1835 case SelectionDAGISel::OPC_CheckChild6Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00001836 case SelectionDAGISel::OPC_CheckChild7Type:
1837 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
1838 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001839 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00001840 case SelectionDAGISel::OPC_CheckCondCode:
1841 Result = !::CheckCondCode(Table, Index, N);
1842 return Index;
1843 case SelectionDAGISel::OPC_CheckValueType:
1844 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
1845 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001846 case SelectionDAGISel::OPC_CheckInteger:
1847 Result = !::CheckInteger(Table, Index, N);
1848 return Index;
Chris Lattnerda828e32010-03-03 07:46:25 +00001849 case SelectionDAGISel::OPC_CheckAndImm:
1850 Result = !::CheckAndImm(Table, Index, N, SDISel);
1851 return Index;
1852 case SelectionDAGISel::OPC_CheckOrImm:
1853 Result = !::CheckOrImm(Table, Index, N, SDISel);
1854 return Index;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00001855 }
1856}
1857
Dan Gohmanb3579832010-04-15 17:08:50 +00001858namespace {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00001859
Chris Lattner2a49d572010-02-28 22:37:22 +00001860struct MatchScope {
1861 /// FailIndex - If this match fails, this is the index to continue with.
1862 unsigned FailIndex;
1863
1864 /// NodeStack - The node stack when the scope was formed.
1865 SmallVector<SDValue, 4> NodeStack;
1866
1867 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
1868 unsigned NumRecordedNodes;
1869
1870 /// NumMatchedMemRefs - The number of matched memref entries.
1871 unsigned NumMatchedMemRefs;
1872
1873 /// InputChain/InputFlag - The current chain/flag
1874 SDValue InputChain, InputFlag;
1875
1876 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
1877 bool HasChainNodesMatched, HasFlagResultNodesMatched;
1878};
1879
Dan Gohmanb3579832010-04-15 17:08:50 +00001880}
1881
Chris Lattner2a49d572010-02-28 22:37:22 +00001882SDNode *SelectionDAGISel::
1883SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
1884 unsigned TableSize) {
1885 // FIXME: Should these even be selected? Handle these cases in the caller?
1886 switch (NodeToMatch->getOpcode()) {
1887 default:
1888 break;
1889 case ISD::EntryToken: // These nodes remain the same.
1890 case ISD::BasicBlock:
1891 case ISD::Register:
Chris Lattner3b9d6212010-03-14 17:53:23 +00001892 //case ISD::VALUETYPE:
1893 //case ISD::CONDCODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00001894 case ISD::HANDLENODE:
Chris Lattnerdecc2672010-04-07 05:20:54 +00001895 case ISD::MDNODE_SDNODE:
Chris Lattner2a49d572010-02-28 22:37:22 +00001896 case ISD::TargetConstant:
1897 case ISD::TargetConstantFP:
1898 case ISD::TargetConstantPool:
1899 case ISD::TargetFrameIndex:
1900 case ISD::TargetExternalSymbol:
1901 case ISD::TargetBlockAddress:
1902 case ISD::TargetJumpTable:
1903 case ISD::TargetGlobalTLSAddress:
1904 case ISD::TargetGlobalAddress:
1905 case ISD::TokenFactor:
1906 case ISD::CopyFromReg:
1907 case ISD::CopyToReg:
Chris Lattner7561d482010-03-14 02:33:54 +00001908 case ISD::EH_LABEL:
Chris Lattnerd1b73822010-03-02 22:20:06 +00001909 NodeToMatch->setNodeId(-1); // Mark selected.
Chris Lattner2a49d572010-02-28 22:37:22 +00001910 return 0;
1911 case ISD::AssertSext:
1912 case ISD::AssertZext:
1913 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
1914 NodeToMatch->getOperand(0));
1915 return 0;
1916 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
Chris Lattner2a49d572010-02-28 22:37:22 +00001917 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
1918 }
1919
1920 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
1921
1922 // Set up the node stack with NodeToMatch as the only node on the stack.
1923 SmallVector<SDValue, 8> NodeStack;
1924 SDValue N = SDValue(NodeToMatch, 0);
1925 NodeStack.push_back(N);
1926
1927 // MatchScopes - Scopes used when matching, if a match failure happens, this
1928 // indicates where to continue checking.
1929 SmallVector<MatchScope, 8> MatchScopes;
1930
1931 // RecordedNodes - This is the set of nodes that have been recorded by the
1932 // state machine.
1933 SmallVector<SDValue, 8> RecordedNodes;
1934
1935 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
1936 // pattern.
1937 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
1938
1939 // These are the current input chain and flag for use when generating nodes.
1940 // Various Emit operations change these. For example, emitting a copytoreg
1941 // uses and updates these.
1942 SDValue InputChain, InputFlag;
1943
1944 // ChainNodesMatched - If a pattern matches nodes that have input/output
1945 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
1946 // which ones they are. The result is captured into this list so that we can
1947 // update the chain results when the pattern is complete.
1948 SmallVector<SDNode*, 3> ChainNodesMatched;
1949 SmallVector<SDNode*, 3> FlagResultNodesMatched;
1950
1951 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
1952 NodeToMatch->dump(CurDAG);
1953 errs() << '\n');
1954
Chris Lattner7390eeb2010-03-01 18:47:11 +00001955 // Determine where to start the interpreter. Normally we start at opcode #0,
1956 // but if the state machine starts with an OPC_SwitchOpcode, then we
1957 // accelerate the first lookup (which is guaranteed to be hot) with the
1958 // OpcodeOffset table.
Chris Lattner2a49d572010-02-28 22:37:22 +00001959 unsigned MatcherIndex = 0;
Chris Lattner7390eeb2010-03-01 18:47:11 +00001960
1961 if (!OpcodeOffset.empty()) {
1962 // Already computed the OpcodeOffset table, just index into it.
1963 if (N.getOpcode() < OpcodeOffset.size())
1964 MatcherIndex = OpcodeOffset[N.getOpcode()];
1965 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
1966
1967 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
1968 // Otherwise, the table isn't computed, but the state machine does start
1969 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
1970 // is the first time we're selecting an instruction.
1971 unsigned Idx = 1;
1972 while (1) {
1973 // Get the size of this case.
1974 unsigned CaseSize = MatcherTable[Idx++];
1975 if (CaseSize & 128)
1976 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
1977 if (CaseSize == 0) break;
1978
1979 // Get the opcode, add the index to the table.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00001980 uint16_t Opc = MatcherTable[Idx++];
1981 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
Chris Lattner7390eeb2010-03-01 18:47:11 +00001982 if (Opc >= OpcodeOffset.size())
1983 OpcodeOffset.resize((Opc+1)*2);
1984 OpcodeOffset[Opc] = Idx;
1985 Idx += CaseSize;
1986 }
1987
1988 // Okay, do the lookup for the first opcode.
1989 if (N.getOpcode() < OpcodeOffset.size())
1990 MatcherIndex = OpcodeOffset[N.getOpcode()];
1991 }
1992
Chris Lattner2a49d572010-02-28 22:37:22 +00001993 while (1) {
1994 assert(MatcherIndex < TableSize && "Invalid index");
Dan Gohman19b38262010-03-09 02:15:05 +00001995#ifndef NDEBUG
1996 unsigned CurrentOpcodeIndex = MatcherIndex;
1997#endif
Chris Lattner2a49d572010-02-28 22:37:22 +00001998 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
1999 switch (Opcode) {
2000 case OPC_Scope: {
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002001 // Okay, the semantics of this operation are that we should push a scope
2002 // then evaluate the first child. However, pushing a scope only to have
2003 // the first check fail (which then pops it) is inefficient. If we can
2004 // determine immediately that the first check (or first several) will
2005 // immediately fail, don't even bother pushing a scope for them.
2006 unsigned FailIndex;
2007
2008 while (1) {
2009 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2010 if (NumToSkip & 128)
2011 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2012 // Found the end of the scope with no match.
2013 if (NumToSkip == 0) {
2014 FailIndex = 0;
2015 break;
2016 }
2017
2018 FailIndex = MatcherIndex+NumToSkip;
2019
Chris Lattnera6f86932010-03-27 18:54:50 +00002020 unsigned MatcherIndexOfPredicate = MatcherIndex;
2021 (void)MatcherIndexOfPredicate; // silence warning.
2022
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002023 // If we can't evaluate this predicate without pushing a scope (e.g. if
2024 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2025 // push the scope and evaluate the full predicate chain.
2026 bool Result;
2027 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
Chris Lattnerda828e32010-03-03 07:46:25 +00002028 Result, *this, RecordedNodes);
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002029 if (!Result)
2030 break;
2031
Chris Lattnera6f86932010-03-27 18:54:50 +00002032 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
2033 << "index " << MatcherIndexOfPredicate
2034 << ", continuing at " << FailIndex << "\n");
Chris Lattnerbed993d2010-03-28 19:46:56 +00002035 ++NumDAGIselRetries;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002036
2037 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2038 // move to the next case.
2039 MatcherIndex = FailIndex;
2040 }
2041
2042 // If the whole scope failed to match, bail.
2043 if (FailIndex == 0) break;
2044
Chris Lattner2a49d572010-02-28 22:37:22 +00002045 // Push a MatchScope which indicates where to go if the first child fails
2046 // to match.
2047 MatchScope NewEntry;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002048 NewEntry.FailIndex = FailIndex;
Chris Lattner2a49d572010-02-28 22:37:22 +00002049 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2050 NewEntry.NumRecordedNodes = RecordedNodes.size();
2051 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2052 NewEntry.InputChain = InputChain;
2053 NewEntry.InputFlag = InputFlag;
2054 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2055 NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
2056 MatchScopes.push_back(NewEntry);
2057 continue;
2058 }
2059 case OPC_RecordNode:
2060 // Remember this node, it may end up being an operand in the pattern.
2061 RecordedNodes.push_back(N);
2062 continue;
2063
2064 case OPC_RecordChild0: case OPC_RecordChild1:
2065 case OPC_RecordChild2: case OPC_RecordChild3:
2066 case OPC_RecordChild4: case OPC_RecordChild5:
2067 case OPC_RecordChild6: case OPC_RecordChild7: {
2068 unsigned ChildNo = Opcode-OPC_RecordChild0;
2069 if (ChildNo >= N.getNumOperands())
2070 break; // Match fails if out of range child #.
2071
2072 RecordedNodes.push_back(N->getOperand(ChildNo));
2073 continue;
2074 }
2075 case OPC_RecordMemRef:
2076 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2077 continue;
2078
2079 case OPC_CaptureFlagInput:
2080 // If the current node has an input flag, capture it in InputFlag.
2081 if (N->getNumOperands() != 0 &&
2082 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
2083 InputFlag = N->getOperand(N->getNumOperands()-1);
2084 continue;
2085
2086 case OPC_MoveChild: {
2087 unsigned ChildNo = MatcherTable[MatcherIndex++];
2088 if (ChildNo >= N.getNumOperands())
2089 break; // Match fails if out of range child #.
2090 N = N.getOperand(ChildNo);
2091 NodeStack.push_back(N);
2092 continue;
2093 }
2094
2095 case OPC_MoveParent:
2096 // Pop the current node off the NodeStack.
2097 NodeStack.pop_back();
2098 assert(!NodeStack.empty() && "Node stack imbalance!");
2099 N = NodeStack.back();
2100 continue;
2101
Chris Lattnerda828e32010-03-03 07:46:25 +00002102 case OPC_CheckSame:
2103 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002104 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002105 case OPC_CheckPatternPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002106 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002107 continue;
2108 case OPC_CheckPredicate:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002109 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2110 N.getNode()))
2111 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002112 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002113 case OPC_CheckComplexPat: {
2114 unsigned CPNum = MatcherTable[MatcherIndex++];
2115 unsigned RecNo = MatcherTable[MatcherIndex++];
2116 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2117 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo], CPNum,
2118 RecordedNodes))
Chris Lattner2a49d572010-02-28 22:37:22 +00002119 break;
2120 continue;
Chris Lattner57bf8a42010-03-04 01:23:08 +00002121 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002122 case OPC_CheckOpcode:
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002123 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2124 continue;
2125
2126 case OPC_CheckType:
2127 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002128 continue;
2129
Chris Lattnereb669212010-03-01 06:59:22 +00002130 case OPC_SwitchOpcode: {
2131 unsigned CurNodeOpcode = N.getOpcode();
Chris Lattner7d892d62010-03-01 07:43:08 +00002132 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
Chris Lattnereb669212010-03-01 06:59:22 +00002133 unsigned CaseSize;
2134 while (1) {
2135 // Get the size of this case.
2136 CaseSize = MatcherTable[MatcherIndex++];
2137 if (CaseSize & 128)
2138 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2139 if (CaseSize == 0) break;
2140
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002141 uint16_t Opc = MatcherTable[MatcherIndex++];
2142 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2143
Chris Lattnereb669212010-03-01 06:59:22 +00002144 // If the opcode matches, then we will execute this case.
Chris Lattnerd5d5a3d2010-03-25 06:33:05 +00002145 if (CurNodeOpcode == Opc)
Chris Lattnereb669212010-03-01 06:59:22 +00002146 break;
2147
2148 // Otherwise, skip over this case.
2149 MatcherIndex += CaseSize;
2150 }
2151
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002152 // If no cases matched, bail out.
Chris Lattnereb669212010-03-01 06:59:22 +00002153 if (CaseSize == 0) break;
2154
2155 // Otherwise, execute the case we found.
2156 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2157 << " to " << MatcherIndex << "\n");
2158 continue;
2159 }
2160
Chris Lattnercfe2eab2010-03-03 06:28:15 +00002161 case OPC_SwitchType: {
2162 MVT::SimpleValueType CurNodeVT = N.getValueType().getSimpleVT().SimpleTy;
2163 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2164 unsigned CaseSize;
2165 while (1) {
2166 // Get the size of this case.
2167 CaseSize = MatcherTable[MatcherIndex++];
2168 if (CaseSize & 128)
2169 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2170 if (CaseSize == 0) break;
2171
2172 MVT::SimpleValueType CaseVT =
2173 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2174 if (CaseVT == MVT::iPTR)
2175 CaseVT = TLI.getPointerTy().SimpleTy;
2176
2177 // If the VT matches, then we will execute this case.
2178 if (CurNodeVT == CaseVT)
2179 break;
2180
2181 // Otherwise, skip over this case.
2182 MatcherIndex += CaseSize;
2183 }
2184
2185 // If no cases matched, bail out.
2186 if (CaseSize == 0) break;
2187
2188 // Otherwise, execute the case we found.
2189 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2190 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2191 continue;
2192 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002193 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2194 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2195 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
Chris Lattnerda828e32010-03-03 07:46:25 +00002196 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2197 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2198 Opcode-OPC_CheckChild0Type))
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002199 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002200 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002201 case OPC_CheckCondCode:
Chris Lattnerda828e32010-03-03 07:46:25 +00002202 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002203 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002204 case OPC_CheckValueType:
2205 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002206 continue;
Chris Lattnerf1b7c7d2010-03-03 07:31:15 +00002207 case OPC_CheckInteger:
2208 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002209 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002210 case OPC_CheckAndImm:
2211 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002212 continue;
Chris Lattnerda828e32010-03-03 07:46:25 +00002213 case OPC_CheckOrImm:
2214 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002215 continue;
Chris Lattner2a49d572010-02-28 22:37:22 +00002216
2217 case OPC_CheckFoldableChainNode: {
2218 assert(NodeStack.size() != 1 && "No parent node");
2219 // Verify that all intermediate nodes between the root and this one have
2220 // a single use.
2221 bool HasMultipleUses = false;
2222 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2223 if (!NodeStack[i].hasOneUse()) {
2224 HasMultipleUses = true;
2225 break;
2226 }
2227 if (HasMultipleUses) break;
2228
2229 // Check to see that the target thinks this is profitable to fold and that
2230 // we can fold it without inducing cycles in the graph.
2231 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2232 NodeToMatch) ||
2233 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
Dan Gohmand858e902010-04-17 15:26:15 +00002234 NodeToMatch, OptLevel,
2235 true/*We validate our own chains*/))
Chris Lattner2a49d572010-02-28 22:37:22 +00002236 break;
2237
2238 continue;
2239 }
Chris Lattner2a49d572010-02-28 22:37:22 +00002240 case OPC_EmitInteger: {
2241 MVT::SimpleValueType VT =
2242 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2243 int64_t Val = MatcherTable[MatcherIndex++];
2244 if (Val & 128)
2245 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2246 RecordedNodes.push_back(CurDAG->getTargetConstant(Val, VT));
2247 continue;
2248 }
2249 case OPC_EmitRegister: {
2250 MVT::SimpleValueType VT =
2251 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2252 unsigned RegNo = MatcherTable[MatcherIndex++];
2253 RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
2254 continue;
2255 }
2256
2257 case OPC_EmitConvertToTarget: {
2258 // Convert from IMM/FPIMM to target version.
2259 unsigned RecNo = MatcherTable[MatcherIndex++];
2260 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2261 SDValue Imm = RecordedNodes[RecNo];
2262
2263 if (Imm->getOpcode() == ISD::Constant) {
2264 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2265 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2266 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2267 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2268 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2269 }
2270
2271 RecordedNodes.push_back(Imm);
2272 continue;
2273 }
2274
Chris Lattneraa4e3392010-03-28 05:50:16 +00002275 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2276 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2277 // These are space-optimized forms of OPC_EmitMergeInputChains.
2278 assert(InputChain.getNode() == 0 &&
2279 "EmitMergeInputChains should be the first chain producing node");
2280 assert(ChainNodesMatched.empty() &&
2281 "Should only have one EmitMergeInputChains per match");
2282
2283 // Read all of the chained nodes.
2284 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2285 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2286 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2287
2288 // FIXME: What if other value results of the node have uses not matched
2289 // by this pattern?
2290 if (ChainNodesMatched.back() != NodeToMatch &&
2291 !RecordedNodes[RecNo].hasOneUse()) {
2292 ChainNodesMatched.clear();
2293 break;
2294 }
2295
2296 // Merge the input chains if they are not intra-pattern references.
2297 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2298
2299 if (InputChain.getNode() == 0)
2300 break; // Failed to merge.
2301 continue;
2302 }
2303
Chris Lattner2a49d572010-02-28 22:37:22 +00002304 case OPC_EmitMergeInputChains: {
2305 assert(InputChain.getNode() == 0 &&
2306 "EmitMergeInputChains should be the first chain producing node");
2307 // This node gets a list of nodes we matched in the input that have
2308 // chains. We want to token factor all of the input chains to these nodes
2309 // together. However, if any of the input chains is actually one of the
2310 // nodes matched in this pattern, then we have an intra-match reference.
2311 // Ignore these because the newly token factored chain should not refer to
2312 // the old nodes.
2313 unsigned NumChains = MatcherTable[MatcherIndex++];
2314 assert(NumChains != 0 && "Can't TF zero chains");
2315
2316 assert(ChainNodesMatched.empty() &&
2317 "Should only have one EmitMergeInputChains per match");
2318
Chris Lattner2a49d572010-02-28 22:37:22 +00002319 // Read all of the chained nodes.
Chris Lattner00592ec2010-03-02 19:34:59 +00002320 for (unsigned i = 0; i != NumChains; ++i) {
2321 unsigned RecNo = MatcherTable[MatcherIndex++];
Chris Lattner2a49d572010-02-28 22:37:22 +00002322 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2323 ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2324
2325 // FIXME: What if other value results of the node have uses not matched
2326 // by this pattern?
2327 if (ChainNodesMatched.back() != NodeToMatch &&
2328 !RecordedNodes[RecNo].hasOneUse()) {
2329 ChainNodesMatched.clear();
2330 break;
2331 }
2332 }
Chris Lattner6b307922010-03-02 00:00:03 +00002333
2334 // If the inner loop broke out, the match fails.
2335 if (ChainNodesMatched.empty())
2336 break;
Chris Lattner2a49d572010-02-28 22:37:22 +00002337
Chris Lattner6b307922010-03-02 00:00:03 +00002338 // Merge the input chains if they are not intra-pattern references.
2339 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2340
2341 if (InputChain.getNode() == 0)
2342 break; // Failed to merge.
Chris Lattner2a49d572010-02-28 22:37:22 +00002343
Chris Lattner2a49d572010-02-28 22:37:22 +00002344 continue;
2345 }
2346
2347 case OPC_EmitCopyToReg: {
2348 unsigned RecNo = MatcherTable[MatcherIndex++];
2349 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2350 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2351
2352 if (InputChain.getNode() == 0)
2353 InputChain = CurDAG->getEntryNode();
2354
2355 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2356 DestPhysReg, RecordedNodes[RecNo],
2357 InputFlag);
2358
2359 InputFlag = InputChain.getValue(1);
2360 continue;
2361 }
2362
2363 case OPC_EmitNodeXForm: {
2364 unsigned XFormNo = MatcherTable[MatcherIndex++];
2365 unsigned RecNo = MatcherTable[MatcherIndex++];
2366 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2367 RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
2368 continue;
2369 }
2370
2371 case OPC_EmitNode:
2372 case OPC_MorphNodeTo: {
Chris Lattner14df8dc2010-02-28 22:38:43 +00002373 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2374 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
Chris Lattner2a49d572010-02-28 22:37:22 +00002375 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2376 // Get the result VT list.
2377 unsigned NumVTs = MatcherTable[MatcherIndex++];
2378 SmallVector<EVT, 4> VTs;
2379 for (unsigned i = 0; i != NumVTs; ++i) {
2380 MVT::SimpleValueType VT =
2381 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2382 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2383 VTs.push_back(VT);
2384 }
2385
2386 if (EmitNodeInfo & OPFL_Chain)
2387 VTs.push_back(MVT::Other);
2388 if (EmitNodeInfo & OPFL_FlagOutput)
2389 VTs.push_back(MVT::Flag);
2390
Chris Lattner7d892d62010-03-01 07:43:08 +00002391 // This is hot code, so optimize the two most common cases of 1 and 2
2392 // results.
2393 SDVTList VTList;
2394 if (VTs.size() == 1)
2395 VTList = CurDAG->getVTList(VTs[0]);
2396 else if (VTs.size() == 2)
2397 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2398 else
2399 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
Chris Lattner2a49d572010-02-28 22:37:22 +00002400
2401 // Get the operand list.
2402 unsigned NumOps = MatcherTable[MatcherIndex++];
2403 SmallVector<SDValue, 8> Ops;
2404 for (unsigned i = 0; i != NumOps; ++i) {
2405 unsigned RecNo = MatcherTable[MatcherIndex++];
2406 if (RecNo & 128)
2407 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2408
2409 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2410 Ops.push_back(RecordedNodes[RecNo]);
2411 }
2412
2413 // If there are variadic operands to add, handle them now.
2414 if (EmitNodeInfo & OPFL_VariadicInfo) {
2415 // Determine the start index to copy from.
2416 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2417 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2418 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2419 "Invalid variadic node");
2420 // Copy all of the variadic operands, not including a potential flag
2421 // input.
2422 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2423 i != e; ++i) {
2424 SDValue V = NodeToMatch->getOperand(i);
2425 if (V.getValueType() == MVT::Flag) break;
2426 Ops.push_back(V);
2427 }
2428 }
2429
2430 // If this has chain/flag inputs, add them.
2431 if (EmitNodeInfo & OPFL_Chain)
2432 Ops.push_back(InputChain);
2433 if ((EmitNodeInfo & OPFL_FlagInput) && InputFlag.getNode() != 0)
2434 Ops.push_back(InputFlag);
2435
2436 // Create the node.
2437 SDNode *Res = 0;
2438 if (Opcode != OPC_MorphNodeTo) {
2439 // If this is a normal EmitNode command, just create the new node and
2440 // add the results to the RecordedNodes list.
2441 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2442 VTList, Ops.data(), Ops.size());
2443
2444 // Add all the non-flag/non-chain results to the RecordedNodes list.
2445 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2446 if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
2447 RecordedNodes.push_back(SDValue(Res, i));
2448 }
2449
2450 } else {
Chris Lattner3ff1e4d2010-03-02 06:55:04 +00002451 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2452 EmitNodeInfo);
Chris Lattner2a49d572010-02-28 22:37:22 +00002453 }
2454
2455 // If the node had chain/flag results, update our notion of the current
2456 // chain and flag.
Chris Lattner82dd3d32010-03-02 07:50:03 +00002457 if (EmitNodeInfo & OPFL_FlagOutput) {
Chris Lattner2a49d572010-02-28 22:37:22 +00002458 InputFlag = SDValue(Res, VTs.size()-1);
2459 if (EmitNodeInfo & OPFL_Chain)
2460 InputChain = SDValue(Res, VTs.size()-2);
2461 } else if (EmitNodeInfo & OPFL_Chain)
2462 InputChain = SDValue(Res, VTs.size()-1);
2463
2464 // If the OPFL_MemRefs flag is set on this node, slap all of the
2465 // accumulated memrefs onto it.
2466 //
2467 // FIXME: This is vastly incorrect for patterns with multiple outputs
2468 // instructions that access memory and for ComplexPatterns that match
2469 // loads.
2470 if (EmitNodeInfo & OPFL_MemRefs) {
2471 MachineSDNode::mmo_iterator MemRefs =
2472 MF->allocateMemRefsArray(MatchedMemRefs.size());
2473 std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
2474 cast<MachineSDNode>(Res)
2475 ->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
2476 }
2477
2478 DEBUG(errs() << " "
2479 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2480 << " node: "; Res->dump(CurDAG); errs() << "\n");
2481
2482 // If this was a MorphNodeTo then we're completely done!
2483 if (Opcode == OPC_MorphNodeTo) {
2484 // Update chain and flag uses.
2485 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
Chris Lattner82dd3d32010-03-02 07:50:03 +00002486 InputFlag, FlagResultNodesMatched, true);
2487 return Res;
Chris Lattner2a49d572010-02-28 22:37:22 +00002488 }
2489
2490 continue;
2491 }
2492
2493 case OPC_MarkFlagResults: {
2494 unsigned NumNodes = MatcherTable[MatcherIndex++];
2495
2496 // Read and remember all the flag-result nodes.
2497 for (unsigned i = 0; i != NumNodes; ++i) {
2498 unsigned RecNo = MatcherTable[MatcherIndex++];
2499 if (RecNo & 128)
2500 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2501
2502 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2503 FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
2504 }
2505 continue;
2506 }
2507
2508 case OPC_CompleteMatch: {
2509 // The match has been completed, and any new nodes (if any) have been
2510 // created. Patch up references to the matched dag to use the newly
2511 // created nodes.
2512 unsigned NumResults = MatcherTable[MatcherIndex++];
2513
2514 for (unsigned i = 0; i != NumResults; ++i) {
2515 unsigned ResSlot = MatcherTable[MatcherIndex++];
2516 if (ResSlot & 128)
2517 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2518
2519 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2520 SDValue Res = RecordedNodes[ResSlot];
2521
Chris Lattnerb0e483e2010-03-28 05:54:03 +00002522 assert(i < NodeToMatch->getNumValues() &&
2523 NodeToMatch->getValueType(i) != MVT::Other &&
2524 NodeToMatch->getValueType(i) != MVT::Flag &&
2525 "Invalid number of results to complete!");
Chris Lattner2a49d572010-02-28 22:37:22 +00002526 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2527 NodeToMatch->getValueType(i) == MVT::iPTR ||
2528 Res.getValueType() == MVT::iPTR ||
2529 NodeToMatch->getValueType(i).getSizeInBits() ==
2530 Res.getValueType().getSizeInBits()) &&
2531 "invalid replacement");
2532 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2533 }
2534
2535 // If the root node defines a flag, add it to the flag nodes to update
2536 // list.
2537 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Flag)
2538 FlagResultNodesMatched.push_back(NodeToMatch);
2539
2540 // Update chain and flag uses.
2541 UpdateChainsAndFlags(NodeToMatch, InputChain, ChainNodesMatched,
Chris Lattner82dd3d32010-03-02 07:50:03 +00002542 InputFlag, FlagResultNodesMatched, false);
Chris Lattner2a49d572010-02-28 22:37:22 +00002543
2544 assert(NodeToMatch->use_empty() &&
2545 "Didn't replace all uses of the node?");
2546
2547 // FIXME: We just return here, which interacts correctly with SelectRoot
2548 // above. We should fix this to not return an SDNode* anymore.
2549 return 0;
2550 }
2551 }
2552
2553 // If the code reached this point, then the match failed. See if there is
2554 // another child to try in the current 'Scope', otherwise pop it until we
2555 // find a case to check.
Dan Gohman19b38262010-03-09 02:15:05 +00002556 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
Chris Lattnerbed993d2010-03-28 19:46:56 +00002557 ++NumDAGIselRetries;
Chris Lattner2a49d572010-02-28 22:37:22 +00002558 while (1) {
2559 if (MatchScopes.empty()) {
2560 CannotYetSelect(NodeToMatch);
2561 return 0;
2562 }
2563
2564 // Restore the interpreter state back to the point where the scope was
2565 // formed.
2566 MatchScope &LastScope = MatchScopes.back();
2567 RecordedNodes.resize(LastScope.NumRecordedNodes);
2568 NodeStack.clear();
2569 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2570 N = NodeStack.back();
2571
Chris Lattner2a49d572010-02-28 22:37:22 +00002572 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2573 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2574 MatcherIndex = LastScope.FailIndex;
2575
Dan Gohman19b38262010-03-09 02:15:05 +00002576 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2577
Chris Lattner2a49d572010-02-28 22:37:22 +00002578 InputChain = LastScope.InputChain;
2579 InputFlag = LastScope.InputFlag;
2580 if (!LastScope.HasChainNodesMatched)
2581 ChainNodesMatched.clear();
2582 if (!LastScope.HasFlagResultNodesMatched)
2583 FlagResultNodesMatched.clear();
2584
2585 // Check to see what the offset is at the new MatcherIndex. If it is zero
2586 // we have reached the end of this scope, otherwise we have another child
2587 // in the current scope to try.
2588 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2589 if (NumToSkip & 128)
2590 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2591
2592 // If we have another child in this scope to match, update FailIndex and
2593 // try it.
2594 if (NumToSkip != 0) {
2595 LastScope.FailIndex = MatcherIndex+NumToSkip;
2596 break;
2597 }
2598
2599 // End of this scope, pop it and try the next child in the containing
2600 // scope.
2601 MatchScopes.pop_back();
2602 }
2603 }
2604}
2605
2606
2607
Dan Gohmaneeb3a002010-01-05 01:24:18 +00002608void SelectionDAGISel::CannotYetSelect(SDNode *N) {
Dan Gohmane1f188f2009-10-29 22:30:23 +00002609 std::string msg;
2610 raw_string_ostream Msg(msg);
2611 Msg << "Cannot yet select: ";
Chris Lattner2c4afd12010-03-04 00:21:16 +00002612
2613 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2614 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2615 N->getOpcode() != ISD::INTRINSIC_VOID) {
2616 N->printrFull(Msg, CurDAG);
2617 } else {
2618 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2619 unsigned iid =
2620 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2621 if (iid < Intrinsic::num_intrinsics)
2622 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2623 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2624 Msg << "target intrinsic %" << TII->getName(iid);
2625 else
2626 Msg << "unknown intrinsic #" << iid;
2627 }
Chris Lattner75361b62010-04-07 22:58:41 +00002628 report_fatal_error(Msg.str());
Dan Gohmane1f188f2009-10-29 22:30:23 +00002629}
2630
Devang Patel19974732007-05-03 01:11:54 +00002631char SelectionDAGISel::ID = 0;