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 "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
38 #include "llvm/CodeGen/SchedulerRegistry.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetFrameInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/Timer.h"
53 #include "llvm/Support/raw_ostream.h"
58 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
60 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
61 cl::desc("Enable verbose messages in the \"fast\" "
62 "instruction selector"));
64 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
65 cl::desc("Enable abort calls when \"fast\" instruction fails"));
67 SchedLiveInCopies("schedule-livein-copies",
68 cl::desc("Schedule copies of livein registers"),
73 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
74 cl::desc("Pop up a window to show dags before the first "
77 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
78 cl::desc("Pop up a window to show dags before legalize types"));
80 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
81 cl::desc("Pop up a window to show dags before legalize"));
83 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
84 cl::desc("Pop up a window to show dags before the second "
87 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
88 cl::desc("Pop up a window to show dags before the post legalize types"
89 " dag combine pass"));
91 ViewISelDAGs("view-isel-dags", cl::Hidden,
92 cl::desc("Pop up a window to show isel dags as they are selected"));
94 ViewSchedDAGs("view-sched-dags", cl::Hidden,
95 cl::desc("Pop up a window to show sched dags as they are processed"));
97 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
98 cl::desc("Pop up a window to show SUnit dags after they are processed"));
100 static const bool ViewDAGCombine1 = false,
101 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
102 ViewDAGCombine2 = false,
103 ViewDAGCombineLT = false,
104 ViewISelDAGs = false, ViewSchedDAGs = false,
105 ViewSUnitDAGs = false;
108 //===---------------------------------------------------------------------===//
110 /// RegisterScheduler class - Track the registration of instruction schedulers.
112 //===---------------------------------------------------------------------===//
113 MachinePassRegistry RegisterScheduler::Registry;
115 //===---------------------------------------------------------------------===//
117 /// ISHeuristic command line option for instruction schedulers.
119 //===---------------------------------------------------------------------===//
120 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
121 RegisterPassParser<RegisterScheduler> >
122 ISHeuristic("pre-RA-sched",
123 cl::init(&createDefaultScheduler),
124 cl::desc("Instruction schedulers available (before register"
127 static RegisterScheduler
128 defaultListDAGScheduler("default", "Best scheduler for the target",
129 createDefaultScheduler);
132 //===--------------------------------------------------------------------===//
133 /// createDefaultScheduler - This creates an instruction scheduler appropriate
135 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
136 CodeGenOpt::Level OptLevel) {
137 const TargetLowering &TLI = IS->getTargetLowering();
139 if (OptLevel == CodeGenOpt::None)
140 return createFastDAGScheduler(IS, OptLevel);
141 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
142 return createTDListDAGScheduler(IS, OptLevel);
143 assert(TLI.getSchedulingPreference() ==
144 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
145 return createBURRListDAGScheduler(IS, OptLevel);
149 // EmitInstrWithCustomInserter - This method should be implemented by targets
150 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
151 // instructions are special in various ways, which require special support to
152 // insert. The specified MachineInstr is created but not inserted into any
153 // basic blocks, and the scheduler passes ownership of it to this method.
154 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
155 MachineBasicBlock *MBB) const {
157 cerr << "If a target marks an instruction with "
158 "'usesCustomDAGSchedInserter', it must implement "
159 "TargetLowering::EmitInstrWithCustomInserter!";
165 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
166 /// physical register has only a single copy use, then coalesced the copy
168 static void EmitLiveInCopy(MachineBasicBlock *MBB,
169 MachineBasicBlock::iterator &InsertPos,
170 unsigned VirtReg, unsigned PhysReg,
171 const TargetRegisterClass *RC,
172 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
173 const MachineRegisterInfo &MRI,
174 const TargetRegisterInfo &TRI,
175 const TargetInstrInfo &TII) {
176 unsigned NumUses = 0;
177 MachineInstr *UseMI = NULL;
178 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
179 UE = MRI.use_end(); UI != UE; ++UI) {
185 // If the number of uses is not one, or the use is not a move instruction,
186 // don't coalesce. Also, only coalesce away a virtual register to virtual
188 bool Coalesced = false;
189 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
191 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
192 TargetRegisterInfo::isVirtualRegister(DstReg)) {
197 // Now find an ideal location to insert the copy.
198 MachineBasicBlock::iterator Pos = InsertPos;
199 while (Pos != MBB->begin()) {
200 MachineInstr *PrevMI = prior(Pos);
201 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
202 // copyRegToReg might emit multiple instructions to do a copy.
203 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
204 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
205 // This is what the BB looks like right now:
210 // We want to insert "r1025 = mov r1". Inserting this copy below the
211 // move to r1024 makes it impossible for that move to be coalesced.
218 break; // Woot! Found a good location.
222 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
223 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
226 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
228 if (&*InsertPos == UseMI) ++InsertPos;
233 /// EmitLiveInCopies - If this is the first basic block in the function,
234 /// and if it has live ins that need to be copied into vregs, emit the
235 /// copies into the block.
236 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
237 const MachineRegisterInfo &MRI,
238 const TargetRegisterInfo &TRI,
239 const TargetInstrInfo &TII) {
240 if (SchedLiveInCopies) {
241 // Emit the copies at a heuristically-determined location in the block.
242 DenseMap<MachineInstr*, unsigned> CopyRegMap;
243 MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
244 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
245 E = MRI.livein_end(); LI != E; ++LI)
247 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
248 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
249 RC, CopyRegMap, MRI, TRI, TII);
252 // Emit the copies into the top of the block.
253 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
254 E = MRI.livein_end(); LI != E; ++LI)
256 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
257 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
258 LI->second, LI->first, RC, RC);
259 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
265 //===----------------------------------------------------------------------===//
266 // SelectionDAGISel code
267 //===----------------------------------------------------------------------===//
269 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
270 FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
271 FuncInfo(new FunctionLoweringInfo(TLI)),
272 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
273 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
279 SelectionDAGISel::~SelectionDAGISel() {
285 unsigned SelectionDAGISel::MakeReg(MVT VT) {
286 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
289 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
290 AU.addRequired<AliasAnalysis>();
291 AU.addRequired<GCModuleInfo>();
292 AU.addRequired<DwarfWriter>();
293 AU.setPreservesAll();
296 bool SelectionDAGISel::runOnFunction(Function &Fn) {
297 // Do some sanity-checking on the command-line options.
298 assert((!EnableFastISelVerbose || EnableFastISel) &&
299 "-fast-isel-verbose requires -fast-isel");
300 assert((!EnableFastISelAbort || EnableFastISel) &&
301 "-fast-isel-abort requires -fast-isel");
303 // Do not codegen any 'available_externally' functions at all, they have
304 // definitions outside the translation unit.
305 if (Fn.hasAvailableExternallyLinkage())
309 // Get alias analysis for load/store combining.
310 AA = &getAnalysis<AliasAnalysis>();
312 TargetMachine &TM = TLI.getTargetMachine();
313 MF = &MachineFunction::construct(&Fn, TM);
314 const TargetInstrInfo &TII = *TM.getInstrInfo();
315 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
317 if (MF->getFunction()->hasGC())
318 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
321 RegInfo = &MF->getRegInfo();
322 DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n");
324 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
325 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
326 CurDAG->init(*MF, MMI, DW);
327 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
330 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
331 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
333 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
335 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
337 // If the first basic block in the function has live ins that need to be
338 // copied into vregs, emit the copies into the top of the block before
339 // emitting the code for the block.
340 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
342 // Add function live-ins to entry block live-in set.
343 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
344 E = RegInfo->livein_end(); I != E; ++I)
345 MF->begin()->addLiveIn(I->first);
348 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
349 "Not all catch info was assigned to a landing pad!");
357 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
358 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
359 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
360 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
361 // Apply the catch info to DestBB.
362 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
364 if (!FLI.MBBMap[SrcBB]->isLandingPad())
365 FLI.CatchInfoFound.insert(EHSel);
370 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
371 /// whether object offset >= 0.
373 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
374 if (!isa<FrameIndexSDNode>(Op)) return false;
376 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
377 int FrameIdx = FrameIdxNode->getIndex();
378 return MFI->isFixedObjectIndex(FrameIdx) &&
379 MFI->getObjectOffset(FrameIdx) >= 0;
382 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
383 /// possibly be overwritten when lowering the outgoing arguments in a tail
384 /// call. Currently the implementation of this call is very conservative and
385 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
386 /// virtual registers would be overwritten by direct lowering.
387 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
388 MachineFrameInfo *MFI) {
389 RegisterSDNode * OpReg = NULL;
390 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
391 (Op.getOpcode()== ISD::CopyFromReg &&
392 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
393 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
394 (Op.getOpcode() == ISD::LOAD &&
395 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
396 (Op.getOpcode() == ISD::MERGE_VALUES &&
397 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
398 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
404 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
405 /// DAG and fixes their tailcall attribute operand.
406 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
407 const TargetLowering& TLI) {
409 SDValue Terminator = DAG.getRoot();
412 if (Terminator.getOpcode() == ISD::RET) {
413 Ret = Terminator.getNode();
416 // Fix tail call attribute of CALL nodes.
417 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
418 BI = DAG.allnodes_end(); BI != BE; ) {
420 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
421 SDValue OpRet(Ret, 0);
422 SDValue OpCall(BI, 0);
423 bool isMarkedTailCall = TheCall->isTailCall();
424 // If CALL node has tail call attribute set to true and the call is not
425 // eligible (no RET or the target rejects) the attribute is fixed to
426 // false. The TargetLowering::IsEligibleForTailCallOptimization function
427 // must correctly identify tail call optimizable calls.
428 if (!isMarkedTailCall) continue;
430 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
431 // Not eligible. Mark CALL node as non tail call. Note that we
432 // can modify the call node in place since calls are not CSE'd.
433 TheCall->setNotTailCall();
435 // Look for tail call clobbered arguments. Emit a series of
436 // copyto/copyfrom virtual register nodes to protect them.
437 SmallVector<SDValue, 32> Ops;
438 SDValue Chain = TheCall->getChain(), InFlag;
439 Ops.push_back(Chain);
440 Ops.push_back(TheCall->getCallee());
441 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
442 SDValue Arg = TheCall->getArg(i);
443 bool isByVal = TheCall->getArgFlags(i).isByVal();
444 MachineFunction &MF = DAG.getMachineFunction();
445 MachineFrameInfo *MFI = MF.getFrameInfo();
447 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
448 MVT VT = Arg.getValueType();
449 unsigned VReg = MF.getRegInfo().
450 createVirtualRegister(TLI.getRegClassFor(VT));
451 Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(),
453 InFlag = Chain.getValue(1);
454 Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(),
456 Chain = Arg.getValue(1);
457 InFlag = Arg.getValue(2);
460 Ops.push_back(TheCall->getArgFlagsVal(i));
462 // Link in chain of CopyTo/CopyFromReg.
464 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
470 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
471 BasicBlock::iterator Begin,
472 BasicBlock::iterator End) {
473 SDL->setCurrentBasicBlock(BB);
475 // Lower all of the non-terminator instructions.
476 for (BasicBlock::iterator I = Begin; I != End; ++I)
477 if (!isa<TerminatorInst>(I))
480 // Ensure that all instructions which are used outside of their defining
481 // blocks are available as virtual registers. Invoke is handled elsewhere.
482 for (BasicBlock::iterator I = Begin; I != End; ++I)
483 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
484 SDL->CopyToExportRegsIfNeeded(I);
486 // Handle PHI nodes in successor blocks.
487 if (End == LLVMBB->end()) {
488 HandlePHINodesInSuccessorBlocks(LLVMBB);
490 // Lower the terminator after the copies are emitted.
491 SDL->visit(*LLVMBB->getTerminator());
494 // Make sure the root of the DAG is up-to-date.
495 CurDAG->setRoot(SDL->getControlRoot());
497 // Check whether calls in this block are real tail calls. Fix up CALL nodes
498 // with correct tailcall attribute so that the target can rely on the tailcall
499 // attribute indicating whether the call is really eligible for tail call
501 if (PerformTailCallOpt)
502 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
504 // Final step, emit the lowered DAG as machine code.
509 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
510 SmallPtrSet<SDNode*, 128> VisitedNodes;
511 SmallVector<SDNode*, 128> Worklist;
513 Worklist.push_back(CurDAG->getRoot().getNode());
519 while (!Worklist.empty()) {
520 SDNode *N = Worklist.back();
523 // If we've already seen this node, ignore it.
524 if (!VisitedNodes.insert(N))
527 // Otherwise, add all chain operands to the worklist.
528 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
529 if (N->getOperand(i).getValueType() == MVT::Other)
530 Worklist.push_back(N->getOperand(i).getNode());
532 // If this is a CopyToReg with a vreg dest, process it.
533 if (N->getOpcode() != ISD::CopyToReg)
536 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
537 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
540 // Ignore non-scalar or non-integer values.
541 SDValue Src = N->getOperand(2);
542 MVT SrcVT = Src.getValueType();
543 if (!SrcVT.isInteger() || SrcVT.isVector())
546 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
547 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
548 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
550 // Only install this information if it tells us something.
551 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
552 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
553 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
554 if (DestReg >= FLI.LiveOutRegInfo.size())
555 FLI.LiveOutRegInfo.resize(DestReg+1);
556 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
557 LOI.NumSignBits = NumSignBits;
558 LOI.KnownOne = KnownOne;
559 LOI.KnownZero = KnownZero;
564 void SelectionDAGISel::CodeGenAndEmitDAG() {
565 std::string GroupName;
566 if (TimePassesIsEnabled)
567 GroupName = "Instruction Selection and Scheduling";
568 std::string BlockName;
569 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
570 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
572 BlockName = CurDAG->getMachineFunction().getFunction()->getNameStr() + ":" +
573 BB->getBasicBlock()->getNameStr();
575 DOUT << "Initial selection DAG:\n";
576 DEBUG(CurDAG->dump());
578 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
580 // Run the DAG combiner in pre-legalize mode.
581 if (TimePassesIsEnabled) {
582 NamedRegionTimer T("DAG Combining 1", GroupName);
583 CurDAG->Combine(Unrestricted, *AA, OptLevel);
585 CurDAG->Combine(Unrestricted, *AA, OptLevel);
588 DOUT << "Optimized lowered selection DAG:\n";
589 DEBUG(CurDAG->dump());
591 // Second step, hack on the DAG until it only uses operations and types that
592 // the target supports.
593 if (!DisableLegalizeTypes) {
594 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
598 if (TimePassesIsEnabled) {
599 NamedRegionTimer T("Type Legalization", GroupName);
600 Changed = CurDAG->LegalizeTypes();
602 Changed = CurDAG->LegalizeTypes();
605 DOUT << "Type-legalized selection DAG:\n";
606 DEBUG(CurDAG->dump());
609 if (ViewDAGCombineLT)
610 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
612 // Run the DAG combiner in post-type-legalize mode.
613 if (TimePassesIsEnabled) {
614 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
615 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
617 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
620 DOUT << "Optimized type-legalized selection DAG:\n";
621 DEBUG(CurDAG->dump());
624 if (TimePassesIsEnabled) {
625 NamedRegionTimer T("Vector Legalization", GroupName);
626 Changed = CurDAG->LegalizeVectors();
628 Changed = CurDAG->LegalizeVectors();
632 if (TimePassesIsEnabled) {
633 NamedRegionTimer T("Type Legalization 2", GroupName);
634 Changed = CurDAG->LegalizeTypes();
636 Changed = CurDAG->LegalizeTypes();
639 if (ViewDAGCombineLT)
640 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
642 // Run the DAG combiner in post-type-legalize mode.
643 if (TimePassesIsEnabled) {
644 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
645 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
647 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
650 DOUT << "Optimized vector-legalized selection DAG:\n";
651 DEBUG(CurDAG->dump());
655 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
657 if (TimePassesIsEnabled) {
658 NamedRegionTimer T("DAG Legalization", GroupName);
659 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
661 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
664 DOUT << "Legalized selection DAG:\n";
665 DEBUG(CurDAG->dump());
667 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
669 // Run the DAG combiner in post-legalize mode.
670 if (TimePassesIsEnabled) {
671 NamedRegionTimer T("DAG Combining 2", GroupName);
672 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
674 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
677 DOUT << "Optimized legalized selection DAG:\n";
678 DEBUG(CurDAG->dump());
680 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
682 if (OptLevel != CodeGenOpt::None)
683 ComputeLiveOutVRegInfo();
685 // Third, instruction select all of the operations to machine code, adding the
686 // code to the MachineBasicBlock.
687 if (TimePassesIsEnabled) {
688 NamedRegionTimer T("Instruction Selection", GroupName);
694 DOUT << "Selected selection DAG:\n";
695 DEBUG(CurDAG->dump());
697 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
699 // Schedule machine code.
700 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
701 if (TimePassesIsEnabled) {
702 NamedRegionTimer T("Instruction Scheduling", GroupName);
703 Scheduler->Run(CurDAG, BB, BB->end());
705 Scheduler->Run(CurDAG, BB, BB->end());
708 if (ViewSUnitDAGs) Scheduler->viewGraph();
710 // Emit machine code to BB. This can change 'BB' to the last block being
712 if (TimePassesIsEnabled) {
713 NamedRegionTimer T("Instruction Creation", GroupName);
714 BB = Scheduler->EmitSchedule();
716 BB = Scheduler->EmitSchedule();
719 // Free the scheduler state.
720 if (TimePassesIsEnabled) {
721 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
727 DOUT << "Selected machine code:\n";
731 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
733 MachineModuleInfo *MMI,
735 const TargetInstrInfo &TII) {
736 // Initialize the Fast-ISel state, if needed.
737 FastISel *FastIS = 0;
739 FastIS = TLI.createFastISel(MF, MMI, DW,
742 FuncInfo->StaticAllocaMap
744 , FuncInfo->CatchInfoLost
748 // Iterate over all basic blocks in the function.
749 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
750 BasicBlock *LLVMBB = &*I;
751 BB = FuncInfo->MBBMap[LLVMBB];
753 BasicBlock::iterator const Begin = LLVMBB->begin();
754 BasicBlock::iterator const End = LLVMBB->end();
755 BasicBlock::iterator BI = Begin;
757 // Lower any arguments needed in this block if this is the entry block.
758 bool SuppressFastISel = false;
759 if (LLVMBB == &Fn.getEntryBlock()) {
760 LowerArguments(LLVMBB);
762 // If any of the arguments has the byval attribute, forgo
763 // fast-isel in the entry block.
766 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
768 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
769 if (EnableFastISelVerbose || EnableFastISelAbort)
770 cerr << "FastISel skips entry block due to byval argument\n";
771 SuppressFastISel = true;
777 if (MMI && BB->isLandingPad()) {
778 // Add a label to mark the beginning of the landing pad. Deletion of the
779 // landing pad can thus be detected via the MachineModuleInfo.
780 unsigned LabelID = MMI->addLandingPad(BB);
782 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
783 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
785 // Mark exception register as live in.
786 unsigned Reg = TLI.getExceptionAddressRegister();
787 if (Reg) BB->addLiveIn(Reg);
789 // Mark exception selector register as live in.
790 Reg = TLI.getExceptionSelectorRegister();
791 if (Reg) BB->addLiveIn(Reg);
793 // FIXME: Hack around an exception handling flaw (PR1508): the personality
794 // function and list of typeids logically belong to the invoke (or, if you
795 // like, the basic block containing the invoke), and need to be associated
796 // with it in the dwarf exception handling tables. Currently however the
797 // information is provided by an intrinsic (eh.selector) that can be moved
798 // to unexpected places by the optimizers: if the unwind edge is critical,
799 // then breaking it can result in the intrinsics being in the successor of
800 // the landing pad, not the landing pad itself. This results in exceptions
801 // not being caught because no typeids are associated with the invoke.
802 // This may not be the only way things can go wrong, but it is the only way
803 // we try to work around for the moment.
804 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
806 if (Br && Br->isUnconditional()) { // Critical edge?
807 BasicBlock::iterator I, E;
808 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
809 if (isa<EHSelectorInst>(I))
813 // No catch info found - try to extract some from the successor.
814 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
818 // Before doing SelectionDAG ISel, see if FastISel has been requested.
819 if (FastIS && !SuppressFastISel) {
820 // Emit code for any incoming arguments. This must happen before
821 // beginning FastISel on the entry block.
822 if (LLVMBB == &Fn.getEntryBlock()) {
823 CurDAG->setRoot(SDL->getControlRoot());
827 FastIS->startNewBlock(BB);
828 // Do FastISel on as many instructions as possible.
829 for (; BI != End; ++BI) {
830 // Just before the terminator instruction, insert instructions to
831 // feed PHI nodes in successor blocks.
832 if (isa<TerminatorInst>(BI))
833 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
834 if (EnableFastISelVerbose || EnableFastISelAbort) {
835 cerr << "FastISel miss: ";
838 assert(!EnableFastISelAbort &&
839 "FastISel didn't handle a PHI in a successor");
843 // First try normal tablegen-generated "fast" selection.
844 if (FastIS->SelectInstruction(BI))
847 // Next, try calling the target to attempt to handle the instruction.
848 if (FastIS->TargetSelectInstruction(BI))
851 // Then handle certain instructions as single-LLVM-Instruction blocks.
852 if (isa<CallInst>(BI)) {
853 if (EnableFastISelVerbose || EnableFastISelAbort) {
854 cerr << "FastISel missed call: ";
858 if (BI->getType() != Type::VoidTy) {
859 unsigned &R = FuncInfo->ValueMap[BI];
861 R = FuncInfo->CreateRegForValue(BI);
864 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
865 SelectBasicBlock(LLVMBB, BI, next(BI));
866 // If the instruction was codegen'd with multiple blocks,
867 // inform the FastISel object where to resume inserting.
868 FastIS->setCurrentBlock(BB);
872 // Otherwise, give up on FastISel for the rest of the block.
873 // For now, be a little lenient about non-branch terminators.
874 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
875 if (EnableFastISelVerbose || EnableFastISelAbort) {
876 cerr << "FastISel miss: ";
879 if (EnableFastISelAbort)
880 // The "fast" selector couldn't handle something and bailed.
881 // For the purpose of debugging, just abort.
882 llvm_unreachable("FastISel didn't select the entire block");
888 // Run SelectionDAG instruction selection on the remainder of the block
889 // not handled by FastISel. If FastISel is not run, this is the entire
892 // If FastISel is run and it has known DebugLoc then use it.
893 if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
894 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
895 SelectBasicBlock(LLVMBB, BI, End);
905 SelectionDAGISel::FinishBasicBlock() {
907 DOUT << "Target-post-processed machine code:\n";
910 DOUT << "Total amount of phi nodes to update: "
911 << SDL->PHINodesToUpdate.size() << "\n";
912 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
913 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
914 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
916 // Next, now that we know what the last MBB the LLVM BB expanded is, update
917 // PHI nodes in successors.
918 if (SDL->SwitchCases.empty() &&
919 SDL->JTCases.empty() &&
920 SDL->BitTestCases.empty()) {
921 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
922 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
923 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
924 "This is not a machine PHI node that we are updating!");
925 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
927 PHI->addOperand(MachineOperand::CreateMBB(BB));
929 SDL->PHINodesToUpdate.clear();
933 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
934 // Lower header first, if it wasn't already lowered
935 if (!SDL->BitTestCases[i].Emitted) {
936 // Set the current basic block to the mbb we wish to insert the code into
937 BB = SDL->BitTestCases[i].Parent;
938 SDL->setCurrentBasicBlock(BB);
940 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
941 CurDAG->setRoot(SDL->getRoot());
946 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
947 // Set the current basic block to the mbb we wish to insert the code into
948 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
949 SDL->setCurrentBasicBlock(BB);
952 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
953 SDL->BitTestCases[i].Reg,
954 SDL->BitTestCases[i].Cases[j]);
956 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
957 SDL->BitTestCases[i].Reg,
958 SDL->BitTestCases[i].Cases[j]);
961 CurDAG->setRoot(SDL->getRoot());
967 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
968 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
969 MachineBasicBlock *PHIBB = PHI->getParent();
970 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
971 "This is not a machine PHI node that we are updating!");
972 // This is "default" BB. We have two jumps to it. From "header" BB and
973 // from last "case" BB.
974 if (PHIBB == SDL->BitTestCases[i].Default) {
975 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
977 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
978 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
980 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
983 // One of "cases" BB.
984 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
986 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
987 if (cBB->succ_end() !=
988 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
989 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
991 PHI->addOperand(MachineOperand::CreateMBB(cBB));
996 SDL->BitTestCases.clear();
998 // If the JumpTable record is filled in, then we need to emit a jump table.
999 // Updating the PHI nodes is tricky in this case, since we need to determine
1000 // whether the PHI is a successor of the range check MBB or the jump table MBB
1001 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
1002 // Lower header first, if it wasn't already lowered
1003 if (!SDL->JTCases[i].first.Emitted) {
1004 // Set the current basic block to the mbb we wish to insert the code into
1005 BB = SDL->JTCases[i].first.HeaderBB;
1006 SDL->setCurrentBasicBlock(BB);
1008 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
1009 CurDAG->setRoot(SDL->getRoot());
1010 CodeGenAndEmitDAG();
1014 // Set the current basic block to the mbb we wish to insert the code into
1015 BB = SDL->JTCases[i].second.MBB;
1016 SDL->setCurrentBasicBlock(BB);
1018 SDL->visitJumpTable(SDL->JTCases[i].second);
1019 CurDAG->setRoot(SDL->getRoot());
1020 CodeGenAndEmitDAG();
1024 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
1025 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
1026 MachineBasicBlock *PHIBB = PHI->getParent();
1027 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1028 "This is not a machine PHI node that we are updating!");
1029 // "default" BB. We can go there only from header BB.
1030 if (PHIBB == SDL->JTCases[i].second.Default) {
1031 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1033 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
1035 // JT BB. Just iterate over successors here
1036 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
1037 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1039 PHI->addOperand(MachineOperand::CreateMBB(BB));
1043 SDL->JTCases.clear();
1045 // If the switch block involved a branch to one of the actual successors, we
1046 // need to update PHI nodes in that block.
1047 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1048 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1049 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1050 "This is not a machine PHI node that we are updating!");
1051 if (BB->isSuccessor(PHI->getParent())) {
1052 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1054 PHI->addOperand(MachineOperand::CreateMBB(BB));
1058 // If we generated any switch lowering information, build and codegen any
1059 // additional DAGs necessary.
1060 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1061 // Set the current basic block to the mbb we wish to insert the code into
1062 BB = SDL->SwitchCases[i].ThisBB;
1063 SDL->setCurrentBasicBlock(BB);
1066 SDL->visitSwitchCase(SDL->SwitchCases[i]);
1067 CurDAG->setRoot(SDL->getRoot());
1068 CodeGenAndEmitDAG();
1071 // Handle any PHI nodes in successors of this chunk, as if we were coming
1072 // from the original BB before switch expansion. Note that PHI nodes can
1073 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1074 // handle them the right number of times.
1075 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
1076 for (MachineBasicBlock::iterator Phi = BB->begin();
1077 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1078 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1079 for (unsigned pn = 0; ; ++pn) {
1080 assert(pn != SDL->PHINodesToUpdate.size() &&
1081 "Didn't find PHI entry!");
1082 if (SDL->PHINodesToUpdate[pn].first == Phi) {
1083 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1085 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1091 // Don't process RHS if same block as LHS.
1092 if (BB == SDL->SwitchCases[i].FalseBB)
1093 SDL->SwitchCases[i].FalseBB = 0;
1095 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1096 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1097 SDL->SwitchCases[i].FalseBB = 0;
1099 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1101 SDL->SwitchCases.clear();
1103 SDL->PHINodesToUpdate.clear();
1107 /// Create the scheduler. If a specific scheduler was specified
1108 /// via the SchedulerRegistry, use it, otherwise select the
1109 /// one preferred by the target.
1111 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1112 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1116 RegisterScheduler::setDefault(Ctor);
1119 return Ctor(this, OptLevel);
1122 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1123 return new ScheduleHazardRecognizer();
1126 //===----------------------------------------------------------------------===//
1127 // Helper functions used by the generated instruction selector.
1128 //===----------------------------------------------------------------------===//
1129 // Calls to these methods are generated by tblgen.
1131 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1132 /// the dag combiner simplified the 255, we still want to match. RHS is the
1133 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1134 /// specified in the .td file (e.g. 255).
1135 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1136 int64_t DesiredMaskS) const {
1137 const APInt &ActualMask = RHS->getAPIntValue();
1138 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1140 // If the actual mask exactly matches, success!
1141 if (ActualMask == DesiredMask)
1144 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1145 if (ActualMask.intersects(~DesiredMask))
1148 // Otherwise, the DAG Combiner may have proven that the value coming in is
1149 // either already zero or is not demanded. Check for known zero input bits.
1150 APInt NeededMask = DesiredMask & ~ActualMask;
1151 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1154 // TODO: check to see if missing bits are just not demanded.
1156 // Otherwise, this pattern doesn't match.
1160 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1161 /// the dag combiner simplified the 255, we still want to match. RHS is the
1162 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1163 /// specified in the .td file (e.g. 255).
1164 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1165 int64_t DesiredMaskS) const {
1166 const APInt &ActualMask = RHS->getAPIntValue();
1167 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1169 // If the actual mask exactly matches, success!
1170 if (ActualMask == DesiredMask)
1173 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1174 if (ActualMask.intersects(~DesiredMask))
1177 // Otherwise, the DAG Combiner may have proven that the value coming in is
1178 // either already zero or is not demanded. Check for known zero input bits.
1179 APInt NeededMask = DesiredMask & ~ActualMask;
1181 APInt KnownZero, KnownOne;
1182 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1184 // If all the missing bits in the or are already known to be set, match!
1185 if ((NeededMask & KnownOne) == NeededMask)
1188 // TODO: check to see if missing bits are just not demanded.
1190 // Otherwise, this pattern doesn't match.
1195 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1196 /// by tblgen. Others should not call it.
1197 void SelectionDAGISel::
1198 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1199 std::vector<SDValue> InOps;
1200 std::swap(InOps, Ops);
1202 Ops.push_back(InOps[0]); // input chain.
1203 Ops.push_back(InOps[1]); // input asm string.
1205 unsigned i = 2, e = InOps.size();
1206 if (InOps[e-1].getValueType() == MVT::Flag)
1207 --e; // Don't process a flag operand if it is here.
1210 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1211 if ((Flags & 7) != 4 /*MEM*/) {
1212 // Just skip over this operand, copying the operands verbatim.
1213 Ops.insert(Ops.end(), InOps.begin()+i,
1214 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1215 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1217 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1218 "Memory operand with multiple values?");
1219 // Otherwise, this is a memory operand. Ask the target to select it.
1220 std::vector<SDValue> SelOps;
1221 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1222 llvm_report_error("Could not match memory address. Inline asm"
1226 // Add this to the output node.
1227 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1228 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1230 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1235 // Add the flag input back if present.
1236 if (e != InOps.size())
1237 Ops.push_back(InOps.back());
1240 /// findFlagUse - Return use of MVT::Flag value produced by the specified
1243 static SDNode *findFlagUse(SDNode *N) {
1244 unsigned FlagResNo = N->getNumValues()-1;
1245 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1246 SDUse &Use = I.getUse();
1247 if (Use.getResNo() == FlagResNo)
1248 return Use.getUser();
1253 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1254 /// This function recursively traverses up the operand chain, ignoring
1256 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1258 SmallPtrSet<SDNode*, 16> &Visited) {
1259 if (Use->getNodeId() < Def->getNodeId() ||
1260 !Visited.insert(Use))
1263 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1264 SDNode *N = Use->getOperand(i).getNode();
1266 if (Use == ImmedUse || Use == Root)
1267 continue; // We are not looking for immediate use.
1272 // Traverse up the operand chain.
1273 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1279 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
1280 /// be reached. Return true if that's the case. However, ignore direct uses
1281 /// by ImmedUse (which would be U in the example illustrated in
1282 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1284 /// FIXME: to be really generic, we should allow direct use by any node
1285 /// that is being folded. But realisticly since we only fold loads which
1286 /// have one non-chain use, we only need to watch out for load/op/store
1287 /// and load/op/cmp case where the root (store / cmp) may reach the load via
1288 /// its chain operand.
1289 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1290 SmallPtrSet<SDNode*, 16> Visited;
1291 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1294 /// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1295 /// U can be folded during instruction selection that starts at Root and
1296 /// folding N is profitable.
1297 bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1298 SDNode *Root) const {
1299 if (OptLevel == CodeGenOpt::None) return false;
1301 // If Root use can somehow reach N through a path that that doesn't contain
1302 // U then folding N would create a cycle. e.g. In the following
1303 // diagram, Root can reach N through X. If N is folded into into Root, then
1304 // X is both a predecessor and a successor of U.
1315 // * indicates nodes to be folded together.
1317 // If Root produces a flag, then it gets (even more) interesting. Since it
1318 // will be "glued" together with its flag use in the scheduler, we need to
1319 // check if it might reach N.
1338 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1339 // (call it Fold), then X is a predecessor of FU and a successor of
1340 // Fold. But since Fold and FU are flagged together, this will create
1341 // a cycle in the scheduling graph.
1343 MVT VT = Root->getValueType(Root->getNumValues()-1);
1344 while (VT == MVT::Flag) {
1345 SDNode *FU = findFlagUse(Root);
1349 VT = Root->getValueType(Root->getNumValues()-1);
1352 return !isNonImmUse(Root, N, U);
1356 char SelectionDAGISel::ID = 0;