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 "SelectionDAGBuild.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/FastISel.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/GCMetadata.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/ScheduleDAGSDNodes.h"
37 #include "llvm/CodeGen/SchedulerRegistry.h"
38 #include "llvm/CodeGen/SelectionDAG.h"
39 #include "llvm/CodeGen/DwarfWriter.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetFrameInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/Timer.h"
55 EnableValueProp("enable-value-prop", cl::Hidden);
57 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 static const bool EnableFastISelVerbose = false,
68 EnableFastISelAbort = false;
71 SchedLiveInCopies("schedule-livein-copies",
72 cl::desc("Schedule copies of livein registers"),
77 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
78 cl::desc("Pop up a window to show dags before the first "
81 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
82 cl::desc("Pop up a window to show dags before legalize types"));
84 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
85 cl::desc("Pop up a window to show dags before legalize"));
87 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
88 cl::desc("Pop up a window to show dags before the second "
91 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
92 cl::desc("Pop up a window to show dags before the post legalize types"
93 " dag combine pass"));
95 ViewISelDAGs("view-isel-dags", cl::Hidden,
96 cl::desc("Pop up a window to show isel dags as they are selected"));
98 ViewSchedDAGs("view-sched-dags", cl::Hidden,
99 cl::desc("Pop up a window to show sched dags as they are processed"));
101 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
102 cl::desc("Pop up a window to show SUnit dags after they are processed"));
104 static const bool ViewDAGCombine1 = false,
105 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
106 ViewDAGCombine2 = false,
107 ViewDAGCombineLT = false,
108 ViewISelDAGs = false, ViewSchedDAGs = false,
109 ViewSUnitDAGs = false;
112 //===---------------------------------------------------------------------===//
114 /// RegisterScheduler class - Track the registration of instruction schedulers.
116 //===---------------------------------------------------------------------===//
117 MachinePassRegistry RegisterScheduler::Registry;
119 //===---------------------------------------------------------------------===//
121 /// ISHeuristic command line option for instruction schedulers.
123 //===---------------------------------------------------------------------===//
124 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
125 RegisterPassParser<RegisterScheduler> >
126 ISHeuristic("pre-RA-sched",
127 cl::init(&createDefaultScheduler),
128 cl::desc("Instruction schedulers available (before register"
131 static RegisterScheduler
132 defaultListDAGScheduler("default", "Best scheduler for the target",
133 createDefaultScheduler);
136 //===--------------------------------------------------------------------===//
137 /// createDefaultScheduler - This creates an instruction scheduler appropriate
139 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
141 const TargetLowering &TLI = IS->getTargetLowering();
144 return createFastDAGScheduler(IS, Fast);
145 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
146 return createTDListDAGScheduler(IS, Fast);
147 assert(TLI.getSchedulingPreference() ==
148 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
149 return createBURRListDAGScheduler(IS, Fast);
153 // EmitInstrWithCustomInserter - This method should be implemented by targets
154 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
155 // instructions are special in various ways, which require special support to
156 // insert. The specified MachineInstr is created but not inserted into any
157 // basic blocks, and the scheduler passes ownership of it to this method.
158 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
159 MachineBasicBlock *MBB) {
160 cerr << "If a target marks an instruction with "
161 << "'usesCustomDAGSchedInserter', it must implement "
162 << "TargetLowering::EmitInstrWithCustomInserter!\n";
167 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
168 /// physical register has only a single copy use, then coalesced the copy
170 static void EmitLiveInCopy(MachineBasicBlock *MBB,
171 MachineBasicBlock::iterator &InsertPos,
172 unsigned VirtReg, unsigned PhysReg,
173 const TargetRegisterClass *RC,
174 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
175 const MachineRegisterInfo &MRI,
176 const TargetRegisterInfo &TRI,
177 const TargetInstrInfo &TII) {
178 unsigned NumUses = 0;
179 MachineInstr *UseMI = NULL;
180 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
181 UE = MRI.use_end(); UI != UE; ++UI) {
187 // If the number of uses is not one, or the use is not a move instruction,
188 // don't coalesce. Also, only coalesce away a virtual register to virtual
190 bool Coalesced = false;
191 unsigned SrcReg, DstReg;
193 TII.isMoveInstr(*UseMI, SrcReg, DstReg) &&
194 TargetRegisterInfo::isVirtualRegister(DstReg)) {
199 // Now find an ideal location to insert the copy.
200 MachineBasicBlock::iterator Pos = InsertPos;
201 while (Pos != MBB->begin()) {
202 MachineInstr *PrevMI = prior(Pos);
203 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
204 // copyRegToReg might emit multiple instructions to do a copy.
205 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
206 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
207 // This is what the BB looks like right now:
212 // We want to insert "r1025 = mov r1". Inserting this copy below the
213 // move to r1024 makes it impossible for that move to be coalesced.
220 break; // Woot! Found a good location.
224 TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
225 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
227 if (&*InsertPos == UseMI) ++InsertPos;
232 /// EmitLiveInCopies - If this is the first basic block in the function,
233 /// and if it has live ins that need to be copied into vregs, emit the
234 /// copies into the block.
235 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
236 const MachineRegisterInfo &MRI,
237 const TargetRegisterInfo &TRI,
238 const TargetInstrInfo &TII) {
239 if (SchedLiveInCopies) {
240 // Emit the copies at a heuristically-determined location in the block.
241 DenseMap<MachineInstr*, unsigned> CopyRegMap;
242 MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
243 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
244 E = MRI.livein_end(); LI != E; ++LI)
246 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
247 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
248 RC, CopyRegMap, MRI, TRI, TII);
251 // Emit the copies into the top of the block.
252 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
253 E = MRI.livein_end(); LI != E; ++LI)
255 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
256 TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
257 LI->second, LI->first, RC, RC);
262 //===----------------------------------------------------------------------===//
263 // SelectionDAGISel code
264 //===----------------------------------------------------------------------===//
266 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, bool fast) :
267 FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
268 FuncInfo(new FunctionLoweringInfo(TLI)),
269 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
270 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
276 SelectionDAGISel::~SelectionDAGISel() {
282 unsigned SelectionDAGISel::MakeReg(MVT VT) {
283 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
286 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
287 AU.addRequired<AliasAnalysis>();
288 AU.addRequired<GCModuleInfo>();
289 AU.addRequired<DwarfWriter>();
290 AU.setPreservesAll();
293 bool SelectionDAGISel::runOnFunction(Function &Fn) {
294 // Do some sanity-checking on the command-line options.
295 assert((!EnableFastISelVerbose || EnableFastISel) &&
296 "-fast-isel-verbose requires -fast-isel");
297 assert((!EnableFastISelAbort || EnableFastISel) &&
298 "-fast-isel-abort requires -fast-isel");
300 // Get alias analysis for load/store combining.
301 AA = &getAnalysis<AliasAnalysis>();
303 TargetMachine &TM = TLI.getTargetMachine();
304 MF = &MachineFunction::construct(&Fn, TM);
305 const TargetInstrInfo &TII = *TM.getInstrInfo();
306 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
308 if (MF->getFunction()->hasGC())
309 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
312 RegInfo = &MF->getRegInfo();
313 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
315 FuncInfo->set(Fn, *MF, EnableFastISel);
316 MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
317 DwarfWriter *DW = getAnalysisToUpdate<DwarfWriter>();
318 CurDAG->init(*MF, MMI, DW);
321 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
322 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
324 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
326 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
328 // If the first basic block in the function has live ins that need to be
329 // copied into vregs, emit the copies into the top of the block before
330 // emitting the code for the block.
331 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
333 // Add function live-ins to entry block live-in set.
334 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
335 E = RegInfo->livein_end(); I != E; ++I)
336 MF->begin()->addLiveIn(I->first);
339 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
340 "Not all catch info was assigned to a landing pad!");
348 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
349 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
350 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
351 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
352 // Apply the catch info to DestBB.
353 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
355 if (!FLI.MBBMap[SrcBB]->isLandingPad())
356 FLI.CatchInfoFound.insert(EHSel);
361 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
362 /// whether object offset >= 0.
364 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
365 if (!isa<FrameIndexSDNode>(Op)) return false;
367 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
368 int FrameIdx = FrameIdxNode->getIndex();
369 return MFI->isFixedObjectIndex(FrameIdx) &&
370 MFI->getObjectOffset(FrameIdx) >= 0;
373 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
374 /// possibly be overwritten when lowering the outgoing arguments in a tail
375 /// call. Currently the implementation of this call is very conservative and
376 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
377 /// virtual registers would be overwritten by direct lowering.
378 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
379 MachineFrameInfo *MFI) {
380 RegisterSDNode * OpReg = NULL;
381 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
382 (Op.getOpcode()== ISD::CopyFromReg &&
383 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
384 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
385 (Op.getOpcode() == ISD::LOAD &&
386 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
387 (Op.getOpcode() == ISD::MERGE_VALUES &&
388 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
389 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
395 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
396 /// DAG and fixes their tailcall attribute operand.
397 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
398 const TargetLowering& TLI) {
400 SDValue Terminator = DAG.getRoot();
403 if (Terminator.getOpcode() == ISD::RET) {
404 Ret = Terminator.getNode();
407 // Fix tail call attribute of CALL nodes.
408 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
409 BI = DAG.allnodes_end(); BI != BE; ) {
411 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
412 SDValue OpRet(Ret, 0);
413 SDValue OpCall(BI, 0);
414 bool isMarkedTailCall = TheCall->isTailCall();
415 // If CALL node has tail call attribute set to true and the call is not
416 // eligible (no RET or the target rejects) the attribute is fixed to
417 // false. The TargetLowering::IsEligibleForTailCallOptimization function
418 // must correctly identify tail call optimizable calls.
419 if (!isMarkedTailCall) continue;
421 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
422 // Not eligible. Mark CALL node as non tail call. Note that we
423 // can modify the call node in place since calls are not CSE'd.
424 TheCall->setNotTailCall();
426 // Look for tail call clobbered arguments. Emit a series of
427 // copyto/copyfrom virtual register nodes to protect them.
428 SmallVector<SDValue, 32> Ops;
429 SDValue Chain = TheCall->getChain(), InFlag;
430 Ops.push_back(Chain);
431 Ops.push_back(TheCall->getCallee());
432 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
433 SDValue Arg = TheCall->getArg(i);
434 bool isByVal = TheCall->getArgFlags(i).isByVal();
435 MachineFunction &MF = DAG.getMachineFunction();
436 MachineFrameInfo *MFI = MF.getFrameInfo();
438 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
439 MVT VT = Arg.getValueType();
440 unsigned VReg = MF.getRegInfo().
441 createVirtualRegister(TLI.getRegClassFor(VT));
442 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
443 InFlag = Chain.getValue(1);
444 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
445 Chain = Arg.getValue(1);
446 InFlag = Arg.getValue(2);
449 Ops.push_back(TheCall->getArgFlagsVal(i));
451 // Link in chain of CopyTo/CopyFromReg.
453 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
459 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
460 BasicBlock::iterator Begin,
461 BasicBlock::iterator End) {
462 SDL->setCurrentBasicBlock(BB);
464 // Lower all of the non-terminator instructions.
465 for (BasicBlock::iterator I = Begin; I != End; ++I)
466 if (!isa<TerminatorInst>(I))
469 // Ensure that all instructions which are used outside of their defining
470 // blocks are available as virtual registers. Invoke is handled elsewhere.
471 for (BasicBlock::iterator I = Begin; I != End; ++I)
472 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
473 DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I);
474 if (VMI != FuncInfo->ValueMap.end())
475 SDL->CopyValueToVirtualRegister(I, VMI->second);
478 // Handle PHI nodes in successor blocks.
479 if (End == LLVMBB->end()) {
480 HandlePHINodesInSuccessorBlocks(LLVMBB);
482 // Lower the terminator after the copies are emitted.
483 SDL->visit(*LLVMBB->getTerminator());
486 // Make sure the root of the DAG is up-to-date.
487 CurDAG->setRoot(SDL->getControlRoot());
489 // Check whether calls in this block are real tail calls. Fix up CALL nodes
490 // with correct tailcall attribute so that the target can rely on the tailcall
491 // attribute indicating whether the call is really eligible for tail call
493 if (PerformTailCallOpt)
494 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
496 // Final step, emit the lowered DAG as machine code.
501 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
502 SmallPtrSet<SDNode*, 128> VisitedNodes;
503 SmallVector<SDNode*, 128> Worklist;
505 Worklist.push_back(CurDAG->getRoot().getNode());
511 while (!Worklist.empty()) {
512 SDNode *N = Worklist.back();
515 // If we've already seen this node, ignore it.
516 if (!VisitedNodes.insert(N))
519 // Otherwise, add all chain operands to the worklist.
520 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
521 if (N->getOperand(i).getValueType() == MVT::Other)
522 Worklist.push_back(N->getOperand(i).getNode());
524 // If this is a CopyToReg with a vreg dest, process it.
525 if (N->getOpcode() != ISD::CopyToReg)
528 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
529 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
532 // Ignore non-scalar or non-integer values.
533 SDValue Src = N->getOperand(2);
534 MVT SrcVT = Src.getValueType();
535 if (!SrcVT.isInteger() || SrcVT.isVector())
538 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
539 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
540 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
542 // Only install this information if it tells us something.
543 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
544 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
545 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
546 if (DestReg >= FLI.LiveOutRegInfo.size())
547 FLI.LiveOutRegInfo.resize(DestReg+1);
548 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
549 LOI.NumSignBits = NumSignBits;
550 LOI.KnownOne = NumSignBits;
551 LOI.KnownZero = NumSignBits;
556 void SelectionDAGISel::CodeGenAndEmitDAG() {
557 std::string GroupName;
558 if (TimePassesIsEnabled)
559 GroupName = "Instruction Selection and Scheduling";
560 std::string BlockName;
561 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
562 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
564 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
565 BB->getBasicBlock()->getName();
567 DOUT << "Initial selection DAG:\n";
568 DEBUG(CurDAG->dump());
570 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
572 // Run the DAG combiner in pre-legalize mode.
573 if (TimePassesIsEnabled) {
574 NamedRegionTimer T("DAG Combining 1", GroupName);
575 CurDAG->Combine(Unrestricted, *AA, Fast);
577 CurDAG->Combine(Unrestricted, *AA, Fast);
580 DOUT << "Optimized lowered selection DAG:\n";
581 DEBUG(CurDAG->dump());
583 // Second step, hack on the DAG until it only uses operations and types that
584 // the target supports.
585 if (!DisableLegalizeTypes) {
586 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
590 if (TimePassesIsEnabled) {
591 NamedRegionTimer T("Type Legalization", GroupName);
592 Changed = CurDAG->LegalizeTypes();
594 Changed = CurDAG->LegalizeTypes();
597 DOUT << "Type-legalized selection DAG:\n";
598 DEBUG(CurDAG->dump());
601 if (ViewDAGCombineLT)
602 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
604 // Run the DAG combiner in post-type-legalize mode.
605 if (TimePassesIsEnabled) {
606 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
607 CurDAG->Combine(NoIllegalTypes, *AA, Fast);
609 CurDAG->Combine(NoIllegalTypes, *AA, Fast);
612 DOUT << "Optimized type-legalized selection DAG:\n";
613 DEBUG(CurDAG->dump());
617 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
619 if (TimePassesIsEnabled) {
620 NamedRegionTimer T("DAG Legalization", GroupName);
621 CurDAG->Legalize(DisableLegalizeTypes);
623 CurDAG->Legalize(DisableLegalizeTypes);
626 DOUT << "Legalized selection DAG:\n";
627 DEBUG(CurDAG->dump());
629 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
631 // Run the DAG combiner in post-legalize mode.
632 if (TimePassesIsEnabled) {
633 NamedRegionTimer T("DAG Combining 2", GroupName);
634 CurDAG->Combine(NoIllegalOperations, *AA, Fast);
636 CurDAG->Combine(NoIllegalOperations, *AA, Fast);
639 DOUT << "Optimized legalized selection DAG:\n";
640 DEBUG(CurDAG->dump());
642 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
644 if (!Fast && EnableValueProp)
645 ComputeLiveOutVRegInfo();
647 // Third, instruction select all of the operations to machine code, adding the
648 // code to the MachineBasicBlock.
649 if (TimePassesIsEnabled) {
650 NamedRegionTimer T("Instruction Selection", GroupName);
656 DOUT << "Selected selection DAG:\n";
657 DEBUG(CurDAG->dump());
659 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
661 // Schedule machine code.
662 ScheduleDAG *Scheduler;
663 if (TimePassesIsEnabled) {
664 NamedRegionTimer T("Instruction Scheduling", GroupName);
665 Scheduler = Schedule();
667 Scheduler = Schedule();
670 if (ViewSUnitDAGs) Scheduler->viewGraph();
672 // Emit machine code to BB. This can change 'BB' to the last block being
674 if (TimePassesIsEnabled) {
675 NamedRegionTimer T("Instruction Creation", GroupName);
676 BB = Scheduler->EmitSchedule();
678 BB = Scheduler->EmitSchedule();
681 // Free the scheduler state.
682 if (TimePassesIsEnabled) {
683 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
689 DOUT << "Selected machine code:\n";
693 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
695 MachineModuleInfo *MMI,
697 const TargetInstrInfo &TII) {
698 // Initialize the Fast-ISel state, if needed.
699 FastISel *FastIS = 0;
701 FastIS = TLI.createFastISel(MF, MMI, DW,
704 FuncInfo->StaticAllocaMap
706 , FuncInfo->CatchInfoLost
710 // Iterate over all basic blocks in the function.
711 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
712 BasicBlock *LLVMBB = &*I;
713 BB = FuncInfo->MBBMap[LLVMBB];
715 BasicBlock::iterator const Begin = LLVMBB->begin();
716 BasicBlock::iterator const End = LLVMBB->end();
717 BasicBlock::iterator BI = Begin;
719 // Lower any arguments needed in this block if this is the entry block.
720 bool SuppressFastISel = false;
721 if (LLVMBB == &Fn.getEntryBlock()) {
722 LowerArguments(LLVMBB);
724 // If any of the arguments has the byval attribute, forgo
725 // fast-isel in the entry block.
728 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
730 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
731 if (EnableFastISelVerbose || EnableFastISelAbort)
732 cerr << "FastISel skips entry block due to byval argument\n";
733 SuppressFastISel = true;
739 if (MMI && BB->isLandingPad()) {
740 // Add a label to mark the beginning of the landing pad. Deletion of the
741 // landing pad can thus be detected via the MachineModuleInfo.
742 unsigned LabelID = MMI->addLandingPad(BB);
744 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
745 BuildMI(BB, II).addImm(LabelID);
747 // Mark exception register as live in.
748 unsigned Reg = TLI.getExceptionAddressRegister();
749 if (Reg) BB->addLiveIn(Reg);
751 // Mark exception selector register as live in.
752 Reg = TLI.getExceptionSelectorRegister();
753 if (Reg) BB->addLiveIn(Reg);
755 // FIXME: Hack around an exception handling flaw (PR1508): the personality
756 // function and list of typeids logically belong to the invoke (or, if you
757 // like, the basic block containing the invoke), and need to be associated
758 // with it in the dwarf exception handling tables. Currently however the
759 // information is provided by an intrinsic (eh.selector) that can be moved
760 // to unexpected places by the optimizers: if the unwind edge is critical,
761 // then breaking it can result in the intrinsics being in the successor of
762 // the landing pad, not the landing pad itself. This results in exceptions
763 // not being caught because no typeids are associated with the invoke.
764 // This may not be the only way things can go wrong, but it is the only way
765 // we try to work around for the moment.
766 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
768 if (Br && Br->isUnconditional()) { // Critical edge?
769 BasicBlock::iterator I, E;
770 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
771 if (isa<EHSelectorInst>(I))
775 // No catch info found - try to extract some from the successor.
776 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
780 // Before doing SelectionDAG ISel, see if FastISel has been requested.
781 if (FastIS && !SuppressFastISel) {
782 // Emit code for any incoming arguments. This must happen before
783 // beginning FastISel on the entry block.
784 if (LLVMBB == &Fn.getEntryBlock()) {
785 CurDAG->setRoot(SDL->getControlRoot());
789 FastIS->startNewBlock(BB);
790 // Do FastISel on as many instructions as possible.
791 for (; BI != End; ++BI) {
792 // Just before the terminator instruction, insert instructions to
793 // feed PHI nodes in successor blocks.
794 if (isa<TerminatorInst>(BI))
795 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
796 if (EnableFastISelVerbose || EnableFastISelAbort) {
797 cerr << "FastISel miss: ";
800 if (EnableFastISelAbort)
801 assert(0 && "FastISel didn't handle a PHI in a successor");
805 // First try normal tablegen-generated "fast" selection.
806 if (FastIS->SelectInstruction(BI))
809 // Next, try calling the target to attempt to handle the instruction.
810 if (FastIS->TargetSelectInstruction(BI))
813 // Then handle certain instructions as single-LLVM-Instruction blocks.
814 if (isa<CallInst>(BI)) {
815 if (EnableFastISelVerbose || EnableFastISelAbort) {
816 cerr << "FastISel missed call: ";
820 if (BI->getType() != Type::VoidTy) {
821 unsigned &R = FuncInfo->ValueMap[BI];
823 R = FuncInfo->CreateRegForValue(BI);
826 SelectBasicBlock(LLVMBB, BI, next(BI));
827 // If the instruction was codegen'd with multiple blocks,
828 // inform the FastISel object where to resume inserting.
829 FastIS->setCurrentBlock(BB);
833 // Otherwise, give up on FastISel for the rest of the block.
834 // For now, be a little lenient about non-branch terminators.
835 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
836 if (EnableFastISelVerbose || EnableFastISelAbort) {
837 cerr << "FastISel miss: ";
840 if (EnableFastISelAbort)
841 // The "fast" selector couldn't handle something and bailed.
842 // For the purpose of debugging, just abort.
843 assert(0 && "FastISel didn't select the entire block");
849 // Run SelectionDAG instruction selection on the remainder of the block
850 // not handled by FastISel. If FastISel is not run, this is the entire
853 SelectBasicBlock(LLVMBB, BI, End);
862 SelectionDAGISel::FinishBasicBlock() {
864 DOUT << "Target-post-processed machine code:\n";
867 DOUT << "Total amount of phi nodes to update: "
868 << SDL->PHINodesToUpdate.size() << "\n";
869 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
870 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
871 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
873 // Next, now that we know what the last MBB the LLVM BB expanded is, update
874 // PHI nodes in successors.
875 if (SDL->SwitchCases.empty() &&
876 SDL->JTCases.empty() &&
877 SDL->BitTestCases.empty()) {
878 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
879 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
880 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
881 "This is not a machine PHI node that we are updating!");
882 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
884 PHI->addOperand(MachineOperand::CreateMBB(BB));
886 SDL->PHINodesToUpdate.clear();
890 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
891 // Lower header first, if it wasn't already lowered
892 if (!SDL->BitTestCases[i].Emitted) {
893 // Set the current basic block to the mbb we wish to insert the code into
894 BB = SDL->BitTestCases[i].Parent;
895 SDL->setCurrentBasicBlock(BB);
897 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
898 CurDAG->setRoot(SDL->getRoot());
903 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
904 // Set the current basic block to the mbb we wish to insert the code into
905 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
906 SDL->setCurrentBasicBlock(BB);
909 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
910 SDL->BitTestCases[i].Reg,
911 SDL->BitTestCases[i].Cases[j]);
913 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
914 SDL->BitTestCases[i].Reg,
915 SDL->BitTestCases[i].Cases[j]);
918 CurDAG->setRoot(SDL->getRoot());
924 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
925 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
926 MachineBasicBlock *PHIBB = PHI->getParent();
927 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
928 "This is not a machine PHI node that we are updating!");
929 // This is "default" BB. We have two jumps to it. From "header" BB and
930 // from last "case" BB.
931 if (PHIBB == SDL->BitTestCases[i].Default) {
932 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
934 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
935 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
937 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
940 // One of "cases" BB.
941 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
943 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
944 if (cBB->succ_end() !=
945 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
946 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
948 PHI->addOperand(MachineOperand::CreateMBB(cBB));
953 SDL->BitTestCases.clear();
955 // If the JumpTable record is filled in, then we need to emit a jump table.
956 // Updating the PHI nodes is tricky in this case, since we need to determine
957 // whether the PHI is a successor of the range check MBB or the jump table MBB
958 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
959 // Lower header first, if it wasn't already lowered
960 if (!SDL->JTCases[i].first.Emitted) {
961 // Set the current basic block to the mbb we wish to insert the code into
962 BB = SDL->JTCases[i].first.HeaderBB;
963 SDL->setCurrentBasicBlock(BB);
965 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
966 CurDAG->setRoot(SDL->getRoot());
971 // Set the current basic block to the mbb we wish to insert the code into
972 BB = SDL->JTCases[i].second.MBB;
973 SDL->setCurrentBasicBlock(BB);
975 SDL->visitJumpTable(SDL->JTCases[i].second);
976 CurDAG->setRoot(SDL->getRoot());
981 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
982 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
983 MachineBasicBlock *PHIBB = PHI->getParent();
984 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
985 "This is not a machine PHI node that we are updating!");
986 // "default" BB. We can go there only from header BB.
987 if (PHIBB == SDL->JTCases[i].second.Default) {
988 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
990 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
992 // JT BB. Just iterate over successors here
993 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
994 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
996 PHI->addOperand(MachineOperand::CreateMBB(BB));
1000 SDL->JTCases.clear();
1002 // If the switch block involved a branch to one of the actual successors, we
1003 // need to update PHI nodes in that block.
1004 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1005 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1006 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1007 "This is not a machine PHI node that we are updating!");
1008 if (BB->isSuccessor(PHI->getParent())) {
1009 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1011 PHI->addOperand(MachineOperand::CreateMBB(BB));
1015 // If we generated any switch lowering information, build and codegen any
1016 // additional DAGs necessary.
1017 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1018 // Set the current basic block to the mbb we wish to insert the code into
1019 BB = SDL->SwitchCases[i].ThisBB;
1020 SDL->setCurrentBasicBlock(BB);
1023 SDL->visitSwitchCase(SDL->SwitchCases[i]);
1024 CurDAG->setRoot(SDL->getRoot());
1025 CodeGenAndEmitDAG();
1028 // Handle any PHI nodes in successors of this chunk, as if we were coming
1029 // from the original BB before switch expansion. Note that PHI nodes can
1030 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1031 // handle them the right number of times.
1032 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
1033 for (MachineBasicBlock::iterator Phi = BB->begin();
1034 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1035 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1036 for (unsigned pn = 0; ; ++pn) {
1037 assert(pn != SDL->PHINodesToUpdate.size() &&
1038 "Didn't find PHI entry!");
1039 if (SDL->PHINodesToUpdate[pn].first == Phi) {
1040 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1042 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1048 // Don't process RHS if same block as LHS.
1049 if (BB == SDL->SwitchCases[i].FalseBB)
1050 SDL->SwitchCases[i].FalseBB = 0;
1052 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1053 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1054 SDL->SwitchCases[i].FalseBB = 0;
1056 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1058 SDL->SwitchCases.clear();
1060 SDL->PHINodesToUpdate.clear();
1064 /// Schedule - Pick a safe ordering for instructions for each
1065 /// target node in the graph.
1067 ScheduleDAG *SelectionDAGISel::Schedule() {
1068 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1072 RegisterScheduler::setDefault(Ctor);
1075 ScheduleDAG *Scheduler = Ctor(this, Fast);
1076 Scheduler->Run(CurDAG, BB);
1082 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1083 return new HazardRecognizer();
1086 //===----------------------------------------------------------------------===//
1087 // Helper functions used by the generated instruction selector.
1088 //===----------------------------------------------------------------------===//
1089 // Calls to these methods are generated by tblgen.
1091 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1092 /// the dag combiner simplified the 255, we still want to match. RHS is the
1093 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1094 /// specified in the .td file (e.g. 255).
1095 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1096 int64_t DesiredMaskS) const {
1097 const APInt &ActualMask = RHS->getAPIntValue();
1098 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1100 // If the actual mask exactly matches, success!
1101 if (ActualMask == DesiredMask)
1104 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1105 if (ActualMask.intersects(~DesiredMask))
1108 // Otherwise, the DAG Combiner may have proven that the value coming in is
1109 // either already zero or is not demanded. Check for known zero input bits.
1110 APInt NeededMask = DesiredMask & ~ActualMask;
1111 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1114 // TODO: check to see if missing bits are just not demanded.
1116 // Otherwise, this pattern doesn't match.
1120 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1121 /// the dag combiner simplified the 255, we still want to match. RHS is the
1122 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1123 /// specified in the .td file (e.g. 255).
1124 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1125 int64_t DesiredMaskS) const {
1126 const APInt &ActualMask = RHS->getAPIntValue();
1127 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1129 // If the actual mask exactly matches, success!
1130 if (ActualMask == DesiredMask)
1133 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1134 if (ActualMask.intersects(~DesiredMask))
1137 // Otherwise, the DAG Combiner may have proven that the value coming in is
1138 // either already zero or is not demanded. Check for known zero input bits.
1139 APInt NeededMask = DesiredMask & ~ActualMask;
1141 APInt KnownZero, KnownOne;
1142 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1144 // If all the missing bits in the or are already known to be set, match!
1145 if ((NeededMask & KnownOne) == NeededMask)
1148 // TODO: check to see if missing bits are just not demanded.
1150 // Otherwise, this pattern doesn't match.
1155 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1156 /// by tblgen. Others should not call it.
1157 void SelectionDAGISel::
1158 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1159 std::vector<SDValue> InOps;
1160 std::swap(InOps, Ops);
1162 Ops.push_back(InOps[0]); // input chain.
1163 Ops.push_back(InOps[1]); // input asm string.
1165 unsigned i = 2, e = InOps.size();
1166 if (InOps[e-1].getValueType() == MVT::Flag)
1167 --e; // Don't process a flag operand if it is here.
1170 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1171 if ((Flags & 7) != 4 /*MEM*/) {
1172 // Just skip over this operand, copying the operands verbatim.
1173 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
1174 i += (Flags >> 3) + 1;
1176 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
1177 // Otherwise, this is a memory operand. Ask the target to select it.
1178 std::vector<SDValue> SelOps;
1179 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1180 cerr << "Could not match memory address. Inline asm failure!\n";
1184 // Add this to the output node.
1185 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1186 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1188 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1193 // Add the flag input back if present.
1194 if (e != InOps.size())
1195 Ops.push_back(InOps.back());
1198 char SelectionDAGISel::ID = 0;