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/MachineFunctionAnalysis.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
39 #include "llvm/CodeGen/SchedulerRegistry.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/CodeGen/DwarfWriter.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetFrameInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/Timer.h"
54 #include "llvm/Support/raw_ostream.h"
59 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
61 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
62 cl::desc("Enable verbose messages in the \"fast\" "
63 "instruction selector"));
65 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
66 cl::desc("Enable abort calls when \"fast\" instruction fails"));
68 SchedLiveInCopies("schedule-livein-copies",
69 cl::desc("Schedule copies of livein registers"),
74 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
75 cl::desc("Pop up a window to show dags before the first "
78 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
79 cl::desc("Pop up a window to show dags before legalize types"));
81 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
82 cl::desc("Pop up a window to show dags before legalize"));
84 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
85 cl::desc("Pop up a window to show dags before the second "
88 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
89 cl::desc("Pop up a window to show dags before the post legalize types"
90 " dag combine pass"));
92 ViewISelDAGs("view-isel-dags", cl::Hidden,
93 cl::desc("Pop up a window to show isel dags as they are selected"));
95 ViewSchedDAGs("view-sched-dags", cl::Hidden,
96 cl::desc("Pop up a window to show sched dags as they are processed"));
98 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
99 cl::desc("Pop up a window to show SUnit dags after they are processed"));
101 static const bool ViewDAGCombine1 = false,
102 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
103 ViewDAGCombine2 = false,
104 ViewDAGCombineLT = false,
105 ViewISelDAGs = false, ViewSchedDAGs = false,
106 ViewSUnitDAGs = false;
109 //===---------------------------------------------------------------------===//
111 /// RegisterScheduler class - Track the registration of instruction schedulers.
113 //===---------------------------------------------------------------------===//
114 MachinePassRegistry RegisterScheduler::Registry;
116 //===---------------------------------------------------------------------===//
118 /// ISHeuristic command line option for instruction schedulers.
120 //===---------------------------------------------------------------------===//
121 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
122 RegisterPassParser<RegisterScheduler> >
123 ISHeuristic("pre-RA-sched",
124 cl::init(&createDefaultScheduler),
125 cl::desc("Instruction schedulers available (before register"
128 static RegisterScheduler
129 defaultListDAGScheduler("default", "Best scheduler for the target",
130 createDefaultScheduler);
133 //===--------------------------------------------------------------------===//
134 /// createDefaultScheduler - This creates an instruction scheduler appropriate
136 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
137 CodeGenOpt::Level OptLevel) {
138 const TargetLowering &TLI = IS->getTargetLowering();
140 if (OptLevel == CodeGenOpt::None)
141 return createFastDAGScheduler(IS, OptLevel);
142 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
143 return createTDListDAGScheduler(IS, OptLevel);
144 assert(TLI.getSchedulingPreference() ==
145 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
146 return createBURRListDAGScheduler(IS, OptLevel);
150 // EmitInstrWithCustomInserter - This method should be implemented by targets
151 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
152 // instructions are special in various ways, which require special support to
153 // insert. The specified MachineInstr is created but not inserted into any
154 // basic blocks, and the scheduler passes ownership of it to this method.
155 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
156 MachineBasicBlock *MBB) const {
158 cerr << "If a target marks an instruction with "
159 "'usesCustomDAGSchedInserter', it must implement "
160 "TargetLowering::EmitInstrWithCustomInserter!";
166 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
167 /// physical register has only a single copy use, then coalesced the copy
169 static void EmitLiveInCopy(MachineBasicBlock *MBB,
170 MachineBasicBlock::iterator &InsertPos,
171 unsigned VirtReg, unsigned PhysReg,
172 const TargetRegisterClass *RC,
173 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
174 const MachineRegisterInfo &MRI,
175 const TargetRegisterInfo &TRI,
176 const TargetInstrInfo &TII) {
177 unsigned NumUses = 0;
178 MachineInstr *UseMI = NULL;
179 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
180 UE = MRI.use_end(); UI != UE; ++UI) {
186 // If the number of uses is not one, or the use is not a move instruction,
187 // don't coalesce. Also, only coalesce away a virtual register to virtual
189 bool Coalesced = false;
190 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
192 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
193 TargetRegisterInfo::isVirtualRegister(DstReg)) {
198 // Now find an ideal location to insert the copy.
199 MachineBasicBlock::iterator Pos = InsertPos;
200 while (Pos != MBB->begin()) {
201 MachineInstr *PrevMI = prior(Pos);
202 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
203 // copyRegToReg might emit multiple instructions to do a copy.
204 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
205 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
206 // This is what the BB looks like right now:
211 // We want to insert "r1025 = mov r1". Inserting this copy below the
212 // move to r1024 makes it impossible for that move to be coalesced.
219 break; // Woot! Found a good location.
223 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
224 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
227 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
229 if (&*InsertPos == UseMI) ++InsertPos;
234 /// EmitLiveInCopies - If this is the first basic block in the function,
235 /// and if it has live ins that need to be copied into vregs, emit the
236 /// copies into the block.
237 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
238 const MachineRegisterInfo &MRI,
239 const TargetRegisterInfo &TRI,
240 const TargetInstrInfo &TII) {
241 if (SchedLiveInCopies) {
242 // Emit the copies at a heuristically-determined location in the block.
243 DenseMap<MachineInstr*, unsigned> CopyRegMap;
244 MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
245 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
246 E = MRI.livein_end(); LI != E; ++LI)
248 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
249 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
250 RC, CopyRegMap, MRI, TRI, TII);
253 // Emit the copies into the top of the block.
254 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
255 E = MRI.livein_end(); LI != E; ++LI)
257 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
258 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
259 LI->second, LI->first, RC, RC);
260 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
266 //===----------------------------------------------------------------------===//
267 // SelectionDAGISel code
268 //===----------------------------------------------------------------------===//
270 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
271 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
272 FuncInfo(new FunctionLoweringInfo(TLI)),
273 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
274 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
280 SelectionDAGISel::~SelectionDAGISel() {
286 unsigned SelectionDAGISel::MakeReg(MVT VT) {
287 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
290 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
291 AU.addRequired<AliasAnalysis>();
292 AU.addRequired<GCModuleInfo>();
293 AU.addRequired<DwarfWriter>();
294 AU.setPreservesAll();
295 MachineFunctionPass::getAnalysisUsage(AU);
298 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
299 Function &Fn = *mf.getFunction();
301 // Do some sanity-checking on the command-line options.
302 assert((!EnableFastISelVerbose || EnableFastISel) &&
303 "-fast-isel-verbose requires -fast-isel");
304 assert((!EnableFastISelAbort || EnableFastISel) &&
305 "-fast-isel-abort requires -fast-isel");
307 // Do not codegen any 'available_externally' functions at all, they have
308 // definitions outside the translation unit.
309 if (Fn.hasAvailableExternallyLinkage())
312 // Get alias analysis for load/store combining.
313 AA = &getAnalysis<AliasAnalysis>();
315 TargetMachine &TM = TLI.getTargetMachine();
317 const TargetInstrInfo &TII = *TM.getInstrInfo();
318 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
320 if (MF->getFunction()->hasGC())
321 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
324 RegInfo = &MF->getRegInfo();
325 DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n");
327 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
328 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
329 CurDAG->init(*MF, MMI, DW);
330 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
333 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
334 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
336 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
338 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
340 // If the first basic block in the function has live ins that need to be
341 // copied into vregs, emit the copies into the top of the block before
342 // emitting the code for the block.
343 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
345 // Add function live-ins to entry block live-in set.
346 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
347 E = RegInfo->livein_end(); I != E; ++I)
348 MF->begin()->addLiveIn(I->first);
351 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
352 "Not all catch info was assigned to a landing pad!");
360 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
361 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
362 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
363 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
364 // Apply the catch info to DestBB.
365 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
367 if (!FLI.MBBMap[SrcBB]->isLandingPad())
368 FLI.CatchInfoFound.insert(EHSel);
373 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
374 /// whether object offset >= 0.
376 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
377 if (!isa<FrameIndexSDNode>(Op)) return false;
379 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
380 int FrameIdx = FrameIdxNode->getIndex();
381 return MFI->isFixedObjectIndex(FrameIdx) &&
382 MFI->getObjectOffset(FrameIdx) >= 0;
385 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
386 /// possibly be overwritten when lowering the outgoing arguments in a tail
387 /// call. Currently the implementation of this call is very conservative and
388 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
389 /// virtual registers would be overwritten by direct lowering.
390 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
391 MachineFrameInfo *MFI) {
392 RegisterSDNode * OpReg = NULL;
393 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
394 (Op.getOpcode()== ISD::CopyFromReg &&
395 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
396 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
397 (Op.getOpcode() == ISD::LOAD &&
398 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
399 (Op.getOpcode() == ISD::MERGE_VALUES &&
400 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
401 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
407 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
408 /// DAG and fixes their tailcall attribute operand.
409 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
410 const TargetLowering& TLI) {
412 SDValue Terminator = DAG.getRoot();
415 if (Terminator.getOpcode() == ISD::RET) {
416 Ret = Terminator.getNode();
419 // Fix tail call attribute of CALL nodes.
420 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
421 BI = DAG.allnodes_end(); BI != BE; ) {
423 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
424 SDValue OpRet(Ret, 0);
425 SDValue OpCall(BI, 0);
426 bool isMarkedTailCall = TheCall->isTailCall();
427 // If CALL node has tail call attribute set to true and the call is not
428 // eligible (no RET or the target rejects) the attribute is fixed to
429 // false. The TargetLowering::IsEligibleForTailCallOptimization function
430 // must correctly identify tail call optimizable calls.
431 if (!isMarkedTailCall) continue;
433 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
434 // Not eligible. Mark CALL node as non tail call. Note that we
435 // can modify the call node in place since calls are not CSE'd.
436 TheCall->setNotTailCall();
438 // Look for tail call clobbered arguments. Emit a series of
439 // copyto/copyfrom virtual register nodes to protect them.
440 SmallVector<SDValue, 32> Ops;
441 SDValue Chain = TheCall->getChain(), InFlag;
442 Ops.push_back(Chain);
443 Ops.push_back(TheCall->getCallee());
444 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
445 SDValue Arg = TheCall->getArg(i);
446 bool isByVal = TheCall->getArgFlags(i).isByVal();
447 MachineFunction &MF = DAG.getMachineFunction();
448 MachineFrameInfo *MFI = MF.getFrameInfo();
450 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
451 MVT VT = Arg.getValueType();
452 unsigned VReg = MF.getRegInfo().
453 createVirtualRegister(TLI.getRegClassFor(VT));
454 Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(),
456 InFlag = Chain.getValue(1);
457 Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(),
459 Chain = Arg.getValue(1);
460 InFlag = Arg.getValue(2);
463 Ops.push_back(TheCall->getArgFlagsVal(i));
465 // Link in chain of CopyTo/CopyFromReg.
467 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
473 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
474 BasicBlock::iterator Begin,
475 BasicBlock::iterator End) {
476 SDL->setCurrentBasicBlock(BB);
478 // Lower all of the non-terminator instructions.
479 for (BasicBlock::iterator I = Begin; I != End; ++I)
480 if (!isa<TerminatorInst>(I))
483 // Ensure that all instructions which are used outside of their defining
484 // blocks are available as virtual registers. Invoke is handled elsewhere.
485 for (BasicBlock::iterator I = Begin; I != End; ++I)
486 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
487 SDL->CopyToExportRegsIfNeeded(I);
489 // Handle PHI nodes in successor blocks.
490 if (End == LLVMBB->end()) {
491 HandlePHINodesInSuccessorBlocks(LLVMBB);
493 // Lower the terminator after the copies are emitted.
494 SDL->visit(*LLVMBB->getTerminator());
497 // Make sure the root of the DAG is up-to-date.
498 CurDAG->setRoot(SDL->getControlRoot());
500 // Check whether calls in this block are real tail calls. Fix up CALL nodes
501 // with correct tailcall attribute so that the target can rely on the tailcall
502 // attribute indicating whether the call is really eligible for tail call
504 if (PerformTailCallOpt)
505 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
507 // Final step, emit the lowered DAG as machine code.
512 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
513 SmallPtrSet<SDNode*, 128> VisitedNodes;
514 SmallVector<SDNode*, 128> Worklist;
516 Worklist.push_back(CurDAG->getRoot().getNode());
522 while (!Worklist.empty()) {
523 SDNode *N = Worklist.back();
526 // If we've already seen this node, ignore it.
527 if (!VisitedNodes.insert(N))
530 // Otherwise, add all chain operands to the worklist.
531 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
532 if (N->getOperand(i).getValueType() == MVT::Other)
533 Worklist.push_back(N->getOperand(i).getNode());
535 // If this is a CopyToReg with a vreg dest, process it.
536 if (N->getOpcode() != ISD::CopyToReg)
539 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
540 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
543 // Ignore non-scalar or non-integer values.
544 SDValue Src = N->getOperand(2);
545 MVT SrcVT = Src.getValueType();
546 if (!SrcVT.isInteger() || SrcVT.isVector())
549 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
550 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
551 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
553 // Only install this information if it tells us something.
554 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
555 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
556 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
557 if (DestReg >= FLI.LiveOutRegInfo.size())
558 FLI.LiveOutRegInfo.resize(DestReg+1);
559 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
560 LOI.NumSignBits = NumSignBits;
561 LOI.KnownOne = KnownOne;
562 LOI.KnownZero = KnownZero;
567 void SelectionDAGISel::CodeGenAndEmitDAG() {
568 std::string GroupName;
569 if (TimePassesIsEnabled)
570 GroupName = "Instruction Selection and Scheduling";
571 std::string BlockName;
572 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
573 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
575 BlockName = CurDAG->getMachineFunction().getFunction()->getNameStr() + ":" +
576 BB->getBasicBlock()->getNameStr();
578 DOUT << "Initial selection DAG:\n";
579 DEBUG(CurDAG->dump());
581 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
583 // Run the DAG combiner in pre-legalize mode.
584 if (TimePassesIsEnabled) {
585 NamedRegionTimer T("DAG Combining 1", GroupName);
586 CurDAG->Combine(Unrestricted, *AA, OptLevel);
588 CurDAG->Combine(Unrestricted, *AA, OptLevel);
591 DOUT << "Optimized lowered selection DAG:\n";
592 DEBUG(CurDAG->dump());
594 // Second step, hack on the DAG until it only uses operations and types that
595 // the target supports.
596 if (!DisableLegalizeTypes) {
597 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
601 if (TimePassesIsEnabled) {
602 NamedRegionTimer T("Type Legalization", GroupName);
603 Changed = CurDAG->LegalizeTypes();
605 Changed = CurDAG->LegalizeTypes();
608 DOUT << "Type-legalized selection DAG:\n";
609 DEBUG(CurDAG->dump());
612 if (ViewDAGCombineLT)
613 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
615 // Run the DAG combiner in post-type-legalize mode.
616 if (TimePassesIsEnabled) {
617 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
618 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
620 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
623 DOUT << "Optimized type-legalized selection DAG:\n";
624 DEBUG(CurDAG->dump());
627 if (TimePassesIsEnabled) {
628 NamedRegionTimer T("Vector Legalization", GroupName);
629 Changed = CurDAG->LegalizeVectors();
631 Changed = CurDAG->LegalizeVectors();
635 if (TimePassesIsEnabled) {
636 NamedRegionTimer T("Type Legalization 2", GroupName);
637 Changed = CurDAG->LegalizeTypes();
639 Changed = CurDAG->LegalizeTypes();
642 if (ViewDAGCombineLT)
643 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
645 // Run the DAG combiner in post-type-legalize mode.
646 if (TimePassesIsEnabled) {
647 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
648 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
650 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
653 DOUT << "Optimized vector-legalized selection DAG:\n";
654 DEBUG(CurDAG->dump());
658 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
660 if (TimePassesIsEnabled) {
661 NamedRegionTimer T("DAG Legalization", GroupName);
662 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
664 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
667 DOUT << "Legalized selection DAG:\n";
668 DEBUG(CurDAG->dump());
670 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
672 // Run the DAG combiner in post-legalize mode.
673 if (TimePassesIsEnabled) {
674 NamedRegionTimer T("DAG Combining 2", GroupName);
675 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
677 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
680 DOUT << "Optimized legalized selection DAG:\n";
681 DEBUG(CurDAG->dump());
683 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
685 if (OptLevel != CodeGenOpt::None)
686 ComputeLiveOutVRegInfo();
688 // Third, instruction select all of the operations to machine code, adding the
689 // code to the MachineBasicBlock.
690 if (TimePassesIsEnabled) {
691 NamedRegionTimer T("Instruction Selection", GroupName);
697 DOUT << "Selected selection DAG:\n";
698 DEBUG(CurDAG->dump());
700 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
702 // Schedule machine code.
703 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
704 if (TimePassesIsEnabled) {
705 NamedRegionTimer T("Instruction Scheduling", GroupName);
706 Scheduler->Run(CurDAG, BB, BB->end());
708 Scheduler->Run(CurDAG, BB, BB->end());
711 if (ViewSUnitDAGs) Scheduler->viewGraph();
713 // Emit machine code to BB. This can change 'BB' to the last block being
715 if (TimePassesIsEnabled) {
716 NamedRegionTimer T("Instruction Creation", GroupName);
717 BB = Scheduler->EmitSchedule();
719 BB = Scheduler->EmitSchedule();
722 // Free the scheduler state.
723 if (TimePassesIsEnabled) {
724 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
730 DOUT << "Selected machine code:\n";
734 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
736 MachineModuleInfo *MMI,
738 const TargetInstrInfo &TII) {
739 // Initialize the Fast-ISel state, if needed.
740 FastISel *FastIS = 0;
742 FastIS = TLI.createFastISel(MF, MMI, DW,
745 FuncInfo->StaticAllocaMap
747 , FuncInfo->CatchInfoLost
751 // Iterate over all basic blocks in the function.
752 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
753 BasicBlock *LLVMBB = &*I;
754 BB = FuncInfo->MBBMap[LLVMBB];
756 BasicBlock::iterator const Begin = LLVMBB->begin();
757 BasicBlock::iterator const End = LLVMBB->end();
758 BasicBlock::iterator BI = Begin;
760 // Lower any arguments needed in this block if this is the entry block.
761 bool SuppressFastISel = false;
762 if (LLVMBB == &Fn.getEntryBlock()) {
763 LowerArguments(LLVMBB);
765 // If any of the arguments has the byval attribute, forgo
766 // fast-isel in the entry block.
769 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
771 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
772 if (EnableFastISelVerbose || EnableFastISelAbort)
773 cerr << "FastISel skips entry block due to byval argument\n";
774 SuppressFastISel = true;
780 if (MMI && BB->isLandingPad()) {
781 // Add a label to mark the beginning of the landing pad. Deletion of the
782 // landing pad can thus be detected via the MachineModuleInfo.
783 unsigned LabelID = MMI->addLandingPad(BB);
785 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
786 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
788 // Mark exception register as live in.
789 unsigned Reg = TLI.getExceptionAddressRegister();
790 if (Reg) BB->addLiveIn(Reg);
792 // Mark exception selector register as live in.
793 Reg = TLI.getExceptionSelectorRegister();
794 if (Reg) BB->addLiveIn(Reg);
796 // FIXME: Hack around an exception handling flaw (PR1508): the personality
797 // function and list of typeids logically belong to the invoke (or, if you
798 // like, the basic block containing the invoke), and need to be associated
799 // with it in the dwarf exception handling tables. Currently however the
800 // information is provided by an intrinsic (eh.selector) that can be moved
801 // to unexpected places by the optimizers: if the unwind edge is critical,
802 // then breaking it can result in the intrinsics being in the successor of
803 // the landing pad, not the landing pad itself. This results in exceptions
804 // not being caught because no typeids are associated with the invoke.
805 // This may not be the only way things can go wrong, but it is the only way
806 // we try to work around for the moment.
807 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
809 if (Br && Br->isUnconditional()) { // Critical edge?
810 BasicBlock::iterator I, E;
811 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
812 if (isa<EHSelectorInst>(I))
816 // No catch info found - try to extract some from the successor.
817 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
821 // Before doing SelectionDAG ISel, see if FastISel has been requested.
822 if (FastIS && !SuppressFastISel) {
823 // Emit code for any incoming arguments. This must happen before
824 // beginning FastISel on the entry block.
825 if (LLVMBB == &Fn.getEntryBlock()) {
826 CurDAG->setRoot(SDL->getControlRoot());
830 FastIS->startNewBlock(BB);
831 // Do FastISel on as many instructions as possible.
832 for (; BI != End; ++BI) {
833 // Just before the terminator instruction, insert instructions to
834 // feed PHI nodes in successor blocks.
835 if (isa<TerminatorInst>(BI))
836 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
837 if (EnableFastISelVerbose || EnableFastISelAbort) {
838 cerr << "FastISel miss: ";
841 assert(!EnableFastISelAbort &&
842 "FastISel didn't handle a PHI in a successor");
846 // First try normal tablegen-generated "fast" selection.
847 if (FastIS->SelectInstruction(BI))
850 // Next, try calling the target to attempt to handle the instruction.
851 if (FastIS->TargetSelectInstruction(BI))
854 // Then handle certain instructions as single-LLVM-Instruction blocks.
855 if (isa<CallInst>(BI)) {
856 if (EnableFastISelVerbose || EnableFastISelAbort) {
857 cerr << "FastISel missed call: ";
861 if (BI->getType() != Type::VoidTy) {
862 unsigned &R = FuncInfo->ValueMap[BI];
864 R = FuncInfo->CreateRegForValue(BI);
867 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
868 SelectBasicBlock(LLVMBB, BI, next(BI));
869 // If the instruction was codegen'd with multiple blocks,
870 // inform the FastISel object where to resume inserting.
871 FastIS->setCurrentBlock(BB);
875 // Otherwise, give up on FastISel for the rest of the block.
876 // For now, be a little lenient about non-branch terminators.
877 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
878 if (EnableFastISelVerbose || EnableFastISelAbort) {
879 cerr << "FastISel miss: ";
882 if (EnableFastISelAbort)
883 // The "fast" selector couldn't handle something and bailed.
884 // For the purpose of debugging, just abort.
885 llvm_unreachable("FastISel didn't select the entire block");
891 // Run SelectionDAG instruction selection on the remainder of the block
892 // not handled by FastISel. If FastISel is not run, this is the entire
895 // If FastISel is run and it has known DebugLoc then use it.
896 if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
897 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
898 SelectBasicBlock(LLVMBB, BI, End);
908 SelectionDAGISel::FinishBasicBlock() {
910 DOUT << "Target-post-processed machine code:\n";
913 DOUT << "Total amount of phi nodes to update: "
914 << SDL->PHINodesToUpdate.size() << "\n";
915 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
916 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
917 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
919 // Next, now that we know what the last MBB the LLVM BB expanded is, update
920 // PHI nodes in successors.
921 if (SDL->SwitchCases.empty() &&
922 SDL->JTCases.empty() &&
923 SDL->BitTestCases.empty()) {
924 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
925 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
926 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
927 "This is not a machine PHI node that we are updating!");
928 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
930 PHI->addOperand(MachineOperand::CreateMBB(BB));
932 SDL->PHINodesToUpdate.clear();
936 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
937 // Lower header first, if it wasn't already lowered
938 if (!SDL->BitTestCases[i].Emitted) {
939 // Set the current basic block to the mbb we wish to insert the code into
940 BB = SDL->BitTestCases[i].Parent;
941 SDL->setCurrentBasicBlock(BB);
943 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
944 CurDAG->setRoot(SDL->getRoot());
949 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
950 // Set the current basic block to the mbb we wish to insert the code into
951 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
952 SDL->setCurrentBasicBlock(BB);
955 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
956 SDL->BitTestCases[i].Reg,
957 SDL->BitTestCases[i].Cases[j]);
959 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
960 SDL->BitTestCases[i].Reg,
961 SDL->BitTestCases[i].Cases[j]);
964 CurDAG->setRoot(SDL->getRoot());
970 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
971 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
972 MachineBasicBlock *PHIBB = PHI->getParent();
973 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
974 "This is not a machine PHI node that we are updating!");
975 // This is "default" BB. We have two jumps to it. From "header" BB and
976 // from last "case" BB.
977 if (PHIBB == SDL->BitTestCases[i].Default) {
978 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
980 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
981 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
983 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
986 // One of "cases" BB.
987 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
989 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
990 if (cBB->succ_end() !=
991 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
992 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
994 PHI->addOperand(MachineOperand::CreateMBB(cBB));
999 SDL->BitTestCases.clear();
1001 // If the JumpTable record is filled in, then we need to emit a jump table.
1002 // Updating the PHI nodes is tricky in this case, since we need to determine
1003 // whether the PHI is a successor of the range check MBB or the jump table MBB
1004 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
1005 // Lower header first, if it wasn't already lowered
1006 if (!SDL->JTCases[i].first.Emitted) {
1007 // Set the current basic block to the mbb we wish to insert the code into
1008 BB = SDL->JTCases[i].first.HeaderBB;
1009 SDL->setCurrentBasicBlock(BB);
1011 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
1012 CurDAG->setRoot(SDL->getRoot());
1013 CodeGenAndEmitDAG();
1017 // Set the current basic block to the mbb we wish to insert the code into
1018 BB = SDL->JTCases[i].second.MBB;
1019 SDL->setCurrentBasicBlock(BB);
1021 SDL->visitJumpTable(SDL->JTCases[i].second);
1022 CurDAG->setRoot(SDL->getRoot());
1023 CodeGenAndEmitDAG();
1027 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
1028 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
1029 MachineBasicBlock *PHIBB = PHI->getParent();
1030 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1031 "This is not a machine PHI node that we are updating!");
1032 // "default" BB. We can go there only from header BB.
1033 if (PHIBB == SDL->JTCases[i].second.Default) {
1034 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1036 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
1038 // JT BB. Just iterate over successors here
1039 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
1040 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1042 PHI->addOperand(MachineOperand::CreateMBB(BB));
1046 SDL->JTCases.clear();
1048 // If the switch block involved a branch to one of the actual successors, we
1049 // need to update PHI nodes in that block.
1050 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1051 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1052 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1053 "This is not a machine PHI node that we are updating!");
1054 if (BB->isSuccessor(PHI->getParent())) {
1055 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1057 PHI->addOperand(MachineOperand::CreateMBB(BB));
1061 // If we generated any switch lowering information, build and codegen any
1062 // additional DAGs necessary.
1063 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1064 // Set the current basic block to the mbb we wish to insert the code into
1065 BB = SDL->SwitchCases[i].ThisBB;
1066 SDL->setCurrentBasicBlock(BB);
1069 SDL->visitSwitchCase(SDL->SwitchCases[i]);
1070 CurDAG->setRoot(SDL->getRoot());
1071 CodeGenAndEmitDAG();
1074 // Handle any PHI nodes in successors of this chunk, as if we were coming
1075 // from the original BB before switch expansion. Note that PHI nodes can
1076 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1077 // handle them the right number of times.
1078 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
1079 for (MachineBasicBlock::iterator Phi = BB->begin();
1080 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1081 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1082 for (unsigned pn = 0; ; ++pn) {
1083 assert(pn != SDL->PHINodesToUpdate.size() &&
1084 "Didn't find PHI entry!");
1085 if (SDL->PHINodesToUpdate[pn].first == Phi) {
1086 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1088 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1094 // Don't process RHS if same block as LHS.
1095 if (BB == SDL->SwitchCases[i].FalseBB)
1096 SDL->SwitchCases[i].FalseBB = 0;
1098 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1099 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1100 SDL->SwitchCases[i].FalseBB = 0;
1102 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1104 SDL->SwitchCases.clear();
1106 SDL->PHINodesToUpdate.clear();
1110 /// Create the scheduler. If a specific scheduler was specified
1111 /// via the SchedulerRegistry, use it, otherwise select the
1112 /// one preferred by the target.
1114 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1115 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1119 RegisterScheduler::setDefault(Ctor);
1122 return Ctor(this, OptLevel);
1125 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1126 return new ScheduleHazardRecognizer();
1129 //===----------------------------------------------------------------------===//
1130 // Helper functions used by the generated instruction selector.
1131 //===----------------------------------------------------------------------===//
1132 // Calls to these methods are generated by tblgen.
1134 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1135 /// the dag combiner simplified the 255, we still want to match. RHS is the
1136 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1137 /// specified in the .td file (e.g. 255).
1138 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1139 int64_t DesiredMaskS) const {
1140 const APInt &ActualMask = RHS->getAPIntValue();
1141 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1143 // If the actual mask exactly matches, success!
1144 if (ActualMask == DesiredMask)
1147 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1148 if (ActualMask.intersects(~DesiredMask))
1151 // Otherwise, the DAG Combiner may have proven that the value coming in is
1152 // either already zero or is not demanded. Check for known zero input bits.
1153 APInt NeededMask = DesiredMask & ~ActualMask;
1154 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1157 // TODO: check to see if missing bits are just not demanded.
1159 // Otherwise, this pattern doesn't match.
1163 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1164 /// the dag combiner simplified the 255, we still want to match. RHS is the
1165 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1166 /// specified in the .td file (e.g. 255).
1167 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1168 int64_t DesiredMaskS) const {
1169 const APInt &ActualMask = RHS->getAPIntValue();
1170 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1172 // If the actual mask exactly matches, success!
1173 if (ActualMask == DesiredMask)
1176 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1177 if (ActualMask.intersects(~DesiredMask))
1180 // Otherwise, the DAG Combiner may have proven that the value coming in is
1181 // either already zero or is not demanded. Check for known zero input bits.
1182 APInt NeededMask = DesiredMask & ~ActualMask;
1184 APInt KnownZero, KnownOne;
1185 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1187 // If all the missing bits in the or are already known to be set, match!
1188 if ((NeededMask & KnownOne) == NeededMask)
1191 // TODO: check to see if missing bits are just not demanded.
1193 // Otherwise, this pattern doesn't match.
1198 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1199 /// by tblgen. Others should not call it.
1200 void SelectionDAGISel::
1201 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1202 std::vector<SDValue> InOps;
1203 std::swap(InOps, Ops);
1205 Ops.push_back(InOps[0]); // input chain.
1206 Ops.push_back(InOps[1]); // input asm string.
1208 unsigned i = 2, e = InOps.size();
1209 if (InOps[e-1].getValueType() == MVT::Flag)
1210 --e; // Don't process a flag operand if it is here.
1213 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1214 if ((Flags & 7) != 4 /*MEM*/) {
1215 // Just skip over this operand, copying the operands verbatim.
1216 Ops.insert(Ops.end(), InOps.begin()+i,
1217 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1218 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1220 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1221 "Memory operand with multiple values?");
1222 // Otherwise, this is a memory operand. Ask the target to select it.
1223 std::vector<SDValue> SelOps;
1224 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1225 llvm_report_error("Could not match memory address. Inline asm"
1229 // Add this to the output node.
1230 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1231 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1233 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1238 // Add the flag input back if present.
1239 if (e != InOps.size())
1240 Ops.push_back(InOps.back());
1243 /// findFlagUse - Return use of MVT::Flag value produced by the specified
1246 static SDNode *findFlagUse(SDNode *N) {
1247 unsigned FlagResNo = N->getNumValues()-1;
1248 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1249 SDUse &Use = I.getUse();
1250 if (Use.getResNo() == FlagResNo)
1251 return Use.getUser();
1256 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1257 /// This function recursively traverses up the operand chain, ignoring
1259 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1261 SmallPtrSet<SDNode*, 16> &Visited) {
1262 if (Use->getNodeId() < Def->getNodeId() ||
1263 !Visited.insert(Use))
1266 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1267 SDNode *N = Use->getOperand(i).getNode();
1269 if (Use == ImmedUse || Use == Root)
1270 continue; // We are not looking for immediate use.
1275 // Traverse up the operand chain.
1276 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1282 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
1283 /// be reached. Return true if that's the case. However, ignore direct uses
1284 /// by ImmedUse (which would be U in the example illustrated in
1285 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1287 /// FIXME: to be really generic, we should allow direct use by any node
1288 /// that is being folded. But realisticly since we only fold loads which
1289 /// have one non-chain use, we only need to watch out for load/op/store
1290 /// and load/op/cmp case where the root (store / cmp) may reach the load via
1291 /// its chain operand.
1292 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1293 SmallPtrSet<SDNode*, 16> Visited;
1294 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1297 /// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1298 /// U can be folded during instruction selection that starts at Root and
1299 /// folding N is profitable.
1300 bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1301 SDNode *Root) const {
1302 if (OptLevel == CodeGenOpt::None) return false;
1304 // If Root use can somehow reach N through a path that that doesn't contain
1305 // U then folding N would create a cycle. e.g. In the following
1306 // diagram, Root can reach N through X. If N is folded into into Root, then
1307 // X is both a predecessor and a successor of U.
1318 // * indicates nodes to be folded together.
1320 // If Root produces a flag, then it gets (even more) interesting. Since it
1321 // will be "glued" together with its flag use in the scheduler, we need to
1322 // check if it might reach N.
1341 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1342 // (call it Fold), then X is a predecessor of FU and a successor of
1343 // Fold. But since Fold and FU are flagged together, this will create
1344 // a cycle in the scheduling graph.
1346 MVT VT = Root->getValueType(Root->getNumValues()-1);
1347 while (VT == MVT::Flag) {
1348 SDNode *FU = findFlagUse(Root);
1352 VT = Root->getValueType(Root->getNumValues()-1);
1355 return !isNonImmUse(Root, N, U);
1359 char SelectionDAGISel::ID = 0;