blob: 4a67b57cc2e8e324da9618015dd2394264082e61 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Dan Gohman84fbac52009-02-06 17:22:58 +000015#include "ScheduleDAGSDNodes.h"
Dan Gohman2048b852009-11-23 18:04:58 +000016#include "SelectionDAGBuilder.h"
Dan Gohman6277eb22009-11-23 17:16:22 +000017#include "FunctionLoweringInfo.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000018#include "llvm/CodeGen/SelectionDAGISel.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000019#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel713f0432009-09-16 21:09:07 +000020#include "llvm/Analysis/DebugInfo.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000021#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000022#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000025#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000026#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000027#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000029#include "llvm/IntrinsicInst.h"
Chris Lattner75c478a2009-10-27 17:02:08 +000030#include "llvm/LLVMContext.h"
Dan Gohman78eca172008-08-19 22:33:34 +000031#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000032#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000033#include "llvm/CodeGen/GCMetadata.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/MachineFunction.h"
Dan Gohmanad2afc22009-07-31 18:16:33 +000035#include "llvm/CodeGen/MachineFunctionAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000036#include "llvm/CodeGen/MachineFrameInfo.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000038#include "llvm/CodeGen/MachineJumpTableInfo.h"
39#include "llvm/CodeGen/MachineModuleInfo.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanfc54c552009-01-15 22:18:12 +000041#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000042#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000043#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel6e7a1612009-01-09 19:11:50 +000044#include "llvm/CodeGen/DwarfWriter.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000045#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Target/TargetFrameInfo.h"
Dan Gohmane1f188f2009-10-29 22:30:23 +000048#include "llvm/Target/TargetIntrinsicInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000049#include "llvm/Target/TargetInstrInfo.h"
50#include "llvm/Target/TargetLowering.h"
51#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000052#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000054#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000055#include "llvm/Support/ErrorHandling.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000056#include "llvm/Support/MathExtras.h"
57#include "llvm/Support/Timer.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000059#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000060using namespace llvm;
61
Chris Lattneread0d882008-06-17 06:09:18 +000062static cl::opt<bool>
Duncan Sands7cb07872008-10-27 08:42:46 +000063DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
Dan Gohman78eca172008-08-19 22:33:34 +000064static cl::opt<bool>
Dan Gohman293d5f82008-09-09 22:06:46 +000065EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
Dan Gohmand659d502008-10-20 21:30:12 +000066 cl::desc("Enable verbose messages in the \"fast\" "
Dan Gohman293d5f82008-09-09 22:06:46 +000067 "instruction selector"));
68static cl::opt<bool>
Dan Gohman4344a5d2008-09-09 23:05:00 +000069EnableFastISelAbort("fast-isel-abort", cl::Hidden,
70 cl::desc("Enable abort calls when \"fast\" instruction fails"));
Dan Gohman8a110532008-09-05 22:59:21 +000071static cl::opt<bool>
Evan Chengdf8ed022009-11-09 06:49:37 +000072SchedLiveInCopies("schedule-livein-copies", cl::Hidden,
Dan Gohman8a110532008-09-05 22:59:21 +000073 cl::desc("Schedule copies of livein registers"),
74 cl::init(false));
Chris Lattneread0d882008-06-17 06:09:18 +000075
Chris Lattnerda8abb02005-09-01 18:44:10 +000076#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000077static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000078ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
79 cl::desc("Pop up a window to show dags before the first "
80 "dag combine pass"));
81static cl::opt<bool>
82ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
83 cl::desc("Pop up a window to show dags before legalize types"));
84static cl::opt<bool>
85ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
86 cl::desc("Pop up a window to show dags before legalize"));
87static cl::opt<bool>
88ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
89 cl::desc("Pop up a window to show dags before the second "
90 "dag combine pass"));
91static cl::opt<bool>
Duncan Sands25cf2272008-11-24 14:53:14 +000092ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
93 cl::desc("Pop up a window to show dags before the post legalize types"
94 " dag combine pass"));
95static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000096ViewISelDAGs("view-isel-dags", cl::Hidden,
97 cl::desc("Pop up a window to show isel dags as they are selected"));
98static cl::opt<bool>
99ViewSchedDAGs("view-sched-dags", cl::Hidden,
100 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +0000101static cl::opt<bool>
102ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +0000103 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +0000104#else
Dan Gohman462dc7f2008-07-21 20:00:07 +0000105static const bool ViewDAGCombine1 = false,
106 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
107 ViewDAGCombine2 = false,
Duncan Sands25cf2272008-11-24 14:53:14 +0000108 ViewDAGCombineLT = false,
Dan Gohman462dc7f2008-07-21 20:00:07 +0000109 ViewISelDAGs = false, ViewSchedDAGs = false,
110 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +0000111#endif
112
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000113//===---------------------------------------------------------------------===//
114///
115/// RegisterScheduler class - Track the registration of instruction schedulers.
116///
117//===---------------------------------------------------------------------===//
118MachinePassRegistry RegisterScheduler::Registry;
119
120//===---------------------------------------------------------------------===//
121///
122/// ISHeuristic command line option for instruction schedulers.
123///
124//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000125static cl::opt<RegisterScheduler::FunctionPassCtor, false,
126 RegisterPassParser<RegisterScheduler> >
127ISHeuristic("pre-RA-sched",
128 cl::init(&createDefaultScheduler),
129 cl::desc("Instruction schedulers available (before register"
130 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000131
Dan Gohman844731a2008-05-13 00:00:25 +0000132static RegisterScheduler
Dan Gohmanb8cab922008-10-14 20:25:08 +0000133defaultListDAGScheduler("default", "Best scheduler for the target",
Dan Gohman844731a2008-05-13 00:00:25 +0000134 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000135
Chris Lattner1c08c712005-01-07 07:47:53 +0000136namespace llvm {
137 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000138 /// createDefaultScheduler - This creates an instruction scheduler appropriate
139 /// for the target.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000140 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
Bill Wendling98a366d2009-04-29 23:29:43 +0000141 CodeGenOpt::Level OptLevel) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000142 const TargetLowering &TLI = IS->getTargetLowering();
143
Bill Wendling98a366d2009-04-29 23:29:43 +0000144 if (OptLevel == CodeGenOpt::None)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000145 return createFastDAGScheduler(IS, OptLevel);
Dan Gohman9e76fea2008-11-20 03:11:19 +0000146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000147 return createTDListDAGScheduler(IS, OptLevel);
Dan Gohman9e76fea2008-11-20 03:11:19 +0000148 assert(TLI.getSchedulingPreference() ==
149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000150 return createBURRListDAGScheduler(IS, OptLevel);
Jim Laskey9373beb2006-08-01 19:14:14 +0000151 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000152}
153
Evan Chengff9b3732008-01-30 18:18:23 +0000154// EmitInstrWithCustomInserter - This method should be implemented by targets
Dan Gohman533297b2009-10-29 18:10:34 +0000155// that mark instructions with the 'usesCustomInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +0000156// instructions are special in various ways, which require special support to
157// insert. The specified MachineInstr is created but not inserted into any
Dan Gohman533297b2009-10-29 18:10:34 +0000158// basic blocks, and this method is called to expand it into a sequence of
159// instructions, potentially also creating new basic blocks and control flow.
160// When new basic blocks are inserted and the edges from MBB to its successors
161// are modified, the method should insert pairs of <OldSucc, NewSucc> into the
162// DenseMap.
Evan Chengff9b3732008-01-30 18:18:23 +0000163MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Evan Chengfb2e7522009-09-18 21:02:19 +0000164 MachineBasicBlock *MBB,
165 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
Torok Edwinf3689232009-07-12 20:07:01 +0000166#ifndef NDEBUG
Chris Lattner4437ae22009-08-23 07:05:07 +0000167 errs() << "If a target marks an instruction with "
Dan Gohman533297b2009-10-29 18:10:34 +0000168 "'usesCustomInserter', it must implement "
Torok Edwinf3689232009-07-12 20:07:01 +0000169 "TargetLowering::EmitInstrWithCustomInserter!";
170#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000171 llvm_unreachable(0);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000172 return 0;
Chris Lattner025c39b2005-08-26 20:54:47 +0000173}
174
Dan Gohman8a110532008-09-05 22:59:21 +0000175/// EmitLiveInCopy - Emit a copy for a live in physical register. If the
176/// physical register has only a single copy use, then coalesced the copy
177/// if possible.
178static void EmitLiveInCopy(MachineBasicBlock *MBB,
179 MachineBasicBlock::iterator &InsertPos,
180 unsigned VirtReg, unsigned PhysReg,
181 const TargetRegisterClass *RC,
182 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
183 const MachineRegisterInfo &MRI,
184 const TargetRegisterInfo &TRI,
185 const TargetInstrInfo &TII) {
186 unsigned NumUses = 0;
187 MachineInstr *UseMI = NULL;
188 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
189 UE = MRI.use_end(); UI != UE; ++UI) {
190 UseMI = &*UI;
191 if (++NumUses > 1)
192 break;
193 }
194
195 // If the number of uses is not one, or the use is not a move instruction,
196 // don't coalesce. Also, only coalesce away a virtual register to virtual
197 // register copy.
198 bool Coalesced = false;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000199 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Dan Gohman8a110532008-09-05 22:59:21 +0000200 if (NumUses == 1 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +0000201 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
Dan Gohman8a110532008-09-05 22:59:21 +0000202 TargetRegisterInfo::isVirtualRegister(DstReg)) {
203 VirtReg = DstReg;
204 Coalesced = true;
205 }
206
207 // Now find an ideal location to insert the copy.
208 MachineBasicBlock::iterator Pos = InsertPos;
209 while (Pos != MBB->begin()) {
210 MachineInstr *PrevMI = prior(Pos);
211 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
212 // copyRegToReg might emit multiple instructions to do a copy.
213 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
214 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
215 // This is what the BB looks like right now:
216 // r1024 = mov r0
217 // ...
218 // r1 = mov r1024
219 //
220 // We want to insert "r1025 = mov r1". Inserting this copy below the
221 // move to r1024 makes it impossible for that move to be coalesced.
222 //
223 // r1025 = mov r1
224 // r1024 = mov r0
225 // ...
226 // r1 = mov 1024
227 // r2 = mov 1025
228 break; // Woot! Found a good location.
229 --Pos;
230 }
231
David Goodwinf1daf7d2009-07-08 23:10:31 +0000232 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
233 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
234 (void) Emitted;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000235
Zhongxing Xu931424a2009-10-16 05:42:28 +0000236 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
Dan Gohman8a110532008-09-05 22:59:21 +0000237 if (Coalesced) {
238 if (&*InsertPos == UseMI) ++InsertPos;
239 MBB->erase(UseMI);
240 }
241}
242
243/// EmitLiveInCopies - If this is the first basic block in the function,
244/// and if it has live ins that need to be copied into vregs, emit the
245/// copies into the block.
246static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
247 const MachineRegisterInfo &MRI,
248 const TargetRegisterInfo &TRI,
249 const TargetInstrInfo &TII) {
250 if (SchedLiveInCopies) {
251 // Emit the copies at a heuristically-determined location in the block.
252 DenseMap<MachineInstr*, unsigned> CopyRegMap;
253 MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
254 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
255 E = MRI.livein_end(); LI != E; ++LI)
256 if (LI->second) {
257 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
258 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
259 RC, CopyRegMap, MRI, TRI, TII);
260 }
261 } else {
262 // Emit the copies into the top of the block.
263 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
264 E = MRI.livein_end(); LI != E; ++LI)
265 if (LI->second) {
266 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
David Goodwinf1daf7d2009-07-08 23:10:31 +0000267 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
268 LI->second, LI->first, RC, RC);
269 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
270 (void) Emitted;
Dan Gohman8a110532008-09-05 22:59:21 +0000271 }
272 }
273}
274
Chris Lattner7041ee32005-01-11 05:56:49 +0000275//===----------------------------------------------------------------------===//
276// SelectionDAGISel code
277//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000278
Bill Wendling98a366d2009-04-29 23:29:43 +0000279SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
Dan Gohmanad2afc22009-07-31 18:16:33 +0000280 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000281 FuncInfo(new FunctionLoweringInfo(TLI)),
282 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
Dan Gohman2048b852009-11-23 18:04:58 +0000283 SDB(new SelectionDAGBuilder(*CurDAG, TLI, *FuncInfo, OL)),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000284 GFI(),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000285 OptLevel(OL),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000286 DAGSize(0)
287{}
288
289SelectionDAGISel::~SelectionDAGISel() {
Dan Gohman2048b852009-11-23 18:04:58 +0000290 delete SDB;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000291 delete CurDAG;
292 delete FuncInfo;
293}
294
Owen Andersone50ed302009-08-10 22:56:29 +0000295unsigned SelectionDAGISel::MakeReg(EVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000296 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000297}
298
Chris Lattner495a0b52005-08-17 06:37:43 +0000299void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000300 AU.addRequired<AliasAnalysis>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000301 AU.addPreserved<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000302 AU.addRequired<GCModuleInfo>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000303 AU.addPreserved<GCModuleInfo>();
Devang Patel6e7a1612009-01-09 19:11:50 +0000304 AU.addRequired<DwarfWriter>();
Dan Gohmana3477fe2009-07-31 23:36:22 +0000305 AU.addPreserved<DwarfWriter>();
Dan Gohmanad2afc22009-07-31 18:16:33 +0000306 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner495a0b52005-08-17 06:37:43 +0000307}
Chris Lattner1c08c712005-01-07 07:47:53 +0000308
Dan Gohmanad2afc22009-07-31 18:16:33 +0000309bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
310 Function &Fn = *mf.getFunction();
311
Dan Gohman4344a5d2008-09-09 23:05:00 +0000312 // Do some sanity-checking on the command-line options.
313 assert((!EnableFastISelVerbose || EnableFastISel) &&
314 "-fast-isel-verbose requires -fast-isel");
315 assert((!EnableFastISelAbort || EnableFastISel) &&
316 "-fast-isel-abort requires -fast-isel");
317
Dan Gohman5f43f922007-08-27 16:26:13 +0000318 // Get alias analysis for load/store combining.
319 AA = &getAnalysis<AliasAnalysis>();
320
Dan Gohmanad2afc22009-07-31 18:16:33 +0000321 MF = &mf;
Dan Gohman8a110532008-09-05 22:59:21 +0000322 const TargetInstrInfo &TII = *TM.getInstrInfo();
323 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
324
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000325 if (Fn.hasGC())
326 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn);
Gordon Henriksence224772008-01-07 01:30:38 +0000327 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000328 GFI = 0;
Dan Gohman79ce2762009-01-15 19:20:50 +0000329 RegInfo = &MF->getRegInfo();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000330 DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000331
Duncan Sands1465d612009-01-28 13:14:17 +0000332 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
333 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
Owen Anderson5dcaceb2009-07-09 18:44:09 +0000334 CurDAG->init(*MF, MMI, DW);
Dan Gohman6277eb22009-11-23 17:16:22 +0000335 FuncInfo->set(Fn, *MF, EnableFastISel);
Dan Gohman2048b852009-11-23 18:04:58 +0000336 SDB->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000337
Dale Johannesen1532f3d2008-04-02 00:25:04 +0000338 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
339 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
340 // Mark landing pad.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000341 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +0000342
Dan Gohman79ce2762009-01-15 19:20:50 +0000343 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000344
Dan Gohman8a110532008-09-05 22:59:21 +0000345 // If the first basic block in the function has live ins that need to be
346 // copied into vregs, emit the copies into the top of the block before
347 // emitting the code for the block.
Dan Gohman79ce2762009-01-15 19:20:50 +0000348 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
Dan Gohman8a110532008-09-05 22:59:21 +0000349
Evan Chengad2070c2007-02-10 02:43:39 +0000350 // Add function live-ins to entry block live-in set.
Dan Gohman8a110532008-09-05 22:59:21 +0000351 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
352 E = RegInfo->livein_end(); I != E; ++I)
Dan Gohman79ce2762009-01-15 19:20:50 +0000353 MF->begin()->addLiveIn(I->first);
Evan Chengad2070c2007-02-10 02:43:39 +0000354
Duncan Sandsf4070822007-06-15 19:04:19 +0000355#ifndef NDEBUG
Dan Gohman7c3234c2008-08-27 23:52:12 +0000356 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
Duncan Sandsf4070822007-06-15 19:04:19 +0000357 "Not all catch info was assigned to a landing pad!");
358#endif
359
Dan Gohman7c3234c2008-08-27 23:52:12 +0000360 FuncInfo->clear();
361
Chris Lattner1c08c712005-01-07 07:47:53 +0000362 return true;
363}
364
Dan Gohman07f111e2009-12-05 00:27:08 +0000365/// SetDebugLoc - Update MF's and SDB's DebugLocs if debug information is
366/// attached with this instruction.
367static void SetDebugLoc(unsigned MDDbgKind,
368 MetadataContext &TheMetadata,
369 Instruction *I,
370 SelectionDAGBuilder *SDB,
371 FastISel *FastIS,
372 MachineFunction *MF) {
373 if (!isa<DbgInfoIntrinsic>(I))
374 if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, I)) {
375 DILocation DILoc(Dbg);
376 DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo());
377
378 SDB->setCurDebugLoc(Loc);
379
380 if (FastIS)
381 FastIS->setCurDebugLoc(Loc);
382
383 // If the function doesn't have a default debug location yet, set
384 // it. This is kind of a hack.
385 if (MF->getDefaultDebugLoc().isUnknown())
386 MF->setDefaultDebugLoc(Loc);
387 }
388}
389
390/// ResetDebugLoc - Set MF's and SDB's DebugLocs to Unknown.
391static void ResetDebugLoc(SelectionDAGBuilder *SDB,
392 FastISel *FastIS) {
393 SDB->setCurDebugLoc(DebugLoc::getUnknownLoc());
394 if (FastIS)
395 SDB->setCurDebugLoc(DebugLoc::getUnknownLoc());
396}
397
Dan Gohmanf350b272008-08-23 02:25:05 +0000398void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
399 BasicBlock::iterator Begin,
Dan Gohmanb4afb132009-11-20 02:51:26 +0000400 BasicBlock::iterator End,
401 bool &HadTailCall) {
Dan Gohman2048b852009-11-23 18:04:58 +0000402 SDB->setCurrentBasicBlock(BB);
Devang Patele30e6782009-09-28 21:41:20 +0000403 MetadataContext &TheMetadata = LLVMBB->getParent()->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +0000404 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
Dan Gohmanf350b272008-08-23 02:25:05 +0000405
Dan Gohman98ca4f22009-08-05 01:29:28 +0000406 // Lower all of the non-terminator instructions. If a call is emitted
407 // as a tail call, cease emitting nodes for this block.
Dan Gohman2048b852009-11-23 18:04:58 +0000408 for (BasicBlock::iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
Dan Gohman07f111e2009-12-05 00:27:08 +0000409 if (MDDbgKind)
410 SetDebugLoc(MDDbgKind, TheMetadata, I, SDB, 0, MF);
411
412 if (!isa<TerminatorInst>(I)) {
Dan Gohman2048b852009-11-23 18:04:58 +0000413 SDB->visit(*I);
Dan Gohman07f111e2009-12-05 00:27:08 +0000414
415 // Set the current debug location back to "unknown" so that it doesn't
416 // spuriously apply to subsequent instructions.
417 ResetDebugLoc(SDB, 0);
418 }
Devang Patel123eaa72009-09-16 20:39:11 +0000419 }
Dan Gohmanf350b272008-08-23 02:25:05 +0000420
Dan Gohman2048b852009-11-23 18:04:58 +0000421 if (!SDB->HasTailCall) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000422 // Ensure that all instructions which are used outside of their defining
423 // blocks are available as virtual registers. Invoke is handled elsewhere.
424 for (BasicBlock::iterator I = Begin; I != End; ++I)
425 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
Dan Gohman2048b852009-11-23 18:04:58 +0000426 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000427
Dan Gohman98ca4f22009-08-05 01:29:28 +0000428 // Handle PHI nodes in successor blocks.
429 if (End == LLVMBB->end()) {
430 HandlePHINodesInSuccessorBlocks(LLVMBB);
Dan Gohman3df24e62008-09-03 23:12:08 +0000431
Dan Gohman98ca4f22009-08-05 01:29:28 +0000432 // Lower the terminator after the copies are emitted.
Dan Gohman07f111e2009-12-05 00:27:08 +0000433 SetDebugLoc(MDDbgKind, TheMetadata, LLVMBB->getTerminator(), SDB, 0, MF);
Dan Gohman2048b852009-11-23 18:04:58 +0000434 SDB->visit(*LLVMBB->getTerminator());
Dan Gohman07f111e2009-12-05 00:27:08 +0000435 ResetDebugLoc(SDB, 0);
Dan Gohman98ca4f22009-08-05 01:29:28 +0000436 }
Dan Gohman3df24e62008-09-03 23:12:08 +0000437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000438
Chris Lattnera651cf62005-01-17 19:43:36 +0000439 // Make sure the root of the DAG is up-to-date.
Dan Gohman2048b852009-11-23 18:04:58 +0000440 CurDAG->setRoot(SDB->getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000441
Dan Gohmanf350b272008-08-23 02:25:05 +0000442 // Final step, emit the lowered DAG as machine code.
443 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000444 HadTailCall = SDB->HasTailCall;
445 SDB->clear();
Chris Lattner1c08c712005-01-07 07:47:53 +0000446}
447
Dan Gohmanf350b272008-08-23 02:25:05 +0000448void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +0000449 SmallPtrSet<SDNode*, 128> VisitedNodes;
450 SmallVector<SDNode*, 128> Worklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Gabor Greifba36cb52008-08-28 21:40:38 +0000452 Worklist.push_back(CurDAG->getRoot().getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000453
Chris Lattneread0d882008-06-17 06:09:18 +0000454 APInt Mask;
455 APInt KnownZero;
456 APInt KnownOne;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Chris Lattneread0d882008-06-17 06:09:18 +0000458 while (!Worklist.empty()) {
459 SDNode *N = Worklist.back();
460 Worklist.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000461
Chris Lattneread0d882008-06-17 06:09:18 +0000462 // If we've already seen this node, ignore it.
463 if (!VisitedNodes.insert(N))
464 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000465
Chris Lattneread0d882008-06-17 06:09:18 +0000466 // Otherwise, add all chain operands to the worklist.
467 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +0000468 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +0000469 Worklist.push_back(N->getOperand(i).getNode());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000470
Chris Lattneread0d882008-06-17 06:09:18 +0000471 // If this is a CopyToReg with a vreg dest, process it.
472 if (N->getOpcode() != ISD::CopyToReg)
473 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000474
Chris Lattneread0d882008-06-17 06:09:18 +0000475 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
476 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
477 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000478
Chris Lattneread0d882008-06-17 06:09:18 +0000479 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +0000480 SDValue Src = N->getOperand(2);
Owen Andersone50ed302009-08-10 22:56:29 +0000481 EVT SrcVT = Src.getValueType();
Chris Lattneread0d882008-06-17 06:09:18 +0000482 if (!SrcVT.isInteger() || SrcVT.isVector())
483 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000484
Dan Gohmanf350b272008-08-23 02:25:05 +0000485 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +0000486 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +0000487 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000488
Chris Lattneread0d882008-06-17 06:09:18 +0000489 // Only install this information if it tells us something.
490 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
491 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000492 if (DestReg >= FuncInfo->LiveOutRegInfo.size())
493 FuncInfo->LiveOutRegInfo.resize(DestReg+1);
494 FunctionLoweringInfo::LiveOutInfo &LOI =
495 FuncInfo->LiveOutRegInfo[DestReg];
Chris Lattneread0d882008-06-17 06:09:18 +0000496 LOI.NumSignBits = NumSignBits;
Dan Gohmana80efce2009-03-27 23:55:04 +0000497 LOI.KnownOne = KnownOne;
498 LOI.KnownZero = KnownZero;
Chris Lattneread0d882008-06-17 06:09:18 +0000499 }
500 }
501}
502
Dan Gohmanf350b272008-08-23 02:25:05 +0000503void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +0000504 std::string GroupName;
505 if (TimePassesIsEnabled)
506 GroupName = "Instruction Selection and Scheduling";
507 std::string BlockName;
508 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
Duncan Sands25cf2272008-11-24 14:53:14 +0000509 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
510 ViewSUnitDAGs)
Dan Gohmanf7d6cd42009-08-01 03:51:09 +0000511 BlockName = MF->getFunction()->getNameStr() + ":" +
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000512 BB->getBasicBlock()->getNameStr();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000513
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000514 DEBUG(errs() << "Initial selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000515 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000516
Dan Gohmanf350b272008-08-23 02:25:05 +0000517 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +0000518
Chris Lattneraf21d552005-10-10 16:47:10 +0000519 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000520 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000521 NamedRegionTimer T("DAG Combining 1", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000522 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000523 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000524 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000525 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000526
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000527 DEBUG(errs() << "Optimized lowered selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000528 DEBUG(CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529
Chris Lattner1c08c712005-01-07 07:47:53 +0000530 // Second step, hack on the DAG until it only uses operations and types that
531 // the target supports.
Duncan Sands7cb07872008-10-27 08:42:46 +0000532 if (!DisableLegalizeTypes) {
Dan Gohmanf350b272008-08-23 02:25:05 +0000533 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
534 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000535
Duncan Sands25cf2272008-11-24 14:53:14 +0000536 bool Changed;
Dan Gohman462dc7f2008-07-21 20:00:07 +0000537 if (TimePassesIsEnabled) {
538 NamedRegionTimer T("Type Legalization", GroupName);
Duncan Sands25cf2272008-11-24 14:53:14 +0000539 Changed = CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000540 } else {
Duncan Sands25cf2272008-11-24 14:53:14 +0000541 Changed = CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000542 }
543
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000544 DEBUG(errs() << "Type-legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000545 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000546
Duncan Sands25cf2272008-11-24 14:53:14 +0000547 if (Changed) {
548 if (ViewDAGCombineLT)
549 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
550
551 // Run the DAG combiner in post-type-legalize mode.
552 if (TimePassesIsEnabled) {
553 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000554 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Duncan Sands25cf2272008-11-24 14:53:14 +0000555 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000556 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Duncan Sands25cf2272008-11-24 14:53:14 +0000557 }
558
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000559 DEBUG(errs() << "Optimized type-legalized selection DAG:\n");
Duncan Sands25cf2272008-11-24 14:53:14 +0000560 DEBUG(CurDAG->dump());
561 }
Eli Friedman5c22c802009-05-23 12:35:30 +0000562
563 if (TimePassesIsEnabled) {
564 NamedRegionTimer T("Vector Legalization", GroupName);
565 Changed = CurDAG->LegalizeVectors();
566 } else {
567 Changed = CurDAG->LegalizeVectors();
568 }
569
570 if (Changed) {
571 if (TimePassesIsEnabled) {
572 NamedRegionTimer T("Type Legalization 2", GroupName);
573 Changed = CurDAG->LegalizeTypes();
574 } else {
575 Changed = CurDAG->LegalizeTypes();
576 }
577
578 if (ViewDAGCombineLT)
579 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
580
581 // Run the DAG combiner in post-type-legalize mode.
582 if (TimePassesIsEnabled) {
583 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
584 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
585 } else {
586 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
587 }
588
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000589 DEBUG(errs() << "Optimized vector-legalized selection DAG:\n");
Eli Friedman5c22c802009-05-23 12:35:30 +0000590 DEBUG(CurDAG->dump());
591 }
Chris Lattner70587ea2008-07-10 23:37:50 +0000592 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000593
Dan Gohmanf350b272008-08-23 02:25:05 +0000594 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000595
Evan Chengebffb662008-07-01 17:59:20 +0000596 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000597 NamedRegionTimer T("DAG Legalization", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000598 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000599 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000600 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000601 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000602
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000603 DEBUG(errs() << "Legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000604 DEBUG(CurDAG->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000605
Dan Gohmanf350b272008-08-23 02:25:05 +0000606 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000607
Chris Lattneraf21d552005-10-10 16:47:10 +0000608 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000609 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000610 NamedRegionTimer T("DAG Combining 2", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000611 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000612 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000613 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000614 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000615
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000616 DEBUG(errs() << "Optimized legalized selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000617 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +0000618
Dan Gohmanf350b272008-08-23 02:25:05 +0000619 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000620
Bill Wendling98a366d2009-04-29 23:29:43 +0000621 if (OptLevel != CodeGenOpt::None)
Dan Gohmanf350b272008-08-23 02:25:05 +0000622 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +0000623
Chris Lattnera33ef482005-03-30 01:10:47 +0000624 // Third, instruction select all of the operations to machine code, adding the
625 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +0000626 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000627 NamedRegionTimer T("Instruction Selection", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +0000628 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +0000629 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +0000630 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +0000631 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000632
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000633 DEBUG(errs() << "Selected selection DAG:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000634 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000635
Dan Gohmanf350b272008-08-23 02:25:05 +0000636 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000637
Dan Gohman5e843682008-07-14 18:19:29 +0000638 // Schedule machine code.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000639 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
Dan Gohman5e843682008-07-14 18:19:29 +0000640 if (TimePassesIsEnabled) {
641 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000642 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000643 } else {
Dan Gohman47ac0f02009-02-11 04:27:20 +0000644 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000645 }
646
Dan Gohman462dc7f2008-07-21 20:00:07 +0000647 if (ViewSUnitDAGs) Scheduler->viewGraph();
648
Daniel Dunbara279bc32009-09-20 02:20:51 +0000649 // Emit machine code to BB. This can change 'BB' to the last block being
Evan Chengdb8d56b2008-06-30 20:45:06 +0000650 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +0000651 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000652 NamedRegionTimer T("Instruction Creation", GroupName);
Dan Gohman2048b852009-11-23 18:04:58 +0000653 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
Evan Chengebffb662008-07-01 17:59:20 +0000654 } else {
Dan Gohman2048b852009-11-23 18:04:58 +0000655 BB = Scheduler->EmitSchedule(&SDB->EdgeMapping);
Dan Gohman5e843682008-07-14 18:19:29 +0000656 }
657
658 // Free the scheduler state.
659 if (TimePassesIsEnabled) {
660 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
661 delete Scheduler;
662 } else {
663 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +0000664 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000665
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000666 DEBUG(errs() << "Selected machine code:\n");
Chris Lattner1c08c712005-01-07 07:47:53 +0000667 DEBUG(BB->dump());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000668}
Chris Lattner1c08c712005-01-07 07:47:53 +0000669
Dan Gohman79ce2762009-01-15 19:20:50 +0000670void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
671 MachineFunction &MF,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000672 MachineModuleInfo *MMI,
Devang Patel83489bb2009-01-13 00:35:13 +0000673 DwarfWriter *DW,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000674 const TargetInstrInfo &TII) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000675 // Initialize the Fast-ISel state, if needed.
676 FastISel *FastIS = 0;
677 if (EnableFastISel)
Dan Gohman79ce2762009-01-15 19:20:50 +0000678 FastIS = TLI.createFastISel(MF, MMI, DW,
Dan Gohmana43abd12008-09-29 21:55:50 +0000679 FuncInfo->ValueMap,
680 FuncInfo->MBBMap,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000681 FuncInfo->StaticAllocaMap
682#ifndef NDEBUG
683 , FuncInfo->CatchInfoLost
684#endif
685 );
Dan Gohmana43abd12008-09-29 21:55:50 +0000686
Devang Patele30e6782009-09-28 21:41:20 +0000687 MetadataContext &TheMetadata = Fn.getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +0000688 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
Devang Patel123eaa72009-09-16 20:39:11 +0000689
Dan Gohmana43abd12008-09-29 21:55:50 +0000690 // Iterate over all basic blocks in the function.
Evan Cheng39fd6e82008-08-07 00:43:25 +0000691 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
692 BasicBlock *LLVMBB = &*I;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000693 BB = FuncInfo->MBBMap[LLVMBB];
Dan Gohmanf350b272008-08-23 02:25:05 +0000694
Dan Gohman3df24e62008-09-03 23:12:08 +0000695 BasicBlock::iterator const Begin = LLVMBB->begin();
696 BasicBlock::iterator const End = LLVMBB->end();
Evan Cheng9f118502008-09-08 16:01:27 +0000697 BasicBlock::iterator BI = Begin;
Dan Gohman5edd3612008-08-28 20:28:56 +0000698
699 // Lower any arguments needed in this block if this is the entry block.
Dan Gohman33134c42008-09-25 17:05:24 +0000700 bool SuppressFastISel = false;
701 if (LLVMBB == &Fn.getEntryBlock()) {
Dan Gohman5edd3612008-08-28 20:28:56 +0000702 LowerArguments(LLVMBB);
Dan Gohmanf350b272008-08-23 02:25:05 +0000703
Dan Gohman33134c42008-09-25 17:05:24 +0000704 // If any of the arguments has the byval attribute, forgo
705 // fast-isel in the entry block.
Dan Gohmana43abd12008-09-29 21:55:50 +0000706 if (FastIS) {
Dan Gohman33134c42008-09-25 17:05:24 +0000707 unsigned j = 1;
708 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
709 I != E; ++I, ++j)
Devang Patel05988662008-09-25 21:00:45 +0000710 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohman77ca41e2008-09-25 17:21:42 +0000711 if (EnableFastISelVerbose || EnableFastISelAbort)
Chris Lattner4437ae22009-08-23 07:05:07 +0000712 errs() << "FastISel skips entry block due to byval argument\n";
Dan Gohman33134c42008-09-25 17:05:24 +0000713 SuppressFastISel = true;
714 break;
715 }
716 }
717 }
718
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000719 if (MMI && BB->isLandingPad()) {
720 // Add a label to mark the beginning of the landing pad. Deletion of the
721 // landing pad can thus be detected via the MachineModuleInfo.
722 unsigned LabelID = MMI->addLandingPad(BB);
723
724 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
Dan Gohman2048b852009-11-23 18:04:58 +0000725 BuildMI(BB, SDB->getCurDebugLoc(), II).addImm(LabelID);
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000726
727 // Mark exception register as live in.
728 unsigned Reg = TLI.getExceptionAddressRegister();
729 if (Reg) BB->addLiveIn(Reg);
730
731 // Mark exception selector register as live in.
732 Reg = TLI.getExceptionSelectorRegister();
733 if (Reg) BB->addLiveIn(Reg);
734
735 // FIXME: Hack around an exception handling flaw (PR1508): the personality
736 // function and list of typeids logically belong to the invoke (or, if you
737 // like, the basic block containing the invoke), and need to be associated
738 // with it in the dwarf exception handling tables. Currently however the
739 // information is provided by an intrinsic (eh.selector) that can be moved
740 // to unexpected places by the optimizers: if the unwind edge is critical,
741 // then breaking it can result in the intrinsics being in the successor of
742 // the landing pad, not the landing pad itself. This results in exceptions
743 // not being caught because no typeids are associated with the invoke.
744 // This may not be the only way things can go wrong, but it is the only way
745 // we try to work around for the moment.
746 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
747
748 if (Br && Br->isUnconditional()) { // Critical edge?
749 BasicBlock::iterator I, E;
750 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
751 if (isa<EHSelectorInst>(I))
752 break;
753
754 if (I == E)
755 // No catch info found - try to extract some from the successor.
Dan Gohman5fca8b12009-11-23 18:12:11 +0000756 CopyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000757 }
758 }
759
Dan Gohmanf350b272008-08-23 02:25:05 +0000760 // Before doing SelectionDAG ISel, see if FastISel has been requested.
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000761 if (FastIS && !SuppressFastISel) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000762 // Emit code for any incoming arguments. This must happen before
763 // beginning FastISel on the entry block.
764 if (LLVMBB == &Fn.getEntryBlock()) {
Dan Gohman2048b852009-11-23 18:04:58 +0000765 CurDAG->setRoot(SDB->getControlRoot());
Dan Gohmana43abd12008-09-29 21:55:50 +0000766 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000767 SDB->clear();
Dan Gohmana43abd12008-09-29 21:55:50 +0000768 }
Dan Gohman241f4642008-10-04 00:56:36 +0000769 FastIS->startNewBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000770 // Do FastISel on as many instructions as possible.
771 for (; BI != End; ++BI) {
Dan Gohman07f111e2009-12-05 00:27:08 +0000772 if (MDDbgKind)
773 SetDebugLoc(MDDbgKind, TheMetadata, BI, SDB, FastIS, &MF);
Devang Patel123eaa72009-09-16 20:39:11 +0000774
Dan Gohmana43abd12008-09-29 21:55:50 +0000775 // Just before the terminator instruction, insert instructions to
776 // feed PHI nodes in successor blocks.
777 if (isa<TerminatorInst>(BI))
778 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
Dan Gohman07f111e2009-12-05 00:27:08 +0000779 ResetDebugLoc(SDB, FastIS);
Dan Gohman4344a5d2008-09-09 23:05:00 +0000780 if (EnableFastISelVerbose || EnableFastISelAbort) {
Chris Lattner4437ae22009-08-23 07:05:07 +0000781 errs() << "FastISel miss: ";
Dan Gohman293d5f82008-09-09 22:06:46 +0000782 BI->dump();
783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784 assert(!EnableFastISelAbort &&
Torok Edwinf3689232009-07-12 20:07:01 +0000785 "FastISel didn't handle a PHI in a successor");
Dan Gohmana43abd12008-09-29 21:55:50 +0000786 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000787 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000788
789 // First try normal tablegen-generated "fast" selection.
Dan Gohman07f111e2009-12-05 00:27:08 +0000790 if (FastIS->SelectInstruction(BI)) {
791 ResetDebugLoc(SDB, FastIS);
Dan Gohmana43abd12008-09-29 21:55:50 +0000792 continue;
Dan Gohman07f111e2009-12-05 00:27:08 +0000793 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000794
795 // Next, try calling the target to attempt to handle the instruction.
Dan Gohman07f111e2009-12-05 00:27:08 +0000796 if (FastIS->TargetSelectInstruction(BI)) {
797 ResetDebugLoc(SDB, FastIS);
Dan Gohmana43abd12008-09-29 21:55:50 +0000798 continue;
Dan Gohman07f111e2009-12-05 00:27:08 +0000799 }
800
801 // Clear out the debug location so that it doesn't carry over to
802 // unrelated instructions.
803 ResetDebugLoc(SDB, FastIS);
Dan Gohmana43abd12008-09-29 21:55:50 +0000804
805 // Then handle certain instructions as single-LLVM-Instruction blocks.
806 if (isa<CallInst>(BI)) {
807 if (EnableFastISelVerbose || EnableFastISelAbort) {
Chris Lattner4437ae22009-08-23 07:05:07 +0000808 errs() << "FastISel missed call: ";
Dan Gohmana43abd12008-09-29 21:55:50 +0000809 BI->dump();
810 }
811
Owen Anderson1d0be152009-08-13 21:58:54 +0000812 if (BI->getType() != Type::getVoidTy(*CurDAG->getContext())) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000813 unsigned &R = FuncInfo->ValueMap[BI];
814 if (!R)
815 R = FuncInfo->CreateRegForValue(BI);
816 }
817
Dan Gohmanb4afb132009-11-20 02:51:26 +0000818 bool HadTailCall = false;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000819 SelectBasicBlock(LLVMBB, BI, llvm::next(BI), HadTailCall);
Dan Gohmanb4afb132009-11-20 02:51:26 +0000820
821 // If the call was emitted as a tail call, we're done with the block.
822 if (HadTailCall) {
823 BI = End;
824 break;
825 }
826
Dan Gohman241f4642008-10-04 00:56:36 +0000827 // If the instruction was codegen'd with multiple blocks,
828 // inform the FastISel object where to resume inserting.
829 FastIS->setCurrentBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000830 continue;
Dan Gohmanf350b272008-08-23 02:25:05 +0000831 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000832
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) {
Chris Lattner4437ae22009-08-23 07:05:07 +0000837 errs() << "FastISel miss: ";
Dan Gohmana43abd12008-09-29 21:55:50 +0000838 BI->dump();
839 }
840 if (EnableFastISelAbort)
841 // The "fast" selector couldn't handle something and bailed.
842 // For the purpose of debugging, just abort.
Torok Edwinc23197a2009-07-14 16:55:14 +0000843 llvm_unreachable("FastISel didn't select the entire block");
Dan Gohmana43abd12008-09-29 21:55:50 +0000844 }
845 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000846 }
847 }
848
Dan Gohmand2ff6472008-09-02 20:17:56 +0000849 // Run SelectionDAG instruction selection on the remainder of the block
850 // not handled by FastISel. If FastISel is not run, this is the entire
Dan Gohman3df24e62008-09-03 23:12:08 +0000851 // block.
Devang Patel390f3ac2009-04-16 01:33:10 +0000852 if (BI != End) {
Dan Gohmanb4afb132009-11-20 02:51:26 +0000853 bool HadTailCall;
854 SelectBasicBlock(LLVMBB, BI, End, HadTailCall);
Devang Patel390f3ac2009-04-16 01:33:10 +0000855 }
Dan Gohmanf350b272008-08-23 02:25:05 +0000856
Dan Gohman7c3234c2008-08-27 23:52:12 +0000857 FinishBasicBlock();
Evan Cheng39fd6e82008-08-07 00:43:25 +0000858 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000859
860 delete FastIS;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000861}
862
Dan Gohmanfed90b62008-07-28 21:51:04 +0000863void
Dan Gohman7c3234c2008-08-27 23:52:12 +0000864SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +0000865
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000866 DEBUG(errs() << "Target-post-processed machine code:\n");
Dan Gohmanf350b272008-08-23 02:25:05 +0000867 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +0000868
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000869 DEBUG(errs() << "Total amount of phi nodes to update: "
Dan Gohman2048b852009-11-23 18:04:58 +0000870 << SDB->PHINodesToUpdate.size() << "\n");
871 DEBUG(for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i)
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000872 errs() << "Node " << i << " : ("
Dan Gohman2048b852009-11-23 18:04:58 +0000873 << SDB->PHINodesToUpdate[i].first
874 << ", " << SDB->PHINodesToUpdate[i].second << ")\n");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000875
Chris Lattnera33ef482005-03-30 01:10:47 +0000876 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +0000877 // PHI nodes in successors.
Dan Gohman2048b852009-11-23 18:04:58 +0000878 if (SDB->SwitchCases.empty() &&
879 SDB->JTCases.empty() &&
880 SDB->BitTestCases.empty()) {
881 for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i) {
882 MachineInstr *PHI = SDB->PHINodesToUpdate[i].first;
Nate Begemanf15485a2006-03-27 01:32:24 +0000883 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
884 "This is not a machine PHI node that we are updating!");
Dan Gohman2048b852009-11-23 18:04:58 +0000885 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000886 false));
887 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +0000888 }
Dan Gohman2048b852009-11-23 18:04:58 +0000889 SDB->PHINodesToUpdate.clear();
Nate Begemanf15485a2006-03-27 01:32:24 +0000890 return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000891 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000892
Dan Gohman2048b852009-11-23 18:04:58 +0000893 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000894 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +0000895 if (!SDB->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000896 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000897 BB = SDB->BitTestCases[i].Parent;
898 SDB->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000899 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +0000900 SDB->visitBitTestHeader(SDB->BitTestCases[i]);
901 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000902 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000903 SDB->clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000904 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000905
Dan Gohman2048b852009-11-23 18:04:58 +0000906 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000907 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000908 BB = SDB->BitTestCases[i].Cases[j].ThisBB;
909 SDB->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000910 // Emit the code
911 if (j+1 != ej)
Dan Gohman2048b852009-11-23 18:04:58 +0000912 SDB->visitBitTestCase(SDB->BitTestCases[i].Cases[j+1].ThisBB,
913 SDB->BitTestCases[i].Reg,
914 SDB->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000915 else
Dan Gohman2048b852009-11-23 18:04:58 +0000916 SDB->visitBitTestCase(SDB->BitTestCases[i].Default,
917 SDB->BitTestCases[i].Reg,
918 SDB->BitTestCases[i].Cases[j]);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000919
920
Dan Gohman2048b852009-11-23 18:04:58 +0000921 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000922 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000923 SDB->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000924 }
925
926 // Update PHI Nodes
Dan Gohman2048b852009-11-23 18:04:58 +0000927 for (unsigned pi = 0, pe = SDB->PHINodesToUpdate.size(); pi != pe; ++pi) {
928 MachineInstr *PHI = SDB->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000929 MachineBasicBlock *PHIBB = PHI->getParent();
930 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
931 "This is not a machine PHI node that we are updating!");
932 // This is "default" BB. We have two jumps to it. From "header" BB and
933 // from last "case" BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000934 if (PHIBB == SDB->BitTestCases[i].Default) {
935 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000936 false));
Dan Gohman2048b852009-11-23 18:04:58 +0000937 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Parent));
938 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000939 false));
Dan Gohman2048b852009-11-23 18:04:58 +0000940 PHI->addOperand(MachineOperand::CreateMBB(SDB->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000941 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000942 }
943 // One of "cases" BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000944 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
Dan Gohman7c3234c2008-08-27 23:52:12 +0000945 j != ej; ++j) {
Dan Gohman2048b852009-11-23 18:04:58 +0000946 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000947 if (cBB->succ_end() !=
948 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Dan Gohman2048b852009-11-23 18:04:58 +0000949 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000950 false));
951 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000952 }
953 }
954 }
955 }
Dan Gohman2048b852009-11-23 18:04:58 +0000956 SDB->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000957
Nate Begeman9453eea2006-04-23 06:26:20 +0000958 // If the JumpTable record is filled in, then we need to emit a jump table.
959 // Updating the PHI nodes is tricky in this case, since we need to determine
960 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman2048b852009-11-23 18:04:58 +0000961 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000962 // Lower header first, if it wasn't already lowered
Dan Gohman2048b852009-11-23 18:04:58 +0000963 if (!SDB->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000964 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000965 BB = SDB->JTCases[i].first.HeaderBB;
966 SDB->setCurrentBasicBlock(BB);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000967 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +0000968 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first);
969 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000970 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000971 SDB->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000972 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000973
Nate Begeman37efe672006-04-22 18:53:45 +0000974 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +0000975 BB = SDB->JTCases[i].second.MBB;
976 SDB->setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +0000977 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +0000978 SDB->visitJumpTable(SDB->JTCases[i].second);
979 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000980 CodeGenAndEmitDAG();
Dan Gohman2048b852009-11-23 18:04:58 +0000981 SDB->clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000982
Nate Begeman37efe672006-04-22 18:53:45 +0000983 // Update PHI Nodes
Dan Gohman2048b852009-11-23 18:04:58 +0000984 for (unsigned pi = 0, pe = SDB->PHINodesToUpdate.size(); pi != pe; ++pi) {
985 MachineInstr *PHI = SDB->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +0000986 MachineBasicBlock *PHIBB = PHI->getParent();
987 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
988 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000989 // "default" BB. We can go there only from header BB.
Dan Gohman2048b852009-11-23 18:04:58 +0000990 if (PHIBB == SDB->JTCases[i].second.Default) {
Evan Chengce319102009-09-19 09:51:03 +0000991 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +0000992 (MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Evan Chengce319102009-09-19 09:51:03 +0000993 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +0000994 (MachineOperand::CreateMBB(SDB->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +0000995 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000996 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +0000997 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Evan Chengce319102009-09-19 09:51:03 +0000998 PHI->addOperand
Dan Gohman2048b852009-11-23 18:04:58 +0000999 (MachineOperand::CreateReg(SDB->PHINodesToUpdate[pi].second, false));
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001000 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00001001 }
1002 }
Nate Begeman37efe672006-04-22 18:53:45 +00001003 }
Dan Gohman2048b852009-11-23 18:04:58 +00001004 SDB->JTCases.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001005
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001006 // If the switch block involved a branch to one of the actual successors, we
1007 // need to update PHI nodes in that block.
Dan Gohman2048b852009-11-23 18:04:58 +00001008 for (unsigned i = 0, e = SDB->PHINodesToUpdate.size(); i != e; ++i) {
1009 MachineInstr *PHI = SDB->PHINodesToUpdate[i].first;
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001010 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1011 "This is not a machine PHI node that we are updating!");
1012 if (BB->isSuccessor(PHI->getParent())) {
Dan Gohman2048b852009-11-23 18:04:58 +00001013 PHI->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001014 false));
1015 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001016 }
1017 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001018
Nate Begemanf15485a2006-03-27 01:32:24 +00001019 // If we generated any switch lowering information, build and codegen any
1020 // additional DAGs necessary.
Dan Gohman2048b852009-11-23 18:04:58 +00001021 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001022 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman2048b852009-11-23 18:04:58 +00001023 MachineBasicBlock *ThisBB = BB = SDB->SwitchCases[i].ThisBB;
1024 SDB->setCurrentBasicBlock(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001025
Nate Begemanf15485a2006-03-27 01:32:24 +00001026 // Emit the code
Dan Gohman2048b852009-11-23 18:04:58 +00001027 SDB->visitSwitchCase(SDB->SwitchCases[i]);
1028 CurDAG->setRoot(SDB->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001029 CodeGenAndEmitDAG();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001030
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001031 // Handle any PHI nodes in successors of this chunk, as if we were coming
1032 // from the original BB before switch expansion. Note that PHI nodes can
1033 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1034 // handle them the right number of times.
Dan Gohman2048b852009-11-23 18:04:58 +00001035 while ((BB = SDB->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Evan Chengfb2e7522009-09-18 21:02:19 +00001036 // If new BB's are created during scheduling, the edges may have been
Evan Chengce319102009-09-19 09:51:03 +00001037 // updated. That is, the edge from ThisBB to BB may have been split and
1038 // BB's predecessor is now another block.
Evan Chengfb2e7522009-09-18 21:02:19 +00001039 DenseMap<MachineBasicBlock*, MachineBasicBlock*>::iterator EI =
Dan Gohman2048b852009-11-23 18:04:58 +00001040 SDB->EdgeMapping.find(BB);
1041 if (EI != SDB->EdgeMapping.end())
Evan Chengfb2e7522009-09-18 21:02:19 +00001042 ThisBB = EI->second;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001043 for (MachineBasicBlock::iterator Phi = BB->begin();
1044 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1045 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1046 for (unsigned pn = 0; ; ++pn) {
Dan Gohman2048b852009-11-23 18:04:58 +00001047 assert(pn != SDB->PHINodesToUpdate.size() &&
Dan Gohman7c3234c2008-08-27 23:52:12 +00001048 "Didn't find PHI entry!");
Dan Gohman2048b852009-11-23 18:04:58 +00001049 if (SDB->PHINodesToUpdate[pn].first == Phi) {
1050 Phi->addOperand(MachineOperand::CreateReg(SDB->PHINodesToUpdate[pn].
Evan Cheng8be58a12009-09-18 08:26:06 +00001051 second, false));
Evan Chengfb2e7522009-09-18 21:02:19 +00001052 Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001053 break;
Evan Cheng8be58a12009-09-18 08:26:06 +00001054 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001055 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001056 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001057
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001058 // Don't process RHS if same block as LHS.
Dan Gohman2048b852009-11-23 18:04:58 +00001059 if (BB == SDB->SwitchCases[i].FalseBB)
1060 SDB->SwitchCases[i].FalseBB = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001061
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001062 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Dan Gohman2048b852009-11-23 18:04:58 +00001063 SDB->SwitchCases[i].TrueBB = SDB->SwitchCases[i].FalseBB;
1064 SDB->SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00001065 }
Dan Gohman2048b852009-11-23 18:04:58 +00001066 assert(SDB->SwitchCases[i].TrueBB == 0 && SDB->SwitchCases[i].FalseBB == 0);
1067 SDB->clear();
Chris Lattnera33ef482005-03-30 01:10:47 +00001068 }
Dan Gohman2048b852009-11-23 18:04:58 +00001069 SDB->SwitchCases.clear();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001070
Dan Gohman2048b852009-11-23 18:04:58 +00001071 SDB->PHINodesToUpdate.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00001072}
Evan Chenga9c20912006-01-21 02:32:06 +00001073
Jim Laskey13ec7022006-08-01 14:21:23 +00001074
Dan Gohman0a3776d2009-02-06 18:26:51 +00001075/// Create the scheduler. If a specific scheduler was specified
1076/// via the SchedulerRegistry, use it, otherwise select the
1077/// one preferred by the target.
Dan Gohman5e843682008-07-14 18:19:29 +00001078///
Dan Gohman47ac0f02009-02-11 04:27:20 +00001079ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001080 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081
Jim Laskey13ec7022006-08-01 14:21:23 +00001082 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001083 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00001084 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00001085 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001086
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001087 return Ctor(this, OptLevel);
Evan Chenga9c20912006-01-21 02:32:06 +00001088}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001089
Dan Gohmanfc54c552009-01-15 22:18:12 +00001090ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1091 return new ScheduleHazardRecognizer();
Jim Laskey9ff542f2006-08-01 18:29:48 +00001092}
1093
Chris Lattner75548062006-10-11 03:58:02 +00001094//===----------------------------------------------------------------------===//
1095// Helper functions used by the generated instruction selector.
1096//===----------------------------------------------------------------------===//
1097// Calls to these methods are generated by tblgen.
1098
1099/// CheckAndMask - The isel is trying to match something like (and X, 255). If
1100/// the dag combiner simplified the 255, we still want to match. RHS is the
1101/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1102/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001103bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00001104 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001105 const APInt &ActualMask = RHS->getAPIntValue();
1106 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107
Chris Lattner75548062006-10-11 03:58:02 +00001108 // If the actual mask exactly matches, success!
1109 if (ActualMask == DesiredMask)
1110 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001111
Chris Lattner75548062006-10-11 03:58:02 +00001112 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001113 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001114 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattner75548062006-10-11 03:58:02 +00001116 // Otherwise, the DAG Combiner may have proven that the value coming in is
1117 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001118 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00001119 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00001120 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001121
Chris Lattner75548062006-10-11 03:58:02 +00001122 // TODO: check to see if missing bits are just not demanded.
1123
1124 // Otherwise, this pattern doesn't match.
1125 return false;
1126}
1127
1128/// CheckOrMask - The isel is trying to match something like (or X, 255). If
1129/// the dag combiner simplified the 255, we still want to match. RHS is the
1130/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1131/// specified in the .td file (e.g. 255).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001132bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001133 int64_t DesiredMaskS) const {
1134 const APInt &ActualMask = RHS->getAPIntValue();
1135 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136
Chris Lattner75548062006-10-11 03:58:02 +00001137 // If the actual mask exactly matches, success!
1138 if (ActualMask == DesiredMask)
1139 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140
Chris Lattner75548062006-10-11 03:58:02 +00001141 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001142 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001143 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001144
Chris Lattner75548062006-10-11 03:58:02 +00001145 // Otherwise, the DAG Combiner may have proven that the value coming in is
1146 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001147 APInt NeededMask = DesiredMask & ~ActualMask;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001148
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001149 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00001150 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001151
Chris Lattner75548062006-10-11 03:58:02 +00001152 // If all the missing bits in the or are already known to be set, match!
1153 if ((NeededMask & KnownOne) == NeededMask)
1154 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001155
Chris Lattner75548062006-10-11 03:58:02 +00001156 // TODO: check to see if missing bits are just not demanded.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001157
Chris Lattner75548062006-10-11 03:58:02 +00001158 // Otherwise, this pattern doesn't match.
1159 return false;
1160}
1161
Jim Laskey9ff542f2006-08-01 18:29:48 +00001162
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001163/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1164/// by tblgen. Others should not call it.
1165void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00001166SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00001167 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001168 std::swap(InOps, Ops);
1169
1170 Ops.push_back(InOps[0]); // input chain.
1171 Ops.push_back(InOps[1]); // input asm string.
1172
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001173 unsigned i = 2, e = InOps.size();
Owen Anderson825b72b2009-08-11 20:47:22 +00001174 if (InOps[e-1].getValueType() == MVT::Flag)
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001175 --e; // Don't process a flag operand if it is here.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001176
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001177 while (i != e) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00001178 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
Dale Johannesen86b49f82008-09-24 01:07:17 +00001179 if ((Flags & 7) != 4 /*MEM*/) {
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001180 // Just skip over this operand, copying the operands verbatim.
Evan Cheng697cbbf2009-03-20 18:03:34 +00001181 Ops.insert(Ops.end(), InOps.begin()+i,
1182 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1183 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001184 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00001185 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1186 "Memory operand with multiple values?");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001187 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00001188 std::vector<SDValue> SelOps;
Dan Gohmanf350b272008-08-23 02:25:05 +00001189 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
Torok Edwin7d696d82009-07-11 13:10:19 +00001190 llvm_report_error("Could not match memory address. Inline asm"
1191 " failure!");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001192 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001193
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001194 // Add this to the output node.
Owen Andersone50ed302009-08-10 22:56:29 +00001195 EVT IntPtrTy = TLI.getPointerTy();
Dale Johannesen86b49f82008-09-24 01:07:17 +00001196 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
Dan Gohmanf350b272008-08-23 02:25:05 +00001197 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001198 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1199 i += 2;
1200 }
1201 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001203 // Add the flag input back if present.
1204 if (e != InOps.size())
1205 Ops.push_back(InOps.back());
1206}
Devang Patel794fd752007-05-01 21:15:47 +00001207
Owen Andersone50ed302009-08-10 22:56:29 +00001208/// findFlagUse - Return use of EVT::Flag value produced by the specified
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001209/// SDNode.
1210///
1211static SDNode *findFlagUse(SDNode *N) {
1212 unsigned FlagResNo = N->getNumValues()-1;
1213 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1214 SDUse &Use = I.getUse();
1215 if (Use.getResNo() == FlagResNo)
1216 return Use.getUser();
1217 }
1218 return NULL;
1219}
1220
1221/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1222/// This function recursively traverses up the operand chain, ignoring
1223/// certain nodes.
1224static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1225 SDNode *Root,
1226 SmallPtrSet<SDNode*, 16> &Visited) {
1227 if (Use->getNodeId() < Def->getNodeId() ||
1228 !Visited.insert(Use))
1229 return false;
1230
1231 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1232 SDNode *N = Use->getOperand(i).getNode();
1233 if (N == Def) {
1234 if (Use == ImmedUse || Use == Root)
1235 continue; // We are not looking for immediate use.
1236 assert(N != Root);
1237 return true;
1238 }
1239
1240 // Traverse up the operand chain.
1241 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1242 return true;
1243 }
1244 return false;
1245}
1246
1247/// isNonImmUse - Start searching from Root up the DAG to check is Def can
1248/// be reached. Return true if that's the case. However, ignore direct uses
1249/// by ImmedUse (which would be U in the example illustrated in
1250/// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1251/// case).
1252/// FIXME: to be really generic, we should allow direct use by any node
1253/// that is being folded. But realisticly since we only fold loads which
1254/// have one non-chain use, we only need to watch out for load/op/store
1255/// and load/op/cmp case where the root (store / cmp) may reach the load via
1256/// its chain operand.
1257static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1258 SmallPtrSet<SDNode*, 16> Visited;
1259 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1260}
1261
1262/// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1263/// U can be folded during instruction selection that starts at Root and
1264/// folding N is profitable.
1265bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1266 SDNode *Root) const {
1267 if (OptLevel == CodeGenOpt::None) return false;
1268
1269 // If Root use can somehow reach N through a path that that doesn't contain
1270 // U then folding N would create a cycle. e.g. In the following
1271 // diagram, Root can reach N through X. If N is folded into into Root, then
1272 // X is both a predecessor and a successor of U.
1273 //
1274 // [N*] //
1275 // ^ ^ //
1276 // / \ //
1277 // [U*] [X]? //
1278 // ^ ^ //
1279 // \ / //
1280 // \ / //
1281 // [Root*] //
1282 //
1283 // * indicates nodes to be folded together.
1284 //
1285 // If Root produces a flag, then it gets (even more) interesting. Since it
1286 // will be "glued" together with its flag use in the scheduler, we need to
1287 // check if it might reach N.
1288 //
1289 // [N*] //
1290 // ^ ^ //
1291 // / \ //
1292 // [U*] [X]? //
1293 // ^ ^ //
1294 // \ \ //
1295 // \ | //
1296 // [Root*] | //
1297 // ^ | //
1298 // f | //
1299 // | / //
1300 // [Y] / //
1301 // ^ / //
1302 // f / //
1303 // | / //
1304 // [FU] //
1305 //
1306 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1307 // (call it Fold), then X is a predecessor of FU and a successor of
1308 // Fold. But since Fold and FU are flagged together, this will create
1309 // a cycle in the scheduling graph.
1310
Owen Andersone50ed302009-08-10 22:56:29 +00001311 EVT VT = Root->getValueType(Root->getNumValues()-1);
Owen Anderson825b72b2009-08-11 20:47:22 +00001312 while (VT == MVT::Flag) {
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001313 SDNode *FU = findFlagUse(Root);
1314 if (FU == NULL)
1315 break;
1316 Root = FU;
1317 VT = Root->getValueType(Root->getNumValues()-1);
1318 }
1319
1320 return !isNonImmUse(Root, N, U);
1321}
1322
Dan Gohmane1f188f2009-10-29 22:30:23 +00001323SDNode *SelectionDAGISel::Select_INLINEASM(SDValue N) {
1324 std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());
1325 SelectInlineAsmMemoryOperands(Ops);
1326
1327 std::vector<EVT> VTs;
1328 VTs.push_back(MVT::Other);
1329 VTs.push_back(MVT::Flag);
1330 SDValue New = CurDAG->getNode(ISD::INLINEASM, N.getDebugLoc(),
1331 VTs, &Ops[0], Ops.size());
1332 return New.getNode();
1333}
1334
1335SDNode *SelectionDAGISel::Select_UNDEF(const SDValue &N) {
1336 return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,
1337 N.getValueType());
1338}
1339
1340SDNode *SelectionDAGISel::Select_DBG_LABEL(const SDValue &N) {
1341 SDValue Chain = N.getOperand(0);
1342 unsigned C = cast<LabelSDNode>(N)->getLabelID();
1343 SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);
1344 return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,
1345 MVT::Other, Tmp, Chain);
1346}
1347
1348SDNode *SelectionDAGISel::Select_EH_LABEL(const SDValue &N) {
1349 SDValue Chain = N.getOperand(0);
1350 unsigned C = cast<LabelSDNode>(N)->getLabelID();
1351 SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);
1352 return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,
1353 MVT::Other, Tmp, Chain);
1354}
1355
1356void SelectionDAGISel::CannotYetSelect(SDValue N) {
1357 std::string msg;
1358 raw_string_ostream Msg(msg);
1359 Msg << "Cannot yet select: ";
1360 N.getNode()->print(Msg, CurDAG);
1361 llvm_report_error(Msg.str());
1362}
1363
1364void SelectionDAGISel::CannotYetSelectIntrinsic(SDValue N) {
1365 errs() << "Cannot yet select: ";
1366 unsigned iid =
1367 cast<ConstantSDNode>(N.getOperand(N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();
1368 if (iid < Intrinsic::num_intrinsics)
1369 llvm_report_error("Cannot yet select: intrinsic %" + Intrinsic::getName((Intrinsic::ID)iid));
1370 else if (const TargetIntrinsicInfo *tii = TM.getIntrinsicInfo())
1371 llvm_report_error(Twine("Cannot yet select: target intrinsic %") +
1372 tii->getName(iid));
1373}
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001374
Devang Patel19974732007-05-03 01:11:54 +00001375char SelectionDAGISel::ID = 0;