1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "ScheduleDAGSDNodes.h"
17 #include "SelectionDAGBuilder.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/GCMetadata.h"
26 #include "llvm/CodeGen/GCStrategy.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
33 #include "llvm/CodeGen/SchedulerRegistry.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/DebugInfo.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/InlineAsm.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetIntrinsicInfo.h"
51 #include "llvm/Target/TargetLibraryInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
56 #include "llvm/Target/TargetSubtargetInfo.h"
57 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
61 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
62 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
63 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
64 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
65 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
66 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
67 STATISTIC(NumFastIselFailLowerArguments,
68 "Number of entry blocks where fast isel failed to lower arguments");
72 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
73 cl::desc("Enable extra verbose messages in the \"fast\" "
74 "instruction selector"));
77 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
78 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
79 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
80 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
81 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
82 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
83 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
85 // Standard binary operators...
86 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
87 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
88 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
89 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
90 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
91 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
92 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
93 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
94 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
95 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
96 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
97 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
99 // Logical operators...
100 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
101 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
102 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
104 // Memory instructions...
105 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
106 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
107 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
108 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
109 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
110 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
111 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
113 // Convert instructions...
114 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
115 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
116 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
117 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
118 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
119 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
120 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
121 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
122 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
123 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
124 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
125 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
127 // Other instructions...
128 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
129 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
130 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
131 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
132 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
133 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
134 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
135 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
136 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
137 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
138 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
139 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
140 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
141 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
142 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
146 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
147 cl::desc("Enable verbose messages in the \"fast\" "
148 "instruction selector"));
150 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
151 cl::desc("Enable abort calls when \"fast\" instruction selection "
152 "fails to lower an instruction"));
154 EnableFastISelAbortArgs("fast-isel-abort-args", cl::Hidden,
155 cl::desc("Enable abort calls when \"fast\" instruction selection "
156 "fails to lower a formal argument"));
160 cl::desc("use Machine Branch Probability Info"),
161 cl::init(true), cl::Hidden);
165 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
166 cl::desc("Pop up a window to show dags before the first "
167 "dag combine pass"));
169 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
170 cl::desc("Pop up a window to show dags before legalize types"));
172 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
173 cl::desc("Pop up a window to show dags before legalize"));
175 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
176 cl::desc("Pop up a window to show dags before the second "
177 "dag combine pass"));
179 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
180 cl::desc("Pop up a window to show dags before the post legalize types"
181 " dag combine pass"));
183 ViewISelDAGs("view-isel-dags", cl::Hidden,
184 cl::desc("Pop up a window to show isel dags as they are selected"));
186 ViewSchedDAGs("view-sched-dags", cl::Hidden,
187 cl::desc("Pop up a window to show sched dags as they are processed"));
189 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
190 cl::desc("Pop up a window to show SUnit dags after they are processed"));
192 static const bool ViewDAGCombine1 = false,
193 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
194 ViewDAGCombine2 = false,
195 ViewDAGCombineLT = false,
196 ViewISelDAGs = false, ViewSchedDAGs = false,
197 ViewSUnitDAGs = false;
200 //===---------------------------------------------------------------------===//
202 /// RegisterScheduler class - Track the registration of instruction schedulers.
204 //===---------------------------------------------------------------------===//
205 MachinePassRegistry RegisterScheduler::Registry;
207 //===---------------------------------------------------------------------===//
209 /// ISHeuristic command line option for instruction schedulers.
211 //===---------------------------------------------------------------------===//
212 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
213 RegisterPassParser<RegisterScheduler> >
214 ISHeuristic("pre-RA-sched",
215 cl::init(&createDefaultScheduler),
216 cl::desc("Instruction schedulers available (before register"
219 static RegisterScheduler
220 defaultListDAGScheduler("default", "Best scheduler for the target",
221 createDefaultScheduler);
224 //===--------------------------------------------------------------------===//
225 /// createDefaultScheduler - This creates an instruction scheduler appropriate
227 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
228 CodeGenOpt::Level OptLevel) {
229 const TargetLowering *TLI = IS->getTargetLowering();
230 const TargetSubtargetInfo &ST = IS->TM.getSubtarget<TargetSubtargetInfo>();
232 if (OptLevel == CodeGenOpt::None || ST.enableMachineScheduler() ||
233 TLI->getSchedulingPreference() == Sched::Source)
234 return createSourceListDAGScheduler(IS, OptLevel);
235 if (TLI->getSchedulingPreference() == Sched::RegPressure)
236 return createBURRListDAGScheduler(IS, OptLevel);
237 if (TLI->getSchedulingPreference() == Sched::Hybrid)
238 return createHybridListDAGScheduler(IS, OptLevel);
239 if (TLI->getSchedulingPreference() == Sched::VLIW)
240 return createVLIWDAGScheduler(IS, OptLevel);
241 assert(TLI->getSchedulingPreference() == Sched::ILP &&
242 "Unknown sched type!");
243 return createILPListDAGScheduler(IS, OptLevel);
247 // EmitInstrWithCustomInserter - This method should be implemented by targets
248 // that mark instructions with the 'usesCustomInserter' flag. These
249 // instructions are special in various ways, which require special support to
250 // insert. The specified MachineInstr is created but not inserted into any
251 // basic blocks, and this method is called to expand it into a sequence of
252 // instructions, potentially also creating new basic blocks and control flow.
253 // When new basic blocks are inserted and the edges from MBB to its successors
254 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
257 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
258 MachineBasicBlock *MBB) const {
260 dbgs() << "If a target marks an instruction with "
261 "'usesCustomInserter', it must implement "
262 "TargetLowering::EmitInstrWithCustomInserter!";
267 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
268 SDNode *Node) const {
269 assert(!MI->hasPostISelHook() &&
270 "If a target marks an instruction with 'hasPostISelHook', "
271 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
274 //===----------------------------------------------------------------------===//
275 // SelectionDAGISel code
276 //===----------------------------------------------------------------------===//
278 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
279 CodeGenOpt::Level OL) :
280 MachineFunctionPass(ID), TM(tm),
281 FuncInfo(new FunctionLoweringInfo(TM)),
282 CurDAG(new SelectionDAG(tm, OL)),
283 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
287 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
288 initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
289 initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
290 initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
293 SelectionDAGISel::~SelectionDAGISel() {
299 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
300 AU.addRequired<AliasAnalysis>();
301 AU.addPreserved<AliasAnalysis>();
302 AU.addRequired<GCModuleInfo>();
303 AU.addPreserved<GCModuleInfo>();
304 AU.addRequired<TargetLibraryInfo>();
305 if (UseMBPI && OptLevel != CodeGenOpt::None)
306 AU.addRequired<BranchProbabilityInfo>();
307 MachineFunctionPass::getAnalysisUsage(AU);
310 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
311 /// may trap on it. In this case we have to split the edge so that the path
312 /// through the predecessor block that doesn't go to the phi block doesn't
313 /// execute the possibly trapping instruction.
315 /// This is required for correctness, so it must be done at -O0.
317 static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
318 // Loop for blocks with phi nodes.
319 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
320 PHINode *PN = dyn_cast<PHINode>(BB->begin());
321 if (PN == 0) continue;
324 // For each block with a PHI node, check to see if any of the input values
325 // are potentially trapping constant expressions. Constant expressions are
326 // the only potentially trapping value that can occur as the argument to a
328 for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
330 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
331 if (CE == 0 || !CE->canTrap()) continue;
333 // The only case we have to worry about is when the edge is critical.
334 // Since this block has a PHI Node, we assume it has multiple input
335 // edges: check to see if the pred has multiple successors.
336 BasicBlock *Pred = PN->getIncomingBlock(i);
337 if (Pred->getTerminator()->getNumSuccessors() == 1)
340 // Okay, we have to split this edge.
341 SplitCriticalEdge(Pred->getTerminator(),
342 GetSuccessorNumber(Pred, BB), SDISel, true);
348 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
349 // Do some sanity-checking on the command-line options.
350 assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
351 "-fast-isel-verbose requires -fast-isel");
352 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
353 "-fast-isel-abort requires -fast-isel");
355 const Function &Fn = *mf.getFunction();
356 const TargetInstrInfo &TII = *TM.getInstrInfo();
357 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
360 RegInfo = &MF->getRegInfo();
361 AA = &getAnalysis<AliasAnalysis>();
362 LibInfo = &getAnalysis<TargetLibraryInfo>();
363 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
364 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
366 TargetSubtargetInfo &ST =
367 const_cast<TargetSubtargetInfo&>(TM.getSubtarget<TargetSubtargetInfo>());
368 ST.resetSubtargetFeatures(MF);
369 TM.resetTargetOptions(MF);
371 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
373 SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
375 CurDAG->init(*MF, TTI);
376 FuncInfo->set(Fn, *MF);
378 if (UseMBPI && OptLevel != CodeGenOpt::None)
379 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
383 SDB->init(GFI, *AA, LibInfo);
385 MF->setHasMSInlineAsm(false);
386 SelectAllBasicBlocks(Fn);
388 // If the first basic block in the function has live ins that need to be
389 // copied into vregs, emit the copies into the top of the block before
390 // emitting the code for the block.
391 MachineBasicBlock *EntryMBB = MF->begin();
392 RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
394 DenseMap<unsigned, unsigned> LiveInMap;
395 if (!FuncInfo->ArgDbgValues.empty())
396 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
397 E = RegInfo->livein_end(); LI != E; ++LI)
399 LiveInMap.insert(std::make_pair(LI->first, LI->second));
401 // Insert DBG_VALUE instructions for function arguments to the entry block.
402 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
403 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
404 bool hasFI = MI->getOperand(0).isFI();
405 unsigned Reg = hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
406 if (TargetRegisterInfo::isPhysicalRegister(Reg))
407 EntryMBB->insert(EntryMBB->begin(), MI);
409 MachineInstr *Def = RegInfo->getVRegDef(Reg);
410 MachineBasicBlock::iterator InsertPos = Def;
411 // FIXME: VR def may not be in entry block.
412 Def->getParent()->insert(llvm::next(InsertPos), MI);
415 // If Reg is live-in then update debug info to track its copy in a vreg.
416 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
417 if (LDI != LiveInMap.end()) {
418 assert(!hasFI && "There's no handling of frame pointer updating here yet "
420 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
421 MachineBasicBlock::iterator InsertPos = Def;
422 const MDNode *Variable =
423 MI->getOperand(MI->getNumOperands()-1).getMetadata();
424 bool IsIndirect = MI->getOperand(1).isImm();
425 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
426 // Def is never a terminator here, so it is ok to increment InsertPos.
427 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
428 TII.get(TargetOpcode::DBG_VALUE),
430 LDI->second, Offset, Variable);
432 // If this vreg is directly copied into an exported register then
433 // that COPY instructions also need DBG_VALUE, if it is the only
434 // user of LDI->second.
435 MachineInstr *CopyUseMI = NULL;
436 for (MachineRegisterInfo::use_iterator
437 UI = RegInfo->use_begin(LDI->second);
438 MachineInstr *UseMI = UI.skipInstruction();) {
439 if (UseMI->isDebugValue()) continue;
440 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
441 CopyUseMI = UseMI; continue;
443 // Otherwise this is another use or second copy use.
444 CopyUseMI = NULL; break;
447 MachineInstr *NewMI =
448 BuildMI(*MF, CopyUseMI->getDebugLoc(),
449 TII.get(TargetOpcode::DBG_VALUE),
451 CopyUseMI->getOperand(0).getReg(),
453 MachineBasicBlock::iterator Pos = CopyUseMI;
454 EntryMBB->insertAfter(Pos, NewMI);
459 // Determine if there are any calls in this machine function.
460 MachineFrameInfo *MFI = MF->getFrameInfo();
461 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
464 if (MFI->hasCalls() && MF->hasMSInlineAsm())
467 const MachineBasicBlock *MBB = I;
468 for (MachineBasicBlock::const_iterator II = MBB->begin(), IE = MBB->end();
470 const MCInstrDesc &MCID = TM.getInstrInfo()->get(II->getOpcode());
471 if ((MCID.isCall() && !MCID.isReturn()) ||
472 II->isStackAligningInlineAsm()) {
473 MFI->setHasCalls(true);
475 if (II->isMSInlineAsm()) {
476 MF->setHasMSInlineAsm(true);
481 // Determine if there is a call to setjmp in the machine function.
482 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
484 // Replace forward-declared registers with the registers containing
485 // the desired value.
486 MachineRegisterInfo &MRI = MF->getRegInfo();
487 for (DenseMap<unsigned, unsigned>::iterator
488 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
490 unsigned From = I->first;
491 unsigned To = I->second;
492 // If To is also scheduled to be replaced, find what its ultimate
495 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
500 MRI.replaceRegWith(From, To);
503 // Freeze the set of reserved registers now that MachineFrameInfo has been
504 // set up. All the information required by getReservedRegs() should be
506 MRI.freezeReservedRegs(*MF);
508 // Release function-specific state. SDB and CurDAG are already cleared
515 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
516 BasicBlock::const_iterator End,
518 // Lower all of the non-terminator instructions. If a call is emitted
519 // as a tail call, cease emitting nodes for this block. Terminators
520 // are handled below.
521 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
524 // Make sure the root of the DAG is up-to-date.
525 CurDAG->setRoot(SDB->getControlRoot());
526 HadTailCall = SDB->HasTailCall;
529 // Final step, emit the lowered DAG as machine code.
533 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
534 SmallPtrSet<SDNode*, 128> VisitedNodes;
535 SmallVector<SDNode*, 128> Worklist;
537 Worklist.push_back(CurDAG->getRoot().getNode());
543 SDNode *N = Worklist.pop_back_val();
545 // If we've already seen this node, ignore it.
546 if (!VisitedNodes.insert(N))
549 // Otherwise, add all chain operands to the worklist.
550 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
551 if (N->getOperand(i).getValueType() == MVT::Other)
552 Worklist.push_back(N->getOperand(i).getNode());
554 // If this is a CopyToReg with a vreg dest, process it.
555 if (N->getOpcode() != ISD::CopyToReg)
558 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
559 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
562 // Ignore non-scalar or non-integer values.
563 SDValue Src = N->getOperand(2);
564 EVT SrcVT = Src.getValueType();
565 if (!SrcVT.isInteger() || SrcVT.isVector())
568 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
569 CurDAG->ComputeMaskedBits(Src, KnownZero, KnownOne);
570 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
571 } while (!Worklist.empty());
574 void SelectionDAGISel::CodeGenAndEmitDAG() {
575 std::string GroupName;
576 if (TimePassesIsEnabled)
577 GroupName = "Instruction Selection and Scheduling";
578 std::string BlockName;
579 int BlockNumber = -1;
582 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
583 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
587 BlockNumber = FuncInfo->MBB->getNumber();
588 BlockName = MF->getName().str() + ":" +
589 FuncInfo->MBB->getBasicBlock()->getName().str();
591 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
592 << " '" << BlockName << "'\n"; CurDAG->dump());
594 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
596 // Run the DAG combiner in pre-legalize mode.
598 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
599 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
602 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
603 << " '" << BlockName << "'\n"; CurDAG->dump());
605 // Second step, hack on the DAG until it only uses operations and types that
606 // the target supports.
607 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
612 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
613 Changed = CurDAG->LegalizeTypes();
616 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
617 << " '" << BlockName << "'\n"; CurDAG->dump());
620 if (ViewDAGCombineLT)
621 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
623 // Run the DAG combiner in post-type-legalize mode.
625 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
626 TimePassesIsEnabled);
627 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
630 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
631 << " '" << BlockName << "'\n"; CurDAG->dump());
636 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
637 Changed = CurDAG->LegalizeVectors();
642 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
643 CurDAG->LegalizeTypes();
646 if (ViewDAGCombineLT)
647 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
649 // Run the DAG combiner in post-type-legalize mode.
651 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
652 TimePassesIsEnabled);
653 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
656 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
657 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
660 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
663 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
667 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
668 << " '" << BlockName << "'\n"; CurDAG->dump());
670 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
672 // Run the DAG combiner in post-legalize mode.
674 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
675 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
678 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
679 << " '" << BlockName << "'\n"; CurDAG->dump());
681 if (OptLevel != CodeGenOpt::None)
682 ComputeLiveOutVRegInfo();
684 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
686 // Third, instruction select all of the operations to machine code, adding the
687 // code to the MachineBasicBlock.
689 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
690 DoInstructionSelection();
693 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
694 << " '" << BlockName << "'\n"; CurDAG->dump());
696 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
698 // Schedule machine code.
699 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
701 NamedRegionTimer T("Instruction Scheduling", GroupName,
702 TimePassesIsEnabled);
703 Scheduler->Run(CurDAG, FuncInfo->MBB);
706 if (ViewSUnitDAGs) Scheduler->viewGraph();
708 // Emit machine code to BB. This can change 'BB' to the last block being
710 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
712 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
714 // FuncInfo->InsertPt is passed by reference and set to the end of the
715 // scheduled instructions.
716 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
719 // If the block was split, make sure we update any references that are used to
720 // update PHI nodes later on.
721 if (FirstMBB != LastMBB)
722 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
724 // Free the scheduler state.
726 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
727 TimePassesIsEnabled);
731 // Free the SelectionDAG state, now that we're finished with it.
736 /// ISelUpdater - helper class to handle updates of the instruction selection
738 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
739 SelectionDAG::allnodes_iterator &ISelPosition;
741 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
742 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
744 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
745 /// deleted is the current ISelPosition node, update ISelPosition.
747 virtual void NodeDeleted(SDNode *N, SDNode *E) {
748 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
752 } // end anonymous namespace
754 void SelectionDAGISel::DoInstructionSelection() {
755 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
756 << FuncInfo->MBB->getNumber()
757 << " '" << FuncInfo->MBB->getName() << "'\n");
761 // Select target instructions for the DAG.
763 // Number all nodes with a topological order and set DAGSize.
764 DAGSize = CurDAG->AssignTopologicalOrder();
766 // Create a dummy node (which is not added to allnodes), that adds
767 // a reference to the root node, preventing it from being deleted,
768 // and tracking any changes of the root.
769 HandleSDNode Dummy(CurDAG->getRoot());
770 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
773 // Make sure that ISelPosition gets properly updated when nodes are deleted
774 // in calls made from this function.
775 ISelUpdater ISU(*CurDAG, ISelPosition);
777 // The AllNodes list is now topological-sorted. Visit the
778 // nodes by starting at the end of the list (the root of the
779 // graph) and preceding back toward the beginning (the entry
781 while (ISelPosition != CurDAG->allnodes_begin()) {
782 SDNode *Node = --ISelPosition;
783 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
784 // but there are currently some corner cases that it misses. Also, this
785 // makes it theoretically possible to disable the DAGCombiner.
786 if (Node->use_empty())
789 SDNode *ResNode = Select(Node);
791 // FIXME: This is pretty gross. 'Select' should be changed to not return
792 // anything at all and this code should be nuked with a tactical strike.
794 // If node should not be replaced, continue with the next one.
795 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
799 ReplaceUses(Node, ResNode);
802 // If after the replacement this node is not used any more,
803 // remove this dead node.
804 if (Node->use_empty()) // Don't delete EntryToken, etc.
805 CurDAG->RemoveDeadNode(Node);
808 CurDAG->setRoot(Dummy.getValue());
811 DEBUG(dbgs() << "===== Instruction selection ends:\n");
813 PostprocessISelDAG();
816 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
817 /// do other setup for EH landing-pad blocks.
818 void SelectionDAGISel::PrepareEHLandingPad() {
819 MachineBasicBlock *MBB = FuncInfo->MBB;
821 // Add a label to mark the beginning of the landing pad. Deletion of the
822 // landing pad can thus be detected via the MachineModuleInfo.
823 MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
825 // Assign the call site to the landing pad's begin label.
826 MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
828 const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
829 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
832 // Mark exception register as live in.
833 const TargetLowering *TLI = getTargetLowering();
834 const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy());
835 if (unsigned Reg = TLI->getExceptionPointerRegister())
836 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
838 // Mark exception selector register as live in.
839 if (unsigned Reg = TLI->getExceptionSelectorRegister())
840 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
843 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
844 /// side-effect free and is either dead or folded into a generated instruction.
845 /// Return false if it needs to be emitted.
846 static bool isFoldedOrDeadInstruction(const Instruction *I,
847 FunctionLoweringInfo *FuncInfo) {
848 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
849 !isa<TerminatorInst>(I) && // Terminators aren't folded.
850 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
851 !isa<LandingPadInst>(I) && // Landingpad instructions aren't folded.
852 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
856 // Collect per Instruction statistics for fast-isel misses. Only those
857 // instructions that cause the bail are accounted for. It does not account for
858 // instructions higher in the block. Thus, summing the per instructions stats
859 // will not add up to what is reported by NumFastIselFailures.
860 static void collectFailStats(const Instruction *I) {
861 switch (I->getOpcode()) {
862 default: assert (0 && "<Invalid operator> ");
865 case Instruction::Ret: NumFastIselFailRet++; return;
866 case Instruction::Br: NumFastIselFailBr++; return;
867 case Instruction::Switch: NumFastIselFailSwitch++; return;
868 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
869 case Instruction::Invoke: NumFastIselFailInvoke++; return;
870 case Instruction::Resume: NumFastIselFailResume++; return;
871 case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
873 // Standard binary operators...
874 case Instruction::Add: NumFastIselFailAdd++; return;
875 case Instruction::FAdd: NumFastIselFailFAdd++; return;
876 case Instruction::Sub: NumFastIselFailSub++; return;
877 case Instruction::FSub: NumFastIselFailFSub++; return;
878 case Instruction::Mul: NumFastIselFailMul++; return;
879 case Instruction::FMul: NumFastIselFailFMul++; return;
880 case Instruction::UDiv: NumFastIselFailUDiv++; return;
881 case Instruction::SDiv: NumFastIselFailSDiv++; return;
882 case Instruction::FDiv: NumFastIselFailFDiv++; return;
883 case Instruction::URem: NumFastIselFailURem++; return;
884 case Instruction::SRem: NumFastIselFailSRem++; return;
885 case Instruction::FRem: NumFastIselFailFRem++; return;
887 // Logical operators...
888 case Instruction::And: NumFastIselFailAnd++; return;
889 case Instruction::Or: NumFastIselFailOr++; return;
890 case Instruction::Xor: NumFastIselFailXor++; return;
892 // Memory instructions...
893 case Instruction::Alloca: NumFastIselFailAlloca++; return;
894 case Instruction::Load: NumFastIselFailLoad++; return;
895 case Instruction::Store: NumFastIselFailStore++; return;
896 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
897 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
898 case Instruction::Fence: NumFastIselFailFence++; return;
899 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
901 // Convert instructions...
902 case Instruction::Trunc: NumFastIselFailTrunc++; return;
903 case Instruction::ZExt: NumFastIselFailZExt++; return;
904 case Instruction::SExt: NumFastIselFailSExt++; return;
905 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
906 case Instruction::FPExt: NumFastIselFailFPExt++; return;
907 case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
908 case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
909 case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
910 case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
911 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
912 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
913 case Instruction::BitCast: NumFastIselFailBitCast++; return;
915 // Other instructions...
916 case Instruction::ICmp: NumFastIselFailICmp++; return;
917 case Instruction::FCmp: NumFastIselFailFCmp++; return;
918 case Instruction::PHI: NumFastIselFailPHI++; return;
919 case Instruction::Select: NumFastIselFailSelect++; return;
920 case Instruction::Call: NumFastIselFailCall++; return;
921 case Instruction::Shl: NumFastIselFailShl++; return;
922 case Instruction::LShr: NumFastIselFailLShr++; return;
923 case Instruction::AShr: NumFastIselFailAShr++; return;
924 case Instruction::VAArg: NumFastIselFailVAArg++; return;
925 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
926 case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
927 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
928 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
929 case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
930 case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
935 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
936 // Initialize the Fast-ISel state, if needed.
937 FastISel *FastIS = 0;
938 if (TM.Options.EnableFastISel)
939 FastIS = getTargetLowering()->createFastISel(*FuncInfo, LibInfo);
941 // Iterate over all basic blocks in the function.
942 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
943 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
944 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
945 const BasicBlock *LLVMBB = *I;
947 if (OptLevel != CodeGenOpt::None) {
948 bool AllPredsVisited = true;
949 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
951 if (!FuncInfo->VisitedBBs.count(*PI)) {
952 AllPredsVisited = false;
957 if (AllPredsVisited) {
958 for (BasicBlock::const_iterator I = LLVMBB->begin();
959 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
960 FuncInfo->ComputePHILiveOutRegInfo(PN);
962 for (BasicBlock::const_iterator I = LLVMBB->begin();
963 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
964 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
967 FuncInfo->VisitedBBs.insert(LLVMBB);
970 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
971 BasicBlock::const_iterator const End = LLVMBB->end();
972 BasicBlock::const_iterator BI = End;
974 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
975 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
977 // Setup an EH landing-pad block.
978 FuncInfo->ExceptionPointerVirtReg = 0;
979 FuncInfo->ExceptionSelectorVirtReg = 0;
980 if (FuncInfo->MBB->isLandingPad())
981 PrepareEHLandingPad();
983 // Before doing SelectionDAG ISel, see if FastISel has been requested.
985 FastIS->startNewBlock();
987 // Emit code for any incoming arguments. This must happen before
988 // beginning FastISel on the entry block.
989 if (LLVMBB == &Fn.getEntryBlock()) {
992 // Lower any arguments needed in this block if this is the entry block.
993 if (!FastIS->LowerArguments()) {
994 // Fast isel failed to lower these arguments
995 ++NumFastIselFailLowerArguments;
996 if (EnableFastISelAbortArgs)
997 llvm_unreachable("FastISel didn't lower all arguments");
999 // Use SelectionDAG argument lowering
1001 CurDAG->setRoot(SDB->getControlRoot());
1003 CodeGenAndEmitDAG();
1006 // If we inserted any instructions at the beginning, make a note of
1007 // where they are, so we can be sure to emit subsequent instructions
1009 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1010 FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
1012 FastIS->setLastLocalValue(0);
1015 unsigned NumFastIselRemaining = std::distance(Begin, End);
1016 // Do FastISel on as many instructions as possible.
1017 for (; BI != Begin; --BI) {
1018 const Instruction *Inst = llvm::prior(BI);
1020 // If we no longer require this instruction, skip it.
1021 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1022 --NumFastIselRemaining;
1026 // Bottom-up: reset the insert pos at the top, after any local-value
1028 FastIS->recomputeInsertPt();
1030 // Try to select the instruction with FastISel.
1031 if (FastIS->SelectInstruction(Inst)) {
1032 --NumFastIselRemaining;
1033 ++NumFastIselSuccess;
1034 // If fast isel succeeded, skip over all the folded instructions, and
1035 // then see if there is a load right before the selected instructions.
1036 // Try to fold the load if so.
1037 const Instruction *BeforeInst = Inst;
1038 while (BeforeInst != Begin) {
1039 BeforeInst = llvm::prior(BasicBlock::const_iterator(BeforeInst));
1040 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1043 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1044 BeforeInst->hasOneUse() &&
1045 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1046 // If we succeeded, don't re-select the load.
1047 BI = llvm::next(BasicBlock::const_iterator(BeforeInst));
1048 --NumFastIselRemaining;
1049 ++NumFastIselSuccess;
1055 if (EnableFastISelVerbose2)
1056 collectFailStats(Inst);
1059 // Then handle certain instructions as single-LLVM-Instruction blocks.
1060 if (isa<CallInst>(Inst)) {
1062 if (EnableFastISelVerbose || EnableFastISelAbort) {
1063 dbgs() << "FastISel missed call: ";
1067 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
1068 unsigned &R = FuncInfo->ValueMap[Inst];
1070 R = FuncInfo->CreateRegs(Inst->getType());
1073 bool HadTailCall = false;
1074 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1075 SelectBasicBlock(Inst, BI, HadTailCall);
1077 // If the call was emitted as a tail call, we're done with the block.
1078 // We also need to delete any previously emitted instructions.
1080 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1085 // Recompute NumFastIselRemaining as Selection DAG instruction
1086 // selection may have handled the call, input args, etc.
1087 unsigned RemainingNow = std::distance(Begin, BI);
1088 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1089 NumFastIselRemaining = RemainingNow;
1093 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
1094 // Don't abort, and use a different message for terminator misses.
1095 NumFastIselFailures += NumFastIselRemaining;
1096 if (EnableFastISelVerbose || EnableFastISelAbort) {
1097 dbgs() << "FastISel missed terminator: ";
1101 NumFastIselFailures += NumFastIselRemaining;
1102 if (EnableFastISelVerbose || EnableFastISelAbort) {
1103 dbgs() << "FastISel miss: ";
1106 if (EnableFastISelAbort)
1107 // The "fast" selector couldn't handle something and bailed.
1108 // For the purpose of debugging, just abort.
1109 llvm_unreachable("FastISel didn't select the entire block");
1114 FastIS->recomputeInsertPt();
1116 // Lower any arguments needed in this block if this is the entry block.
1117 if (LLVMBB == &Fn.getEntryBlock()) {
1126 ++NumFastIselBlocks;
1129 // Run SelectionDAG instruction selection on the remainder of the block
1130 // not handled by FastISel. If FastISel is not run, this is the entire
1133 SelectBasicBlock(Begin, BI, HadTailCall);
1137 FuncInfo->PHINodesToUpdate.clear();
1141 SDB->clearDanglingDebugInfo();
1145 SelectionDAGISel::FinishBasicBlock() {
1147 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1148 << FuncInfo->PHINodesToUpdate.size() << "\n";
1149 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1150 dbgs() << "Node " << i << " : ("
1151 << FuncInfo->PHINodesToUpdate[i].first
1152 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1154 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1155 // PHI nodes in successors.
1156 if (SDB->SwitchCases.empty() &&
1157 SDB->JTCases.empty() &&
1158 SDB->BitTestCases.empty()) {
1159 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1160 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1161 assert(PHI->isPHI() &&
1162 "This is not a machine PHI node that we are updating!");
1163 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1165 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1170 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1171 // Lower header first, if it wasn't already lowered
1172 if (!SDB->BitTestCases[i].Emitted) {
1173 // Set the current basic block to the mbb we wish to insert the code into
1174 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1175 FuncInfo->InsertPt = FuncInfo->MBB->end();
1177 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1178 CurDAG->setRoot(SDB->getRoot());
1180 CodeGenAndEmitDAG();
1183 uint32_t UnhandledWeight = 0;
1184 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
1185 UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
1187 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1188 UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
1189 // Set the current basic block to the mbb we wish to insert the code into
1190 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1191 FuncInfo->InsertPt = FuncInfo->MBB->end();
1194 SDB->visitBitTestCase(SDB->BitTestCases[i],
1195 SDB->BitTestCases[i].Cases[j+1].ThisBB,
1197 SDB->BitTestCases[i].Reg,
1198 SDB->BitTestCases[i].Cases[j],
1201 SDB->visitBitTestCase(SDB->BitTestCases[i],
1202 SDB->BitTestCases[i].Default,
1204 SDB->BitTestCases[i].Reg,
1205 SDB->BitTestCases[i].Cases[j],
1209 CurDAG->setRoot(SDB->getRoot());
1211 CodeGenAndEmitDAG();
1215 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1217 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1218 MachineBasicBlock *PHIBB = PHI->getParent();
1219 assert(PHI->isPHI() &&
1220 "This is not a machine PHI node that we are updating!");
1221 // This is "default" BB. We have two jumps to it. From "header" BB and
1222 // from last "case" BB.
1223 if (PHIBB == SDB->BitTestCases[i].Default)
1224 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1225 .addMBB(SDB->BitTestCases[i].Parent)
1226 .addReg(FuncInfo->PHINodesToUpdate[pi].second)
1227 .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
1228 // One of "cases" BB.
1229 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1231 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1232 if (cBB->isSuccessor(PHIBB))
1233 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1237 SDB->BitTestCases.clear();
1239 // If the JumpTable record is filled in, then we need to emit a jump table.
1240 // Updating the PHI nodes is tricky in this case, since we need to determine
1241 // whether the PHI is a successor of the range check MBB or the jump table MBB
1242 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1243 // Lower header first, if it wasn't already lowered
1244 if (!SDB->JTCases[i].first.Emitted) {
1245 // Set the current basic block to the mbb we wish to insert the code into
1246 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1247 FuncInfo->InsertPt = FuncInfo->MBB->end();
1249 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1251 CurDAG->setRoot(SDB->getRoot());
1253 CodeGenAndEmitDAG();
1256 // Set the current basic block to the mbb we wish to insert the code into
1257 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1258 FuncInfo->InsertPt = FuncInfo->MBB->end();
1260 SDB->visitJumpTable(SDB->JTCases[i].second);
1261 CurDAG->setRoot(SDB->getRoot());
1263 CodeGenAndEmitDAG();
1266 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1268 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1269 MachineBasicBlock *PHIBB = PHI->getParent();
1270 assert(PHI->isPHI() &&
1271 "This is not a machine PHI node that we are updating!");
1272 // "default" BB. We can go there only from header BB.
1273 if (PHIBB == SDB->JTCases[i].second.Default)
1274 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1275 .addMBB(SDB->JTCases[i].first.HeaderBB);
1276 // JT BB. Just iterate over successors here
1277 if (FuncInfo->MBB->isSuccessor(PHIBB))
1278 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1281 SDB->JTCases.clear();
1283 // If the switch block involved a branch to one of the actual successors, we
1284 // need to update PHI nodes in that block.
1285 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1286 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1287 assert(PHI->isPHI() &&
1288 "This is not a machine PHI node that we are updating!");
1289 if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
1290 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1293 // If we generated any switch lowering information, build and codegen any
1294 // additional DAGs necessary.
1295 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1296 // Set the current basic block to the mbb we wish to insert the code into
1297 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1298 FuncInfo->InsertPt = FuncInfo->MBB->end();
1300 // Determine the unique successors.
1301 SmallVector<MachineBasicBlock *, 2> Succs;
1302 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1303 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1304 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1306 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1307 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1308 CurDAG->setRoot(SDB->getRoot());
1310 CodeGenAndEmitDAG();
1312 // Remember the last block, now that any splitting is done, for use in
1313 // populating PHI nodes in successors.
1314 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1316 // Handle any PHI nodes in successors of this chunk, as if we were coming
1317 // from the original BB before switch expansion. Note that PHI nodes can
1318 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1319 // handle them the right number of times.
1320 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1321 FuncInfo->MBB = Succs[i];
1322 FuncInfo->InsertPt = FuncInfo->MBB->end();
1323 // FuncInfo->MBB may have been removed from the CFG if a branch was
1325 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1326 for (MachineBasicBlock::iterator
1327 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1328 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1329 MachineInstrBuilder PHI(*MF, MBBI);
1330 // This value for this PHI node is recorded in PHINodesToUpdate.
1331 for (unsigned pn = 0; ; ++pn) {
1332 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1333 "Didn't find PHI entry!");
1334 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1335 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1343 SDB->SwitchCases.clear();
1347 /// Create the scheduler. If a specific scheduler was specified
1348 /// via the SchedulerRegistry, use it, otherwise select the
1349 /// one preferred by the target.
1351 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1352 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1356 RegisterScheduler::setDefault(Ctor);
1359 return Ctor(this, OptLevel);
1362 //===----------------------------------------------------------------------===//
1363 // Helper functions used by the generated instruction selector.
1364 //===----------------------------------------------------------------------===//
1365 // Calls to these methods are generated by tblgen.
1367 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1368 /// the dag combiner simplified the 255, we still want to match. RHS is the
1369 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1370 /// specified in the .td file (e.g. 255).
1371 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1372 int64_t DesiredMaskS) const {
1373 const APInt &ActualMask = RHS->getAPIntValue();
1374 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1376 // If the actual mask exactly matches, success!
1377 if (ActualMask == DesiredMask)
1380 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1381 if (ActualMask.intersects(~DesiredMask))
1384 // Otherwise, the DAG Combiner may have proven that the value coming in is
1385 // either already zero or is not demanded. Check for known zero input bits.
1386 APInt NeededMask = DesiredMask & ~ActualMask;
1387 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1390 // TODO: check to see if missing bits are just not demanded.
1392 // Otherwise, this pattern doesn't match.
1396 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1397 /// the dag combiner simplified the 255, we still want to match. RHS is the
1398 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1399 /// specified in the .td file (e.g. 255).
1400 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1401 int64_t DesiredMaskS) const {
1402 const APInt &ActualMask = RHS->getAPIntValue();
1403 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1405 // If the actual mask exactly matches, success!
1406 if (ActualMask == DesiredMask)
1409 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1410 if (ActualMask.intersects(~DesiredMask))
1413 // Otherwise, the DAG Combiner may have proven that the value coming in is
1414 // either already zero or is not demanded. Check for known zero input bits.
1415 APInt NeededMask = DesiredMask & ~ActualMask;
1417 APInt KnownZero, KnownOne;
1418 CurDAG->ComputeMaskedBits(LHS, KnownZero, KnownOne);
1420 // If all the missing bits in the or are already known to be set, match!
1421 if ((NeededMask & KnownOne) == NeededMask)
1424 // TODO: check to see if missing bits are just not demanded.
1426 // Otherwise, this pattern doesn't match.
1431 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1432 /// by tblgen. Others should not call it.
1433 void SelectionDAGISel::
1434 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1435 std::vector<SDValue> InOps;
1436 std::swap(InOps, Ops);
1438 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1439 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1440 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1441 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1443 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1444 if (InOps[e-1].getValueType() == MVT::Glue)
1445 --e; // Don't process a glue operand if it is here.
1448 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1449 if (!InlineAsm::isMemKind(Flags)) {
1450 // Just skip over this operand, copying the operands verbatim.
1451 Ops.insert(Ops.end(), InOps.begin()+i,
1452 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1453 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1455 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1456 "Memory operand with multiple values?");
1457 // Otherwise, this is a memory operand. Ask the target to select it.
1458 std::vector<SDValue> SelOps;
1459 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1460 report_fatal_error("Could not match memory address. Inline asm"
1463 // Add this to the output node.
1465 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1466 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1467 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1472 // Add the glue input back if present.
1473 if (e != InOps.size())
1474 Ops.push_back(InOps.back());
1477 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1480 static SDNode *findGlueUse(SDNode *N) {
1481 unsigned FlagResNo = N->getNumValues()-1;
1482 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1483 SDUse &Use = I.getUse();
1484 if (Use.getResNo() == FlagResNo)
1485 return Use.getUser();
1490 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1491 /// This function recursively traverses up the operand chain, ignoring
1493 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1494 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1495 bool IgnoreChains) {
1496 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1497 // greater than all of its (recursive) operands. If we scan to a point where
1498 // 'use' is smaller than the node we're scanning for, then we know we will
1501 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1502 // happen because we scan down to newly selected nodes in the case of glue
1504 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1507 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1508 // won't fail if we scan it again.
1509 if (!Visited.insert(Use))
1512 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1513 // Ignore chain uses, they are validated by HandleMergeInputChains.
1514 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1517 SDNode *N = Use->getOperand(i).getNode();
1519 if (Use == ImmedUse || Use == Root)
1520 continue; // We are not looking for immediate use.
1525 // Traverse up the operand chain.
1526 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1532 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1533 /// operand node N of U during instruction selection that starts at Root.
1534 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1535 SDNode *Root) const {
1536 if (OptLevel == CodeGenOpt::None) return false;
1537 return N.hasOneUse();
1540 /// IsLegalToFold - Returns true if the specific operand node N of
1541 /// U can be folded during instruction selection that starts at Root.
1542 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1543 CodeGenOpt::Level OptLevel,
1544 bool IgnoreChains) {
1545 if (OptLevel == CodeGenOpt::None) return false;
1547 // If Root use can somehow reach N through a path that that doesn't contain
1548 // U then folding N would create a cycle. e.g. In the following
1549 // diagram, Root can reach N through X. If N is folded into into Root, then
1550 // X is both a predecessor and a successor of U.
1561 // * indicates nodes to be folded together.
1563 // If Root produces glue, then it gets (even more) interesting. Since it
1564 // will be "glued" together with its glue use in the scheduler, we need to
1565 // check if it might reach N.
1584 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1585 // (call it Fold), then X is a predecessor of GU and a successor of
1586 // Fold. But since Fold and GU are glued together, this will create
1587 // a cycle in the scheduling graph.
1589 // If the node has glue, walk down the graph to the "lowest" node in the
1591 EVT VT = Root->getValueType(Root->getNumValues()-1);
1592 while (VT == MVT::Glue) {
1593 SDNode *GU = findGlueUse(Root);
1597 VT = Root->getValueType(Root->getNumValues()-1);
1599 // If our query node has a glue result with a use, we've walked up it. If
1600 // the user (which has already been selected) has a chain or indirectly uses
1601 // the chain, our WalkChainUsers predicate will not consider it. Because of
1602 // this, we cannot ignore chains in this predicate.
1603 IgnoreChains = false;
1607 SmallPtrSet<SDNode*, 16> Visited;
1608 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1611 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1612 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1613 SelectInlineAsmMemoryOperands(Ops);
1615 EVT VTs[] = { MVT::Other, MVT::Glue };
1616 SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N),
1617 VTs, &Ops[0], Ops.size());
1619 return New.getNode();
1622 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1623 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1626 /// GetVBR - decode a vbr encoding whose top bit is set.
1627 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
1628 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1629 assert(Val >= 128 && "Not a VBR");
1630 Val &= 127; // Remove first vbr bit.
1635 NextBits = MatcherTable[Idx++];
1636 Val |= (NextBits&127) << Shift;
1638 } while (NextBits & 128);
1644 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1645 /// interior glue and chain results to use the new glue and chain results.
1646 void SelectionDAGISel::
1647 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1648 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1650 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1651 bool isMorphNodeTo) {
1652 SmallVector<SDNode*, 4> NowDeadNodes;
1654 // Now that all the normal results are replaced, we replace the chain and
1655 // glue results if present.
1656 if (!ChainNodesMatched.empty()) {
1657 assert(InputChain.getNode() != 0 &&
1658 "Matched input chains but didn't produce a chain");
1659 // Loop over all of the nodes we matched that produced a chain result.
1660 // Replace all the chain results with the final chain we ended up with.
1661 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1662 SDNode *ChainNode = ChainNodesMatched[i];
1664 // If this node was already deleted, don't look at it.
1665 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1668 // Don't replace the results of the root node if we're doing a
1670 if (ChainNode == NodeToMatch && isMorphNodeTo)
1673 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1674 if (ChainVal.getValueType() == MVT::Glue)
1675 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1676 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1677 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
1679 // If the node became dead and we haven't already seen it, delete it.
1680 if (ChainNode->use_empty() &&
1681 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1682 NowDeadNodes.push_back(ChainNode);
1686 // If the result produces glue, update any glue results in the matched
1687 // pattern with the glue result.
1688 if (InputGlue.getNode() != 0) {
1689 // Handle any interior nodes explicitly marked.
1690 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1691 SDNode *FRN = GlueResultNodesMatched[i];
1693 // If this node was already deleted, don't look at it.
1694 if (FRN->getOpcode() == ISD::DELETED_NODE)
1697 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
1698 "Doesn't have a glue result");
1699 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1702 // If the node became dead and we haven't already seen it, delete it.
1703 if (FRN->use_empty() &&
1704 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1705 NowDeadNodes.push_back(FRN);
1709 if (!NowDeadNodes.empty())
1710 CurDAG->RemoveDeadNodes(NowDeadNodes);
1712 DEBUG(dbgs() << "ISEL: Match complete!\n");
1718 CR_LeadsToInteriorNode
1721 /// WalkChainUsers - Walk down the users of the specified chained node that is
1722 /// part of the pattern we're matching, looking at all of the users we find.
1723 /// This determines whether something is an interior node, whether we have a
1724 /// non-pattern node in between two pattern nodes (which prevent folding because
1725 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1726 /// between pattern nodes (in which case the TF becomes part of the pattern).
1728 /// The walk we do here is guaranteed to be small because we quickly get down to
1729 /// already selected nodes "below" us.
1731 WalkChainUsers(const SDNode *ChainedNode,
1732 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1733 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1734 ChainResult Result = CR_Simple;
1736 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1737 E = ChainedNode->use_end(); UI != E; ++UI) {
1738 // Make sure the use is of the chain, not some other value we produce.
1739 if (UI.getUse().getValueType() != MVT::Other) continue;
1743 // If we see an already-selected machine node, then we've gone beyond the
1744 // pattern that we're selecting down into the already selected chunk of the
1746 if (User->isMachineOpcode() ||
1747 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1750 unsigned UserOpcode = User->getOpcode();
1751 if (UserOpcode == ISD::CopyToReg ||
1752 UserOpcode == ISD::CopyFromReg ||
1753 UserOpcode == ISD::INLINEASM ||
1754 UserOpcode == ISD::EH_LABEL ||
1755 UserOpcode == ISD::LIFETIME_START ||
1756 UserOpcode == ISD::LIFETIME_END) {
1757 // If their node ID got reset to -1 then they've already been selected.
1758 // Treat them like a MachineOpcode.
1759 if (User->getNodeId() == -1)
1763 // If we have a TokenFactor, we handle it specially.
1764 if (User->getOpcode() != ISD::TokenFactor) {
1765 // If the node isn't a token factor and isn't part of our pattern, then it
1766 // must be a random chained node in between two nodes we're selecting.
1767 // This happens when we have something like:
1772 // Because we structurally match the load/store as a read/modify/write,
1773 // but the call is chained between them. We cannot fold in this case
1774 // because it would induce a cycle in the graph.
1775 if (!std::count(ChainedNodesInPattern.begin(),
1776 ChainedNodesInPattern.end(), User))
1777 return CR_InducesCycle;
1779 // Otherwise we found a node that is part of our pattern. For example in:
1783 // This would happen when we're scanning down from the load and see the
1784 // store as a user. Record that there is a use of ChainedNode that is
1785 // part of the pattern and keep scanning uses.
1786 Result = CR_LeadsToInteriorNode;
1787 InteriorChainedNodes.push_back(User);
1791 // If we found a TokenFactor, there are two cases to consider: first if the
1792 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1793 // uses of the TF are in our pattern) we just want to ignore it. Second,
1794 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1800 // | \ DAG's like cheese
1803 // [TokenFactor] [Op]
1810 // In this case, the TokenFactor becomes part of our match and we rewrite it
1811 // as a new TokenFactor.
1813 // To distinguish these two cases, do a recursive walk down the uses.
1814 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1816 // If the uses of the TokenFactor are just already-selected nodes, ignore
1817 // it, it is "below" our pattern.
1819 case CR_InducesCycle:
1820 // If the uses of the TokenFactor lead to nodes that are not part of our
1821 // pattern that are not selected, folding would turn this into a cycle,
1823 return CR_InducesCycle;
1824 case CR_LeadsToInteriorNode:
1825 break; // Otherwise, keep processing.
1828 // Okay, we know we're in the interesting interior case. The TokenFactor
1829 // is now going to be considered part of the pattern so that we rewrite its
1830 // uses (it may have uses that are not part of the pattern) with the
1831 // ultimate chain result of the generated code. We will also add its chain
1832 // inputs as inputs to the ultimate TokenFactor we create.
1833 Result = CR_LeadsToInteriorNode;
1834 ChainedNodesInPattern.push_back(User);
1835 InteriorChainedNodes.push_back(User);
1842 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1843 /// operation for when the pattern matched at least one node with a chains. The
1844 /// input vector contains a list of all of the chained nodes that we match. We
1845 /// must determine if this is a valid thing to cover (i.e. matching it won't
1846 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1847 /// be used as the input node chain for the generated nodes.
1849 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1850 SelectionDAG *CurDAG) {
1851 // Walk all of the chained nodes we've matched, recursively scanning down the
1852 // users of the chain result. This adds any TokenFactor nodes that are caught
1853 // in between chained nodes to the chained and interior nodes list.
1854 SmallVector<SDNode*, 3> InteriorChainedNodes;
1855 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1856 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1857 InteriorChainedNodes) == CR_InducesCycle)
1858 return SDValue(); // Would induce a cycle.
1861 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1862 // that we are interested in. Form our input TokenFactor node.
1863 SmallVector<SDValue, 3> InputChains;
1864 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1865 // Add the input chain of this node to the InputChains list (which will be
1866 // the operands of the generated TokenFactor) if it's not an interior node.
1867 SDNode *N = ChainNodesMatched[i];
1868 if (N->getOpcode() != ISD::TokenFactor) {
1869 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1872 // Otherwise, add the input chain.
1873 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1874 assert(InChain.getValueType() == MVT::Other && "Not a chain");
1875 InputChains.push_back(InChain);
1879 // If we have a token factor, we want to add all inputs of the token factor
1880 // that are not part of the pattern we're matching.
1881 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1882 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1883 N->getOperand(op).getNode()))
1884 InputChains.push_back(N->getOperand(op));
1889 if (InputChains.size() == 1)
1890 return InputChains[0];
1891 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
1892 MVT::Other, &InputChains[0], InputChains.size());
1895 /// MorphNode - Handle morphing a node in place for the selector.
1896 SDNode *SelectionDAGISel::
1897 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1898 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1899 // It is possible we're using MorphNodeTo to replace a node with no
1900 // normal results with one that has a normal result (or we could be
1901 // adding a chain) and the input could have glue and chains as well.
1902 // In this case we need to shift the operands down.
1903 // FIXME: This is a horrible hack and broken in obscure cases, no worse
1904 // than the old isel though.
1905 int OldGlueResultNo = -1, OldChainResultNo = -1;
1907 unsigned NTMNumResults = Node->getNumValues();
1908 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
1909 OldGlueResultNo = NTMNumResults-1;
1910 if (NTMNumResults != 1 &&
1911 Node->getValueType(NTMNumResults-2) == MVT::Other)
1912 OldChainResultNo = NTMNumResults-2;
1913 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1914 OldChainResultNo = NTMNumResults-1;
1916 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1917 // that this deletes operands of the old node that become dead.
1918 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1920 // MorphNodeTo can operate in two ways: if an existing node with the
1921 // specified operands exists, it can just return it. Otherwise, it
1922 // updates the node in place to have the requested operands.
1924 // If we updated the node in place, reset the node ID. To the isel,
1925 // this should be just like a newly allocated machine node.
1929 unsigned ResNumResults = Res->getNumValues();
1930 // Move the glue if needed.
1931 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
1932 (unsigned)OldGlueResultNo != ResNumResults-1)
1933 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
1934 SDValue(Res, ResNumResults-1));
1936 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
1939 // Move the chain reference if needed.
1940 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1941 (unsigned)OldChainResultNo != ResNumResults-1)
1942 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1943 SDValue(Res, ResNumResults-1));
1945 // Otherwise, no replacement happened because the node already exists. Replace
1946 // Uses of the old node with the new one.
1948 CurDAG->ReplaceAllUsesWith(Node, Res);
1953 /// CheckSame - Implements OP_CheckSame.
1954 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1955 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1957 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
1958 // Accept if it is exactly the same as a previously recorded node.
1959 unsigned RecNo = MatcherTable[MatcherIndex++];
1960 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1961 return N == RecordedNodes[RecNo].first;
1964 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1965 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1966 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1967 const SelectionDAGISel &SDISel) {
1968 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1971 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
1972 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1973 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1974 const SelectionDAGISel &SDISel, SDNode *N) {
1975 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1978 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1979 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1981 uint16_t Opc = MatcherTable[MatcherIndex++];
1982 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1983 return N->getOpcode() == Opc;
1986 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1987 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1988 SDValue N, const TargetLowering *TLI) {
1989 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1990 if (N.getValueType() == VT) return true;
1992 // Handle the case when VT is iPTR.
1993 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
1996 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1997 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1998 SDValue N, const TargetLowering *TLI,
2000 if (ChildNo >= N.getNumOperands())
2001 return false; // Match fails if out of range child #.
2002 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
2005 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2006 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2008 return cast<CondCodeSDNode>(N)->get() ==
2009 (ISD::CondCode)MatcherTable[MatcherIndex++];
2012 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2013 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2014 SDValue N, const TargetLowering *TLI) {
2015 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2016 if (cast<VTSDNode>(N)->getVT() == VT)
2019 // Handle the case when VT is iPTR.
2020 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
2023 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2024 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2026 int64_t Val = MatcherTable[MatcherIndex++];
2028 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2030 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2031 return C != 0 && C->getSExtValue() == Val;
2034 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2035 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2036 SDValue N, const SelectionDAGISel &SDISel) {
2037 int64_t Val = MatcherTable[MatcherIndex++];
2039 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2041 if (N->getOpcode() != ISD::AND) return false;
2043 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2044 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2047 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2048 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2049 SDValue N, const SelectionDAGISel &SDISel) {
2050 int64_t Val = MatcherTable[MatcherIndex++];
2052 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2054 if (N->getOpcode() != ISD::OR) return false;
2056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2057 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2060 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2061 /// scope, evaluate the current node. If the current predicate is known to
2062 /// fail, set Result=true and return anything. If the current predicate is
2063 /// known to pass, set Result=false and return the MatcherIndex to continue
2064 /// with. If the current predicate is unknown, set Result=false and return the
2065 /// MatcherIndex to continue with.
2066 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2067 unsigned Index, SDValue N,
2069 const SelectionDAGISel &SDISel,
2070 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2071 switch (Table[Index++]) {
2074 return Index-1; // Could not evaluate this predicate.
2075 case SelectionDAGISel::OPC_CheckSame:
2076 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2078 case SelectionDAGISel::OPC_CheckPatternPredicate:
2079 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2081 case SelectionDAGISel::OPC_CheckPredicate:
2082 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2084 case SelectionDAGISel::OPC_CheckOpcode:
2085 Result = !::CheckOpcode(Table, Index, N.getNode());
2087 case SelectionDAGISel::OPC_CheckType:
2088 Result = !::CheckType(Table, Index, N, SDISel.getTargetLowering());
2090 case SelectionDAGISel::OPC_CheckChild0Type:
2091 case SelectionDAGISel::OPC_CheckChild1Type:
2092 case SelectionDAGISel::OPC_CheckChild2Type:
2093 case SelectionDAGISel::OPC_CheckChild3Type:
2094 case SelectionDAGISel::OPC_CheckChild4Type:
2095 case SelectionDAGISel::OPC_CheckChild5Type:
2096 case SelectionDAGISel::OPC_CheckChild6Type:
2097 case SelectionDAGISel::OPC_CheckChild7Type:
2098 Result = !::CheckChildType(Table, Index, N, SDISel.getTargetLowering(),
2099 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
2101 case SelectionDAGISel::OPC_CheckCondCode:
2102 Result = !::CheckCondCode(Table, Index, N);
2104 case SelectionDAGISel::OPC_CheckValueType:
2105 Result = !::CheckValueType(Table, Index, N, SDISel.getTargetLowering());
2107 case SelectionDAGISel::OPC_CheckInteger:
2108 Result = !::CheckInteger(Table, Index, N);
2110 case SelectionDAGISel::OPC_CheckAndImm:
2111 Result = !::CheckAndImm(Table, Index, N, SDISel);
2113 case SelectionDAGISel::OPC_CheckOrImm:
2114 Result = !::CheckOrImm(Table, Index, N, SDISel);
2122 /// FailIndex - If this match fails, this is the index to continue with.
2125 /// NodeStack - The node stack when the scope was formed.
2126 SmallVector<SDValue, 4> NodeStack;
2128 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2129 unsigned NumRecordedNodes;
2131 /// NumMatchedMemRefs - The number of matched memref entries.
2132 unsigned NumMatchedMemRefs;
2134 /// InputChain/InputGlue - The current chain/glue
2135 SDValue InputChain, InputGlue;
2137 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2138 bool HasChainNodesMatched, HasGlueResultNodesMatched;
2143 SDNode *SelectionDAGISel::
2144 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2145 unsigned TableSize) {
2146 // FIXME: Should these even be selected? Handle these cases in the caller?
2147 switch (NodeToMatch->getOpcode()) {
2150 case ISD::EntryToken: // These nodes remain the same.
2151 case ISD::BasicBlock:
2153 case ISD::RegisterMask:
2154 //case ISD::VALUETYPE:
2155 //case ISD::CONDCODE:
2156 case ISD::HANDLENODE:
2157 case ISD::MDNODE_SDNODE:
2158 case ISD::TargetConstant:
2159 case ISD::TargetConstantFP:
2160 case ISD::TargetConstantPool:
2161 case ISD::TargetFrameIndex:
2162 case ISD::TargetExternalSymbol:
2163 case ISD::TargetBlockAddress:
2164 case ISD::TargetJumpTable:
2165 case ISD::TargetGlobalTLSAddress:
2166 case ISD::TargetGlobalAddress:
2167 case ISD::TokenFactor:
2168 case ISD::CopyFromReg:
2169 case ISD::CopyToReg:
2171 case ISD::LIFETIME_START:
2172 case ISD::LIFETIME_END:
2173 NodeToMatch->setNodeId(-1); // Mark selected.
2175 case ISD::AssertSext:
2176 case ISD::AssertZext:
2177 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2178 NodeToMatch->getOperand(0));
2180 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2181 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2184 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2186 // Set up the node stack with NodeToMatch as the only node on the stack.
2187 SmallVector<SDValue, 8> NodeStack;
2188 SDValue N = SDValue(NodeToMatch, 0);
2189 NodeStack.push_back(N);
2191 // MatchScopes - Scopes used when matching, if a match failure happens, this
2192 // indicates where to continue checking.
2193 SmallVector<MatchScope, 8> MatchScopes;
2195 // RecordedNodes - This is the set of nodes that have been recorded by the
2196 // state machine. The second value is the parent of the node, or null if the
2197 // root is recorded.
2198 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2200 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2202 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2204 // These are the current input chain and glue for use when generating nodes.
2205 // Various Emit operations change these. For example, emitting a copytoreg
2206 // uses and updates these.
2207 SDValue InputChain, InputGlue;
2209 // ChainNodesMatched - If a pattern matches nodes that have input/output
2210 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2211 // which ones they are. The result is captured into this list so that we can
2212 // update the chain results when the pattern is complete.
2213 SmallVector<SDNode*, 3> ChainNodesMatched;
2214 SmallVector<SDNode*, 3> GlueResultNodesMatched;
2216 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2217 NodeToMatch->dump(CurDAG);
2220 // Determine where to start the interpreter. Normally we start at opcode #0,
2221 // but if the state machine starts with an OPC_SwitchOpcode, then we
2222 // accelerate the first lookup (which is guaranteed to be hot) with the
2223 // OpcodeOffset table.
2224 unsigned MatcherIndex = 0;
2226 if (!OpcodeOffset.empty()) {
2227 // Already computed the OpcodeOffset table, just index into it.
2228 if (N.getOpcode() < OpcodeOffset.size())
2229 MatcherIndex = OpcodeOffset[N.getOpcode()];
2230 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2232 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2233 // Otherwise, the table isn't computed, but the state machine does start
2234 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2235 // is the first time we're selecting an instruction.
2238 // Get the size of this case.
2239 unsigned CaseSize = MatcherTable[Idx++];
2241 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2242 if (CaseSize == 0) break;
2244 // Get the opcode, add the index to the table.
2245 uint16_t Opc = MatcherTable[Idx++];
2246 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2247 if (Opc >= OpcodeOffset.size())
2248 OpcodeOffset.resize((Opc+1)*2);
2249 OpcodeOffset[Opc] = Idx;
2253 // Okay, do the lookup for the first opcode.
2254 if (N.getOpcode() < OpcodeOffset.size())
2255 MatcherIndex = OpcodeOffset[N.getOpcode()];
2259 assert(MatcherIndex < TableSize && "Invalid index");
2261 unsigned CurrentOpcodeIndex = MatcherIndex;
2263 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2266 // Okay, the semantics of this operation are that we should push a scope
2267 // then evaluate the first child. However, pushing a scope only to have
2268 // the first check fail (which then pops it) is inefficient. If we can
2269 // determine immediately that the first check (or first several) will
2270 // immediately fail, don't even bother pushing a scope for them.
2274 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2275 if (NumToSkip & 128)
2276 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2277 // Found the end of the scope with no match.
2278 if (NumToSkip == 0) {
2283 FailIndex = MatcherIndex+NumToSkip;
2285 unsigned MatcherIndexOfPredicate = MatcherIndex;
2286 (void)MatcherIndexOfPredicate; // silence warning.
2288 // If we can't evaluate this predicate without pushing a scope (e.g. if
2289 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2290 // push the scope and evaluate the full predicate chain.
2292 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2293 Result, *this, RecordedNodes);
2297 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
2298 << "index " << MatcherIndexOfPredicate
2299 << ", continuing at " << FailIndex << "\n");
2300 ++NumDAGIselRetries;
2302 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2303 // move to the next case.
2304 MatcherIndex = FailIndex;
2307 // If the whole scope failed to match, bail.
2308 if (FailIndex == 0) break;
2310 // Push a MatchScope which indicates where to go if the first child fails
2312 MatchScope NewEntry;
2313 NewEntry.FailIndex = FailIndex;
2314 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2315 NewEntry.NumRecordedNodes = RecordedNodes.size();
2316 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2317 NewEntry.InputChain = InputChain;
2318 NewEntry.InputGlue = InputGlue;
2319 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2320 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2321 MatchScopes.push_back(NewEntry);
2324 case OPC_RecordNode: {
2325 // Remember this node, it may end up being an operand in the pattern.
2327 if (NodeStack.size() > 1)
2328 Parent = NodeStack[NodeStack.size()-2].getNode();
2329 RecordedNodes.push_back(std::make_pair(N, Parent));
2333 case OPC_RecordChild0: case OPC_RecordChild1:
2334 case OPC_RecordChild2: case OPC_RecordChild3:
2335 case OPC_RecordChild4: case OPC_RecordChild5:
2336 case OPC_RecordChild6: case OPC_RecordChild7: {
2337 unsigned ChildNo = Opcode-OPC_RecordChild0;
2338 if (ChildNo >= N.getNumOperands())
2339 break; // Match fails if out of range child #.
2341 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2345 case OPC_RecordMemRef:
2346 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2349 case OPC_CaptureGlueInput:
2350 // If the current node has an input glue, capture it in InputGlue.
2351 if (N->getNumOperands() != 0 &&
2352 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2353 InputGlue = N->getOperand(N->getNumOperands()-1);
2356 case OPC_MoveChild: {
2357 unsigned ChildNo = MatcherTable[MatcherIndex++];
2358 if (ChildNo >= N.getNumOperands())
2359 break; // Match fails if out of range child #.
2360 N = N.getOperand(ChildNo);
2361 NodeStack.push_back(N);
2365 case OPC_MoveParent:
2366 // Pop the current node off the NodeStack.
2367 NodeStack.pop_back();
2368 assert(!NodeStack.empty() && "Node stack imbalance!");
2369 N = NodeStack.back();
2373 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2375 case OPC_CheckPatternPredicate:
2376 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2378 case OPC_CheckPredicate:
2379 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2383 case OPC_CheckComplexPat: {
2384 unsigned CPNum = MatcherTable[MatcherIndex++];
2385 unsigned RecNo = MatcherTable[MatcherIndex++];
2386 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2387 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2388 RecordedNodes[RecNo].first, CPNum,
2393 case OPC_CheckOpcode:
2394 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2398 if (!::CheckType(MatcherTable, MatcherIndex, N, getTargetLowering()))
2402 case OPC_SwitchOpcode: {
2403 unsigned CurNodeOpcode = N.getOpcode();
2404 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2407 // Get the size of this case.
2408 CaseSize = MatcherTable[MatcherIndex++];
2410 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2411 if (CaseSize == 0) break;
2413 uint16_t Opc = MatcherTable[MatcherIndex++];
2414 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2416 // If the opcode matches, then we will execute this case.
2417 if (CurNodeOpcode == Opc)
2420 // Otherwise, skip over this case.
2421 MatcherIndex += CaseSize;
2424 // If no cases matched, bail out.
2425 if (CaseSize == 0) break;
2427 // Otherwise, execute the case we found.
2428 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
2429 << " to " << MatcherIndex << "\n");
2433 case OPC_SwitchType: {
2434 MVT CurNodeVT = N.getValueType().getSimpleVT();
2435 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2438 // Get the size of this case.
2439 CaseSize = MatcherTable[MatcherIndex++];
2441 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2442 if (CaseSize == 0) break;
2444 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2445 if (CaseVT == MVT::iPTR)
2446 CaseVT = getTargetLowering()->getPointerTy();
2448 // If the VT matches, then we will execute this case.
2449 if (CurNodeVT == CaseVT)
2452 // Otherwise, skip over this case.
2453 MatcherIndex += CaseSize;
2456 // If no cases matched, bail out.
2457 if (CaseSize == 0) break;
2459 // Otherwise, execute the case we found.
2460 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2461 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2464 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2465 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2466 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2467 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2468 if (!::CheckChildType(MatcherTable, MatcherIndex, N, getTargetLowering(),
2469 Opcode-OPC_CheckChild0Type))
2472 case OPC_CheckCondCode:
2473 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2475 case OPC_CheckValueType:
2476 if (!::CheckValueType(MatcherTable, MatcherIndex, N, getTargetLowering()))
2479 case OPC_CheckInteger:
2480 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2482 case OPC_CheckAndImm:
2483 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2485 case OPC_CheckOrImm:
2486 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2489 case OPC_CheckFoldableChainNode: {
2490 assert(NodeStack.size() != 1 && "No parent node");
2491 // Verify that all intermediate nodes between the root and this one have
2493 bool HasMultipleUses = false;
2494 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2495 if (!NodeStack[i].hasOneUse()) {
2496 HasMultipleUses = true;
2499 if (HasMultipleUses) break;
2501 // Check to see that the target thinks this is profitable to fold and that
2502 // we can fold it without inducing cycles in the graph.
2503 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2505 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2506 NodeToMatch, OptLevel,
2507 true/*We validate our own chains*/))
2512 case OPC_EmitInteger: {
2513 MVT::SimpleValueType VT =
2514 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2515 int64_t Val = MatcherTable[MatcherIndex++];
2517 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2518 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2519 CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
2522 case OPC_EmitRegister: {
2523 MVT::SimpleValueType VT =
2524 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2525 unsigned RegNo = MatcherTable[MatcherIndex++];
2526 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2527 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2530 case OPC_EmitRegister2: {
2531 // For targets w/ more than 256 register names, the register enum
2532 // values are stored in two bytes in the matcher table (just like
2534 MVT::SimpleValueType VT =
2535 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2536 unsigned RegNo = MatcherTable[MatcherIndex++];
2537 RegNo |= MatcherTable[MatcherIndex++] << 8;
2538 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2539 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2543 case OPC_EmitConvertToTarget: {
2544 // Convert from IMM/FPIMM to target version.
2545 unsigned RecNo = MatcherTable[MatcherIndex++];
2546 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2547 SDValue Imm = RecordedNodes[RecNo].first;
2549 if (Imm->getOpcode() == ISD::Constant) {
2550 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
2551 Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
2552 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2553 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2554 Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
2557 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
2561 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2562 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2563 // These are space-optimized forms of OPC_EmitMergeInputChains.
2564 assert(InputChain.getNode() == 0 &&
2565 "EmitMergeInputChains should be the first chain producing node");
2566 assert(ChainNodesMatched.empty() &&
2567 "Should only have one EmitMergeInputChains per match");
2569 // Read all of the chained nodes.
2570 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2571 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2572 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2574 // FIXME: What if other value results of the node have uses not matched
2576 if (ChainNodesMatched.back() != NodeToMatch &&
2577 !RecordedNodes[RecNo].first.hasOneUse()) {
2578 ChainNodesMatched.clear();
2582 // Merge the input chains if they are not intra-pattern references.
2583 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2585 if (InputChain.getNode() == 0)
2586 break; // Failed to merge.
2590 case OPC_EmitMergeInputChains: {
2591 assert(InputChain.getNode() == 0 &&
2592 "EmitMergeInputChains should be the first chain producing node");
2593 // This node gets a list of nodes we matched in the input that have
2594 // chains. We want to token factor all of the input chains to these nodes
2595 // together. However, if any of the input chains is actually one of the
2596 // nodes matched in this pattern, then we have an intra-match reference.
2597 // Ignore these because the newly token factored chain should not refer to
2599 unsigned NumChains = MatcherTable[MatcherIndex++];
2600 assert(NumChains != 0 && "Can't TF zero chains");
2602 assert(ChainNodesMatched.empty() &&
2603 "Should only have one EmitMergeInputChains per match");
2605 // Read all of the chained nodes.
2606 for (unsigned i = 0; i != NumChains; ++i) {
2607 unsigned RecNo = MatcherTable[MatcherIndex++];
2608 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2609 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2611 // FIXME: What if other value results of the node have uses not matched
2613 if (ChainNodesMatched.back() != NodeToMatch &&
2614 !RecordedNodes[RecNo].first.hasOneUse()) {
2615 ChainNodesMatched.clear();
2620 // If the inner loop broke out, the match fails.
2621 if (ChainNodesMatched.empty())
2624 // Merge the input chains if they are not intra-pattern references.
2625 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2627 if (InputChain.getNode() == 0)
2628 break; // Failed to merge.
2633 case OPC_EmitCopyToReg: {
2634 unsigned RecNo = MatcherTable[MatcherIndex++];
2635 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2636 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2638 if (InputChain.getNode() == 0)
2639 InputChain = CurDAG->getEntryNode();
2641 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
2642 DestPhysReg, RecordedNodes[RecNo].first,
2645 InputGlue = InputChain.getValue(1);
2649 case OPC_EmitNodeXForm: {
2650 unsigned XFormNo = MatcherTable[MatcherIndex++];
2651 unsigned RecNo = MatcherTable[MatcherIndex++];
2652 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2653 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
2654 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
2659 case OPC_MorphNodeTo: {
2660 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2661 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2662 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2663 // Get the result VT list.
2664 unsigned NumVTs = MatcherTable[MatcherIndex++];
2665 SmallVector<EVT, 4> VTs;
2666 for (unsigned i = 0; i != NumVTs; ++i) {
2667 MVT::SimpleValueType VT =
2668 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2669 if (VT == MVT::iPTR) VT = getTargetLowering()->getPointerTy().SimpleTy;
2673 if (EmitNodeInfo & OPFL_Chain)
2674 VTs.push_back(MVT::Other);
2675 if (EmitNodeInfo & OPFL_GlueOutput)
2676 VTs.push_back(MVT::Glue);
2678 // This is hot code, so optimize the two most common cases of 1 and 2
2681 if (VTs.size() == 1)
2682 VTList = CurDAG->getVTList(VTs[0]);
2683 else if (VTs.size() == 2)
2684 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2686 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2688 // Get the operand list.
2689 unsigned NumOps = MatcherTable[MatcherIndex++];
2690 SmallVector<SDValue, 8> Ops;
2691 for (unsigned i = 0; i != NumOps; ++i) {
2692 unsigned RecNo = MatcherTable[MatcherIndex++];
2694 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2696 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2697 Ops.push_back(RecordedNodes[RecNo].first);
2700 // If there are variadic operands to add, handle them now.
2701 if (EmitNodeInfo & OPFL_VariadicInfo) {
2702 // Determine the start index to copy from.
2703 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2704 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2705 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2706 "Invalid variadic node");
2707 // Copy all of the variadic operands, not including a potential glue
2709 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2711 SDValue V = NodeToMatch->getOperand(i);
2712 if (V.getValueType() == MVT::Glue) break;
2717 // If this has chain/glue inputs, add them.
2718 if (EmitNodeInfo & OPFL_Chain)
2719 Ops.push_back(InputChain);
2720 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
2721 Ops.push_back(InputGlue);
2725 if (Opcode != OPC_MorphNodeTo) {
2726 // If this is a normal EmitNode command, just create the new node and
2727 // add the results to the RecordedNodes list.
2728 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
2731 // Add all the non-glue/non-chain results to the RecordedNodes list.
2732 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2733 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
2734 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
2738 } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
2739 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2742 // NodeToMatch was eliminated by CSE when the target changed the DAG.
2743 // We will visit the equivalent node later.
2744 DEBUG(dbgs() << "Node was eliminated by CSE\n");
2748 // If the node had chain/glue results, update our notion of the current
2750 if (EmitNodeInfo & OPFL_GlueOutput) {
2751 InputGlue = SDValue(Res, VTs.size()-1);
2752 if (EmitNodeInfo & OPFL_Chain)
2753 InputChain = SDValue(Res, VTs.size()-2);
2754 } else if (EmitNodeInfo & OPFL_Chain)
2755 InputChain = SDValue(Res, VTs.size()-1);
2757 // If the OPFL_MemRefs glue is set on this node, slap all of the
2758 // accumulated memrefs onto it.
2760 // FIXME: This is vastly incorrect for patterns with multiple outputs
2761 // instructions that access memory and for ComplexPatterns that match
2763 if (EmitNodeInfo & OPFL_MemRefs) {
2764 // Only attach load or store memory operands if the generated
2765 // instruction may load or store.
2766 const MCInstrDesc &MCID = TM.getInstrInfo()->get(TargetOpc);
2767 bool mayLoad = MCID.mayLoad();
2768 bool mayStore = MCID.mayStore();
2770 unsigned NumMemRefs = 0;
2771 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
2772 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2773 if ((*I)->isLoad()) {
2776 } else if ((*I)->isStore()) {
2784 MachineSDNode::mmo_iterator MemRefs =
2785 MF->allocateMemRefsArray(NumMemRefs);
2787 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
2788 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
2789 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2790 if ((*I)->isLoad()) {
2793 } else if ((*I)->isStore()) {
2801 cast<MachineSDNode>(Res)
2802 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
2806 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2807 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
2809 // If this was a MorphNodeTo then we're completely done!
2810 if (Opcode == OPC_MorphNodeTo) {
2811 // Update chain and glue uses.
2812 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2813 InputGlue, GlueResultNodesMatched, true);
2820 case OPC_MarkGlueResults: {
2821 unsigned NumNodes = MatcherTable[MatcherIndex++];
2823 // Read and remember all the glue-result nodes.
2824 for (unsigned i = 0; i != NumNodes; ++i) {
2825 unsigned RecNo = MatcherTable[MatcherIndex++];
2827 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2829 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2830 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2835 case OPC_CompleteMatch: {
2836 // The match has been completed, and any new nodes (if any) have been
2837 // created. Patch up references to the matched dag to use the newly
2839 unsigned NumResults = MatcherTable[MatcherIndex++];
2841 for (unsigned i = 0; i != NumResults; ++i) {
2842 unsigned ResSlot = MatcherTable[MatcherIndex++];
2844 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2846 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2847 SDValue Res = RecordedNodes[ResSlot].first;
2849 assert(i < NodeToMatch->getNumValues() &&
2850 NodeToMatch->getValueType(i) != MVT::Other &&
2851 NodeToMatch->getValueType(i) != MVT::Glue &&
2852 "Invalid number of results to complete!");
2853 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2854 NodeToMatch->getValueType(i) == MVT::iPTR ||
2855 Res.getValueType() == MVT::iPTR ||
2856 NodeToMatch->getValueType(i).getSizeInBits() ==
2857 Res.getValueType().getSizeInBits()) &&
2858 "invalid replacement");
2859 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2862 // If the root node defines glue, add it to the glue nodes to update list.
2863 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
2864 GlueResultNodesMatched.push_back(NodeToMatch);
2866 // Update chain and glue uses.
2867 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2868 InputGlue, GlueResultNodesMatched, false);
2870 assert(NodeToMatch->use_empty() &&
2871 "Didn't replace all uses of the node?");
2873 // FIXME: We just return here, which interacts correctly with SelectRoot
2874 // above. We should fix this to not return an SDNode* anymore.
2879 // If the code reached this point, then the match failed. See if there is
2880 // another child to try in the current 'Scope', otherwise pop it until we
2881 // find a case to check.
2882 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
2883 ++NumDAGIselRetries;
2885 if (MatchScopes.empty()) {
2886 CannotYetSelect(NodeToMatch);
2890 // Restore the interpreter state back to the point where the scope was
2892 MatchScope &LastScope = MatchScopes.back();
2893 RecordedNodes.resize(LastScope.NumRecordedNodes);
2895 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2896 N = NodeStack.back();
2898 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2899 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2900 MatcherIndex = LastScope.FailIndex;
2902 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
2904 InputChain = LastScope.InputChain;
2905 InputGlue = LastScope.InputGlue;
2906 if (!LastScope.HasChainNodesMatched)
2907 ChainNodesMatched.clear();
2908 if (!LastScope.HasGlueResultNodesMatched)
2909 GlueResultNodesMatched.clear();
2911 // Check to see what the offset is at the new MatcherIndex. If it is zero
2912 // we have reached the end of this scope, otherwise we have another child
2913 // in the current scope to try.
2914 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2915 if (NumToSkip & 128)
2916 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2918 // If we have another child in this scope to match, update FailIndex and
2920 if (NumToSkip != 0) {
2921 LastScope.FailIndex = MatcherIndex+NumToSkip;
2925 // End of this scope, pop it and try the next child in the containing
2927 MatchScopes.pop_back();
2934 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2936 raw_string_ostream Msg(msg);
2937 Msg << "Cannot select: ";
2939 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2940 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2941 N->getOpcode() != ISD::INTRINSIC_VOID) {
2942 N->printrFull(Msg, CurDAG);
2943 Msg << "\nIn function: " << MF->getName();
2945 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2947 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2948 if (iid < Intrinsic::num_intrinsics)
2949 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2950 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2951 Msg << "target intrinsic %" << TII->getName(iid);
2953 Msg << "unknown intrinsic #" << iid;
2955 report_fatal_error(Msg.str());
2958 char SelectionDAGISel::ID = 0;