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 unsigned Offset = MI->getOperand(1).getImm();
425 // Def is never a terminator here, so it is ok to increment InsertPos.
426 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
427 TII.get(TargetOpcode::DBG_VALUE))
428 .addReg(LDI->second, RegState::Debug)
429 .addImm(Offset).addMetadata(Variable);
431 // If this vreg is directly copied into an exported register then
432 // that COPY instructions also need DBG_VALUE, if it is the only
433 // user of LDI->second.
434 MachineInstr *CopyUseMI = NULL;
435 for (MachineRegisterInfo::use_iterator
436 UI = RegInfo->use_begin(LDI->second);
437 MachineInstr *UseMI = UI.skipInstruction();) {
438 if (UseMI->isDebugValue()) continue;
439 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
440 CopyUseMI = UseMI; continue;
442 // Otherwise this is another use or second copy use.
443 CopyUseMI = NULL; break;
446 MachineInstr *NewMI =
447 BuildMI(*MF, CopyUseMI->getDebugLoc(),
448 TII.get(TargetOpcode::DBG_VALUE))
449 .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
450 .addImm(Offset).addMetadata(Variable);
451 MachineBasicBlock::iterator Pos = CopyUseMI;
452 EntryMBB->insertAfter(Pos, NewMI);
457 // Determine if there are any calls in this machine function.
458 MachineFrameInfo *MFI = MF->getFrameInfo();
459 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
462 if (MFI->hasCalls() && MF->hasMSInlineAsm())
465 const MachineBasicBlock *MBB = I;
466 for (MachineBasicBlock::const_iterator II = MBB->begin(), IE = MBB->end();
468 const MCInstrDesc &MCID = TM.getInstrInfo()->get(II->getOpcode());
469 if ((MCID.isCall() && !MCID.isReturn()) ||
470 II->isStackAligningInlineAsm()) {
471 MFI->setHasCalls(true);
473 if (II->isMSInlineAsm()) {
474 MF->setHasMSInlineAsm(true);
479 // Determine if there is a call to setjmp in the machine function.
480 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
482 // Replace forward-declared registers with the registers containing
483 // the desired value.
484 MachineRegisterInfo &MRI = MF->getRegInfo();
485 for (DenseMap<unsigned, unsigned>::iterator
486 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
488 unsigned From = I->first;
489 unsigned To = I->second;
490 // If To is also scheduled to be replaced, find what its ultimate
493 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
498 MRI.replaceRegWith(From, To);
501 // Freeze the set of reserved registers now that MachineFrameInfo has been
502 // set up. All the information required by getReservedRegs() should be
504 MRI.freezeReservedRegs(*MF);
506 // Release function-specific state. SDB and CurDAG are already cleared
513 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
514 BasicBlock::const_iterator End,
516 // Lower all of the non-terminator instructions. If a call is emitted
517 // as a tail call, cease emitting nodes for this block. Terminators
518 // are handled below.
519 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
522 // Make sure the root of the DAG is up-to-date.
523 CurDAG->setRoot(SDB->getControlRoot());
524 HadTailCall = SDB->HasTailCall;
527 // Final step, emit the lowered DAG as machine code.
531 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
532 SmallPtrSet<SDNode*, 128> VisitedNodes;
533 SmallVector<SDNode*, 128> Worklist;
535 Worklist.push_back(CurDAG->getRoot().getNode());
541 SDNode *N = Worklist.pop_back_val();
543 // If we've already seen this node, ignore it.
544 if (!VisitedNodes.insert(N))
547 // Otherwise, add all chain operands to the worklist.
548 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
549 if (N->getOperand(i).getValueType() == MVT::Other)
550 Worklist.push_back(N->getOperand(i).getNode());
552 // If this is a CopyToReg with a vreg dest, process it.
553 if (N->getOpcode() != ISD::CopyToReg)
556 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
557 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
560 // Ignore non-scalar or non-integer values.
561 SDValue Src = N->getOperand(2);
562 EVT SrcVT = Src.getValueType();
563 if (!SrcVT.isInteger() || SrcVT.isVector())
566 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
567 CurDAG->ComputeMaskedBits(Src, KnownZero, KnownOne);
568 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
569 } while (!Worklist.empty());
572 void SelectionDAGISel::CodeGenAndEmitDAG() {
573 std::string GroupName;
574 if (TimePassesIsEnabled)
575 GroupName = "Instruction Selection and Scheduling";
576 std::string BlockName;
577 int BlockNumber = -1;
580 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
581 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
585 BlockNumber = FuncInfo->MBB->getNumber();
586 BlockName = MF->getName().str() + ":" +
587 FuncInfo->MBB->getBasicBlock()->getName().str();
589 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
590 << " '" << BlockName << "'\n"; CurDAG->dump());
592 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
594 // Run the DAG combiner in pre-legalize mode.
596 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
597 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
600 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
601 << " '" << BlockName << "'\n"; CurDAG->dump());
603 // Second step, hack on the DAG until it only uses operations and types that
604 // the target supports.
605 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
610 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
611 Changed = CurDAG->LegalizeTypes();
614 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
615 << " '" << BlockName << "'\n"; CurDAG->dump());
618 if (ViewDAGCombineLT)
619 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
621 // Run the DAG combiner in post-type-legalize mode.
623 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
624 TimePassesIsEnabled);
625 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
628 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
629 << " '" << BlockName << "'\n"; CurDAG->dump());
634 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
635 Changed = CurDAG->LegalizeVectors();
640 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
641 CurDAG->LegalizeTypes();
644 if (ViewDAGCombineLT)
645 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
647 // Run the DAG combiner in post-type-legalize mode.
649 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
650 TimePassesIsEnabled);
651 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
654 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
655 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
658 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
661 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
665 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
666 << " '" << BlockName << "'\n"; CurDAG->dump());
668 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
670 // Run the DAG combiner in post-legalize mode.
672 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
673 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
676 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
677 << " '" << BlockName << "'\n"; CurDAG->dump());
679 if (OptLevel != CodeGenOpt::None)
680 ComputeLiveOutVRegInfo();
682 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
684 // Third, instruction select all of the operations to machine code, adding the
685 // code to the MachineBasicBlock.
687 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
688 DoInstructionSelection();
691 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
692 << " '" << BlockName << "'\n"; CurDAG->dump());
694 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
696 // Schedule machine code.
697 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
699 NamedRegionTimer T("Instruction Scheduling", GroupName,
700 TimePassesIsEnabled);
701 Scheduler->Run(CurDAG, FuncInfo->MBB);
704 if (ViewSUnitDAGs) Scheduler->viewGraph();
706 // Emit machine code to BB. This can change 'BB' to the last block being
708 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
710 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
712 // FuncInfo->InsertPt is passed by reference and set to the end of the
713 // scheduled instructions.
714 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
717 // If the block was split, make sure we update any references that are used to
718 // update PHI nodes later on.
719 if (FirstMBB != LastMBB)
720 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
722 // Free the scheduler state.
724 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
725 TimePassesIsEnabled);
729 // Free the SelectionDAG state, now that we're finished with it.
734 /// ISelUpdater - helper class to handle updates of the instruction selection
736 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
737 SelectionDAG::allnodes_iterator &ISelPosition;
739 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
740 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
742 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
743 /// deleted is the current ISelPosition node, update ISelPosition.
745 virtual void NodeDeleted(SDNode *N, SDNode *E) {
746 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
750 } // end anonymous namespace
752 void SelectionDAGISel::DoInstructionSelection() {
753 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
754 << FuncInfo->MBB->getNumber()
755 << " '" << FuncInfo->MBB->getName() << "'\n");
759 // Select target instructions for the DAG.
761 // Number all nodes with a topological order and set DAGSize.
762 DAGSize = CurDAG->AssignTopologicalOrder();
764 // Create a dummy node (which is not added to allnodes), that adds
765 // a reference to the root node, preventing it from being deleted,
766 // and tracking any changes of the root.
767 HandleSDNode Dummy(CurDAG->getRoot());
768 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
771 // Make sure that ISelPosition gets properly updated when nodes are deleted
772 // in calls made from this function.
773 ISelUpdater ISU(*CurDAG, ISelPosition);
775 // The AllNodes list is now topological-sorted. Visit the
776 // nodes by starting at the end of the list (the root of the
777 // graph) and preceding back toward the beginning (the entry
779 while (ISelPosition != CurDAG->allnodes_begin()) {
780 SDNode *Node = --ISelPosition;
781 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
782 // but there are currently some corner cases that it misses. Also, this
783 // makes it theoretically possible to disable the DAGCombiner.
784 if (Node->use_empty())
787 SDNode *ResNode = Select(Node);
789 // FIXME: This is pretty gross. 'Select' should be changed to not return
790 // anything at all and this code should be nuked with a tactical strike.
792 // If node should not be replaced, continue with the next one.
793 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
797 ReplaceUses(Node, ResNode);
800 // If after the replacement this node is not used any more,
801 // remove this dead node.
802 if (Node->use_empty()) // Don't delete EntryToken, etc.
803 CurDAG->RemoveDeadNode(Node);
806 CurDAG->setRoot(Dummy.getValue());
809 DEBUG(dbgs() << "===== Instruction selection ends:\n");
811 PostprocessISelDAG();
814 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
815 /// do other setup for EH landing-pad blocks.
816 void SelectionDAGISel::PrepareEHLandingPad() {
817 MachineBasicBlock *MBB = FuncInfo->MBB;
819 // Add a label to mark the beginning of the landing pad. Deletion of the
820 // landing pad can thus be detected via the MachineModuleInfo.
821 MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
823 // Assign the call site to the landing pad's begin label.
824 MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
826 const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
827 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
830 // Mark exception register as live in.
831 const TargetLowering *TLI = getTargetLowering();
832 unsigned Reg = TLI->getExceptionPointerRegister();
833 if (Reg) MBB->addLiveIn(Reg);
835 // Mark exception selector register as live in.
836 Reg = TLI->getExceptionSelectorRegister();
837 if (Reg) MBB->addLiveIn(Reg);
840 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
841 /// side-effect free and is either dead or folded into a generated instruction.
842 /// Return false if it needs to be emitted.
843 static bool isFoldedOrDeadInstruction(const Instruction *I,
844 FunctionLoweringInfo *FuncInfo) {
845 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
846 !isa<TerminatorInst>(I) && // Terminators aren't folded.
847 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
848 !isa<LandingPadInst>(I) && // Landingpad instructions aren't folded.
849 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
853 // Collect per Instruction statistics for fast-isel misses. Only those
854 // instructions that cause the bail are accounted for. It does not account for
855 // instructions higher in the block. Thus, summing the per instructions stats
856 // will not add up to what is reported by NumFastIselFailures.
857 static void collectFailStats(const Instruction *I) {
858 switch (I->getOpcode()) {
859 default: assert (0 && "<Invalid operator> ");
862 case Instruction::Ret: NumFastIselFailRet++; return;
863 case Instruction::Br: NumFastIselFailBr++; return;
864 case Instruction::Switch: NumFastIselFailSwitch++; return;
865 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
866 case Instruction::Invoke: NumFastIselFailInvoke++; return;
867 case Instruction::Resume: NumFastIselFailResume++; return;
868 case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
870 // Standard binary operators...
871 case Instruction::Add: NumFastIselFailAdd++; return;
872 case Instruction::FAdd: NumFastIselFailFAdd++; return;
873 case Instruction::Sub: NumFastIselFailSub++; return;
874 case Instruction::FSub: NumFastIselFailFSub++; return;
875 case Instruction::Mul: NumFastIselFailMul++; return;
876 case Instruction::FMul: NumFastIselFailFMul++; return;
877 case Instruction::UDiv: NumFastIselFailUDiv++; return;
878 case Instruction::SDiv: NumFastIselFailSDiv++; return;
879 case Instruction::FDiv: NumFastIselFailFDiv++; return;
880 case Instruction::URem: NumFastIselFailURem++; return;
881 case Instruction::SRem: NumFastIselFailSRem++; return;
882 case Instruction::FRem: NumFastIselFailFRem++; return;
884 // Logical operators...
885 case Instruction::And: NumFastIselFailAnd++; return;
886 case Instruction::Or: NumFastIselFailOr++; return;
887 case Instruction::Xor: NumFastIselFailXor++; return;
889 // Memory instructions...
890 case Instruction::Alloca: NumFastIselFailAlloca++; return;
891 case Instruction::Load: NumFastIselFailLoad++; return;
892 case Instruction::Store: NumFastIselFailStore++; return;
893 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
894 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
895 case Instruction::Fence: NumFastIselFailFence++; return;
896 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
898 // Convert instructions...
899 case Instruction::Trunc: NumFastIselFailTrunc++; return;
900 case Instruction::ZExt: NumFastIselFailZExt++; return;
901 case Instruction::SExt: NumFastIselFailSExt++; return;
902 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
903 case Instruction::FPExt: NumFastIselFailFPExt++; return;
904 case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
905 case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
906 case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
907 case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
908 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
909 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
910 case Instruction::BitCast: NumFastIselFailBitCast++; return;
912 // Other instructions...
913 case Instruction::ICmp: NumFastIselFailICmp++; return;
914 case Instruction::FCmp: NumFastIselFailFCmp++; return;
915 case Instruction::PHI: NumFastIselFailPHI++; return;
916 case Instruction::Select: NumFastIselFailSelect++; return;
917 case Instruction::Call: NumFastIselFailCall++; return;
918 case Instruction::Shl: NumFastIselFailShl++; return;
919 case Instruction::LShr: NumFastIselFailLShr++; return;
920 case Instruction::AShr: NumFastIselFailAShr++; return;
921 case Instruction::VAArg: NumFastIselFailVAArg++; return;
922 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
923 case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
924 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
925 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
926 case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
927 case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
932 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
933 // Initialize the Fast-ISel state, if needed.
934 FastISel *FastIS = 0;
935 if (TM.Options.EnableFastISel)
936 FastIS = getTargetLowering()->createFastISel(*FuncInfo, LibInfo);
938 // Iterate over all basic blocks in the function.
939 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
940 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
941 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
942 const BasicBlock *LLVMBB = *I;
944 if (OptLevel != CodeGenOpt::None) {
945 bool AllPredsVisited = true;
946 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
948 if (!FuncInfo->VisitedBBs.count(*PI)) {
949 AllPredsVisited = false;
954 if (AllPredsVisited) {
955 for (BasicBlock::const_iterator I = LLVMBB->begin();
956 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
957 FuncInfo->ComputePHILiveOutRegInfo(PN);
959 for (BasicBlock::const_iterator I = LLVMBB->begin();
960 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
961 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
964 FuncInfo->VisitedBBs.insert(LLVMBB);
967 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
968 BasicBlock::const_iterator const End = LLVMBB->end();
969 BasicBlock::const_iterator BI = End;
971 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
972 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
974 // Setup an EH landing-pad block.
975 if (FuncInfo->MBB->isLandingPad())
976 PrepareEHLandingPad();
978 // Before doing SelectionDAG ISel, see if FastISel has been requested.
980 FastIS->startNewBlock();
982 // Emit code for any incoming arguments. This must happen before
983 // beginning FastISel on the entry block.
984 if (LLVMBB == &Fn.getEntryBlock()) {
987 // Lower any arguments needed in this block if this is the entry block.
988 if (!FastIS->LowerArguments()) {
989 // Fast isel failed to lower these arguments
990 ++NumFastIselFailLowerArguments;
991 if (EnableFastISelAbortArgs)
992 llvm_unreachable("FastISel didn't lower all arguments");
994 // Use SelectionDAG argument lowering
996 CurDAG->setRoot(SDB->getControlRoot());
1001 // If we inserted any instructions at the beginning, make a note of
1002 // where they are, so we can be sure to emit subsequent instructions
1004 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1005 FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
1007 FastIS->setLastLocalValue(0);
1010 unsigned NumFastIselRemaining = std::distance(Begin, End);
1011 // Do FastISel on as many instructions as possible.
1012 for (; BI != Begin; --BI) {
1013 const Instruction *Inst = llvm::prior(BI);
1015 // If we no longer require this instruction, skip it.
1016 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1017 --NumFastIselRemaining;
1021 // Bottom-up: reset the insert pos at the top, after any local-value
1023 FastIS->recomputeInsertPt();
1025 // Try to select the instruction with FastISel.
1026 if (FastIS->SelectInstruction(Inst)) {
1027 --NumFastIselRemaining;
1028 ++NumFastIselSuccess;
1029 // If fast isel succeeded, skip over all the folded instructions, and
1030 // then see if there is a load right before the selected instructions.
1031 // Try to fold the load if so.
1032 const Instruction *BeforeInst = Inst;
1033 while (BeforeInst != Begin) {
1034 BeforeInst = llvm::prior(BasicBlock::const_iterator(BeforeInst));
1035 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1038 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1039 BeforeInst->hasOneUse() &&
1040 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1041 // If we succeeded, don't re-select the load.
1042 BI = llvm::next(BasicBlock::const_iterator(BeforeInst));
1043 --NumFastIselRemaining;
1044 ++NumFastIselSuccess;
1050 if (EnableFastISelVerbose2)
1051 collectFailStats(Inst);
1054 // Then handle certain instructions as single-LLVM-Instruction blocks.
1055 if (isa<CallInst>(Inst)) {
1057 if (EnableFastISelVerbose || EnableFastISelAbort) {
1058 dbgs() << "FastISel missed call: ";
1062 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
1063 unsigned &R = FuncInfo->ValueMap[Inst];
1065 R = FuncInfo->CreateRegs(Inst->getType());
1068 bool HadTailCall = false;
1069 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1070 SelectBasicBlock(Inst, BI, HadTailCall);
1072 // If the call was emitted as a tail call, we're done with the block.
1073 // We also need to delete any previously emitted instructions.
1075 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1080 // Recompute NumFastIselRemaining as Selection DAG instruction
1081 // selection may have handled the call, input args, etc.
1082 unsigned RemainingNow = std::distance(Begin, BI);
1083 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1084 NumFastIselRemaining = RemainingNow;
1088 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
1089 // Don't abort, and use a different message for terminator misses.
1090 NumFastIselFailures += NumFastIselRemaining;
1091 if (EnableFastISelVerbose || EnableFastISelAbort) {
1092 dbgs() << "FastISel missed terminator: ";
1096 NumFastIselFailures += NumFastIselRemaining;
1097 if (EnableFastISelVerbose || EnableFastISelAbort) {
1098 dbgs() << "FastISel miss: ";
1101 if (EnableFastISelAbort)
1102 // The "fast" selector couldn't handle something and bailed.
1103 // For the purpose of debugging, just abort.
1104 llvm_unreachable("FastISel didn't select the entire block");
1109 FastIS->recomputeInsertPt();
1111 // Lower any arguments needed in this block if this is the entry block.
1112 if (LLVMBB == &Fn.getEntryBlock()) {
1121 ++NumFastIselBlocks;
1124 // Run SelectionDAG instruction selection on the remainder of the block
1125 // not handled by FastISel. If FastISel is not run, this is the entire
1128 SelectBasicBlock(Begin, BI, HadTailCall);
1132 FuncInfo->PHINodesToUpdate.clear();
1136 SDB->clearDanglingDebugInfo();
1140 SelectionDAGISel::FinishBasicBlock() {
1142 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1143 << FuncInfo->PHINodesToUpdate.size() << "\n";
1144 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1145 dbgs() << "Node " << i << " : ("
1146 << FuncInfo->PHINodesToUpdate[i].first
1147 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1149 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1150 // PHI nodes in successors.
1151 if (SDB->SwitchCases.empty() &&
1152 SDB->JTCases.empty() &&
1153 SDB->BitTestCases.empty()) {
1154 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1155 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1156 assert(PHI->isPHI() &&
1157 "This is not a machine PHI node that we are updating!");
1158 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1160 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1165 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1166 // Lower header first, if it wasn't already lowered
1167 if (!SDB->BitTestCases[i].Emitted) {
1168 // Set the current basic block to the mbb we wish to insert the code into
1169 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1170 FuncInfo->InsertPt = FuncInfo->MBB->end();
1172 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1173 CurDAG->setRoot(SDB->getRoot());
1175 CodeGenAndEmitDAG();
1178 uint32_t UnhandledWeight = 0;
1179 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
1180 UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
1182 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1183 UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
1184 // Set the current basic block to the mbb we wish to insert the code into
1185 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1186 FuncInfo->InsertPt = FuncInfo->MBB->end();
1189 SDB->visitBitTestCase(SDB->BitTestCases[i],
1190 SDB->BitTestCases[i].Cases[j+1].ThisBB,
1192 SDB->BitTestCases[i].Reg,
1193 SDB->BitTestCases[i].Cases[j],
1196 SDB->visitBitTestCase(SDB->BitTestCases[i],
1197 SDB->BitTestCases[i].Default,
1199 SDB->BitTestCases[i].Reg,
1200 SDB->BitTestCases[i].Cases[j],
1204 CurDAG->setRoot(SDB->getRoot());
1206 CodeGenAndEmitDAG();
1210 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1212 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1213 MachineBasicBlock *PHIBB = PHI->getParent();
1214 assert(PHI->isPHI() &&
1215 "This is not a machine PHI node that we are updating!");
1216 // This is "default" BB. We have two jumps to it. From "header" BB and
1217 // from last "case" BB.
1218 if (PHIBB == SDB->BitTestCases[i].Default)
1219 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1220 .addMBB(SDB->BitTestCases[i].Parent)
1221 .addReg(FuncInfo->PHINodesToUpdate[pi].second)
1222 .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
1223 // One of "cases" BB.
1224 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1226 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1227 if (cBB->isSuccessor(PHIBB))
1228 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1232 SDB->BitTestCases.clear();
1234 // If the JumpTable record is filled in, then we need to emit a jump table.
1235 // Updating the PHI nodes is tricky in this case, since we need to determine
1236 // whether the PHI is a successor of the range check MBB or the jump table MBB
1237 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1238 // Lower header first, if it wasn't already lowered
1239 if (!SDB->JTCases[i].first.Emitted) {
1240 // Set the current basic block to the mbb we wish to insert the code into
1241 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1242 FuncInfo->InsertPt = FuncInfo->MBB->end();
1244 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1246 CurDAG->setRoot(SDB->getRoot());
1248 CodeGenAndEmitDAG();
1251 // Set the current basic block to the mbb we wish to insert the code into
1252 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1253 FuncInfo->InsertPt = FuncInfo->MBB->end();
1255 SDB->visitJumpTable(SDB->JTCases[i].second);
1256 CurDAG->setRoot(SDB->getRoot());
1258 CodeGenAndEmitDAG();
1261 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1263 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1264 MachineBasicBlock *PHIBB = PHI->getParent();
1265 assert(PHI->isPHI() &&
1266 "This is not a machine PHI node that we are updating!");
1267 // "default" BB. We can go there only from header BB.
1268 if (PHIBB == SDB->JTCases[i].second.Default)
1269 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1270 .addMBB(SDB->JTCases[i].first.HeaderBB);
1271 // JT BB. Just iterate over successors here
1272 if (FuncInfo->MBB->isSuccessor(PHIBB))
1273 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1276 SDB->JTCases.clear();
1278 // If the switch block involved a branch to one of the actual successors, we
1279 // need to update PHI nodes in that block.
1280 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1281 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1282 assert(PHI->isPHI() &&
1283 "This is not a machine PHI node that we are updating!");
1284 if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
1285 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1288 // If we generated any switch lowering information, build and codegen any
1289 // additional DAGs necessary.
1290 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1291 // Set the current basic block to the mbb we wish to insert the code into
1292 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1293 FuncInfo->InsertPt = FuncInfo->MBB->end();
1295 // Determine the unique successors.
1296 SmallVector<MachineBasicBlock *, 2> Succs;
1297 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1298 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1299 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1301 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1302 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1303 CurDAG->setRoot(SDB->getRoot());
1305 CodeGenAndEmitDAG();
1307 // Remember the last block, now that any splitting is done, for use in
1308 // populating PHI nodes in successors.
1309 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1311 // Handle any PHI nodes in successors of this chunk, as if we were coming
1312 // from the original BB before switch expansion. Note that PHI nodes can
1313 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1314 // handle them the right number of times.
1315 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1316 FuncInfo->MBB = Succs[i];
1317 FuncInfo->InsertPt = FuncInfo->MBB->end();
1318 // FuncInfo->MBB may have been removed from the CFG if a branch was
1320 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1321 for (MachineBasicBlock::iterator
1322 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1323 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1324 MachineInstrBuilder PHI(*MF, MBBI);
1325 // This value for this PHI node is recorded in PHINodesToUpdate.
1326 for (unsigned pn = 0; ; ++pn) {
1327 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1328 "Didn't find PHI entry!");
1329 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1330 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1338 SDB->SwitchCases.clear();
1342 /// Create the scheduler. If a specific scheduler was specified
1343 /// via the SchedulerRegistry, use it, otherwise select the
1344 /// one preferred by the target.
1346 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1347 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1351 RegisterScheduler::setDefault(Ctor);
1354 return Ctor(this, OptLevel);
1357 //===----------------------------------------------------------------------===//
1358 // Helper functions used by the generated instruction selector.
1359 //===----------------------------------------------------------------------===//
1360 // Calls to these methods are generated by tblgen.
1362 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1363 /// the dag combiner simplified the 255, we still want to match. RHS is the
1364 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1365 /// specified in the .td file (e.g. 255).
1366 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1367 int64_t DesiredMaskS) const {
1368 const APInt &ActualMask = RHS->getAPIntValue();
1369 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1371 // If the actual mask exactly matches, success!
1372 if (ActualMask == DesiredMask)
1375 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1376 if (ActualMask.intersects(~DesiredMask))
1379 // Otherwise, the DAG Combiner may have proven that the value coming in is
1380 // either already zero or is not demanded. Check for known zero input bits.
1381 APInt NeededMask = DesiredMask & ~ActualMask;
1382 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1385 // TODO: check to see if missing bits are just not demanded.
1387 // Otherwise, this pattern doesn't match.
1391 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1392 /// the dag combiner simplified the 255, we still want to match. RHS is the
1393 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1394 /// specified in the .td file (e.g. 255).
1395 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1396 int64_t DesiredMaskS) const {
1397 const APInt &ActualMask = RHS->getAPIntValue();
1398 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1400 // If the actual mask exactly matches, success!
1401 if (ActualMask == DesiredMask)
1404 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1405 if (ActualMask.intersects(~DesiredMask))
1408 // Otherwise, the DAG Combiner may have proven that the value coming in is
1409 // either already zero or is not demanded. Check for known zero input bits.
1410 APInt NeededMask = DesiredMask & ~ActualMask;
1412 APInt KnownZero, KnownOne;
1413 CurDAG->ComputeMaskedBits(LHS, KnownZero, KnownOne);
1415 // If all the missing bits in the or are already known to be set, match!
1416 if ((NeededMask & KnownOne) == NeededMask)
1419 // TODO: check to see if missing bits are just not demanded.
1421 // Otherwise, this pattern doesn't match.
1426 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1427 /// by tblgen. Others should not call it.
1428 void SelectionDAGISel::
1429 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1430 std::vector<SDValue> InOps;
1431 std::swap(InOps, Ops);
1433 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1434 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1435 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1436 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1438 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1439 if (InOps[e-1].getValueType() == MVT::Glue)
1440 --e; // Don't process a glue operand if it is here.
1443 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1444 if (!InlineAsm::isMemKind(Flags)) {
1445 // Just skip over this operand, copying the operands verbatim.
1446 Ops.insert(Ops.end(), InOps.begin()+i,
1447 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1448 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1450 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1451 "Memory operand with multiple values?");
1452 // Otherwise, this is a memory operand. Ask the target to select it.
1453 std::vector<SDValue> SelOps;
1454 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1455 report_fatal_error("Could not match memory address. Inline asm"
1458 // Add this to the output node.
1460 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1461 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1462 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1467 // Add the glue input back if present.
1468 if (e != InOps.size())
1469 Ops.push_back(InOps.back());
1472 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1475 static SDNode *findGlueUse(SDNode *N) {
1476 unsigned FlagResNo = N->getNumValues()-1;
1477 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1478 SDUse &Use = I.getUse();
1479 if (Use.getResNo() == FlagResNo)
1480 return Use.getUser();
1485 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1486 /// This function recursively traverses up the operand chain, ignoring
1488 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1489 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1490 bool IgnoreChains) {
1491 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1492 // greater than all of its (recursive) operands. If we scan to a point where
1493 // 'use' is smaller than the node we're scanning for, then we know we will
1496 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1497 // happen because we scan down to newly selected nodes in the case of glue
1499 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1502 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1503 // won't fail if we scan it again.
1504 if (!Visited.insert(Use))
1507 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1508 // Ignore chain uses, they are validated by HandleMergeInputChains.
1509 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1512 SDNode *N = Use->getOperand(i).getNode();
1514 if (Use == ImmedUse || Use == Root)
1515 continue; // We are not looking for immediate use.
1520 // Traverse up the operand chain.
1521 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1527 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1528 /// operand node N of U during instruction selection that starts at Root.
1529 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1530 SDNode *Root) const {
1531 if (OptLevel == CodeGenOpt::None) return false;
1532 return N.hasOneUse();
1535 /// IsLegalToFold - Returns true if the specific operand node N of
1536 /// U can be folded during instruction selection that starts at Root.
1537 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1538 CodeGenOpt::Level OptLevel,
1539 bool IgnoreChains) {
1540 if (OptLevel == CodeGenOpt::None) return false;
1542 // If Root use can somehow reach N through a path that that doesn't contain
1543 // U then folding N would create a cycle. e.g. In the following
1544 // diagram, Root can reach N through X. If N is folded into into Root, then
1545 // X is both a predecessor and a successor of U.
1556 // * indicates nodes to be folded together.
1558 // If Root produces glue, then it gets (even more) interesting. Since it
1559 // will be "glued" together with its glue use in the scheduler, we need to
1560 // check if it might reach N.
1579 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1580 // (call it Fold), then X is a predecessor of GU and a successor of
1581 // Fold. But since Fold and GU are glued together, this will create
1582 // a cycle in the scheduling graph.
1584 // If the node has glue, walk down the graph to the "lowest" node in the
1586 EVT VT = Root->getValueType(Root->getNumValues()-1);
1587 while (VT == MVT::Glue) {
1588 SDNode *GU = findGlueUse(Root);
1592 VT = Root->getValueType(Root->getNumValues()-1);
1594 // If our query node has a glue result with a use, we've walked up it. If
1595 // the user (which has already been selected) has a chain or indirectly uses
1596 // the chain, our WalkChainUsers predicate will not consider it. Because of
1597 // this, we cannot ignore chains in this predicate.
1598 IgnoreChains = false;
1602 SmallPtrSet<SDNode*, 16> Visited;
1603 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1606 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1607 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1608 SelectInlineAsmMemoryOperands(Ops);
1610 EVT VTs[] = { MVT::Other, MVT::Glue };
1611 SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N),
1612 VTs, &Ops[0], Ops.size());
1614 return New.getNode();
1617 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1618 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1621 /// GetVBR - decode a vbr encoding whose top bit is set.
1622 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
1623 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1624 assert(Val >= 128 && "Not a VBR");
1625 Val &= 127; // Remove first vbr bit.
1630 NextBits = MatcherTable[Idx++];
1631 Val |= (NextBits&127) << Shift;
1633 } while (NextBits & 128);
1639 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1640 /// interior glue and chain results to use the new glue and chain results.
1641 void SelectionDAGISel::
1642 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1643 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1645 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1646 bool isMorphNodeTo) {
1647 SmallVector<SDNode*, 4> NowDeadNodes;
1649 // Now that all the normal results are replaced, we replace the chain and
1650 // glue results if present.
1651 if (!ChainNodesMatched.empty()) {
1652 assert(InputChain.getNode() != 0 &&
1653 "Matched input chains but didn't produce a chain");
1654 // Loop over all of the nodes we matched that produced a chain result.
1655 // Replace all the chain results with the final chain we ended up with.
1656 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1657 SDNode *ChainNode = ChainNodesMatched[i];
1659 // If this node was already deleted, don't look at it.
1660 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1663 // Don't replace the results of the root node if we're doing a
1665 if (ChainNode == NodeToMatch && isMorphNodeTo)
1668 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1669 if (ChainVal.getValueType() == MVT::Glue)
1670 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1671 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1672 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
1674 // If the node became dead and we haven't already seen it, delete it.
1675 if (ChainNode->use_empty() &&
1676 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1677 NowDeadNodes.push_back(ChainNode);
1681 // If the result produces glue, update any glue results in the matched
1682 // pattern with the glue result.
1683 if (InputGlue.getNode() != 0) {
1684 // Handle any interior nodes explicitly marked.
1685 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1686 SDNode *FRN = GlueResultNodesMatched[i];
1688 // If this node was already deleted, don't look at it.
1689 if (FRN->getOpcode() == ISD::DELETED_NODE)
1692 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
1693 "Doesn't have a glue result");
1694 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1697 // If the node became dead and we haven't already seen it, delete it.
1698 if (FRN->use_empty() &&
1699 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1700 NowDeadNodes.push_back(FRN);
1704 if (!NowDeadNodes.empty())
1705 CurDAG->RemoveDeadNodes(NowDeadNodes);
1707 DEBUG(dbgs() << "ISEL: Match complete!\n");
1713 CR_LeadsToInteriorNode
1716 /// WalkChainUsers - Walk down the users of the specified chained node that is
1717 /// part of the pattern we're matching, looking at all of the users we find.
1718 /// This determines whether something is an interior node, whether we have a
1719 /// non-pattern node in between two pattern nodes (which prevent folding because
1720 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1721 /// between pattern nodes (in which case the TF becomes part of the pattern).
1723 /// The walk we do here is guaranteed to be small because we quickly get down to
1724 /// already selected nodes "below" us.
1726 WalkChainUsers(const SDNode *ChainedNode,
1727 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1728 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1729 ChainResult Result = CR_Simple;
1731 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1732 E = ChainedNode->use_end(); UI != E; ++UI) {
1733 // Make sure the use is of the chain, not some other value we produce.
1734 if (UI.getUse().getValueType() != MVT::Other) continue;
1738 // If we see an already-selected machine node, then we've gone beyond the
1739 // pattern that we're selecting down into the already selected chunk of the
1741 if (User->isMachineOpcode() ||
1742 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1745 unsigned UserOpcode = User->getOpcode();
1746 if (UserOpcode == ISD::CopyToReg ||
1747 UserOpcode == ISD::CopyFromReg ||
1748 UserOpcode == ISD::INLINEASM ||
1749 UserOpcode == ISD::EH_LABEL ||
1750 UserOpcode == ISD::LIFETIME_START ||
1751 UserOpcode == ISD::LIFETIME_END) {
1752 // If their node ID got reset to -1 then they've already been selected.
1753 // Treat them like a MachineOpcode.
1754 if (User->getNodeId() == -1)
1758 // If we have a TokenFactor, we handle it specially.
1759 if (User->getOpcode() != ISD::TokenFactor) {
1760 // If the node isn't a token factor and isn't part of our pattern, then it
1761 // must be a random chained node in between two nodes we're selecting.
1762 // This happens when we have something like:
1767 // Because we structurally match the load/store as a read/modify/write,
1768 // but the call is chained between them. We cannot fold in this case
1769 // because it would induce a cycle in the graph.
1770 if (!std::count(ChainedNodesInPattern.begin(),
1771 ChainedNodesInPattern.end(), User))
1772 return CR_InducesCycle;
1774 // Otherwise we found a node that is part of our pattern. For example in:
1778 // This would happen when we're scanning down from the load and see the
1779 // store as a user. Record that there is a use of ChainedNode that is
1780 // part of the pattern and keep scanning uses.
1781 Result = CR_LeadsToInteriorNode;
1782 InteriorChainedNodes.push_back(User);
1786 // If we found a TokenFactor, there are two cases to consider: first if the
1787 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1788 // uses of the TF are in our pattern) we just want to ignore it. Second,
1789 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1795 // | \ DAG's like cheese
1798 // [TokenFactor] [Op]
1805 // In this case, the TokenFactor becomes part of our match and we rewrite it
1806 // as a new TokenFactor.
1808 // To distinguish these two cases, do a recursive walk down the uses.
1809 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1811 // If the uses of the TokenFactor are just already-selected nodes, ignore
1812 // it, it is "below" our pattern.
1814 case CR_InducesCycle:
1815 // If the uses of the TokenFactor lead to nodes that are not part of our
1816 // pattern that are not selected, folding would turn this into a cycle,
1818 return CR_InducesCycle;
1819 case CR_LeadsToInteriorNode:
1820 break; // Otherwise, keep processing.
1823 // Okay, we know we're in the interesting interior case. The TokenFactor
1824 // is now going to be considered part of the pattern so that we rewrite its
1825 // uses (it may have uses that are not part of the pattern) with the
1826 // ultimate chain result of the generated code. We will also add its chain
1827 // inputs as inputs to the ultimate TokenFactor we create.
1828 Result = CR_LeadsToInteriorNode;
1829 ChainedNodesInPattern.push_back(User);
1830 InteriorChainedNodes.push_back(User);
1837 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1838 /// operation for when the pattern matched at least one node with a chains. The
1839 /// input vector contains a list of all of the chained nodes that we match. We
1840 /// must determine if this is a valid thing to cover (i.e. matching it won't
1841 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1842 /// be used as the input node chain for the generated nodes.
1844 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1845 SelectionDAG *CurDAG) {
1846 // Walk all of the chained nodes we've matched, recursively scanning down the
1847 // users of the chain result. This adds any TokenFactor nodes that are caught
1848 // in between chained nodes to the chained and interior nodes list.
1849 SmallVector<SDNode*, 3> InteriorChainedNodes;
1850 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1851 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1852 InteriorChainedNodes) == CR_InducesCycle)
1853 return SDValue(); // Would induce a cycle.
1856 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1857 // that we are interested in. Form our input TokenFactor node.
1858 SmallVector<SDValue, 3> InputChains;
1859 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1860 // Add the input chain of this node to the InputChains list (which will be
1861 // the operands of the generated TokenFactor) if it's not an interior node.
1862 SDNode *N = ChainNodesMatched[i];
1863 if (N->getOpcode() != ISD::TokenFactor) {
1864 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1867 // Otherwise, add the input chain.
1868 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1869 assert(InChain.getValueType() == MVT::Other && "Not a chain");
1870 InputChains.push_back(InChain);
1874 // If we have a token factor, we want to add all inputs of the token factor
1875 // that are not part of the pattern we're matching.
1876 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1877 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1878 N->getOperand(op).getNode()))
1879 InputChains.push_back(N->getOperand(op));
1884 if (InputChains.size() == 1)
1885 return InputChains[0];
1886 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
1887 MVT::Other, &InputChains[0], InputChains.size());
1890 /// MorphNode - Handle morphing a node in place for the selector.
1891 SDNode *SelectionDAGISel::
1892 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1893 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1894 // It is possible we're using MorphNodeTo to replace a node with no
1895 // normal results with one that has a normal result (or we could be
1896 // adding a chain) and the input could have glue and chains as well.
1897 // In this case we need to shift the operands down.
1898 // FIXME: This is a horrible hack and broken in obscure cases, no worse
1899 // than the old isel though.
1900 int OldGlueResultNo = -1, OldChainResultNo = -1;
1902 unsigned NTMNumResults = Node->getNumValues();
1903 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
1904 OldGlueResultNo = NTMNumResults-1;
1905 if (NTMNumResults != 1 &&
1906 Node->getValueType(NTMNumResults-2) == MVT::Other)
1907 OldChainResultNo = NTMNumResults-2;
1908 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1909 OldChainResultNo = NTMNumResults-1;
1911 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1912 // that this deletes operands of the old node that become dead.
1913 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1915 // MorphNodeTo can operate in two ways: if an existing node with the
1916 // specified operands exists, it can just return it. Otherwise, it
1917 // updates the node in place to have the requested operands.
1919 // If we updated the node in place, reset the node ID. To the isel,
1920 // this should be just like a newly allocated machine node.
1924 unsigned ResNumResults = Res->getNumValues();
1925 // Move the glue if needed.
1926 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
1927 (unsigned)OldGlueResultNo != ResNumResults-1)
1928 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
1929 SDValue(Res, ResNumResults-1));
1931 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
1934 // Move the chain reference if needed.
1935 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1936 (unsigned)OldChainResultNo != ResNumResults-1)
1937 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1938 SDValue(Res, ResNumResults-1));
1940 // Otherwise, no replacement happened because the node already exists. Replace
1941 // Uses of the old node with the new one.
1943 CurDAG->ReplaceAllUsesWith(Node, Res);
1948 /// CheckSame - Implements OP_CheckSame.
1949 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1950 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1952 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
1953 // Accept if it is exactly the same as a previously recorded node.
1954 unsigned RecNo = MatcherTable[MatcherIndex++];
1955 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
1956 return N == RecordedNodes[RecNo].first;
1959 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
1960 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1961 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1962 const SelectionDAGISel &SDISel) {
1963 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
1966 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
1967 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1968 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1969 const SelectionDAGISel &SDISel, SDNode *N) {
1970 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
1973 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1974 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1976 uint16_t Opc = MatcherTable[MatcherIndex++];
1977 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
1978 return N->getOpcode() == Opc;
1981 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1982 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1983 SDValue N, const TargetLowering *TLI) {
1984 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
1985 if (N.getValueType() == VT) return true;
1987 // Handle the case when VT is iPTR.
1988 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
1991 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
1992 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
1993 SDValue N, const TargetLowering *TLI,
1995 if (ChildNo >= N.getNumOperands())
1996 return false; // Match fails if out of range child #.
1997 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
2000 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2001 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2003 return cast<CondCodeSDNode>(N)->get() ==
2004 (ISD::CondCode)MatcherTable[MatcherIndex++];
2007 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2008 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2009 SDValue N, const TargetLowering *TLI) {
2010 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2011 if (cast<VTSDNode>(N)->getVT() == VT)
2014 // Handle the case when VT is iPTR.
2015 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
2018 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2019 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2021 int64_t Val = MatcherTable[MatcherIndex++];
2023 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2025 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2026 return C != 0 && C->getSExtValue() == Val;
2029 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2030 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2031 SDValue N, const SelectionDAGISel &SDISel) {
2032 int64_t Val = MatcherTable[MatcherIndex++];
2034 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2036 if (N->getOpcode() != ISD::AND) return false;
2038 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2039 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2042 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2043 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2044 SDValue N, const SelectionDAGISel &SDISel) {
2045 int64_t Val = MatcherTable[MatcherIndex++];
2047 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2049 if (N->getOpcode() != ISD::OR) return false;
2051 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2052 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2055 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2056 /// scope, evaluate the current node. If the current predicate is known to
2057 /// fail, set Result=true and return anything. If the current predicate is
2058 /// known to pass, set Result=false and return the MatcherIndex to continue
2059 /// with. If the current predicate is unknown, set Result=false and return the
2060 /// MatcherIndex to continue with.
2061 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2062 unsigned Index, SDValue N,
2064 const SelectionDAGISel &SDISel,
2065 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2066 switch (Table[Index++]) {
2069 return Index-1; // Could not evaluate this predicate.
2070 case SelectionDAGISel::OPC_CheckSame:
2071 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2073 case SelectionDAGISel::OPC_CheckPatternPredicate:
2074 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2076 case SelectionDAGISel::OPC_CheckPredicate:
2077 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2079 case SelectionDAGISel::OPC_CheckOpcode:
2080 Result = !::CheckOpcode(Table, Index, N.getNode());
2082 case SelectionDAGISel::OPC_CheckType:
2083 Result = !::CheckType(Table, Index, N, SDISel.getTargetLowering());
2085 case SelectionDAGISel::OPC_CheckChild0Type:
2086 case SelectionDAGISel::OPC_CheckChild1Type:
2087 case SelectionDAGISel::OPC_CheckChild2Type:
2088 case SelectionDAGISel::OPC_CheckChild3Type:
2089 case SelectionDAGISel::OPC_CheckChild4Type:
2090 case SelectionDAGISel::OPC_CheckChild5Type:
2091 case SelectionDAGISel::OPC_CheckChild6Type:
2092 case SelectionDAGISel::OPC_CheckChild7Type:
2093 Result = !::CheckChildType(Table, Index, N, SDISel.getTargetLowering(),
2094 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
2096 case SelectionDAGISel::OPC_CheckCondCode:
2097 Result = !::CheckCondCode(Table, Index, N);
2099 case SelectionDAGISel::OPC_CheckValueType:
2100 Result = !::CheckValueType(Table, Index, N, SDISel.getTargetLowering());
2102 case SelectionDAGISel::OPC_CheckInteger:
2103 Result = !::CheckInteger(Table, Index, N);
2105 case SelectionDAGISel::OPC_CheckAndImm:
2106 Result = !::CheckAndImm(Table, Index, N, SDISel);
2108 case SelectionDAGISel::OPC_CheckOrImm:
2109 Result = !::CheckOrImm(Table, Index, N, SDISel);
2117 /// FailIndex - If this match fails, this is the index to continue with.
2120 /// NodeStack - The node stack when the scope was formed.
2121 SmallVector<SDValue, 4> NodeStack;
2123 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2124 unsigned NumRecordedNodes;
2126 /// NumMatchedMemRefs - The number of matched memref entries.
2127 unsigned NumMatchedMemRefs;
2129 /// InputChain/InputGlue - The current chain/glue
2130 SDValue InputChain, InputGlue;
2132 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2133 bool HasChainNodesMatched, HasGlueResultNodesMatched;
2138 SDNode *SelectionDAGISel::
2139 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2140 unsigned TableSize) {
2141 // FIXME: Should these even be selected? Handle these cases in the caller?
2142 switch (NodeToMatch->getOpcode()) {
2145 case ISD::EntryToken: // These nodes remain the same.
2146 case ISD::BasicBlock:
2148 case ISD::RegisterMask:
2149 //case ISD::VALUETYPE:
2150 //case ISD::CONDCODE:
2151 case ISD::HANDLENODE:
2152 case ISD::MDNODE_SDNODE:
2153 case ISD::TargetConstant:
2154 case ISD::TargetConstantFP:
2155 case ISD::TargetConstantPool:
2156 case ISD::TargetFrameIndex:
2157 case ISD::TargetExternalSymbol:
2158 case ISD::TargetBlockAddress:
2159 case ISD::TargetJumpTable:
2160 case ISD::TargetGlobalTLSAddress:
2161 case ISD::TargetGlobalAddress:
2162 case ISD::TokenFactor:
2163 case ISD::CopyFromReg:
2164 case ISD::CopyToReg:
2166 case ISD::LIFETIME_START:
2167 case ISD::LIFETIME_END:
2168 NodeToMatch->setNodeId(-1); // Mark selected.
2170 case ISD::AssertSext:
2171 case ISD::AssertZext:
2172 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2173 NodeToMatch->getOperand(0));
2175 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2176 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2179 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2181 // Set up the node stack with NodeToMatch as the only node on the stack.
2182 SmallVector<SDValue, 8> NodeStack;
2183 SDValue N = SDValue(NodeToMatch, 0);
2184 NodeStack.push_back(N);
2186 // MatchScopes - Scopes used when matching, if a match failure happens, this
2187 // indicates where to continue checking.
2188 SmallVector<MatchScope, 8> MatchScopes;
2190 // RecordedNodes - This is the set of nodes that have been recorded by the
2191 // state machine. The second value is the parent of the node, or null if the
2192 // root is recorded.
2193 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2195 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2197 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2199 // These are the current input chain and glue for use when generating nodes.
2200 // Various Emit operations change these. For example, emitting a copytoreg
2201 // uses and updates these.
2202 SDValue InputChain, InputGlue;
2204 // ChainNodesMatched - If a pattern matches nodes that have input/output
2205 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2206 // which ones they are. The result is captured into this list so that we can
2207 // update the chain results when the pattern is complete.
2208 SmallVector<SDNode*, 3> ChainNodesMatched;
2209 SmallVector<SDNode*, 3> GlueResultNodesMatched;
2211 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2212 NodeToMatch->dump(CurDAG);
2215 // Determine where to start the interpreter. Normally we start at opcode #0,
2216 // but if the state machine starts with an OPC_SwitchOpcode, then we
2217 // accelerate the first lookup (which is guaranteed to be hot) with the
2218 // OpcodeOffset table.
2219 unsigned MatcherIndex = 0;
2221 if (!OpcodeOffset.empty()) {
2222 // Already computed the OpcodeOffset table, just index into it.
2223 if (N.getOpcode() < OpcodeOffset.size())
2224 MatcherIndex = OpcodeOffset[N.getOpcode()];
2225 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2227 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2228 // Otherwise, the table isn't computed, but the state machine does start
2229 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2230 // is the first time we're selecting an instruction.
2233 // Get the size of this case.
2234 unsigned CaseSize = MatcherTable[Idx++];
2236 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2237 if (CaseSize == 0) break;
2239 // Get the opcode, add the index to the table.
2240 uint16_t Opc = MatcherTable[Idx++];
2241 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2242 if (Opc >= OpcodeOffset.size())
2243 OpcodeOffset.resize((Opc+1)*2);
2244 OpcodeOffset[Opc] = Idx;
2248 // Okay, do the lookup for the first opcode.
2249 if (N.getOpcode() < OpcodeOffset.size())
2250 MatcherIndex = OpcodeOffset[N.getOpcode()];
2254 assert(MatcherIndex < TableSize && "Invalid index");
2256 unsigned CurrentOpcodeIndex = MatcherIndex;
2258 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2261 // Okay, the semantics of this operation are that we should push a scope
2262 // then evaluate the first child. However, pushing a scope only to have
2263 // the first check fail (which then pops it) is inefficient. If we can
2264 // determine immediately that the first check (or first several) will
2265 // immediately fail, don't even bother pushing a scope for them.
2269 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2270 if (NumToSkip & 128)
2271 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2272 // Found the end of the scope with no match.
2273 if (NumToSkip == 0) {
2278 FailIndex = MatcherIndex+NumToSkip;
2280 unsigned MatcherIndexOfPredicate = MatcherIndex;
2281 (void)MatcherIndexOfPredicate; // silence warning.
2283 // If we can't evaluate this predicate without pushing a scope (e.g. if
2284 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2285 // push the scope and evaluate the full predicate chain.
2287 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2288 Result, *this, RecordedNodes);
2292 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
2293 << "index " << MatcherIndexOfPredicate
2294 << ", continuing at " << FailIndex << "\n");
2295 ++NumDAGIselRetries;
2297 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2298 // move to the next case.
2299 MatcherIndex = FailIndex;
2302 // If the whole scope failed to match, bail.
2303 if (FailIndex == 0) break;
2305 // Push a MatchScope which indicates where to go if the first child fails
2307 MatchScope NewEntry;
2308 NewEntry.FailIndex = FailIndex;
2309 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2310 NewEntry.NumRecordedNodes = RecordedNodes.size();
2311 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2312 NewEntry.InputChain = InputChain;
2313 NewEntry.InputGlue = InputGlue;
2314 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2315 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2316 MatchScopes.push_back(NewEntry);
2319 case OPC_RecordNode: {
2320 // Remember this node, it may end up being an operand in the pattern.
2322 if (NodeStack.size() > 1)
2323 Parent = NodeStack[NodeStack.size()-2].getNode();
2324 RecordedNodes.push_back(std::make_pair(N, Parent));
2328 case OPC_RecordChild0: case OPC_RecordChild1:
2329 case OPC_RecordChild2: case OPC_RecordChild3:
2330 case OPC_RecordChild4: case OPC_RecordChild5:
2331 case OPC_RecordChild6: case OPC_RecordChild7: {
2332 unsigned ChildNo = Opcode-OPC_RecordChild0;
2333 if (ChildNo >= N.getNumOperands())
2334 break; // Match fails if out of range child #.
2336 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2340 case OPC_RecordMemRef:
2341 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2344 case OPC_CaptureGlueInput:
2345 // If the current node has an input glue, capture it in InputGlue.
2346 if (N->getNumOperands() != 0 &&
2347 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2348 InputGlue = N->getOperand(N->getNumOperands()-1);
2351 case OPC_MoveChild: {
2352 unsigned ChildNo = MatcherTable[MatcherIndex++];
2353 if (ChildNo >= N.getNumOperands())
2354 break; // Match fails if out of range child #.
2355 N = N.getOperand(ChildNo);
2356 NodeStack.push_back(N);
2360 case OPC_MoveParent:
2361 // Pop the current node off the NodeStack.
2362 NodeStack.pop_back();
2363 assert(!NodeStack.empty() && "Node stack imbalance!");
2364 N = NodeStack.back();
2368 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2370 case OPC_CheckPatternPredicate:
2371 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2373 case OPC_CheckPredicate:
2374 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2378 case OPC_CheckComplexPat: {
2379 unsigned CPNum = MatcherTable[MatcherIndex++];
2380 unsigned RecNo = MatcherTable[MatcherIndex++];
2381 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2382 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2383 RecordedNodes[RecNo].first, CPNum,
2388 case OPC_CheckOpcode:
2389 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2393 if (!::CheckType(MatcherTable, MatcherIndex, N, getTargetLowering()))
2397 case OPC_SwitchOpcode: {
2398 unsigned CurNodeOpcode = N.getOpcode();
2399 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2402 // Get the size of this case.
2403 CaseSize = MatcherTable[MatcherIndex++];
2405 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2406 if (CaseSize == 0) break;
2408 uint16_t Opc = MatcherTable[MatcherIndex++];
2409 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2411 // If the opcode matches, then we will execute this case.
2412 if (CurNodeOpcode == Opc)
2415 // Otherwise, skip over this case.
2416 MatcherIndex += CaseSize;
2419 // If no cases matched, bail out.
2420 if (CaseSize == 0) break;
2422 // Otherwise, execute the case we found.
2423 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
2424 << " to " << MatcherIndex << "\n");
2428 case OPC_SwitchType: {
2429 MVT CurNodeVT = N.getValueType().getSimpleVT();
2430 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2433 // Get the size of this case.
2434 CaseSize = MatcherTable[MatcherIndex++];
2436 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2437 if (CaseSize == 0) break;
2439 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2440 if (CaseVT == MVT::iPTR)
2441 CaseVT = getTargetLowering()->getPointerTy();
2443 // If the VT matches, then we will execute this case.
2444 if (CurNodeVT == CaseVT)
2447 // Otherwise, skip over this case.
2448 MatcherIndex += CaseSize;
2451 // If no cases matched, bail out.
2452 if (CaseSize == 0) break;
2454 // Otherwise, execute the case we found.
2455 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2456 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2459 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2460 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2461 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2462 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2463 if (!::CheckChildType(MatcherTable, MatcherIndex, N, getTargetLowering(),
2464 Opcode-OPC_CheckChild0Type))
2467 case OPC_CheckCondCode:
2468 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2470 case OPC_CheckValueType:
2471 if (!::CheckValueType(MatcherTable, MatcherIndex, N, getTargetLowering()))
2474 case OPC_CheckInteger:
2475 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2477 case OPC_CheckAndImm:
2478 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2480 case OPC_CheckOrImm:
2481 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2484 case OPC_CheckFoldableChainNode: {
2485 assert(NodeStack.size() != 1 && "No parent node");
2486 // Verify that all intermediate nodes between the root and this one have
2488 bool HasMultipleUses = false;
2489 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2490 if (!NodeStack[i].hasOneUse()) {
2491 HasMultipleUses = true;
2494 if (HasMultipleUses) break;
2496 // Check to see that the target thinks this is profitable to fold and that
2497 // we can fold it without inducing cycles in the graph.
2498 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2500 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2501 NodeToMatch, OptLevel,
2502 true/*We validate our own chains*/))
2507 case OPC_EmitInteger: {
2508 MVT::SimpleValueType VT =
2509 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2510 int64_t Val = MatcherTable[MatcherIndex++];
2512 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2513 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2514 CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
2517 case OPC_EmitRegister: {
2518 MVT::SimpleValueType VT =
2519 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2520 unsigned RegNo = MatcherTable[MatcherIndex++];
2521 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2522 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2525 case OPC_EmitRegister2: {
2526 // For targets w/ more than 256 register names, the register enum
2527 // values are stored in two bytes in the matcher table (just like
2529 MVT::SimpleValueType VT =
2530 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2531 unsigned RegNo = MatcherTable[MatcherIndex++];
2532 RegNo |= MatcherTable[MatcherIndex++] << 8;
2533 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2534 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2538 case OPC_EmitConvertToTarget: {
2539 // Convert from IMM/FPIMM to target version.
2540 unsigned RecNo = MatcherTable[MatcherIndex++];
2541 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2542 SDValue Imm = RecordedNodes[RecNo].first;
2544 if (Imm->getOpcode() == ISD::Constant) {
2545 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
2546 Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
2547 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2548 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2549 Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
2552 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
2556 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2557 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2558 // These are space-optimized forms of OPC_EmitMergeInputChains.
2559 assert(InputChain.getNode() == 0 &&
2560 "EmitMergeInputChains should be the first chain producing node");
2561 assert(ChainNodesMatched.empty() &&
2562 "Should only have one EmitMergeInputChains per match");
2564 // Read all of the chained nodes.
2565 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2566 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2567 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2569 // FIXME: What if other value results of the node have uses not matched
2571 if (ChainNodesMatched.back() != NodeToMatch &&
2572 !RecordedNodes[RecNo].first.hasOneUse()) {
2573 ChainNodesMatched.clear();
2577 // Merge the input chains if they are not intra-pattern references.
2578 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2580 if (InputChain.getNode() == 0)
2581 break; // Failed to merge.
2585 case OPC_EmitMergeInputChains: {
2586 assert(InputChain.getNode() == 0 &&
2587 "EmitMergeInputChains should be the first chain producing node");
2588 // This node gets a list of nodes we matched in the input that have
2589 // chains. We want to token factor all of the input chains to these nodes
2590 // together. However, if any of the input chains is actually one of the
2591 // nodes matched in this pattern, then we have an intra-match reference.
2592 // Ignore these because the newly token factored chain should not refer to
2594 unsigned NumChains = MatcherTable[MatcherIndex++];
2595 assert(NumChains != 0 && "Can't TF zero chains");
2597 assert(ChainNodesMatched.empty() &&
2598 "Should only have one EmitMergeInputChains per match");
2600 // Read all of the chained nodes.
2601 for (unsigned i = 0; i != NumChains; ++i) {
2602 unsigned RecNo = MatcherTable[MatcherIndex++];
2603 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2604 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2606 // FIXME: What if other value results of the node have uses not matched
2608 if (ChainNodesMatched.back() != NodeToMatch &&
2609 !RecordedNodes[RecNo].first.hasOneUse()) {
2610 ChainNodesMatched.clear();
2615 // If the inner loop broke out, the match fails.
2616 if (ChainNodesMatched.empty())
2619 // Merge the input chains if they are not intra-pattern references.
2620 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2622 if (InputChain.getNode() == 0)
2623 break; // Failed to merge.
2628 case OPC_EmitCopyToReg: {
2629 unsigned RecNo = MatcherTable[MatcherIndex++];
2630 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2631 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2633 if (InputChain.getNode() == 0)
2634 InputChain = CurDAG->getEntryNode();
2636 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
2637 DestPhysReg, RecordedNodes[RecNo].first,
2640 InputGlue = InputChain.getValue(1);
2644 case OPC_EmitNodeXForm: {
2645 unsigned XFormNo = MatcherTable[MatcherIndex++];
2646 unsigned RecNo = MatcherTable[MatcherIndex++];
2647 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2648 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
2649 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
2654 case OPC_MorphNodeTo: {
2655 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2656 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2657 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2658 // Get the result VT list.
2659 unsigned NumVTs = MatcherTable[MatcherIndex++];
2660 SmallVector<EVT, 4> VTs;
2661 for (unsigned i = 0; i != NumVTs; ++i) {
2662 MVT::SimpleValueType VT =
2663 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2664 if (VT == MVT::iPTR) VT = getTargetLowering()->getPointerTy().SimpleTy;
2668 if (EmitNodeInfo & OPFL_Chain)
2669 VTs.push_back(MVT::Other);
2670 if (EmitNodeInfo & OPFL_GlueOutput)
2671 VTs.push_back(MVT::Glue);
2673 // This is hot code, so optimize the two most common cases of 1 and 2
2676 if (VTs.size() == 1)
2677 VTList = CurDAG->getVTList(VTs[0]);
2678 else if (VTs.size() == 2)
2679 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2681 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2683 // Get the operand list.
2684 unsigned NumOps = MatcherTable[MatcherIndex++];
2685 SmallVector<SDValue, 8> Ops;
2686 for (unsigned i = 0; i != NumOps; ++i) {
2687 unsigned RecNo = MatcherTable[MatcherIndex++];
2689 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2691 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2692 Ops.push_back(RecordedNodes[RecNo].first);
2695 // If there are variadic operands to add, handle them now.
2696 if (EmitNodeInfo & OPFL_VariadicInfo) {
2697 // Determine the start index to copy from.
2698 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2699 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2700 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2701 "Invalid variadic node");
2702 // Copy all of the variadic operands, not including a potential glue
2704 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2706 SDValue V = NodeToMatch->getOperand(i);
2707 if (V.getValueType() == MVT::Glue) break;
2712 // If this has chain/glue inputs, add them.
2713 if (EmitNodeInfo & OPFL_Chain)
2714 Ops.push_back(InputChain);
2715 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
2716 Ops.push_back(InputGlue);
2720 if (Opcode != OPC_MorphNodeTo) {
2721 // If this is a normal EmitNode command, just create the new node and
2722 // add the results to the RecordedNodes list.
2723 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
2726 // Add all the non-glue/non-chain results to the RecordedNodes list.
2727 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2728 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
2729 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
2733 } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
2734 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2737 // NodeToMatch was eliminated by CSE when the target changed the DAG.
2738 // We will visit the equivalent node later.
2739 DEBUG(dbgs() << "Node was eliminated by CSE\n");
2743 // If the node had chain/glue results, update our notion of the current
2745 if (EmitNodeInfo & OPFL_GlueOutput) {
2746 InputGlue = SDValue(Res, VTs.size()-1);
2747 if (EmitNodeInfo & OPFL_Chain)
2748 InputChain = SDValue(Res, VTs.size()-2);
2749 } else if (EmitNodeInfo & OPFL_Chain)
2750 InputChain = SDValue(Res, VTs.size()-1);
2752 // If the OPFL_MemRefs glue is set on this node, slap all of the
2753 // accumulated memrefs onto it.
2755 // FIXME: This is vastly incorrect for patterns with multiple outputs
2756 // instructions that access memory and for ComplexPatterns that match
2758 if (EmitNodeInfo & OPFL_MemRefs) {
2759 // Only attach load or store memory operands if the generated
2760 // instruction may load or store.
2761 const MCInstrDesc &MCID = TM.getInstrInfo()->get(TargetOpc);
2762 bool mayLoad = MCID.mayLoad();
2763 bool mayStore = MCID.mayStore();
2765 unsigned NumMemRefs = 0;
2766 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
2767 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2768 if ((*I)->isLoad()) {
2771 } else if ((*I)->isStore()) {
2779 MachineSDNode::mmo_iterator MemRefs =
2780 MF->allocateMemRefsArray(NumMemRefs);
2782 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
2783 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
2784 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2785 if ((*I)->isLoad()) {
2788 } else if ((*I)->isStore()) {
2796 cast<MachineSDNode>(Res)
2797 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
2801 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2802 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
2804 // If this was a MorphNodeTo then we're completely done!
2805 if (Opcode == OPC_MorphNodeTo) {
2806 // Update chain and glue uses.
2807 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2808 InputGlue, GlueResultNodesMatched, true);
2815 case OPC_MarkGlueResults: {
2816 unsigned NumNodes = MatcherTable[MatcherIndex++];
2818 // Read and remember all the glue-result nodes.
2819 for (unsigned i = 0; i != NumNodes; ++i) {
2820 unsigned RecNo = MatcherTable[MatcherIndex++];
2822 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2824 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2825 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2830 case OPC_CompleteMatch: {
2831 // The match has been completed, and any new nodes (if any) have been
2832 // created. Patch up references to the matched dag to use the newly
2834 unsigned NumResults = MatcherTable[MatcherIndex++];
2836 for (unsigned i = 0; i != NumResults; ++i) {
2837 unsigned ResSlot = MatcherTable[MatcherIndex++];
2839 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2841 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2842 SDValue Res = RecordedNodes[ResSlot].first;
2844 assert(i < NodeToMatch->getNumValues() &&
2845 NodeToMatch->getValueType(i) != MVT::Other &&
2846 NodeToMatch->getValueType(i) != MVT::Glue &&
2847 "Invalid number of results to complete!");
2848 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2849 NodeToMatch->getValueType(i) == MVT::iPTR ||
2850 Res.getValueType() == MVT::iPTR ||
2851 NodeToMatch->getValueType(i).getSizeInBits() ==
2852 Res.getValueType().getSizeInBits()) &&
2853 "invalid replacement");
2854 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2857 // If the root node defines glue, add it to the glue nodes to update list.
2858 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
2859 GlueResultNodesMatched.push_back(NodeToMatch);
2861 // Update chain and glue uses.
2862 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2863 InputGlue, GlueResultNodesMatched, false);
2865 assert(NodeToMatch->use_empty() &&
2866 "Didn't replace all uses of the node?");
2868 // FIXME: We just return here, which interacts correctly with SelectRoot
2869 // above. We should fix this to not return an SDNode* anymore.
2874 // If the code reached this point, then the match failed. See if there is
2875 // another child to try in the current 'Scope', otherwise pop it until we
2876 // find a case to check.
2877 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
2878 ++NumDAGIselRetries;
2880 if (MatchScopes.empty()) {
2881 CannotYetSelect(NodeToMatch);
2885 // Restore the interpreter state back to the point where the scope was
2887 MatchScope &LastScope = MatchScopes.back();
2888 RecordedNodes.resize(LastScope.NumRecordedNodes);
2890 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2891 N = NodeStack.back();
2893 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2894 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2895 MatcherIndex = LastScope.FailIndex;
2897 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
2899 InputChain = LastScope.InputChain;
2900 InputGlue = LastScope.InputGlue;
2901 if (!LastScope.HasChainNodesMatched)
2902 ChainNodesMatched.clear();
2903 if (!LastScope.HasGlueResultNodesMatched)
2904 GlueResultNodesMatched.clear();
2906 // Check to see what the offset is at the new MatcherIndex. If it is zero
2907 // we have reached the end of this scope, otherwise we have another child
2908 // in the current scope to try.
2909 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2910 if (NumToSkip & 128)
2911 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2913 // If we have another child in this scope to match, update FailIndex and
2915 if (NumToSkip != 0) {
2916 LastScope.FailIndex = MatcherIndex+NumToSkip;
2920 // End of this scope, pop it and try the next child in the containing
2922 MatchScopes.pop_back();
2929 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2931 raw_string_ostream Msg(msg);
2932 Msg << "Cannot select: ";
2934 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2935 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2936 N->getOpcode() != ISD::INTRINSIC_VOID) {
2937 N->printrFull(Msg, CurDAG);
2938 Msg << "\nIn function: " << MF->getName();
2940 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2942 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2943 if (iid < Intrinsic::num_intrinsics)
2944 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2945 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2946 Msg << "target intrinsic %" << TII->getName(iid);
2948 Msg << "unknown intrinsic #" << iid;
2950 report_fatal_error(Msg.str());
2953 char SelectionDAGISel::ID = 0;