blob: 1f9e2668f8eb9cff2176de9d0edb614857dd60ff [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 Gohmanf0cbcd42008-09-03 16:12:24 +000016#include "SelectionDAGBuild.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000018#include "llvm/Analysis/AliasAnalysis.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Dan Gohman78eca172008-08-19 22:33:34 +000028#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000029#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000030#include "llvm/CodeGen/GCMetadata.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000034#include "llvm/CodeGen/MachineJumpTableInfo.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanfc54c552009-01-15 22:18:12 +000037#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000038#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel6e7a1612009-01-09 19:11:50 +000040#include "llvm/CodeGen/DwarfWriter.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000041#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Target/TargetFrameInfo.h"
44#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetLowering.h"
46#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000047#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000048#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000049#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000050#include "llvm/Support/ErrorHandling.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000051#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/Timer.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000053#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000054using namespace llvm;
55
Chris Lattneread0d882008-06-17 06:09:18 +000056static cl::opt<bool>
Duncan Sands7cb07872008-10-27 08:42:46 +000057DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
Dan Gohman78eca172008-08-19 22:33:34 +000058static cl::opt<bool>
Dan Gohman293d5f82008-09-09 22:06:46 +000059EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
Dan Gohmand659d502008-10-20 21:30:12 +000060 cl::desc("Enable verbose messages in the \"fast\" "
Dan Gohman293d5f82008-09-09 22:06:46 +000061 "instruction selector"));
62static cl::opt<bool>
Dan Gohman4344a5d2008-09-09 23:05:00 +000063EnableFastISelAbort("fast-isel-abort", cl::Hidden,
64 cl::desc("Enable abort calls when \"fast\" instruction fails"));
Dan Gohman8a110532008-09-05 22:59:21 +000065static cl::opt<bool>
66SchedLiveInCopies("schedule-livein-copies",
67 cl::desc("Schedule copies of livein registers"),
68 cl::init(false));
Chris Lattneread0d882008-06-17 06:09:18 +000069
Chris Lattnerda8abb02005-09-01 18:44:10 +000070#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000071static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000072ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
73 cl::desc("Pop up a window to show dags before the first "
74 "dag combine pass"));
75static cl::opt<bool>
76ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before legalize types"));
78static cl::opt<bool>
79ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
80 cl::desc("Pop up a window to show dags before legalize"));
81static cl::opt<bool>
82ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
83 cl::desc("Pop up a window to show dags before the second "
84 "dag combine pass"));
85static cl::opt<bool>
Duncan Sands25cf2272008-11-24 14:53:14 +000086ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
87 cl::desc("Pop up a window to show dags before the post legalize types"
88 " dag combine pass"));
89static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000090ViewISelDAGs("view-isel-dags", cl::Hidden,
91 cl::desc("Pop up a window to show isel dags as they are selected"));
92static cl::opt<bool>
93ViewSchedDAGs("view-sched-dags", cl::Hidden,
94 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000095static cl::opt<bool>
96ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000097 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000098#else
Dan Gohman462dc7f2008-07-21 20:00:07 +000099static const bool ViewDAGCombine1 = false,
100 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
101 ViewDAGCombine2 = false,
Duncan Sands25cf2272008-11-24 14:53:14 +0000102 ViewDAGCombineLT = false,
Dan Gohman462dc7f2008-07-21 20:00:07 +0000103 ViewISelDAGs = false, ViewSchedDAGs = false,
104 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +0000105#endif
106
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000107//===---------------------------------------------------------------------===//
108///
109/// RegisterScheduler class - Track the registration of instruction schedulers.
110///
111//===---------------------------------------------------------------------===//
112MachinePassRegistry RegisterScheduler::Registry;
113
114//===---------------------------------------------------------------------===//
115///
116/// ISHeuristic command line option for instruction schedulers.
117///
118//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000119static cl::opt<RegisterScheduler::FunctionPassCtor, false,
120 RegisterPassParser<RegisterScheduler> >
121ISHeuristic("pre-RA-sched",
122 cl::init(&createDefaultScheduler),
123 cl::desc("Instruction schedulers available (before register"
124 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000125
Dan Gohman844731a2008-05-13 00:00:25 +0000126static RegisterScheduler
Dan Gohmanb8cab922008-10-14 20:25:08 +0000127defaultListDAGScheduler("default", "Best scheduler for the target",
Dan Gohman844731a2008-05-13 00:00:25 +0000128 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000129
Chris Lattner1c08c712005-01-07 07:47:53 +0000130namespace llvm {
131 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000132 /// createDefaultScheduler - This creates an instruction scheduler appropriate
133 /// for the target.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000134 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
Bill Wendling98a366d2009-04-29 23:29:43 +0000135 CodeGenOpt::Level OptLevel) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000136 const TargetLowering &TLI = IS->getTargetLowering();
137
Bill Wendling98a366d2009-04-29 23:29:43 +0000138 if (OptLevel == CodeGenOpt::None)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000139 return createFastDAGScheduler(IS, OptLevel);
Dan Gohman9e76fea2008-11-20 03:11:19 +0000140 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000141 return createTDListDAGScheduler(IS, OptLevel);
Dan Gohman9e76fea2008-11-20 03:11:19 +0000142 assert(TLI.getSchedulingPreference() ==
143 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000144 return createBURRListDAGScheduler(IS, OptLevel);
Jim Laskey9373beb2006-08-01 19:14:14 +0000145 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000146}
147
Evan Chengff9b3732008-01-30 18:18:23 +0000148// EmitInstrWithCustomInserter - This method should be implemented by targets
149// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +0000150// instructions are special in various ways, which require special support to
151// insert. The specified MachineInstr is created but not inserted into any
152// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +0000153MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Dan Gohman1fdbc1d2009-02-07 16:15:20 +0000154 MachineBasicBlock *MBB) const {
Torok Edwinf3689232009-07-12 20:07:01 +0000155#ifndef NDEBUG
156 cerr << "If a target marks an instruction with "
157 "'usesCustomDAGSchedInserter', it must implement "
158 "TargetLowering::EmitInstrWithCustomInserter!";
159#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000160 llvm_unreachable(0);
Chris Lattner025c39b2005-08-26 20:54:47 +0000161 return 0;
162}
163
Dan Gohman8a110532008-09-05 22:59:21 +0000164/// EmitLiveInCopy - Emit a copy for a live in physical register. If the
165/// physical register has only a single copy use, then coalesced the copy
166/// if possible.
167static void EmitLiveInCopy(MachineBasicBlock *MBB,
168 MachineBasicBlock::iterator &InsertPos,
169 unsigned VirtReg, unsigned PhysReg,
170 const TargetRegisterClass *RC,
171 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
172 const MachineRegisterInfo &MRI,
173 const TargetRegisterInfo &TRI,
174 const TargetInstrInfo &TII) {
175 unsigned NumUses = 0;
176 MachineInstr *UseMI = NULL;
177 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
178 UE = MRI.use_end(); UI != UE; ++UI) {
179 UseMI = &*UI;
180 if (++NumUses > 1)
181 break;
182 }
183
184 // If the number of uses is not one, or the use is not a move instruction,
185 // don't coalesce. Also, only coalesce away a virtual register to virtual
186 // register copy.
187 bool Coalesced = false;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000188 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Dan Gohman8a110532008-09-05 22:59:21 +0000189 if (NumUses == 1 &&
Evan Cheng04ee5a12009-01-20 19:12:24 +0000190 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
Dan Gohman8a110532008-09-05 22:59:21 +0000191 TargetRegisterInfo::isVirtualRegister(DstReg)) {
192 VirtReg = DstReg;
193 Coalesced = true;
194 }
195
196 // Now find an ideal location to insert the copy.
197 MachineBasicBlock::iterator Pos = InsertPos;
198 while (Pos != MBB->begin()) {
199 MachineInstr *PrevMI = prior(Pos);
200 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
201 // copyRegToReg might emit multiple instructions to do a copy.
202 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
203 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
204 // This is what the BB looks like right now:
205 // r1024 = mov r0
206 // ...
207 // r1 = mov r1024
208 //
209 // We want to insert "r1025 = mov r1". Inserting this copy below the
210 // move to r1024 makes it impossible for that move to be coalesced.
211 //
212 // r1025 = mov r1
213 // r1024 = mov r0
214 // ...
215 // r1 = mov 1024
216 // r2 = mov 1025
217 break; // Woot! Found a good location.
218 --Pos;
219 }
220
David Goodwinf1daf7d2009-07-08 23:10:31 +0000221 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
222 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
223 (void) Emitted;
224
225CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
Dan Gohman8a110532008-09-05 22:59:21 +0000226 if (Coalesced) {
227 if (&*InsertPos == UseMI) ++InsertPos;
228 MBB->erase(UseMI);
229 }
230}
231
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.
235static 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)
245 if (LI->second) {
246 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
247 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
248 RC, CopyRegMap, MRI, TRI, TII);
249 }
250 } else {
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)
254 if (LI->second) {
255 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
David Goodwinf1daf7d2009-07-08 23:10:31 +0000256 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
257 LI->second, LI->first, RC, RC);
258 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
259 (void) Emitted;
Dan Gohman8a110532008-09-05 22:59:21 +0000260 }
261 }
262}
263
Chris Lattner7041ee32005-01-11 05:56:49 +0000264//===----------------------------------------------------------------------===//
265// SelectionDAGISel code
266//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000267
Bill Wendling98a366d2009-04-29 23:29:43 +0000268SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
Dan Gohman79ce2762009-01-15 19:20:50 +0000269 FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000270 FuncInfo(new FunctionLoweringInfo(TLI)),
271 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000272 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000273 GFI(),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000274 OptLevel(OL),
Dan Gohman7c3234c2008-08-27 23:52:12 +0000275 DAGSize(0)
276{}
277
278SelectionDAGISel::~SelectionDAGISel() {
279 delete SDL;
280 delete CurDAG;
281 delete FuncInfo;
282}
283
Duncan Sands83ec4b62008-06-06 12:08:01 +0000284unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000285 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000286}
287
Chris Lattner495a0b52005-08-17 06:37:43 +0000288void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000289 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000290 AU.addRequired<GCModuleInfo>();
Devang Patel6e7a1612009-01-09 19:11:50 +0000291 AU.addRequired<DwarfWriter>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +0000292 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +0000293}
Chris Lattner1c08c712005-01-07 07:47:53 +0000294
Chris Lattner1c08c712005-01-07 07:47:53 +0000295bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman4344a5d2008-09-09 23:05:00 +0000296 // Do some sanity-checking on the command-line options.
297 assert((!EnableFastISelVerbose || EnableFastISel) &&
298 "-fast-isel-verbose requires -fast-isel");
299 assert((!EnableFastISelAbort || EnableFastISel) &&
300 "-fast-isel-abort requires -fast-isel");
301
Devang Patel16f2ffd2009-04-16 02:33:41 +0000302 // Do not codegen any 'available_externally' functions at all, they have
303 // definitions outside the translation unit.
304 if (Fn.hasAvailableExternallyLinkage())
305 return false;
306
307
Dan Gohman5f43f922007-08-27 16:26:13 +0000308 // Get alias analysis for load/store combining.
309 AA = &getAnalysis<AliasAnalysis>();
310
Dan Gohman8a110532008-09-05 22:59:21 +0000311 TargetMachine &TM = TLI.getTargetMachine();
Dan Gohman79ce2762009-01-15 19:20:50 +0000312 MF = &MachineFunction::construct(&Fn, TM);
Dan Gohman8a110532008-09-05 22:59:21 +0000313 const TargetInstrInfo &TII = *TM.getInstrInfo();
314 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
315
Dan Gohman79ce2762009-01-15 19:20:50 +0000316 if (MF->getFunction()->hasGC())
317 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +0000318 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000319 GFI = 0;
Dan Gohman79ce2762009-01-15 19:20:50 +0000320 RegInfo = &MF->getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +0000321 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000322
Duncan Sands1465d612009-01-28 13:14:17 +0000323 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
324 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
Owen Anderson5dcaceb2009-07-09 18:44:09 +0000325 CurDAG->init(*MF, MMI, DW);
Devang Patelb51d40c2009-02-03 18:46:32 +0000326 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
Dan Gohman7c3234c2008-08-27 23:52:12 +0000327 SDL->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000328
Dale Johannesen1532f3d2008-04-02 00:25:04 +0000329 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
330 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
331 // Mark landing pad.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000332 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +0000333
Dan Gohman79ce2762009-01-15 19:20:50 +0000334 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000335
Dan Gohman8a110532008-09-05 22:59:21 +0000336 // If the first basic block in the function has live ins that need to be
337 // copied into vregs, emit the copies into the top of the block before
338 // emitting the code for the block.
Dan Gohman79ce2762009-01-15 19:20:50 +0000339 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
Dan Gohman8a110532008-09-05 22:59:21 +0000340
Evan Chengad2070c2007-02-10 02:43:39 +0000341 // Add function live-ins to entry block live-in set.
Dan Gohman8a110532008-09-05 22:59:21 +0000342 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
343 E = RegInfo->livein_end(); I != E; ++I)
Dan Gohman79ce2762009-01-15 19:20:50 +0000344 MF->begin()->addLiveIn(I->first);
Evan Chengad2070c2007-02-10 02:43:39 +0000345
Duncan Sandsf4070822007-06-15 19:04:19 +0000346#ifndef NDEBUG
Dan Gohman7c3234c2008-08-27 23:52:12 +0000347 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
Duncan Sandsf4070822007-06-15 19:04:19 +0000348 "Not all catch info was assigned to a landing pad!");
349#endif
350
Dan Gohman7c3234c2008-08-27 23:52:12 +0000351 FuncInfo->clear();
352
Chris Lattner1c08c712005-01-07 07:47:53 +0000353 return true;
354}
355
Duncan Sandsf4070822007-06-15 19:04:19 +0000356static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
357 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000358 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000359 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000360 // Apply the catch info to DestBB.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000361 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
Duncan Sandsf4070822007-06-15 19:04:19 +0000362#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +0000363 if (!FLI.MBBMap[SrcBB]->isLandingPad())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000364 FLI.CatchInfoFound.insert(EHSel);
Duncan Sandsf4070822007-06-15 19:04:19 +0000365#endif
366 }
367}
368
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000369/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
370/// whether object offset >= 0.
371static bool
Dan Gohman79ce2762009-01-15 19:20:50 +0000372IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000373 if (!isa<FrameIndexSDNode>(Op)) return false;
374
375 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
376 int FrameIdx = FrameIdxNode->getIndex();
377 return MFI->isFixedObjectIndex(FrameIdx) &&
378 MFI->getObjectOffset(FrameIdx) >= 0;
379}
380
381/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
382/// possibly be overwritten when lowering the outgoing arguments in a tail
383/// call. Currently the implementation of this call is very conservative and
384/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
385/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +0000386static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Dan Gohman79ce2762009-01-15 19:20:50 +0000387 MachineFrameInfo *MFI) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000388 RegisterSDNode * OpReg = NULL;
389 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
390 (Op.getOpcode()== ISD::CopyFromReg &&
391 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
392 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
393 (Op.getOpcode() == ISD::LOAD &&
394 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
395 (Op.getOpcode() == ISD::MERGE_VALUES &&
Gabor Greif99a6cb92008-08-26 22:36:50 +0000396 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
397 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000398 getOperand(1))))
399 return true;
400 return false;
401}
402
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000403/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +0000404/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000405static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
Dan Gohmane9530ec2009-01-15 16:58:17 +0000406 const TargetLowering& TLI) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000407 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +0000408 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000409
410 // Find RET node.
411 if (Terminator.getOpcode() == ISD::RET) {
Gabor Greifba36cb52008-08-28 21:40:38 +0000412 Ret = Terminator.getNode();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000413 }
414
415 // Fix tail call attribute of CALL nodes.
416 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +0000417 BI = DAG.allnodes_end(); BI != BE; ) {
418 --BI;
Dan Gohman095cc292008-09-13 01:54:27 +0000419 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
Dan Gohman475871a2008-07-27 21:46:04 +0000420 SDValue OpRet(Ret, 0);
421 SDValue OpCall(BI, 0);
Dan Gohman095cc292008-09-13 01:54:27 +0000422 bool isMarkedTailCall = TheCall->isTailCall();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000423 // If CALL node has tail call attribute set to true and the call is not
424 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +0000425 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000426 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000427 if (!isMarkedTailCall) continue;
428 if (Ret==NULL ||
Dan Gohman095cc292008-09-13 01:54:27 +0000429 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
430 // Not eligible. Mark CALL node as non tail call. Note that we
431 // can modify the call node in place since calls are not CSE'd.
432 TheCall->setNotTailCall();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000433 } else {
434 // Look for tail call clobbered arguments. Emit a series of
435 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +0000436 SmallVector<SDValue, 32> Ops;
Dan Gohman095cc292008-09-13 01:54:27 +0000437 SDValue Chain = TheCall->getChain(), InFlag;
438 Ops.push_back(Chain);
439 Ops.push_back(TheCall->getCallee());
440 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
441 SDValue Arg = TheCall->getArg(i);
442 bool isByVal = TheCall->getArgFlags(i).isByVal();
443 MachineFunction &MF = DAG.getMachineFunction();
444 MachineFrameInfo *MFI = MF.getFrameInfo();
445 if (!isByVal &&
446 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
447 MVT VT = Arg.getValueType();
448 unsigned VReg = MF.getRegInfo().
449 createVirtualRegister(TLI.getRegClassFor(VT));
Dale Johannesen6f38cb62009-02-07 19:59:05 +0000450 Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(),
Dale Johannesenc460ae92009-02-04 00:13:36 +0000451 VReg, Arg, InFlag);
Dan Gohman095cc292008-09-13 01:54:27 +0000452 InFlag = Chain.getValue(1);
Dale Johannesen6f38cb62009-02-07 19:59:05 +0000453 Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(),
Dale Johannesenc460ae92009-02-04 00:13:36 +0000454 VReg, VT, InFlag);
Dan Gohman095cc292008-09-13 01:54:27 +0000455 Chain = Arg.getValue(1);
456 InFlag = Arg.getValue(2);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000457 }
458 Ops.push_back(Arg);
Dan Gohman095cc292008-09-13 01:54:27 +0000459 Ops.push_back(TheCall->getArgFlagsVal(i));
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +0000460 }
461 // Link in chain of CopyTo/CopyFromReg.
462 Ops[0] = Chain;
463 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000464 }
465 }
466 }
467}
468
Dan Gohmanf350b272008-08-23 02:25:05 +0000469void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
470 BasicBlock::iterator Begin,
Dan Gohman5edd3612008-08-28 20:28:56 +0000471 BasicBlock::iterator End) {
Dan Gohman7c3234c2008-08-27 23:52:12 +0000472 SDL->setCurrentBasicBlock(BB);
Dan Gohmanf350b272008-08-23 02:25:05 +0000473
Dan Gohmanf350b272008-08-23 02:25:05 +0000474 // Lower all of the non-terminator instructions.
475 for (BasicBlock::iterator I = Begin; I != End; ++I)
476 if (!isa<TerminatorInst>(I))
Dan Gohman7c3234c2008-08-27 23:52:12 +0000477 SDL->visit(*I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000478
479 // Ensure that all instructions which are used outside of their defining
480 // blocks are available as virtual registers. Invoke is handled elsewhere.
481 for (BasicBlock::iterator I = Begin; I != End; ++I)
Dan Gohmanad62f532009-04-23 23:13:24 +0000482 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
483 SDL->CopyToExportRegsIfNeeded(I);
Dan Gohmanf350b272008-08-23 02:25:05 +0000484
485 // Handle PHI nodes in successor blocks.
Dan Gohman3df24e62008-09-03 23:12:08 +0000486 if (End == LLVMBB->end()) {
Dan Gohman7c3234c2008-08-27 23:52:12 +0000487 HandlePHINodesInSuccessorBlocks(LLVMBB);
Dan Gohman3df24e62008-09-03 23:12:08 +0000488
489 // Lower the terminator after the copies are emitted.
490 SDL->visit(*LLVMBB->getTerminator());
491 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000492
Chris Lattnera651cf62005-01-17 19:43:36 +0000493 // Make sure the root of the DAG is up-to-date.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000494 CurDAG->setRoot(SDL->getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +0000495
496 // Check whether calls in this block are real tail calls. Fix up CALL nodes
497 // with correct tailcall attribute so that the target can rely on the tailcall
498 // attribute indicating whether the call is really eligible for tail call
499 // optimization.
Dan Gohman1937e2f2008-09-16 01:42:28 +0000500 if (PerformTailCallOpt)
501 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
Dan Gohmanf350b272008-08-23 02:25:05 +0000502
503 // Final step, emit the lowered DAG as machine code.
504 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +0000505 SDL->clear();
Chris Lattner1c08c712005-01-07 07:47:53 +0000506}
507
Dan Gohmanf350b272008-08-23 02:25:05 +0000508void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +0000509 SmallPtrSet<SDNode*, 128> VisitedNodes;
510 SmallVector<SDNode*, 128> Worklist;
511
Gabor Greifba36cb52008-08-28 21:40:38 +0000512 Worklist.push_back(CurDAG->getRoot().getNode());
Chris Lattneread0d882008-06-17 06:09:18 +0000513
514 APInt Mask;
515 APInt KnownZero;
516 APInt KnownOne;
517
518 while (!Worklist.empty()) {
519 SDNode *N = Worklist.back();
520 Worklist.pop_back();
521
522 // If we've already seen this node, ignore it.
523 if (!VisitedNodes.insert(N))
524 continue;
525
526 // Otherwise, add all chain operands to the worklist.
527 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
528 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +0000529 Worklist.push_back(N->getOperand(i).getNode());
Chris Lattneread0d882008-06-17 06:09:18 +0000530
531 // If this is a CopyToReg with a vreg dest, process it.
532 if (N->getOpcode() != ISD::CopyToReg)
533 continue;
534
535 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
536 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
537 continue;
538
539 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +0000540 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +0000541 MVT SrcVT = Src.getValueType();
542 if (!SrcVT.isInteger() || SrcVT.isVector())
543 continue;
544
Dan Gohmanf350b272008-08-23 02:25:05 +0000545 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +0000546 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +0000547 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Chris Lattneread0d882008-06-17 06:09:18 +0000548
549 // Only install this information if it tells us something.
550 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
551 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf350b272008-08-23 02:25:05 +0000552 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
Chris Lattneread0d882008-06-17 06:09:18 +0000553 if (DestReg >= FLI.LiveOutRegInfo.size())
554 FLI.LiveOutRegInfo.resize(DestReg+1);
555 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
556 LOI.NumSignBits = NumSignBits;
Dan Gohmana80efce2009-03-27 23:55:04 +0000557 LOI.KnownOne = KnownOne;
558 LOI.KnownZero = KnownZero;
Chris Lattneread0d882008-06-17 06:09:18 +0000559 }
560 }
561}
562
Dan Gohmanf350b272008-08-23 02:25:05 +0000563void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +0000564 std::string GroupName;
565 if (TimePassesIsEnabled)
566 GroupName = "Instruction Selection and Scheduling";
567 std::string BlockName;
568 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
Duncan Sands25cf2272008-11-24 14:53:14 +0000569 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
570 ViewSUnitDAGs)
Dan Gohmanf350b272008-08-23 02:25:05 +0000571 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
Dan Gohman462dc7f2008-07-21 20:00:07 +0000572 BB->getBasicBlock()->getName();
573
574 DOUT << "Initial selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +0000575 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000576
Dan Gohmanf350b272008-08-23 02:25:05 +0000577 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +0000578
Chris Lattneraf21d552005-10-10 16:47:10 +0000579 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000580 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000581 NamedRegionTimer T("DAG Combining 1", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000582 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000583 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000584 CurDAG->Combine(Unrestricted, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000585 }
Nate Begeman2300f552005-09-07 00:15:36 +0000586
Dan Gohman417e11b2007-10-08 15:12:17 +0000587 DOUT << "Optimized lowered selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +0000588 DEBUG(CurDAG->dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +0000589
Chris Lattner1c08c712005-01-07 07:47:53 +0000590 // Second step, hack on the DAG until it only uses operations and types that
591 // the target supports.
Duncan Sands7cb07872008-10-27 08:42:46 +0000592 if (!DisableLegalizeTypes) {
Dan Gohmanf350b272008-08-23 02:25:05 +0000593 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
594 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000595
Duncan Sands25cf2272008-11-24 14:53:14 +0000596 bool Changed;
Dan Gohman462dc7f2008-07-21 20:00:07 +0000597 if (TimePassesIsEnabled) {
598 NamedRegionTimer T("Type Legalization", GroupName);
Duncan Sands25cf2272008-11-24 14:53:14 +0000599 Changed = CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000600 } else {
Duncan Sands25cf2272008-11-24 14:53:14 +0000601 Changed = CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +0000602 }
603
604 DOUT << "Type-legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +0000605 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000606
Duncan Sands25cf2272008-11-24 14:53:14 +0000607 if (Changed) {
608 if (ViewDAGCombineLT)
609 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
610
611 // Run the DAG combiner in post-type-legalize mode.
612 if (TimePassesIsEnabled) {
613 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000614 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Duncan Sands25cf2272008-11-24 14:53:14 +0000615 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000616 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
Duncan Sands25cf2272008-11-24 14:53:14 +0000617 }
618
619 DOUT << "Optimized type-legalized selection DAG:\n";
620 DEBUG(CurDAG->dump());
621 }
Eli Friedman5c22c802009-05-23 12:35:30 +0000622
623 if (TimePassesIsEnabled) {
624 NamedRegionTimer T("Vector Legalization", GroupName);
625 Changed = CurDAG->LegalizeVectors();
626 } else {
627 Changed = CurDAG->LegalizeVectors();
628 }
629
630 if (Changed) {
631 if (TimePassesIsEnabled) {
632 NamedRegionTimer T("Type Legalization 2", GroupName);
633 Changed = CurDAG->LegalizeTypes();
634 } else {
635 Changed = CurDAG->LegalizeTypes();
636 }
637
638 if (ViewDAGCombineLT)
639 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
640
641 // Run the DAG combiner in post-type-legalize mode.
642 if (TimePassesIsEnabled) {
643 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
644 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
645 } else {
646 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
647 }
648
649 DOUT << "Optimized vector-legalized selection DAG:\n";
650 DEBUG(CurDAG->dump());
651 }
Chris Lattner70587ea2008-07-10 23:37:50 +0000652 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +0000653
Dan Gohmanf350b272008-08-23 02:25:05 +0000654 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000655
Evan Chengebffb662008-07-01 17:59:20 +0000656 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000657 NamedRegionTimer T("DAG Legalization", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000658 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000659 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000660 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000661 }
Nate Begemanf15485a2006-03-27 01:32:24 +0000662
Bill Wendling832171c2006-12-07 20:04:42 +0000663 DOUT << "Legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +0000664 DEBUG(CurDAG->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +0000665
Dan Gohmanf350b272008-08-23 02:25:05 +0000666 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000667
Chris Lattneraf21d552005-10-10 16:47:10 +0000668 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +0000669 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000670 NamedRegionTimer T("DAG Combining 2", GroupName);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000671 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000672 } else {
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +0000673 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
Evan Chengebffb662008-07-01 17:59:20 +0000674 }
Nate Begeman2300f552005-09-07 00:15:36 +0000675
Dan Gohman417e11b2007-10-08 15:12:17 +0000676 DOUT << "Optimized legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +0000677 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +0000678
Dan Gohmanf350b272008-08-23 02:25:05 +0000679 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +0000680
Bill Wendling98a366d2009-04-29 23:29:43 +0000681 if (OptLevel != CodeGenOpt::None)
Dan Gohmanf350b272008-08-23 02:25:05 +0000682 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +0000683
Chris Lattnera33ef482005-03-30 01:10:47 +0000684 // Third, instruction select all of the operations to machine code, adding the
685 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +0000686 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000687 NamedRegionTimer T("Instruction Selection", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +0000688 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +0000689 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +0000690 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +0000691 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000692
Dan Gohman462dc7f2008-07-21 20:00:07 +0000693 DOUT << "Selected selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +0000694 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +0000695
Dan Gohmanf350b272008-08-23 02:25:05 +0000696 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +0000697
Dan Gohman5e843682008-07-14 18:19:29 +0000698 // Schedule machine code.
Dan Gohman47ac0f02009-02-11 04:27:20 +0000699 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
Dan Gohman5e843682008-07-14 18:19:29 +0000700 if (TimePassesIsEnabled) {
701 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000702 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000703 } else {
Dan Gohman47ac0f02009-02-11 04:27:20 +0000704 Scheduler->Run(CurDAG, BB, BB->end());
Dan Gohman5e843682008-07-14 18:19:29 +0000705 }
706
Dan Gohman462dc7f2008-07-21 20:00:07 +0000707 if (ViewSUnitDAGs) Scheduler->viewGraph();
708
Evan Chengdb8d56b2008-06-30 20:45:06 +0000709 // Emit machine code to BB. This can change 'BB' to the last block being
710 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +0000711 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +0000712 NamedRegionTimer T("Instruction Creation", GroupName);
713 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +0000714 } else {
Dan Gohman5e843682008-07-14 18:19:29 +0000715 BB = Scheduler->EmitSchedule();
716 }
717
718 // Free the scheduler state.
719 if (TimePassesIsEnabled) {
720 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
721 delete Scheduler;
722 } else {
723 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +0000724 }
Evan Chengdb8d56b2008-06-30 20:45:06 +0000725
Bill Wendling832171c2006-12-07 20:04:42 +0000726 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000727 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +0000728}
Chris Lattner1c08c712005-01-07 07:47:53 +0000729
Dan Gohman79ce2762009-01-15 19:20:50 +0000730void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
731 MachineFunction &MF,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000732 MachineModuleInfo *MMI,
Devang Patel83489bb2009-01-13 00:35:13 +0000733 DwarfWriter *DW,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000734 const TargetInstrInfo &TII) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000735 // Initialize the Fast-ISel state, if needed.
736 FastISel *FastIS = 0;
737 if (EnableFastISel)
Dan Gohman79ce2762009-01-15 19:20:50 +0000738 FastIS = TLI.createFastISel(MF, MMI, DW,
Dan Gohmana43abd12008-09-29 21:55:50 +0000739 FuncInfo->ValueMap,
740 FuncInfo->MBBMap,
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000741 FuncInfo->StaticAllocaMap
742#ifndef NDEBUG
743 , FuncInfo->CatchInfoLost
744#endif
745 );
Dan Gohmana43abd12008-09-29 21:55:50 +0000746
747 // Iterate over all basic blocks in the function.
Evan Cheng39fd6e82008-08-07 00:43:25 +0000748 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
749 BasicBlock *LLVMBB = &*I;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000750 BB = FuncInfo->MBBMap[LLVMBB];
Dan Gohmanf350b272008-08-23 02:25:05 +0000751
Dan Gohman3df24e62008-09-03 23:12:08 +0000752 BasicBlock::iterator const Begin = LLVMBB->begin();
753 BasicBlock::iterator const End = LLVMBB->end();
Evan Cheng9f118502008-09-08 16:01:27 +0000754 BasicBlock::iterator BI = Begin;
Dan Gohman5edd3612008-08-28 20:28:56 +0000755
756 // Lower any arguments needed in this block if this is the entry block.
Dan Gohman33134c42008-09-25 17:05:24 +0000757 bool SuppressFastISel = false;
758 if (LLVMBB == &Fn.getEntryBlock()) {
Dan Gohman5edd3612008-08-28 20:28:56 +0000759 LowerArguments(LLVMBB);
Dan Gohmanf350b272008-08-23 02:25:05 +0000760
Dan Gohman33134c42008-09-25 17:05:24 +0000761 // If any of the arguments has the byval attribute, forgo
762 // fast-isel in the entry block.
Dan Gohmana43abd12008-09-29 21:55:50 +0000763 if (FastIS) {
Dan Gohman33134c42008-09-25 17:05:24 +0000764 unsigned j = 1;
765 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
766 I != E; ++I, ++j)
Devang Patel05988662008-09-25 21:00:45 +0000767 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohman77ca41e2008-09-25 17:21:42 +0000768 if (EnableFastISelVerbose || EnableFastISelAbort)
769 cerr << "FastISel skips entry block due to byval argument\n";
Dan Gohman33134c42008-09-25 17:05:24 +0000770 SuppressFastISel = true;
771 break;
772 }
773 }
774 }
775
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000776 if (MMI && BB->isLandingPad()) {
777 // Add a label to mark the beginning of the landing pad. Deletion of the
778 // landing pad can thus be detected via the MachineModuleInfo.
779 unsigned LabelID = MMI->addLandingPad(BB);
780
781 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
Bill Wendlingb2884872009-02-03 01:55:42 +0000782 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000783
784 // Mark exception register as live in.
785 unsigned Reg = TLI.getExceptionAddressRegister();
786 if (Reg) BB->addLiveIn(Reg);
787
788 // Mark exception selector register as live in.
789 Reg = TLI.getExceptionSelectorRegister();
790 if (Reg) BB->addLiveIn(Reg);
791
792 // FIXME: Hack around an exception handling flaw (PR1508): the personality
793 // function and list of typeids logically belong to the invoke (or, if you
794 // like, the basic block containing the invoke), and need to be associated
795 // with it in the dwarf exception handling tables. Currently however the
796 // information is provided by an intrinsic (eh.selector) that can be moved
797 // to unexpected places by the optimizers: if the unwind edge is critical,
798 // then breaking it can result in the intrinsics being in the successor of
799 // the landing pad, not the landing pad itself. This results in exceptions
800 // not being caught because no typeids are associated with the invoke.
801 // This may not be the only way things can go wrong, but it is the only way
802 // we try to work around for the moment.
803 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
804
805 if (Br && Br->isUnconditional()) { // Critical edge?
806 BasicBlock::iterator I, E;
807 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
808 if (isa<EHSelectorInst>(I))
809 break;
810
811 if (I == E)
812 // No catch info found - try to extract some from the successor.
813 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
814 }
815 }
816
Dan Gohmanf350b272008-08-23 02:25:05 +0000817 // Before doing SelectionDAG ISel, see if FastISel has been requested.
Dan Gohmandd5b58a2008-10-14 23:54:11 +0000818 if (FastIS && !SuppressFastISel) {
Dan Gohmana43abd12008-09-29 21:55:50 +0000819 // Emit code for any incoming arguments. This must happen before
820 // beginning FastISel on the entry block.
821 if (LLVMBB == &Fn.getEntryBlock()) {
822 CurDAG->setRoot(SDL->getControlRoot());
823 CodeGenAndEmitDAG();
824 SDL->clear();
825 }
Dan Gohman241f4642008-10-04 00:56:36 +0000826 FastIS->startNewBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000827 // Do FastISel on as many instructions as possible.
828 for (; BI != End; ++BI) {
829 // Just before the terminator instruction, insert instructions to
830 // feed PHI nodes in successor blocks.
831 if (isa<TerminatorInst>(BI))
832 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
Dan Gohman4344a5d2008-09-09 23:05:00 +0000833 if (EnableFastISelVerbose || EnableFastISelAbort) {
Dan Gohman293d5f82008-09-09 22:06:46 +0000834 cerr << "FastISel miss: ";
835 BI->dump();
836 }
Torok Edwinf3689232009-07-12 20:07:01 +0000837 assert(!EnableFastISelAbort &&
838 "FastISel didn't handle a PHI in a successor");
Dan Gohmana43abd12008-09-29 21:55:50 +0000839 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000840 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000841
842 // First try normal tablegen-generated "fast" selection.
843 if (FastIS->SelectInstruction(BI))
844 continue;
845
846 // Next, try calling the target to attempt to handle the instruction.
847 if (FastIS->TargetSelectInstruction(BI))
848 continue;
849
850 // Then handle certain instructions as single-LLVM-Instruction blocks.
851 if (isa<CallInst>(BI)) {
852 if (EnableFastISelVerbose || EnableFastISelAbort) {
853 cerr << "FastISel missed call: ";
854 BI->dump();
855 }
856
857 if (BI->getType() != Type::VoidTy) {
858 unsigned &R = FuncInfo->ValueMap[BI];
859 if (!R)
860 R = FuncInfo->CreateRegForValue(BI);
861 }
862
Devang Patel390f3ac2009-04-16 01:33:10 +0000863 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
Dan Gohmana43abd12008-09-29 21:55:50 +0000864 SelectBasicBlock(LLVMBB, BI, next(BI));
Dan Gohman241f4642008-10-04 00:56:36 +0000865 // If the instruction was codegen'd with multiple blocks,
866 // inform the FastISel object where to resume inserting.
867 FastIS->setCurrentBlock(BB);
Dan Gohmana43abd12008-09-29 21:55:50 +0000868 continue;
Dan Gohmanf350b272008-08-23 02:25:05 +0000869 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000870
871 // Otherwise, give up on FastISel for the rest of the block.
872 // For now, be a little lenient about non-branch terminators.
873 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
874 if (EnableFastISelVerbose || EnableFastISelAbort) {
875 cerr << "FastISel miss: ";
876 BI->dump();
877 }
878 if (EnableFastISelAbort)
879 // The "fast" selector couldn't handle something and bailed.
880 // For the purpose of debugging, just abort.
Torok Edwinc23197a2009-07-14 16:55:14 +0000881 llvm_unreachable("FastISel didn't select the entire block");
Dan Gohmana43abd12008-09-29 21:55:50 +0000882 }
883 break;
Dan Gohmanf350b272008-08-23 02:25:05 +0000884 }
885 }
886
Dan Gohmand2ff6472008-09-02 20:17:56 +0000887 // Run SelectionDAG instruction selection on the remainder of the block
888 // not handled by FastISel. If FastISel is not run, this is the entire
Dan Gohman3df24e62008-09-03 23:12:08 +0000889 // block.
Devang Patel390f3ac2009-04-16 01:33:10 +0000890 if (BI != End) {
891 // If FastISel is run and it has known DebugLoc then use it.
892 if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
893 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
Evan Cheng9f118502008-09-08 16:01:27 +0000894 SelectBasicBlock(LLVMBB, BI, End);
Devang Patel390f3ac2009-04-16 01:33:10 +0000895 }
Dan Gohmanf350b272008-08-23 02:25:05 +0000896
Dan Gohman7c3234c2008-08-27 23:52:12 +0000897 FinishBasicBlock();
Evan Cheng39fd6e82008-08-07 00:43:25 +0000898 }
Dan Gohmana43abd12008-09-29 21:55:50 +0000899
900 delete FastIS;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000901}
902
Dan Gohmanfed90b62008-07-28 21:51:04 +0000903void
Dan Gohman7c3234c2008-08-27 23:52:12 +0000904SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +0000905
Dan Gohmanf350b272008-08-23 02:25:05 +0000906 DOUT << "Target-post-processed machine code:\n";
907 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +0000908
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000909 DOUT << "Total amount of phi nodes to update: "
Dan Gohman7c3234c2008-08-27 23:52:12 +0000910 << SDL->PHINodesToUpdate.size() << "\n";
911 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
912 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
913 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +0000914
Chris Lattnera33ef482005-03-30 01:10:47 +0000915 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +0000916 // PHI nodes in successors.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000917 if (SDL->SwitchCases.empty() &&
918 SDL->JTCases.empty() &&
919 SDL->BitTestCases.empty()) {
920 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
921 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
Nate Begemanf15485a2006-03-27 01:32:24 +0000922 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
923 "This is not a machine PHI node that we are updating!");
Dan Gohman7c3234c2008-08-27 23:52:12 +0000924 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000925 false));
926 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +0000927 }
Dan Gohman7c3234c2008-08-27 23:52:12 +0000928 SDL->PHINodesToUpdate.clear();
Nate Begemanf15485a2006-03-27 01:32:24 +0000929 return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000930 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000931
Dan Gohman7c3234c2008-08-27 23:52:12 +0000932 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000933 // Lower header first, if it wasn't already lowered
Dan Gohman7c3234c2008-08-27 23:52:12 +0000934 if (!SDL->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000935 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +0000936 BB = SDL->BitTestCases[i].Parent;
937 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000938 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +0000939 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
940 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000941 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +0000942 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000943 }
944
Dan Gohman7c3234c2008-08-27 23:52:12 +0000945 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000946 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +0000947 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
948 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000949 // Emit the code
950 if (j+1 != ej)
Dan Gohman7c3234c2008-08-27 23:52:12 +0000951 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
952 SDL->BitTestCases[i].Reg,
953 SDL->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000954 else
Dan Gohman7c3234c2008-08-27 23:52:12 +0000955 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
956 SDL->BitTestCases[i].Reg,
957 SDL->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000958
959
Dan Gohman7c3234c2008-08-27 23:52:12 +0000960 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +0000961 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +0000962 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000963 }
964
965 // Update PHI Nodes
Dan Gohman7c3234c2008-08-27 23:52:12 +0000966 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
967 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000968 MachineBasicBlock *PHIBB = PHI->getParent();
969 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
970 "This is not a machine PHI node that we are updating!");
971 // This is "default" BB. We have two jumps to it. From "header" BB and
972 // from last "case" BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000973 if (PHIBB == SDL->BitTestCases[i].Default) {
974 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000975 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +0000976 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
977 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000978 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +0000979 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000980 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000981 }
982 // One of "cases" BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000983 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
984 j != ej; ++j) {
985 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000986 if (cBB->succ_end() !=
987 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +0000988 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +0000989 false));
990 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000991 }
992 }
993 }
994 }
Dan Gohman7c3234c2008-08-27 23:52:12 +0000995 SDL->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000996
Nate Begeman9453eea2006-04-23 06:26:20 +0000997 // If the JumpTable record is filled in, then we need to emit a jump table.
998 // Updating the PHI nodes is tricky in this case, since we need to determine
999 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman7c3234c2008-08-27 23:52:12 +00001000 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001001 // Lower header first, if it wasn't already lowered
Dan Gohman7c3234c2008-08-27 23:52:12 +00001002 if (!SDL->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001003 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00001004 BB = SDL->JTCases[i].first.HeaderBB;
1005 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001006 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00001007 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
1008 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001009 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001010 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001011 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001012
Nate Begeman37efe672006-04-22 18:53:45 +00001013 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00001014 BB = SDL->JTCases[i].second.MBB;
1015 SDL->setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00001016 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00001017 SDL->visitJumpTable(SDL->JTCases[i].second);
1018 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001019 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001020 SDL->clear();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001021
Nate Begeman37efe672006-04-22 18:53:45 +00001022 // Update PHI Nodes
Dan Gohman7c3234c2008-08-27 23:52:12 +00001023 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
1024 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +00001025 MachineBasicBlock *PHIBB = PHI->getParent();
1026 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1027 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001028 // "default" BB. We can go there only from header BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001029 if (PHIBB == SDL->JTCases[i].second.Default) {
1030 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001031 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00001032 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00001033 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001034 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00001035 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00001036 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001037 false));
1038 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00001039 }
1040 }
Nate Begeman37efe672006-04-22 18:53:45 +00001041 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00001042 SDL->JTCases.clear();
Nate Begeman37efe672006-04-22 18:53:45 +00001043
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001044 // If the switch block involved a branch to one of the actual successors, we
1045 // need to update PHI nodes in that block.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001046 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1047 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001048 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1049 "This is not a machine PHI node that we are updating!");
1050 if (BB->isSuccessor(PHI->getParent())) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00001051 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001052 false));
1053 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001054 }
1055 }
1056
Nate Begemanf15485a2006-03-27 01:32:24 +00001057 // If we generated any switch lowering information, build and codegen any
1058 // additional DAGs necessary.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001059 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001060 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00001061 BB = SDL->SwitchCases[i].ThisBB;
1062 SDL->setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001063
Nate Begemanf15485a2006-03-27 01:32:24 +00001064 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00001065 SDL->visitSwitchCase(SDL->SwitchCases[i]);
1066 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00001067 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00001068 SDL->clear();
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001069
1070 // Handle any PHI nodes in successors of this chunk, as if we were coming
1071 // from the original BB before switch expansion. Note that PHI nodes can
1072 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1073 // handle them the right number of times.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001074 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001075 for (MachineBasicBlock::iterator Phi = BB->begin();
1076 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1077 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1078 for (unsigned pn = 0; ; ++pn) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00001079 assert(pn != SDL->PHINodesToUpdate.size() &&
1080 "Didn't find PHI entry!");
1081 if (SDL->PHINodesToUpdate[pn].first == Phi) {
1082 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00001083 second, false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00001084 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001085 break;
1086 }
1087 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001088 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001089
1090 // Don't process RHS if same block as LHS.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001091 if (BB == SDL->SwitchCases[i].FalseBB)
1092 SDL->SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00001093
1094 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001095 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1096 SDL->SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00001097 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00001098 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00001099 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00001100 SDL->SwitchCases.clear();
1101
1102 SDL->PHINodesToUpdate.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00001103}
Evan Chenga9c20912006-01-21 02:32:06 +00001104
Jim Laskey13ec7022006-08-01 14:21:23 +00001105
Dan Gohman0a3776d2009-02-06 18:26:51 +00001106/// Create the scheduler. If a specific scheduler was specified
1107/// via the SchedulerRegistry, use it, otherwise select the
1108/// one preferred by the target.
Dan Gohman5e843682008-07-14 18:19:29 +00001109///
Dan Gohman47ac0f02009-02-11 04:27:20 +00001110ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001111 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00001112
1113 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00001114 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00001115 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00001116 }
Jim Laskey13ec7022006-08-01 14:21:23 +00001117
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001118 return Ctor(this, OptLevel);
Evan Chenga9c20912006-01-21 02:32:06 +00001119}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001120
Dan Gohmanfc54c552009-01-15 22:18:12 +00001121ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1122 return new ScheduleHazardRecognizer();
Jim Laskey9ff542f2006-08-01 18:29:48 +00001123}
1124
Chris Lattner75548062006-10-11 03:58:02 +00001125//===----------------------------------------------------------------------===//
1126// Helper functions used by the generated instruction selector.
1127//===----------------------------------------------------------------------===//
1128// Calls to these methods are generated by tblgen.
1129
1130/// CheckAndMask - The isel is trying to match something like (and X, 255). If
1131/// the dag combiner simplified the 255, we still want to match. RHS is the
1132/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1133/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00001134bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00001135 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001136 const APInt &ActualMask = RHS->getAPIntValue();
1137 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00001138
1139 // If the actual mask exactly matches, success!
1140 if (ActualMask == DesiredMask)
1141 return true;
1142
1143 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001144 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001145 return false;
1146
1147 // Otherwise, the DAG Combiner may have proven that the value coming in is
1148 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001149 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00001150 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00001151 return true;
1152
1153 // TODO: check to see if missing bits are just not demanded.
1154
1155 // Otherwise, this pattern doesn't match.
1156 return false;
1157}
1158
1159/// CheckOrMask - The isel is trying to match something like (or X, 255). If
1160/// the dag combiner simplified the 255, we still want to match. RHS is the
1161/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1162/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00001163bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001164 int64_t DesiredMaskS) const {
1165 const APInt &ActualMask = RHS->getAPIntValue();
1166 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00001167
1168 // If the actual mask exactly matches, success!
1169 if (ActualMask == DesiredMask)
1170 return true;
1171
1172 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001173 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00001174 return false;
1175
1176 // Otherwise, the DAG Combiner may have proven that the value coming in is
1177 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001178 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00001179
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001180 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00001181 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00001182
1183 // If all the missing bits in the or are already known to be set, match!
1184 if ((NeededMask & KnownOne) == NeededMask)
1185 return true;
1186
1187 // TODO: check to see if missing bits are just not demanded.
1188
1189 // Otherwise, this pattern doesn't match.
1190 return false;
1191}
1192
Jim Laskey9ff542f2006-08-01 18:29:48 +00001193
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001194/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1195/// by tblgen. Others should not call it.
1196void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00001197SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00001198 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001199 std::swap(InOps, Ops);
1200
1201 Ops.push_back(InOps[0]); // input chain.
1202 Ops.push_back(InOps[1]); // input asm string.
1203
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001204 unsigned i = 2, e = InOps.size();
1205 if (InOps[e-1].getValueType() == MVT::Flag)
1206 --e; // Don't process a flag operand if it is here.
1207
1208 while (i != e) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00001209 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
Dale Johannesen86b49f82008-09-24 01:07:17 +00001210 if ((Flags & 7) != 4 /*MEM*/) {
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001211 // Just skip over this operand, copying the operands verbatim.
Evan Cheng697cbbf2009-03-20 18:03:34 +00001212 Ops.insert(Ops.end(), InOps.begin()+i,
1213 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1214 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001215 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00001216 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1217 "Memory operand with multiple values?");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001218 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00001219 std::vector<SDValue> SelOps;
Dan Gohmanf350b272008-08-23 02:25:05 +00001220 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
Torok Edwin7d696d82009-07-11 13:10:19 +00001221 llvm_report_error("Could not match memory address. Inline asm"
1222 " failure!");
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001223 }
1224
1225 // Add this to the output node.
Dan Gohmanf350b272008-08-23 02:25:05 +00001226 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
Dale Johannesen86b49f82008-09-24 01:07:17 +00001227 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
Dan Gohmanf350b272008-08-23 02:25:05 +00001228 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00001229 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1230 i += 2;
1231 }
1232 }
1233
1234 // Add the flag input back if present.
1235 if (e != InOps.size())
1236 Ops.push_back(InOps.back());
1237}
Devang Patel794fd752007-05-01 21:15:47 +00001238
Anton Korobeynikovc1c6ef82009-05-08 18:51:58 +00001239/// findFlagUse - Return use of MVT::Flag value produced by the specified
1240/// SDNode.
1241///
1242static SDNode *findFlagUse(SDNode *N) {
1243 unsigned FlagResNo = N->getNumValues()-1;
1244 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1245 SDUse &Use = I.getUse();
1246 if (Use.getResNo() == FlagResNo)
1247 return Use.getUser();
1248 }
1249 return NULL;
1250}
1251
1252/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1253/// This function recursively traverses up the operand chain, ignoring
1254/// certain nodes.
1255static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1256 SDNode *Root,
1257 SmallPtrSet<SDNode*, 16> &Visited) {
1258 if (Use->getNodeId() < Def->getNodeId() ||
1259 !Visited.insert(Use))
1260 return false;
1261
1262 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1263 SDNode *N = Use->getOperand(i).getNode();
1264 if (N == Def) {
1265 if (Use == ImmedUse || Use == Root)
1266 continue; // We are not looking for immediate use.
1267 assert(N != Root);
1268 return true;
1269 }
1270
1271 // Traverse up the operand chain.
1272 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1273 return true;
1274 }
1275 return false;
1276}
1277
1278/// isNonImmUse - Start searching from Root up the DAG to check is Def can
1279/// be reached. Return true if that's the case. However, ignore direct uses
1280/// by ImmedUse (which would be U in the example illustrated in
1281/// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1282/// case).
1283/// FIXME: to be really generic, we should allow direct use by any node
1284/// that is being folded. But realisticly since we only fold loads which
1285/// have one non-chain use, we only need to watch out for load/op/store
1286/// and load/op/cmp case where the root (store / cmp) may reach the load via
1287/// its chain operand.
1288static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1289 SmallPtrSet<SDNode*, 16> Visited;
1290 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1291}
1292
1293/// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1294/// U can be folded during instruction selection that starts at Root and
1295/// folding N is profitable.
1296bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1297 SDNode *Root) const {
1298 if (OptLevel == CodeGenOpt::None) return false;
1299
1300 // If Root use can somehow reach N through a path that that doesn't contain
1301 // U then folding N would create a cycle. e.g. In the following
1302 // diagram, Root can reach N through X. If N is folded into into Root, then
1303 // X is both a predecessor and a successor of U.
1304 //
1305 // [N*] //
1306 // ^ ^ //
1307 // / \ //
1308 // [U*] [X]? //
1309 // ^ ^ //
1310 // \ / //
1311 // \ / //
1312 // [Root*] //
1313 //
1314 // * indicates nodes to be folded together.
1315 //
1316 // If Root produces a flag, then it gets (even more) interesting. Since it
1317 // will be "glued" together with its flag use in the scheduler, we need to
1318 // check if it might reach N.
1319 //
1320 // [N*] //
1321 // ^ ^ //
1322 // / \ //
1323 // [U*] [X]? //
1324 // ^ ^ //
1325 // \ \ //
1326 // \ | //
1327 // [Root*] | //
1328 // ^ | //
1329 // f | //
1330 // | / //
1331 // [Y] / //
1332 // ^ / //
1333 // f / //
1334 // | / //
1335 // [FU] //
1336 //
1337 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1338 // (call it Fold), then X is a predecessor of FU and a successor of
1339 // Fold. But since Fold and FU are flagged together, this will create
1340 // a cycle in the scheduling graph.
1341
1342 MVT VT = Root->getValueType(Root->getNumValues()-1);
1343 while (VT == MVT::Flag) {
1344 SDNode *FU = findFlagUse(Root);
1345 if (FU == NULL)
1346 break;
1347 Root = FU;
1348 VT = Root->getValueType(Root->getNumValues()-1);
1349 }
1350
1351 return !isNonImmUse(Root, N, U);
1352}
1353
1354
Devang Patel19974732007-05-03 01:11:54 +00001355char SelectionDAGISel::ID = 0;